Support configurable background image and transparency (#1126)

This commit is contained in:
Aditya Chandel
2025-09-09 22:18:52 -06:00
committed by GitHub
parent d8be663a4d
commit 1008a9476b
25 changed files with 1159 additions and 147 deletions
@@ -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<UploadResponse> 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<UploadResponse> 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<Void> resetToDefault() {
try {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
backgroundUploadService.resetToDefault(authenticatedUser.getId());
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.internalServerError().build();
}
}
}
@@ -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<Resource> 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();
}
}
}
@@ -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;
}
@@ -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;
}
@@ -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";
}
}
@@ -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<Resource> 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<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
@@ -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<Book> 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);
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 626 KiB