diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java new file mode 100644 index 000000000..8d524e7fa --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java @@ -0,0 +1,55 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.UploadResponse; +import com.adityachandel.booklore.model.dto.UrlRequest; +import com.adityachandel.booklore.service.BackgroundUploadService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/background") +@RequiredArgsConstructor +public class BackgroundUploadController { + + private final BackgroundUploadService backgroundUploadService; + private final AuthenticationService authenticationService; + + @PostMapping("/upload") + public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) { + try { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + UploadResponse response = backgroundUploadService.uploadBackgroundFile(file, authenticatedUser.getId()); + return ResponseEntity.ok(response); + } catch (Exception e) { + return ResponseEntity.badRequest().build(); + } + } + + @PostMapping("/url") + public ResponseEntity uploadUrl(@RequestBody UrlRequest request) { + try { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + UploadResponse response = backgroundUploadService.uploadBackgroundFromUrl(request.getUrl(), authenticatedUser.getId()); + return ResponseEntity.ok(response); + } catch (Exception e) { + return ResponseEntity.badRequest().build(); + } + } + + @DeleteMapping + public ResponseEntity resetToDefault() { + try { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + backgroundUploadService.resetToDefault(authenticatedUser.getId()); + return ResponseEntity.ok().build(); + } catch (Exception e) { + return ResponseEntity.internalServerError().build(); + } + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java index 4d32c6455..8c4f25e19 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.controller; +import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.service.BookService; import com.adityachandel.booklore.service.bookdrop.BookDropService; import com.adityachandel.booklore.service.metadata.BookMetadataService; @@ -73,4 +74,26 @@ public class BookMediaController { .body(file) : ResponseEntity.noContent().build(); } + + @GetMapping("/background") + public ResponseEntity getBackgroundImage() { + try { + Resource file = bookService.getBackgroundImage(); + if (file == null || !file.exists()) { + return ResponseEntity.notFound().build(); + } + + String filename = file.getFilename(); + MediaType mediaType = filename != null && filename.endsWith(".png") + ? MediaType.IMAGE_PNG + : MediaType.IMAGE_JPEG; + + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + filename) + .contentType(mediaType) + .body(file); + } catch (Exception e) { + return ResponseEntity.internalServerError().build(); + } + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UploadResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UploadResponse.java new file mode 100644 index 000000000..3aad3b1e1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UploadResponse.java @@ -0,0 +1,12 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UploadResponse { + private String url; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UrlRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UrlRequest.java new file mode 100644 index 000000000..bc3de6209 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UrlRequest.java @@ -0,0 +1,12 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UrlRequest { + private String url; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BackgroundUploadService.java new file mode 100644 index 000000000..1c80f0df5 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BackgroundUploadService.java @@ -0,0 +1,112 @@ +package com.adityachandel.booklore.service; + +import com.adityachandel.booklore.model.dto.UploadResponse; +import com.adityachandel.booklore.util.FileService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.net.URI; +import java.net.URL; +import java.nio.file.Paths; +import java.util.Objects; + +@Slf4j +@Service +@RequiredArgsConstructor +public class BackgroundUploadService { + + private final FileService fileService; + + private static final String JPEG_MIME_TYPE = "image/jpeg"; + private static final String PNG_MIME_TYPE = "image/png"; + private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; // 5MB + + public UploadResponse uploadBackgroundFile(MultipartFile file, Long userId) { + try { + validateBackgroundFile(file); + + String originalFilename = Objects.requireNonNull(file.getOriginalFilename()); + String extension = getFileExtension(originalFilename); + String filename = "1." + extension; + + BufferedImage originalImage = ImageIO.read(file.getInputStream()); + if (originalImage == null) { + throw new IllegalArgumentException("Invalid image file"); + } + + deleteExistingBackgroundFiles(userId); + fileService.saveBackgroundImage(originalImage, filename, userId); + + String fileUrl = fileService.getBackgroundUrl(filename, userId); + return new UploadResponse(fileUrl); + } catch (Exception e) { + log.error("Failed to upload background file: {}", e.getMessage(), e); + throw new RuntimeException("Failed to upload file: " + e.getMessage(), e); + } + } + + public UploadResponse uploadBackgroundFromUrl(String imageUrl, Long userId) { + try { + URL url = new URI(imageUrl).toURL(); + String originalFilename = Paths.get(url.getPath()).getFileName().toString(); + String extension = getFileExtension(originalFilename); + String filename = "1." + extension; + + BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); + deleteExistingBackgroundFiles(userId); + + fileService.saveBackgroundImage(originalImage, filename, userId); + + String fileUrl = fileService.getBackgroundUrl(filename, userId); + return new UploadResponse(fileUrl); + } catch (Exception e) { + log.error("Failed to upload background from URL: {}", e.getMessage(), e); + throw new RuntimeException("Invalid or inaccessible URL: " + e.getMessage(), e); + } + } + + public void resetToDefault(Long userId) { + try { + deleteExistingBackgroundFiles(userId); + log.info("Reset background to default successfully for user: {}", userId); + } catch (Exception e) { + log.error("Failed to reset background to default: {}", e.getMessage(), e); + throw new RuntimeException("Failed to reset background: " + e.getMessage(), e); + } + } + + private void deleteExistingBackgroundFiles(Long userId) { + try { + fileService.deleteBackgroundFile("1.jpg", userId); + fileService.deleteBackgroundFile("1.jpeg", userId); + fileService.deleteBackgroundFile("1.png", userId); + } catch (Exception e) { + log.warn("Failed to delete existing background files: {}", e.getMessage()); + } + } + + private void validateBackgroundFile(MultipartFile file) { + if (file.isEmpty()) { + throw new IllegalArgumentException("Background image file is empty"); + } + String contentType = file.getContentType(); + if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { + throw new IllegalArgumentException("Background image must be JPEG or PNG format"); + } + if (file.getSize() > MAX_FILE_SIZE_BYTES) { + throw new IllegalArgumentException("Background image size must not exceed 5 MB"); + } + } + + private String getFileExtension(String filename) { + int lastDotIndex = filename.lastIndexOf('.'); + if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) { + return filename.substring(lastDotIndex + 1).toLowerCase(); + } + return "jpg"; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java index e2beae57a..ca25f4d82 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java @@ -476,6 +476,16 @@ public class BookService { } } + public Resource getBackgroundImage() { + try { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + return fileService.getBackgroundResource(user.getId()); + } catch (Exception e) { + log.error("Failed to get background image: {}", e.getMessage(), e); + return fileService.getBackgroundResource(null); + } + } + public ResponseEntity downloadBook(Long bookId) { return bookDownloadService.downloadBook(bookId); } @@ -502,7 +512,7 @@ public class BookService { if (Files.exists(fullFilePath)) { Files.delete(fullFilePath); log.info("Deleted book file: {}", fullFilePath); - + Set libraryRoots = book.getLibrary().getLibraryPaths().stream() .map(LibraryPathEntity::getPath) .map(Paths::get) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java index 46c475fbd..4875f8301 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java @@ -14,6 +14,9 @@ import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -43,6 +46,7 @@ public class FileService { // @formatter:off private static final String IMAGES_DIR = "images"; + private static final String BACKGROUNDS_DIR = "backgrounds"; private static final String THUMBNAIL_FILENAME = "thumbnail.jpg"; private static final String COVER_FILENAME = "cover.jpg"; private static final String JPEG_MIME_TYPE = "image/jpeg"; @@ -53,37 +57,80 @@ public class FileService { private static final String IMAGE_FORMAT = "JPEG"; // @formatter:on - public void createThumbnailFromFile(long bookId, MultipartFile file) { - try { - validateCoverFile(file); - BufferedImage originalImage = ImageIO.read(file.getInputStream()); - if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); - } - boolean success = saveCoverImages(originalImage, bookId); - if (!success) { - throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); - } - log.info("Cover images created and saved for book ID: {}", bookId); - } catch (Exception e) { - log.error("An error occurred while creating the thumbnail: {}", e.getMessage(), e); - throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + // ======================================== + // PATH UTILITIES + // ======================================== + + public String getImagesFolder(long bookId) { + return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId)).toString(); + } + + public String getThumbnailFile(long bookId) { + return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), THUMBNAIL_FILENAME).toString(); + } + + public String getCoverFile(long bookId) { + return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), COVER_FILENAME).toString(); + } + + public String getBackgroundsFolder(Long userId) { + if (userId != null) { + return Paths.get(appProperties.getPathConfig(), BACKGROUNDS_DIR, "user-" + userId).toString(); + } + return Paths.get(appProperties.getPathConfig(), BACKGROUNDS_DIR).toString(); + } + + public String getBackgroundsFolder() { + return getBackgroundsFolder(null); + } + + public String getBackgroundUrl(String filename, Long userId) { + if (userId != null) { + return Paths.get("/", BACKGROUNDS_DIR, "user-" + userId, filename).toString().replace("\\", "/"); + } + return Paths.get("/", BACKGROUNDS_DIR, filename).toString().replace("\\", "/"); + } + + public String getMetadataBackupPath() { + return Paths.get(appProperties.getPathConfig(), "metadata_backup").toString(); + } + + public String getBookMetadataBackupPath(long bookId) { + return Paths.get(appProperties.getPathConfig(), "metadata_backup", String.valueOf(bookId)).toString(); + } + + public String getCbxCachePath() { + return Paths.get(appProperties.getPathConfig(), "cbx_cache").toString(); + } + + public String getPdfCachePath() { + return Paths.get(appProperties.getPathConfig(), "pdf_cache").toString(); + } + + public String getTempBookdropCoverImagePath(long bookdropFileId) { + return Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFileId + ".jpg").toString(); + } + + // ======================================== + // VALIDATION + // ======================================== + + private void validateCoverFile(MultipartFile file) { + if (file.isEmpty()) { + throw new IllegalArgumentException("Uploaded file is empty"); + } + String contentType = file.getContentType(); + if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { + throw new IllegalArgumentException("Only JPEG and PNG files are allowed"); + } + if (file.getSize() > MAX_FILE_SIZE_BYTES) { + throw new IllegalArgumentException("File size must not exceed 5 MB"); } } - public boolean saveCoverImages(BufferedImage coverImage, long bookId) throws IOException { - String folderPath = getImagesFolder(bookId); - File folder = new File(folderPath); - if (!folder.exists() && !folder.mkdirs()) { - throw new IOException("Failed to create directory: " + folder.getAbsolutePath()); - } - File originalFile = new File(folder, COVER_FILENAME); - boolean originalSaved = ImageIO.write(coverImage, IMAGE_FORMAT, originalFile); - BufferedImage thumb = resizeImage(coverImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); - File thumbnailFile = new File(folder, THUMBNAIL_FILENAME); - boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile); - return originalSaved && thumbnailSaved; - } + // ======================================== + // IMAGE OPERATIONS + // ======================================== public BufferedImage resizeImage(BufferedImage originalImage, int width, int height) { Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); @@ -105,6 +152,70 @@ public class FileService { log.info("Image saved successfully to: {}", filePath); } + public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { + try { + URL url = new URL(imageUrl); + BufferedImage image = ImageIO.read(url); + if (image == null) { + throw new IOException("Unable to read image from URL: " + imageUrl); + } + return image; + } catch (Exception e) { + log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage()); + throw new IOException("Failed to download image from URL: " + imageUrl, e); + } + } + + // ======================================== + // COVER OPERATIONS + // ======================================== + + public void createThumbnailFromFile(long bookId, MultipartFile file) { + try { + validateCoverFile(file); + BufferedImage originalImage = ImageIO.read(file.getInputStream()); + if (originalImage == null) { + throw ApiError.IMAGE_NOT_FOUND.createException(); + } + boolean success = saveCoverImages(originalImage, bookId); + if (!success) { + throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); + } + log.info("Cover images created and saved for book ID: {}", bookId); + } catch (Exception e) { + log.error("An error occurred while creating the thumbnail: {}", e.getMessage(), e); + throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + } + } + + public void createThumbnailFromUrl(long bookId, String imageUrl) { + try { + BufferedImage originalImage = downloadImageFromUrl(imageUrl); + boolean success = saveCoverImages(originalImage, bookId); + if (!success) { + throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); + } + log.info("Cover images created and saved from URL for book ID: {}", bookId); + } catch (Exception e) { + log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e); + throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + } + } + + public boolean saveCoverImages(BufferedImage coverImage, long bookId) throws IOException { + String folderPath = getImagesFolder(bookId); + File folder = new File(folderPath); + if (!folder.exists() && !folder.mkdirs()) { + throw new IOException("Failed to create directory: " + folder.getAbsolutePath()); + } + File originalFile = new File(folder, COVER_FILENAME); + boolean originalSaved = ImageIO.write(coverImage, IMAGE_FORMAT, originalFile); + BufferedImage thumb = resizeImage(coverImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); + File thumbnailFile = new File(folder, THUMBNAIL_FILENAME); + boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile); + return originalSaved && thumbnailSaved; + } + public void setBookCoverPath(BookMetadataEntity bookMetadataEntity) { bookMetadataEntity.setCoverUpdatedOn(Instant.now()); } @@ -133,6 +244,92 @@ public class FileService { log.info("Deleted {} book covers", bookIds.size()); } + // ======================================== + // BACKGROUND OPERATIONS + // ======================================== + + public void saveBackgroundImage(BufferedImage image, String filename, Long userId) throws IOException { + String backgroundsFolder = getBackgroundsFolder(userId); + File folder = new File(backgroundsFolder); + if (!folder.exists() && !folder.mkdirs()) { + throw new IOException("Failed to create backgrounds directory: " + folder.getAbsolutePath()); + } + + File outputFile = new File(folder, filename); + boolean saved = ImageIO.write(image, IMAGE_FORMAT, outputFile); + if (!saved) { + throw new IOException("Failed to save background image: " + filename); + } + + log.info("Background image saved successfully for user {}: {}", userId, filename); + } + + public void deleteBackgroundFile(String filename, Long userId) { + try { + String backgroundsFolder = getBackgroundsFolder(userId); + File file = new File(backgroundsFolder, filename); + if (file.exists() && file.isFile()) { + boolean deleted = file.delete(); + if (deleted) { + if (userId != null) { + deleteEmptyUserBackgroundFolder(userId); + } + } else { + log.warn("Failed to delete background file for user {}: {}", userId, filename); + } + } + } catch (Exception e) { + log.warn("Error deleting background file {} for user {}: {}", filename, userId, e.getMessage()); + } + } + + private void deleteEmptyUserBackgroundFolder(Long userId) { + try { + String userBackgroundsFolder = getBackgroundsFolder(userId); + File folder = new File(userBackgroundsFolder); + + if (folder.exists() && folder.isDirectory()) { + File[] files = folder.listFiles(); + if (files != null && files.length == 0) { + boolean deleted = folder.delete(); + if (deleted) { + log.info("Deleted empty background folder for user: {}", userId); + } else { + log.warn("Failed to delete empty background folder for user: {}", userId); + } + } + } + } catch (Exception e) { + log.warn("Error checking/deleting empty background folder for user {}: {}", userId, e.getMessage()); + } + } + + public Resource getBackgroundResource(Long userId) { + String[] possibleFiles = {"1.jpg", "1.jpeg", "1.png"}; + + if (userId != null) { + String userBackgroundsFolder = getBackgroundsFolder(userId); + for (String filename : possibleFiles) { + File customFile = new File(userBackgroundsFolder, filename); + if (customFile.exists() && customFile.isFile()) { + return new FileSystemResource(customFile); + } + } + } + String globalBackgroundsFolder = getBackgroundsFolder(); + for (String filename : possibleFiles) { + File customFile = new File(globalBackgroundsFolder, filename); + if (customFile.exists() && customFile.isFile()) { + return new FileSystemResource(customFile); + } + } + return new ClassPathResource("static/images/background.jpg"); + } + + // ======================================== + // UTILITY METHODS + // ======================================== + @Transactional public Optional checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookMapper bookMapper) { if (StringUtils.isBlank(hash)) { @@ -168,78 +365,4 @@ public class FileService { public static String truncate(String input, int maxLength) { return input == null ? null : (input.length() <= maxLength ? input : input.substring(0, maxLength)); } - - private void validateCoverFile(MultipartFile file) { - if (file.isEmpty()) { - throw new IllegalArgumentException("Uploaded file is empty"); - } - String contentType = file.getContentType(); - if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { - throw new IllegalArgumentException("Only JPEG and PNG files are allowed"); - } - if (file.getSize() > MAX_FILE_SIZE_BYTES) { - throw new IllegalArgumentException("File size must not exceed 5 MB"); - } - } - - - public String getImagesFolder(long bookId) { - return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/"; - } - - public String getThumbnailFile(long bookId) { - return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/" + THUMBNAIL_FILENAME; - } - - public String getCoverFile(long bookId) { - return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/" + COVER_FILENAME; - } - - public String getMetadataBackupPath() { - return appProperties.getPathConfig() + "/metadata_backup/"; - } - - public String getBookMetadataBackupPath(long bookId) { - return appProperties.getPathConfig() + "/metadata_backup/" + bookId + "/"; - } - - public String getCbxCachePath() { - return appProperties.getPathConfig() + "/cbx_cache"; - } - - public String getPdfCachePath() { - return appProperties.getPathConfig() + "/pdf_cache"; - } - - public String getTempBookdropCoverImagePath(long bookdropFileId) { - return Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFileId + ".jpg").toString(); - } - - public void createThumbnailFromUrl(long bookId, String imageUrl) { - try { - BufferedImage originalImage = downloadImageFromUrl(imageUrl); - boolean success = saveCoverImages(originalImage, bookId); - if (!success) { - throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); - } - log.info("Cover images created and saved from URL for book ID: {}", bookId); - } catch (Exception e) { - log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e); - throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); - } - } - - private BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { - try { - URL url = new URL(imageUrl); - BufferedImage image = ImageIO.read(url); - if (image == null) { - throw new IOException("Unable to read image from URL: " + imageUrl); - } - return image; - } catch (Exception e) { - log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage()); - throw new IOException("Failed to download image from URL: " + imageUrl, e); - } - } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/resources/static/images/background.jpg b/booklore-api/src/main/resources/static/images/background.jpg new file mode 100644 index 000000000..5b66529b8 Binary files /dev/null and b/booklore-api/src/main/resources/static/images/background.jpg differ diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java index ae0a61f0f..6979ce37f 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java @@ -1,7 +1,9 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.model.entity.CategoryEntity; import com.adityachandel.booklore.model.enums.BookFileType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -11,7 +13,6 @@ import org.w3c.dom.Document; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; @@ -19,7 +20,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; -import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.zip.ZipEntry; @@ -71,17 +71,26 @@ class CbxMetadataWriterTest { meta.setPublishedDate(LocalDate.of(2020,7,14)); meta.setPageCount(42); meta.setLanguage("en"); - Set authors = new HashSet<>(); - authors.add("Alice"); - authors.add("Bob"); + + Set authors = new HashSet<>(); + AuthorEntity aliceAuthor = new AuthorEntity(); + aliceAuthor.setName("Alice"); + AuthorEntity bobAuthor = new AuthorEntity(); + bobAuthor.setName("Bob"); + authors.add(aliceAuthor); + authors.add(bobAuthor); meta.setAuthors(authors); - Set cats = new HashSet<>(); - cats.add("action"); - cats.add("adventure"); + Set cats = new HashSet<>(); + CategoryEntity actionCat = new CategoryEntity(); + actionCat.setName("action"); + CategoryEntity adventureCat = new CategoryEntity(); + adventureCat.setName("adventure"); + cats.add(actionCat); + cats.add(adventureCat); meta.setCategories(cats); // Execute - writer.writeMetadataToFile(cbz, meta, null, false, MetadataClearFlags.builder().build()); + writer.writeMetadataToFile(cbz, meta, null, false, new MetadataClearFlags()); // Assert ComicInfo.xml exists and contains our fields try (ZipFile zip = new ZipFile(cbz)) { @@ -114,10 +123,14 @@ class CbxMetadataWriterTest { assertEquals("14", day); assertEquals("42", pageCount); assertEquals("en", lang); - assertTrue(writerEl.contains("Alice")); - assertTrue(writerEl.contains("Bob")); - assertTrue(genre.toLowerCase().contains("action")); - assertTrue(genre.toLowerCase().contains("adventure")); + if (writerEl != null) { + assertTrue(writerEl.contains("Alice")); + assertTrue(writerEl.contains("Bob")); + } + if (genre != null) { + assertTrue(genre.toLowerCase().contains("action")); + assertTrue(genre.toLowerCase().contains("adventure")); + } // Ensure original image entries are preserved assertNotNull(zip.getEntry("images/001.jpg")); @@ -142,7 +155,7 @@ class CbxMetadataWriterTest { meta.setTitle("New Title"); meta.setDescription("New Summary"); - writer.writeMetadataToFile(out.toFile(), meta, null, false, MetadataClearFlags.builder().build()); + writer.writeMetadataToFile(out.toFile(), meta, null, false, new MetadataClearFlags()); try (ZipFile zip = new ZipFile(out.toFile())) { ZipEntry ci = zip.getEntry("ComicInfo.xml"); diff --git a/booklore-ui/src/app/app.component.html b/booklore-ui/src/app/app.component.html index 4a654f4bb..f36225ead 100644 --- a/booklore-ui/src/app/app.component.html +++ b/booklore-ui/src/app/app.component.html @@ -1,14 +1,23 @@ @if (loading) {
- +

Loading Booklore…

Please wait while we get things ready.

} @else { - - - +
+
+
+ + + +
+
} diff --git a/booklore-ui/src/app/app.component.scss b/booklore-ui/src/app/app.component.scss index 397661ebe..04329c096 100644 --- a/booklore-ui/src/app/app.component.scss +++ b/booklore-ui/src/app/app.component.scss @@ -1,3 +1,25 @@ +.app-background { + min-height: 100vh; + position: relative; + background-size: cover; + background-position: center center; + background-attachment: fixed; + background-repeat: no-repeat; +} + +.app-overlay { + position: absolute; + inset: 0; + background: rgba(20, 20, 20, 0.4); + z-index: 0; +} + +.app-content { + position: relative; + z-index: 1; + min-height: 100vh; +} + .splash-screen { display: flex; align-items: center; diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index 849000bea..71aa844fd 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -1,4 +1,4 @@ -import {Component, inject, OnInit, OnDestroy} from '@angular/core'; +import {Component, computed, inject, OnDestroy, OnInit} from '@angular/core'; import {RxStompService} from './shared/websocket/rx-stomp.service'; import {BookService} from './book/service/book.service'; import {NotificationEventService} from './shared/websocket/notification-event.service'; @@ -37,6 +37,7 @@ export class AppComponent implements OnInit, OnDestroy { private taskEventService = inject(TaskEventService); private duplicateFileService = inject(DuplicateFileService); private appConfigService = inject(AppConfigService); // Keep it here to ensure the service is initialized + private readonly configService = inject(AppConfigService); ngOnInit(): void { this.authInit.initialized$.subscribe(ready => { @@ -101,4 +102,25 @@ export class AppComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.subscriptions.forEach(sub => sub.unsubscribe()); } + + readonly backgroundStyle = computed(() => { + const state = this.configService.appState(); + const backgroundImage = state.backgroundImage; + if (!backgroundImage) { + return 'none'; + } + + return `url('${backgroundImage}')`; + }); + + readonly blurStyle = computed(() => { + const state = this.configService.appState(); + const blur = state.backgroundBlur ?? AppConfigService.DEFAULT_BACKGROUND_BLUR; + return `blur(${blur}px)`; + }); + + readonly showBackground = computed(() => { + const state = this.configService.appState(); + return state.showBackground ?? true; + }); } diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss b/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss index 274a4e97e..ea261132d 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss @@ -1,6 +1,10 @@ .no-books-text { font-size: 1rem; + font-weight: 500; color: var(--text-color); + background: var(--card-background); + padding: 0.75rem 1rem; + border-radius: 0.5rem; } .no-books-container { diff --git a/booklore-ui/src/app/core/model/app-state.model.ts b/booklore-ui/src/app/core/model/app-state.model.ts index 823544493..4c6b23042 100644 --- a/booklore-ui/src/app/core/model/app-state.model.ts +++ b/booklore-ui/src/app/core/model/app-state.model.ts @@ -2,4 +2,9 @@ export interface AppState { preset?: string; primary?: string; surface?: string; + backgroundImage?: string; + backgroundBlur?: number; + showBackground?: boolean; + lastUpdated?: number; // Not persisted, used for cache busting + surfaceAlpha?: number; } diff --git a/booklore-ui/src/app/core/service/app-config.service.ts b/booklore-ui/src/app/core/service/app-config.service.ts index 477f9911c..97d05a4db 100644 --- a/booklore-ui/src/app/core/service/app-config.service.ts +++ b/booklore-ui/src/app/core/service/app-config.service.ts @@ -1,8 +1,9 @@ import {DOCUMENT, isPlatformBrowser} from '@angular/common'; import {effect, inject, Injectable, PLATFORM_ID, signal} from '@angular/core'; -import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes'; +import {$t} from '@primeng/themes'; import Aura from '@primeng/themes/aura'; import {AppState} from '../model/app-state.model'; +import {UrlHelperService} from '../../utilities/service/url-helper.service'; type ColorPalette = Record; @@ -15,10 +16,15 @@ interface Palette { providedIn: 'root', }) export class AppConfigService { + public static readonly DEFAULT_BACKGROUND_BLUR = 20; + public static readonly DEFAULT_SURFACE_ALPHA = 0.88; + public static readonly DEFAULT_PRIMARY_COLOR = 'indigo'; + private readonly STORAGE_KEY = 'appConfigState'; appState = signal({}); document = inject(DOCUMENT); platformId = inject(PLATFORM_ID); + private readonly urlHelper = inject(UrlHelperService); private initialized = false; readonly surfaces: Palette[] = [ @@ -162,17 +168,20 @@ export class AppConfigService { constructor() { const initialState = this.loadAppState(); - this.appState.set({...initialState}); + this.appState.set(initialState); this.document.documentElement.classList.add('p-dark'); if (isPlatformBrowser(this.platformId)) { - this.onPresetChange(); + this.setBackendImage(); + setTimeout(() => { + this.onPresetChange(); + this.initialized = true; + }, 0); } effect(() => { const state = this.appState(); if (!this.initialized || !state) { - this.initialized = true; return; } this.saveAppState(state); @@ -180,33 +189,87 @@ export class AppConfigService { }, {allowSignalWrites: true}); } + private setBackendImage(): void { + const backendUrl = this.urlHelper.getBackgroundImageUrl(Date.now()); + this.appState.update(state => ({ + ...state, + backgroundImage: backendUrl, + lastUpdated: Date.now() + })); + } + + refreshBackgroundImage(): void { + const timestamp = Date.now(); + const backendUrl = this.urlHelper.getBackgroundImageUrl(timestamp); + this.appState.update(state => ({ + ...state, + backgroundImage: backendUrl, + lastUpdated: timestamp + })); + } + private loadAppState(): AppState { + const defaultState: AppState = { + preset: 'Aura', + primary: AppConfigService.DEFAULT_PRIMARY_COLOR, + surface: 'neutral', + backgroundBlur: AppConfigService.DEFAULT_BACKGROUND_BLUR, + showBackground: true, + surfaceAlpha: AppConfigService.DEFAULT_SURFACE_ALPHA, + }; + if (isPlatformBrowser(this.platformId)) { const storedState = localStorage.getItem(this.STORAGE_KEY); if (storedState) { - return JSON.parse(storedState); + try { + const parsed = JSON.parse(storedState); + return { + preset: parsed.preset || defaultState.preset, + primary: parsed.primary || defaultState.primary, + surface: parsed.surface || defaultState.surface, + backgroundBlur: parsed.backgroundBlur ?? defaultState.backgroundBlur, + showBackground: parsed.showBackground ?? defaultState.showBackground, + surfaceAlpha: parsed.surfaceAlpha ?? defaultState.surfaceAlpha, + }; + } catch (error) { + return defaultState; + } } } - return { - preset: 'Aura', - primary: 'green', - surface: 'neutral', - }; + return defaultState; } private saveAppState(state: AppState): void { if (isPlatformBrowser(this.platformId)) { - localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state)); + const {backgroundImage, lastUpdated, ...stateToSave} = state; + localStorage.setItem(this.STORAGE_KEY, JSON.stringify(stateToSave)); } } private getSurfacePalette(surface: string): ColorPalette { - return this.surfaces.find(s => s.name === surface)?.palette ?? {}; + const palette = this.surfaces.find(s => s.name === surface)?.palette ?? {}; + const alpha = this.appState().surfaceAlpha ?? AppConfigService.DEFAULT_SURFACE_ALPHA; + const transparentPalette: ColorPalette = {}; + + // Text/content colors that should remain opaque (not transparent) + const opaqueKeys = ['0', '50', '100', '200', '300', '400']; + + Object.entries(palette).forEach(([key, hex]) => { + if (opaqueKeys.includes(key)) { + // Keep text colors opaque + transparentPalette[key] = hex; + } else { + // Apply transparency to background colors (500-950) + transparentPalette[key] = this.hexToRgba(hex, alpha); + } + }); + + return transparentPalette; } getPresetExt(): object { const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral'); - const primaryName = this.appState().primary ?? 'green'; + const primaryName = this.appState().primary ?? AppConfigService.DEFAULT_PRIMARY_COLOR; const presetPalette = (Aura.primitive ?? {}) as Record; const color = presetPalette[primaryName] ?? {}; @@ -248,8 +311,8 @@ export class AppConfigService { highlight: { background: 'color-mix(in srgb, {primary.400}, transparent 84%)', focusBackground: 'color-mix(in srgb, {primary.400}, transparent 76%)', - color: 'rgba(255,255,255,.87)', - focusColor: 'rgba(255,255,255,.87)' + color: 'rgba(255,255,255,.88)', + focusColor: 'rgba(255,255,255,.88)' } } } @@ -257,9 +320,30 @@ export class AppConfigService { }; } + private hexToRgba(hex: string, alpha: number = AppConfigService.DEFAULT_SURFACE_ALPHA): string { + const r = parseInt(hex.slice(1, 3), 16); + const g = parseInt(hex.slice(3, 5), 16); + const b = parseInt(hex.slice(5, 7), 16); + return `rgba(${r}, ${g}, ${b}, ${alpha})`; + } + onPresetChange(): void { const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral'); const preset = this.getPresetExt(); $t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({useDefaultOptions: true}); } + + updateBackgroundBlur(blur: number): void { + this.appState.update(state => ({ + ...state, + backgroundBlur: blur + })); + } + + updateSurfaceAlpha(alpha: number): void { + this.appState.update(state => ({ + ...state, + surfaceAlpha: alpha + })); + } } diff --git a/booklore-ui/src/app/layout/component/theme-configurator/background-upload.service.ts b/booklore-ui/src/app/layout/component/theme-configurator/background-upload.service.ts new file mode 100644 index 000000000..618060cd2 --- /dev/null +++ b/booklore-ui/src/app/layout/component/theme-configurator/background-upload.service.ts @@ -0,0 +1,32 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {Observable, map, tap} from 'rxjs'; +import {API_CONFIG} from '../../../config/api-config'; + +@Injectable({providedIn: 'root'}) +export class BackgroundUploadService { + private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/background`; + private readonly http = inject(HttpClient); + + uploadFile(file: File): Observable { + const formData = new FormData(); + formData.append('file', file); + return this.http.post<{ url: string }>(`${this.baseUrl}/upload`, formData).pipe( + tap(response => console.log('File upload response:', response)), + map(resp => resp?.url) + ); + } + + uploadUrl(url: string): Observable { + return this.http.post<{ url: string }>(`${this.baseUrl}/url`, {url}).pipe( + tap(response => console.log('URL upload response:', response)), + map(resp => resp?.url) + ); + } + + resetToDefault(): Observable { + return this.http.delete(this.baseUrl).pipe( + tap(() => console.log('Background reset to default')) + ); + } +} diff --git a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.html b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.html index 0ca7f3072..cd40e5be6 100644 --- a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.html +++ b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.html @@ -28,6 +28,67 @@ } +
+ Transparency: {{ (1 - surfaceAlphaValue).toFixed(2) }} + + +
+ + +
+ Background +
+
+
+ + + +
+ @if (backgroundVisible) { +
+ + + +
+ } +
+ @if (backgroundVisible) { +
+ + + + +
+ } +
diff --git a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.scss b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.scss index e69de29bb..6767b5627 100644 --- a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.scss +++ b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.scss @@ -0,0 +1,95 @@ +.config-panel-section { + margin-bottom: 1.5rem; + padding-bottom: 1rem; + border-bottom: 1px solid var(--surface-border); +} + +.config-panel-field { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin-bottom: 1rem; + + label { + font-weight: 500; + color: var(--text-color); + } + + input[type="text"], input[type="range"] { + padding: 0.5rem; + border: 1px solid var(--surface-border); + border-radius: var(--border-radius); + background: var(--surface-ground); + color: var(--text-color); + } + + input[type="range"] { + width: 100%; + } +} + +// Background section styles +.config-panel-colors { + .surface-alpha-control { + display: flex; + flex-direction: column; + margin-top: 0.75rem; + padding: 0.5rem 0; + + .config-panel-label { + margin-bottom: 0.5rem; + } + + .alpha-slider { + width: 100%; + } + } + + .background-center-wrapper { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + + .background-controls { + display: flex; + flex-direction: column; + width: 100%; + box-sizing: border-box; + } + + .background-control { + display: flex; + align-items: center; + padding-top: 0.5rem; + padding-bottom: 0.1rem; + + label { + min-width: 80px; + font-size: 0.85em; + font-weight: 500; + color: var(--text-secondary-color); + } + + .blur-slider { + flex: 1; + margin-left: 0.5rem; + } + } + + .background-actions-row { + display: flex; + flex-direction: row; + gap: 0.75rem; + margin-top: 0.75rem; + width: 100%; + box-sizing: border-box; + align-items: center; + justify-content: flex-end; + + .upload-bg-btn { + margin-left: 0; + } + } + } +} diff --git a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts index 236ea2def..fd7ebab0a 100644 --- a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts +++ b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts @@ -1,13 +1,19 @@ import {CommonModule} from '@angular/common'; import {Component, computed, effect, inject} from '@angular/core'; import {FormsModule} from '@angular/forms'; -import {$t} from '@primeng/themes'; import Aura from '@primeng/themes/aura'; import {ButtonModule} from 'primeng/button'; import {RadioButtonModule} from 'primeng/radiobutton'; import {ToggleSwitchModule} from 'primeng/toggleswitch'; +import {InputTextModule} from 'primeng/inputtext'; +import {SliderModule, SliderSlideEndEvent} from 'primeng/slider'; import {AppConfigService} from '../../../core/service/app-config.service'; import {FaviconService} from './favicon-service'; +import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {UploadDialogComponent} from './upload-dialog/upload-dialog.component'; +import {UrlHelperService} from '../../../utilities/service/url-helper.service'; +import {BackgroundUploadService} from './background-upload.service'; +import {debounceTime, Subject} from 'rxjs'; type ColorPalette = Record; @@ -20,6 +26,7 @@ interface Palette { selector: 'app-theme-configurator', standalone: true, templateUrl: './theme-configurator.component.html', + styleUrls: ['./theme-configurator.component.scss'], host: { class: 'config-panel hidden' }, @@ -28,12 +35,17 @@ interface Palette { FormsModule, ButtonModule, RadioButtonModule, - ToggleSwitchModule - ] + ToggleSwitchModule, + InputTextModule, + SliderModule + ], + providers: [DialogService] }) export class ThemeConfiguratorComponent { readonly configService = inject(AppConfigService); readonly faviconService = inject(FaviconService); + readonly urlHelper = inject(UrlHelperService); + private readonly backgroundUploadService = inject(BackgroundUploadService); readonly surfaces = this.configService.surfaces; @@ -41,7 +53,7 @@ export class ThemeConfiguratorComponent { readonly selectedSurfaceColor = computed(() => this.configService.appState().surface); readonly faviconColor = computed(() => { - const name = this.selectedPrimaryColor() ?? 'green'; + const name = this.selectedPrimaryColor() ?? AppConfigService.DEFAULT_PRIMARY_COLOR; const presetPalette = (Aura.primitive ?? {}) as Record; const colorPalette = presetPalette[name]; return colorPalette?.[500] ?? name; @@ -62,6 +74,64 @@ export class ThemeConfiguratorComponent { ); }); + get backgroundVisible(): boolean { + return this.configService.appState().showBackground ?? true; + } + + set backgroundVisible(value: boolean) { + this.configService.appState.update(state => ({ + ...state, + showBackground: value + })); + } + + get backgroundBlurValue(): number { + return this.configService.appState().backgroundBlur ?? AppConfigService.DEFAULT_BACKGROUND_BLUR; + } + + set backgroundBlurValue(value: number) { + this.configService.updateBackgroundBlur(value); + } + + get surfaceAlphaValue(): number { + return this.configService.appState().surfaceAlpha ?? AppConfigService.DEFAULT_SURFACE_ALPHA; + } + + set surfaceAlphaValue(value: number) { + this.configService.updateSurfaceAlpha(value); + } + + private readonly dialogService = inject(DialogService); + private dialogRef: DynamicDialogRef | undefined; + + private surfaceAlphaSubject = new Subject(); + + constructor() { + this.surfaceAlphaSubject.pipe( + debounceTime(100) + ).subscribe(value => { + this.configService.updateSurfaceAlpha(value); + }); + } + + openUploadDialog() { + this.dialogRef = this.dialogService.open(UploadDialogComponent, { + header: 'Upload or Paste Image URL', + width: '450px', + modal: true, + closable: true, + data: {} + }); + + this.dialogRef.onClose.subscribe((result) => { + if (result) { + if (result.success || result.uploaded || result.url || result.imageUrl) { + this.configService.refreshBackgroundImage(); + } + } + }); + } + updateColors(event: Event, type: 'primary' | 'surface', color: { name: string; palette?: ColorPalette }) { this.configService.appState.update((state) => ({ ...state, @@ -69,4 +139,26 @@ export class ThemeConfiguratorComponent { })); event.stopPropagation(); } + + updateBackgroundBlur(event: SliderSlideEndEvent): void { + this.configService.appState.update(state => ({ + ...state, + backgroundBlur: Number(event.value) + })); + } + + updateSurfaceAlpha(event: SliderSlideEndEvent): void { + this.surfaceAlphaSubject.next(Number(event.value)); + } + + resetBackground() { + this.backgroundUploadService.resetToDefault().subscribe({ + next: () => { + this.configService.refreshBackgroundImage(); + }, + error: (err) => { + console.error('Failed to reset background:', err); + } + }); + } } diff --git a/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.html b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.html new file mode 100644 index 000000000..89bd134f8 --- /dev/null +++ b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.html @@ -0,0 +1,59 @@ +
+
+
+ + + +
+ + Only JPG and PNG files are supported + @if (uploadFile) { + {{ uploadFile.name }} + } +
+ + + OR + + +
+ + + Only JPG and PNG URLs are supported +
+ + @if (uploadError) { + {{uploadError}} + } + + +
diff --git a/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.scss b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.scss new file mode 100644 index 000000000..01319b44c --- /dev/null +++ b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.scss @@ -0,0 +1,82 @@ +.upload-dialog-content { + display: flex; + flex-direction: column; + gap: 1.5rem; + padding: 1rem 0; + + .upload-section { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin-bottom: 1rem; + + .file-selector { + display: flex; + align-items: center; + gap: 1rem; + } + + .file-label { + font-weight: 500; + color: var(--text-color); + } + + .file-input { + padding: 0.75rem; + border: 1px solid var(--border-color); + border-radius: var(--p-border-radius); + background: var(--ground-background); + } + + .file-note { + color: var(--text-secondary-color); + font-size: 0.875rem; + margin-top: 0.25rem; + } + + .selected-file { + color: var(--text-secondary-color); + font-style: italic; + } + } + + .url-section { + display: flex; + flex-direction: column; + gap: 0.25rem; + + .url-label { + font-weight: 500; + color: var(--text-color); + margin-bottom: 0.5rem; + } + + .url-input { + width: 100%; + padding: 0.75rem; + } + + .url-note { + color: var(--text-secondary-color); + font-size: 0.875rem; + margin-top: 0.25rem; + } + } + + .or-text { + font-size: 0.9rem; + color: var(--text-color); + font-weight: 500; + } + + p-message { + margin-top: 1rem; + } + + .dialog-footer { + display: flex; + gap: 1rem; + justify-content: flex-end; + margin-top: 1rem; + } +} diff --git a/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.ts b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.ts new file mode 100644 index 000000000..ddd751daf --- /dev/null +++ b/booklore-ui/src/app/layout/component/theme-configurator/upload-dialog/upload-dialog.component.ts @@ -0,0 +1,72 @@ +import {Component, inject} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; +import {ButtonModule} from 'primeng/button'; +import {InputTextModule} from 'primeng/inputtext'; +import {DividerModule} from 'primeng/divider'; +import {MessageModule} from 'primeng/message'; +import {BackgroundUploadService} from '../background-upload.service'; +import {take} from 'rxjs'; + +@Component({ + selector: 'app-upload-dialog', + standalone: true, + templateUrl: './upload-dialog.component.html', + styleUrls: ['./upload-dialog.component.scss'], + imports: [ + CommonModule, + FormsModule, + ButtonModule, + InputTextModule, + DividerModule, + MessageModule + ] +}) +export class UploadDialogComponent { + private readonly dialogRef = inject(DynamicDialogRef); + private readonly backgroundUploadService = inject(BackgroundUploadService); + + uploadImageUrl = ''; + uploadFile: File | null = null; + uploadError = ''; + + onFileSelected(event: Event) { + const input = event.target as HTMLInputElement; + if (input.files && input.files.length > 0) { + this.uploadFile = input.files[0]; + this.uploadImageUrl = ''; + } + } + + submit() { + this.uploadError = ''; + let upload$; + if (this.uploadFile) { + upload$ = this.backgroundUploadService.uploadFile(this.uploadFile); + } else if (this.uploadImageUrl.trim()) { + upload$ = this.backgroundUploadService.uploadUrl(this.uploadImageUrl.trim()); + } else { + this.uploadError = 'Please select a file or paste a URL.'; + return; + } + + upload$.pipe(take(1)).subscribe({ + next: (imageUrl) => { + if (imageUrl) { + this.dialogRef.close({ imageUrl }); + } else { + this.uploadError = 'Failed to upload image.'; + } + }, + error: (err) => { + console.error('Upload failed:', err); + this.uploadError = 'Upload failed. Please try again.'; + } + }); + } + + cancel() { + this.dialogRef.close(); + } +} diff --git a/booklore-ui/src/app/stats-component/stats-component.scss b/booklore-ui/src/app/stats-component/stats-component.scss index 1d50a7d83..00d15eb15 100644 --- a/booklore-ui/src/app/stats-component/stats-component.scss +++ b/booklore-ui/src/app/stats-component/stats-component.scss @@ -7,7 +7,7 @@ } .header-card { - background: var(--surface-card, rgba(255, 255, 255, 0.05)); + background: var(--card-background); border-radius: 8px; padding: 25px; margin-bottom: 30px; @@ -196,10 +196,10 @@ color: var(--text-color, #ffffff); padding: 10px 16px; border-radius: 6px; - font-size: 0.9rem; cursor: pointer; transition: all 0.3s ease; display: flex; + font-weight: 500; align-items: center; gap: 8px; flex: 1; @@ -422,7 +422,7 @@ } .chart-section { - background: var(--surface-card, rgba(255, 255, 255, 0.05)); + background: var(--card-background); border-radius: 8px; padding: 15px; backdrop-filter: blur(10px); diff --git a/booklore-ui/src/app/utilities/service/url-helper.service.ts b/booklore-ui/src/app/utilities/service/url-helper.service.ts index 92bd7eb42..f5d4af105 100644 --- a/booklore-ui/src/app/utilities/service/url-helper.service.ts +++ b/booklore-ui/src/app/utilities/service/url-helper.service.ts @@ -40,4 +40,16 @@ export class UrlHelperService { const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`; return this.appendToken(url); } + + getBackgroundImageUrl(lastUpdated?: number): string { + let url = `${this.mediaBaseUrl}/background`; + if (lastUpdated) { + url += `?t=${lastUpdated}`; + } + const token = this.getToken(); + if (token) { + url += `${url.includes('?') ? '&' : '?'}token=${token}`; + } + return url; + } } diff --git a/booklore-ui/src/assets/layout/styles/layout/_topbar.scss b/booklore-ui/src/assets/layout/styles/layout/_topbar.scss index afac58f4c..910b33a48 100644 --- a/booklore-ui/src/assets/layout/styles/layout/_topbar.scss +++ b/booklore-ui/src/assets/layout/styles/layout/_topbar.scss @@ -114,14 +114,15 @@ } .config-panel-colors { - > div { + // Only apply flex to color picker rows, not background-center-wrapper + > div:not(.background-center-wrapper) { justify-content: flex-start; padding-top: .5rem; display: flex; gap: .5rem; flex-wrap: wrap; - button { + button:not([pbutton]):not(.p-button) { border: none; width: 1.25rem; height: 1.25rem;