Support configurable file/folder naming pattern for uploaded files
This commit is contained in:
committed by
Aditya Chandel
parent
c1d8e84742
commit
767fa835be
@@ -0,0 +1,18 @@
|
|||||||
|
package com.adityachandel.booklore.config;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class BeanConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WebSocketMessageBrokerStats webSocketMessageBrokerStats;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
webSocketMessageBrokerStats.setLoggingPeriod(30 * 24 * 60 * 60 * 1000L); // 30 days
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,16 @@ import io.jsonwebtoken.*;
|
|||||||
import io.jsonwebtoken.security.Keys;
|
import io.jsonwebtoken.security.Keys;
|
||||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
import com.adityachandel.booklore.service.JwtSecretService;
|
import com.adityachandel.booklore.service.JwtSecretService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKey;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
@Component
|
@Component
|
||||||
public class JwtUtils {
|
public class JwtUtils {
|
||||||
|
|
||||||
@@ -52,9 +57,9 @@ public class JwtUtils {
|
|||||||
extractClaims(token);
|
extractClaims(token);
|
||||||
return true;
|
return true;
|
||||||
} catch (ExpiredJwtException e) {
|
} catch (ExpiredJwtException e) {
|
||||||
System.out.println("Token expired: " + e.getMessage());
|
log.debug("Token expired: {}", e.getMessage());
|
||||||
} catch (JwtException e) {
|
} catch (JwtException e) {
|
||||||
System.out.println("Invalid token: " + e.getMessage());
|
log.debug("Invalid token: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -11,6 +11,8 @@ import org.springframework.web.bind.annotation.RequestParam;
|
|||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/files")
|
@RequestMapping("/api/v1/files")
|
||||||
@@ -20,7 +22,7 @@ public class FileUploadController {
|
|||||||
|
|
||||||
@PreAuthorize("@securityUtil.canUpload()")
|
@PreAuthorize("@securityUtil.canUpload()")
|
||||||
@PostMapping(value = "/upload", consumes = "multipart/form-data")
|
@PostMapping(value = "/upload", consumes = "multipart/form-data")
|
||||||
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) {
|
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
|
||||||
if (file.isEmpty()) {
|
if (file.isEmpty()) {
|
||||||
throw new IllegalArgumentException("Uploaded file is missing.");
|
throw new IllegalArgumentException("Uploaded file is missing.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.adityachandel.booklore.model;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class UploadedFileMetadata {
|
||||||
|
private String title;
|
||||||
|
private Set<String> authors;
|
||||||
|
}
|
||||||
+3
-10
@@ -11,16 +11,9 @@ import lombok.NoArgsConstructor;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class AppSettings {
|
public class AppSettings {
|
||||||
private CoverSettings coverSettings;
|
private String coverResolution;
|
||||||
private MetadataRefreshOptions metadataRefreshOptions;
|
private MetadataRefreshOptions metadataRefreshOptions;
|
||||||
private boolean autoBookSearch;
|
private boolean autoBookSearch;
|
||||||
private boolean similarBookRecommendation;
|
private boolean similarBookRecommendation;
|
||||||
|
private String uploadPattern;
|
||||||
@Data
|
}
|
||||||
@Builder
|
|
||||||
@AllArgsConstructor
|
|
||||||
@NoArgsConstructor
|
|
||||||
public static class CoverSettings {
|
|
||||||
private String resolution;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+21
-33
@@ -26,6 +26,7 @@ public class AppSettingService {
|
|||||||
public static final String AUTO_BOOK_SEARCH = "auto_book_search";
|
public static final String AUTO_BOOK_SEARCH = "auto_book_search";
|
||||||
public static final String COVER_IMAGE_RESOLUTION = "cover_image_resolution";
|
public static final String COVER_IMAGE_RESOLUTION = "cover_image_resolution";
|
||||||
public static final String SIMILAR_BOOK_RECOMMENDATION = "similar_book_recommendation";
|
public static final String SIMILAR_BOOK_RECOMMENDATION = "similar_book_recommendation";
|
||||||
|
public static final String UPLOAD_FILE_PATTERN = "upload_file_pattern";
|
||||||
|
|
||||||
private volatile AppSettings appSettings;
|
private volatile AppSettings appSettings;
|
||||||
private final ReentrantLock lock = new ReentrantLock();
|
private final ReentrantLock lock = new ReentrantLock();
|
||||||
@@ -44,21 +45,19 @@ public class AppSettingService {
|
|||||||
return appSettings;
|
return appSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isSimilarBookRecommendationEnabled() {
|
|
||||||
return getAppSettings().isSimilarBookRecommendation();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void updateSetting(String name, Object val) throws JsonProcessingException {
|
public void updateSetting(String name, Object val) throws JsonProcessingException {
|
||||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||||
if (setting == null) {
|
if (setting == null) {
|
||||||
throw new IllegalArgumentException("Setting not found for name: " + name);
|
throw new IllegalArgumentException("Setting not found for name: " + name);
|
||||||
}
|
}
|
||||||
if (name.equals(QUICK_BOOK_MATCH)) {
|
|
||||||
|
if (QUICK_BOOK_MATCH.equals(name)) {
|
||||||
setting.setVal(objectMapper.writeValueAsString(val));
|
setting.setVal(objectMapper.writeValueAsString(val));
|
||||||
} else {
|
} else {
|
||||||
setting.setVal(val.toString());
|
setting.setVal(val.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
appSettingsRepository.save(setting);
|
appSettingsRepository.save(setting);
|
||||||
refreshCache();
|
refreshCache();
|
||||||
}
|
}
|
||||||
@@ -75,7 +74,6 @@ public class AppSettingService {
|
|||||||
private AppSettings buildAppSettings() {
|
private AppSettings buildAppSettings() {
|
||||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||||
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||||
|
|
||||||
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
||||||
|
|
||||||
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
||||||
@@ -83,36 +81,26 @@ public class AppSettingService {
|
|||||||
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
||||||
builder.metadataRefreshOptions(options);
|
builder.metadataRefreshOptions(options);
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
throw new RuntimeException("Failed to parse setting 'quick_book_match'", e);
|
throw new RuntimeException("Failed to parse setting: " + QUICK_BOOK_MATCH, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settingsMap.containsKey(COVER_IMAGE_RESOLUTION)) {
|
builder.coverResolution(getOrCreateSetting(COVER_IMAGE_RESOLUTION, "250x350"));
|
||||||
builder.coverSettings(AppSettings.CoverSettings.builder()
|
builder.autoBookSearch(Boolean.parseBoolean(getOrCreateSetting(AUTO_BOOK_SEARCH, "true")));
|
||||||
.resolution(settingsMap.get(COVER_IMAGE_RESOLUTION))
|
builder.uploadPattern(getOrCreateSetting(UPLOAD_FILE_PATTERN, ""));
|
||||||
.build());
|
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||||
}
|
|
||||||
|
|
||||||
if (settingsMap.containsKey(AUTO_BOOK_SEARCH)) {
|
|
||||||
builder.autoBookSearch(Boolean.parseBoolean(settingsMap.get(AUTO_BOOK_SEARCH)));
|
|
||||||
} else {
|
|
||||||
AppSettingEntity setting = new AppSettingEntity();
|
|
||||||
setting.setName(AUTO_BOOK_SEARCH);
|
|
||||||
setting.setVal("true");
|
|
||||||
appSettingsRepository.save(setting);
|
|
||||||
builder.autoBookSearch(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settingsMap.containsKey(SIMILAR_BOOK_RECOMMENDATION)) {
|
|
||||||
builder.similarBookRecommendation(Boolean.parseBoolean(settingsMap.get(SIMILAR_BOOK_RECOMMENDATION)));
|
|
||||||
} else {
|
|
||||||
AppSettingEntity setting = new AppSettingEntity();
|
|
||||||
setting.setName(SIMILAR_BOOK_RECOMMENDATION);
|
|
||||||
setting.setVal("true");
|
|
||||||
appSettingsRepository.save(setting);
|
|
||||||
builder.similarBookRecommendation(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String getOrCreateSetting(String name, String defaultValue) {
|
||||||
|
AppSettingEntity existing = appSettingsRepository.findByName(name);
|
||||||
|
if (existing != null) {
|
||||||
|
return existing.getVal();
|
||||||
|
}
|
||||||
|
AppSettingEntity newSetting = new AppSettingEntity();
|
||||||
|
newSetting.setName(name);
|
||||||
|
newSetting.setVal(defaultValue);
|
||||||
|
appSettingsRepository.save(newSetting);
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||||
|
|
||||||
|
public interface BookFileMetadataExtractor {
|
||||||
|
|
||||||
|
UploadedFileMetadata extractMetadata(String filePath);
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||||
|
import com.adityachandel.booklore.util.FileUtils;
|
||||||
|
import io.documentnode.epub4j.domain.Author;
|
||||||
|
import io.documentnode.epub4j.domain.Book;
|
||||||
|
import io.documentnode.epub4j.epub.EpubReader;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.pdfbox.Loader;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class EpubMetadataExtractor implements BookFileMetadataExtractor {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||||
|
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||||
|
|
||||||
|
try (FileInputStream fis = new FileInputStream(filePath)) {
|
||||||
|
Book epubBook = new EpubReader().readEpub(fis);
|
||||||
|
|
||||||
|
String title = epubBook.getTitle();
|
||||||
|
if (title != null && !title.isBlank()) {
|
||||||
|
metadata.setTitle(title);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Author> epubAuthors = epubBook.getMetadata().getAuthors();
|
||||||
|
if (!epubAuthors.isEmpty()) {
|
||||||
|
Set<String> authors = epubAuthors.stream()
|
||||||
|
.map(author -> author.getFirstname() + " " + author.getLastname())
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(s -> !s.isBlank())
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
metadata.setAuthors(authors);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to extract metadata from EPUB file {}: {}", filePath, e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Unexpected error while reading EPUB file {}: {}", filePath, e.getMessage());
|
||||||
|
}
|
||||||
|
return metadata;
|
||||||
|
}
|
||||||
|
}
|
||||||
+75
-26
@@ -1,8 +1,10 @@
|
|||||||
package com.adityachandel.booklore.service;
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
import com.adityachandel.booklore.exception.ApiError;
|
import com.adityachandel.booklore.exception.ApiError;
|
||||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||||
import com.adityachandel.booklore.model.dto.Book;
|
import com.adityachandel.booklore.model.dto.Book;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||||
|
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||||
@@ -18,16 +20,18 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class FileUploadService {
|
public class FileUploadService {
|
||||||
|
|
||||||
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
|
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;
|
||||||
private static final String PDF_MIME_TYPE = "application/pdf";
|
private static final String PDF_MIME_TYPE = "application/pdf";
|
||||||
private static final String EPUB_MIME_TYPE = "application/epub+zip";
|
private static final String EPUB_MIME_TYPE = "application/epub+zip";
|
||||||
|
|
||||||
@@ -35,11 +39,16 @@ public class FileUploadService {
|
|||||||
private final PdfProcessor pdfProcessor;
|
private final PdfProcessor pdfProcessor;
|
||||||
private final EpubProcessor epubProcessor;
|
private final EpubProcessor epubProcessor;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
|
private final AppSettingService appSettingService;
|
||||||
|
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||||
|
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||||
|
|
||||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) {
|
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
|
||||||
|
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||||
validateFile(file);
|
validateFile(file);
|
||||||
|
|
||||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
|
||||||
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
|
|
||||||
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
|
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
|
||||||
.stream()
|
.stream()
|
||||||
@@ -47,29 +56,53 @@ public class FileUploadService {
|
|||||||
.findFirst()
|
.findFirst()
|
||||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||||
|
|
||||||
Path storagePath = Paths.get(libraryPathEntity.getPath(), Objects.requireNonNull(file.getOriginalFilename()));
|
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
|
||||||
File storageFile = storagePath.toFile();
|
UploadedFileMetadata metadata;
|
||||||
|
|
||||||
if (storageFile.exists()) {
|
|
||||||
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
file.transferTo(storagePath); // storagePath here is required for windows, otherwise it will be resoled relative to Tomcat FS
|
file.transferTo(tempPath);
|
||||||
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
|
|
||||||
Book book = processFile(file, libraryEntity, libraryPathEntity, storageFile);
|
String fileType = Objects.requireNonNull(file.getContentType());
|
||||||
|
|
||||||
|
if (fileType.equalsIgnoreCase(PDF_MIME_TYPE)) {
|
||||||
|
metadata = pdfMetadataExtractor.extractMetadata(tempPath.toString());
|
||||||
|
} else if (fileType.equalsIgnoreCase(EPUB_MIME_TYPE)) {
|
||||||
|
metadata = epubMetadataExtractor.extractMetadata(tempPath.toString());
|
||||||
|
} else {
|
||||||
|
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim();
|
||||||
|
String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : "";
|
||||||
|
String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename());
|
||||||
|
|
||||||
|
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
|
||||||
|
File finalFile = finalPath.toFile();
|
||||||
|
|
||||||
|
if (finalFile.exists()) {
|
||||||
|
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.createDirectories(finalPath.getParent());
|
||||||
|
Files.move(tempPath, finalPath);
|
||||||
|
|
||||||
|
log.info("File uploaded to final location: {}", finalPath);
|
||||||
|
|
||||||
|
Book book = processFile(file, libraryEntity, libraryPathEntity, finalFile);
|
||||||
notificationService.sendMessage(Topic.BOOK_ADD, book);
|
notificationService.sendMessage(Topic.BOOK_ADD, book);
|
||||||
log.info("Book processed successfully: {}", book.getMetadata().getTitle());
|
log.info("Book processed successfully: {}", book.getMetadata().getTitle());
|
||||||
return book;
|
return book;
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Error saving file", e);
|
|
||||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(tempPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateFile(MultipartFile file) {
|
private void validateFile(MultipartFile file) {
|
||||||
String fileType = file.getContentType();
|
String fileType = file.getContentType();
|
||||||
if ((!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType))) {
|
if (!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType)) {
|
||||||
throw ApiError.INVALID_FILE_FORMAT.createException();
|
throw ApiError.INVALID_FILE_FORMAT.createException();
|
||||||
}
|
}
|
||||||
if (file.getSize() > MAX_FILE_SIZE) {
|
if (file.getSize() > MAX_FILE_SIZE) {
|
||||||
@@ -93,18 +126,34 @@ public class FileUploadService {
|
|||||||
.fileName(file.getOriginalFilename())
|
.fileName(file.getOriginalFilename())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
switch (fileType) {
|
return switch (fileType) {
|
||||||
case PDF -> {
|
case PDF -> pdfProcessor.processFile(libraryFile, false);
|
||||||
return pdfProcessor.processFile(libraryFile, false);
|
case EPUB -> epubProcessor.processFile(libraryFile, false);
|
||||||
}
|
};
|
||||||
case EPUB -> {
|
}
|
||||||
return epubProcessor.processFile(libraryFile, false);
|
|
||||||
}
|
private String resolveUploadPath(String pattern, String title, String authors, String filename) {
|
||||||
default -> {
|
String path = pattern;
|
||||||
log.warn("Unsupported file type for processing: {}", fileType);
|
boolean hasTitle = !title.isEmpty();
|
||||||
throw ApiError.INVALID_FILE_FORMAT.createException();
|
boolean hasAuthors = !authors.isEmpty();
|
||||||
}
|
|
||||||
|
if (hasTitle) {
|
||||||
|
path = path.replace("{title}", sanitize(title));
|
||||||
}
|
}
|
||||||
|
if (hasAuthors) {
|
||||||
|
path = path.replace("{authors}", sanitize(authors));
|
||||||
|
}
|
||||||
|
if (!hasTitle && pattern.contains("{title}")) {
|
||||||
|
return filename;
|
||||||
|
}
|
||||||
|
if (!hasAuthors && pattern.contains("{authors}")) {
|
||||||
|
return hasTitle ? path.replace("{authors}", "").replaceAll("//+", "/") + "/" + filename : filename;
|
||||||
|
}
|
||||||
|
return path + "/" + filename;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String sanitize(String value) {
|
||||||
|
return value.replaceAll("[\\/:*?\"<>|]", "").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookFileType determineFileType(String fileType) {
|
private BookFileType determineFileType(String fileType) {
|
||||||
|
|||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.pdfbox.Loader;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class PdfMetadataExtractor implements BookFileMetadataExtractor {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||||
|
File file = new File(filePath);
|
||||||
|
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||||
|
try (PDDocument pdf = Loader.loadPDF(file)) {
|
||||||
|
PDDocumentInformation info = pdf.getDocumentInformation();
|
||||||
|
if (info != null) {
|
||||||
|
if (info.getTitle() != null && !info.getTitle().isBlank()) {
|
||||||
|
metadata.setTitle(info.getTitle());
|
||||||
|
}
|
||||||
|
if (info.getAuthor() != null && !info.getAuthor().isBlank()) {
|
||||||
|
metadata.setAuthors(Set.of(info.getAuthor().split(",")));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.warn("No document information found in: {}", filePath);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Error loading PDF file: {}, error: {}", filePath, e.getMessage());
|
||||||
|
}
|
||||||
|
return metadata;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -34,7 +34,7 @@ public class FileProcessingUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean saveCoverImage(BufferedImage coverImage, long bookId) throws IOException {
|
public boolean saveCoverImage(BufferedImage coverImage, long bookId) throws IOException {
|
||||||
String resolution = appSettingService.getAppSettings().getCoverSettings().getResolution();
|
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||||
String[] split = resolution.split("x");
|
String[] split = resolution.split("x");
|
||||||
int x = Integer.parseInt(split[0]);
|
int x = Integer.parseInt(split[0]);
|
||||||
int y = Integer.parseInt(split[1]);
|
int y = Integer.parseInt(split[1]);
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||||
|
|
||||||
export interface CoverSettings {
|
|
||||||
resolution: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AppSettings {
|
export interface AppSettings {
|
||||||
autoBookSearch: boolean;
|
autoBookSearch: boolean;
|
||||||
similarBookRecommendation: boolean;
|
similarBookRecommendation: boolean;
|
||||||
metadataRefreshOptions: MetadataRefreshOptions;
|
metadataRefreshOptions: MetadataRefreshOptions;
|
||||||
coverSettings?: CoverSettings
|
coverResolution: string;
|
||||||
|
uploadPattern: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<div class="flex flex-col space-y-6 p-4 m-4 custom-border">
|
||||||
|
<div>
|
||||||
|
<h2 class="mb-3 text-lg">Enter Custom File Naming Pattern:</h2>
|
||||||
|
<div class="flex gap-4 items-center">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
[(ngModel)]="uploadPattern"
|
||||||
|
class="p-inputtext w-[500px]"
|
||||||
|
placeholder="e.g., {title} - {authors}"
|
||||||
|
(input)="onPatternChange(uploadPattern)"
|
||||||
|
/>
|
||||||
|
<p-button label="Save" icon="pi pi-check" (onClick)="savePattern()" [disabled]="!!errorMessage"></p-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-2">Preview:</h3>
|
||||||
|
<p class="text-lg text-green-500">{{ generatePreview() }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="text-gray-400">
|
||||||
|
<h3 class="mb-1 font-bold">Example Patterns:</h3>
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class=" table-auto">
|
||||||
|
<colgroup>
|
||||||
|
<col style="width: auto;"/>
|
||||||
|
<col style="width: 20px;"/>
|
||||||
|
<col/>
|
||||||
|
</colgroup>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td class="pr-2 break-words text-left">{title} - {authors}/filename.pdf</td>
|
||||||
|
<td class="text-gray-300 text-center">→</td>
|
||||||
|
<td class="pl-2 break-words text-left">/The Book Thief - Markus Zusak/filename.pdf</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pr-2 break-words text-left">{title}/{authors}/filename.pdf</td>
|
||||||
|
<td class="text-gray-300 text-center">→</td>
|
||||||
|
<td class="pl-2 break-words text-left">/The Book Thief/Markus Zusak/filename.pdf</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pr-2 break-words text-left">{title} ({authors})/filename.pdf</td>
|
||||||
|
<td class="text-gray-300 text-center">→</td>
|
||||||
|
<td class="pl-2 break-words text-left">/The Book Thief (Markus Zusak)/filename.pdf</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pr-2 break-words text-left">{title}/filename.pdf</td>
|
||||||
|
<td class="text-gray-300 text-center">→</td>
|
||||||
|
<td class="pl-2 break-words text-left">/The Book Thief/filename.pdf</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="pr-2 break-words text-left">EMPTY</td>
|
||||||
|
<td class="text-gray-300 text-center">→</td>
|
||||||
|
<td class="pl-2 break-words text-left">/filename.pdf</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="text text-gray-400">
|
||||||
|
<strong>Note:</strong>
|
||||||
|
<ul class="list-disc pl-6">
|
||||||
|
<li>Only the placeholders {title} and {authors} are supported. These values will be extracted from the metadata of the uploaded PDF or EPUB file.</li>
|
||||||
|
<li>Multiple authors will be joined using commas.</li>
|
||||||
|
<li>If <code>{bookname}</code> is used but missing, the path defaults to <code>/filename.pdf</code>.</li>
|
||||||
|
<li>If <code>{authors}</code> is used but missing, it falls back to <code>{bookname}/filename.pdf</code> if the title exists, otherwise <code>/filename.pdf</code>.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.custom-border {
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: var(--card-border);
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import {Component, inject, OnInit} from '@angular/core';
|
||||||
|
import {FormsModule} from '@angular/forms';
|
||||||
|
import {Button} from 'primeng/button';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {AppSettingsService} from '../core/service/app-settings.service';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {AppSettings} from '../core/model/app-settings.model';
|
||||||
|
import {filter, take} from 'rxjs/operators';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-file-upload-pattern',
|
||||||
|
templateUrl: './file-upload-pattern.component.html',
|
||||||
|
standalone: true,
|
||||||
|
imports: [FormsModule, Button],
|
||||||
|
styleUrls: ['./file-upload-pattern.component.scss']
|
||||||
|
})
|
||||||
|
export class FileUploadPatternComponent implements OnInit {
|
||||||
|
title: string = 'The Book Thief';
|
||||||
|
authors: string = 'Markus Zusak';
|
||||||
|
uploadPattern: string = '';
|
||||||
|
errorMessage: string = '';
|
||||||
|
|
||||||
|
private appSettingsService = inject(AppSettingsService);
|
||||||
|
private messageService = inject(MessageService);
|
||||||
|
|
||||||
|
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.appSettings$.pipe(
|
||||||
|
filter(settings => settings != null),
|
||||||
|
take(1)
|
||||||
|
).subscribe(settings => {
|
||||||
|
this.uploadPattern = settings?.uploadPattern || '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
generatePreview(): string {
|
||||||
|
let path = this.uploadPattern
|
||||||
|
.replace('{title}', this.title)
|
||||||
|
.replace('{authors}', this.authors)
|
||||||
|
.replace(/\/+$/, '')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
return path ? `/${path}/filename.pdf` : '/filename.pdf';
|
||||||
|
}
|
||||||
|
|
||||||
|
validatePattern(pattern: string): void {
|
||||||
|
const isValid = /^[\w\s\-{}\/().]*$/.test(pattern);
|
||||||
|
this.errorMessage = isValid ? '' : 'Pattern contains invalid characters.';
|
||||||
|
}
|
||||||
|
|
||||||
|
onPatternChange(pattern: string): void {
|
||||||
|
this.uploadPattern = pattern;
|
||||||
|
this.validatePattern(pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
savePattern(): void {
|
||||||
|
this.saveSetting('upload_file_pattern', this.uploadPattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
private saveSetting(key: string, value: unknown): void {
|
||||||
|
this.appSettingsService.saveSettings([{key, newValue: value}]).subscribe({
|
||||||
|
next: () => this.showMessage('success', 'Settings Saved', 'The settings were successfully saved!'),
|
||||||
|
error: () => this.showMessage('error', 'Error', 'There was an error saving the settings.')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
|
||||||
|
this.messageService.add({severity, summary, detail});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,6 +71,18 @@
|
|||||||
|
|
||||||
<p-divider></p-divider>
|
<p-divider></p-divider>
|
||||||
|
|
||||||
|
<p class="text-xl pb-2 pt-8">
|
||||||
|
Uploaded Files Pattern
|
||||||
|
<i class="pi pi-info-circle text-sky-600"
|
||||||
|
pTooltip="Define a naming pattern for future uploads using available metadata. Existing files will remain unchanged."
|
||||||
|
tooltipPosition="right"
|
||||||
|
style="cursor: pointer;">
|
||||||
|
</i>
|
||||||
|
</p>
|
||||||
|
<app-file-upload-pattern></app-file-upload-pattern>
|
||||||
|
|
||||||
|
<p-divider></p-divider>
|
||||||
|
|
||||||
<p class="text-xl pb-4 pt-8">
|
<p class="text-xl pb-4 pt-8">
|
||||||
Quick Book Match Preferences
|
Quick Book Match Preferences
|
||||||
<i class="pi pi-info-circle text-sky-600"
|
<i class="pi pi-info-circle text-sky-600"
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {AppSettings} from '../../core/model/app-settings.model';
|
|||||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||||
import {MetadataAdvancedFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component';
|
import {MetadataAdvancedFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component';
|
||||||
import {filter, take} from 'rxjs/operators';
|
import {filter, take} from 'rxjs/operators';
|
||||||
|
import {FileUploadPatternComponent} from '../../file-upload-pattern/file-upload-pattern.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-global-preferences',
|
selector: 'app-global-preferences',
|
||||||
@@ -28,7 +29,8 @@ import {filter, take} from 'rxjs/operators';
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
ToggleSwitch,
|
ToggleSwitch,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
MetadataAdvancedFetchOptionsComponent
|
MetadataAdvancedFetchOptionsComponent,
|
||||||
|
FileUploadPatternComponent
|
||||||
],
|
],
|
||||||
templateUrl: './global-preferences.component.html',
|
templateUrl: './global-preferences.component.html',
|
||||||
styleUrl: './global-preferences.component.scss'
|
styleUrl: './global-preferences.component.scss'
|
||||||
@@ -58,8 +60,8 @@ export class GlobalPreferencesComponent implements OnInit {
|
|||||||
filter(settings => settings != null),
|
filter(settings => settings != null),
|
||||||
take(1)
|
take(1)
|
||||||
).subscribe(settings => {
|
).subscribe(settings => {
|
||||||
if (settings.coverSettings) {
|
if (settings?.coverResolution) {
|
||||||
this.selectedResolution = settings.coverSettings.resolution;
|
this.selectedResolution = settings.coverResolution;
|
||||||
}
|
}
|
||||||
if (settings.metadataRefreshOptions) {
|
if (settings.metadataRefreshOptions) {
|
||||||
this.currentMetadataOptions = settings.metadataRefreshOptions;
|
this.currentMetadataOptions = settings.metadataRefreshOptions;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
@use "sass:meta";
|
@use "sass:meta";
|
||||||
@import "../node_modules/primeicons/primeicons.css";
|
@import "../node_modules/primeicons/primeicons.css";
|
||||||
|
|
||||||
@include meta.load-css("assets/layout/styles/global.scss");
|
@include meta.load-css("assets/layout/styles/global.scss");
|
||||||
|
|
||||||
@tailwind base;
|
@tailwind base;
|
||||||
@@ -10,3 +11,7 @@ html {
|
|||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
|
||||||
Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.p-toast {
|
||||||
|
top: 4rem !important;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user