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 com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.service.JwtSecretService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@@ -52,9 +57,9 @@ public class JwtUtils {
|
||||
extractClaims(token);
|
||||
return true;
|
||||
} catch (ExpiredJwtException e) {
|
||||
System.out.println("Token expired: " + e.getMessage());
|
||||
log.debug("Token expired: {}", e.getMessage());
|
||||
} catch (JwtException e) {
|
||||
System.out.println("Invalid token: " + e.getMessage());
|
||||
log.debug("Invalid token: {}", e.getMessage());
|
||||
}
|
||||
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.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/files")
|
||||
@@ -20,7 +22,7 @@ public class FileUploadController {
|
||||
|
||||
@PreAuthorize("@securityUtil.canUpload()")
|
||||
@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()) {
|
||||
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
|
||||
@NoArgsConstructor
|
||||
public class AppSettings {
|
||||
private CoverSettings coverSettings;
|
||||
private String coverResolution;
|
||||
private MetadataRefreshOptions metadataRefreshOptions;
|
||||
private boolean autoBookSearch;
|
||||
private boolean similarBookRecommendation;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class CoverSettings {
|
||||
private String resolution;
|
||||
}
|
||||
}
|
||||
private String uploadPattern;
|
||||
}
|
||||
+21
-33
@@ -26,6 +26,7 @@ public class AppSettingService {
|
||||
public static final String AUTO_BOOK_SEARCH = "auto_book_search";
|
||||
public static final String COVER_IMAGE_RESOLUTION = "cover_image_resolution";
|
||||
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 final ReentrantLock lock = new ReentrantLock();
|
||||
@@ -44,21 +45,19 @@ public class AppSettingService {
|
||||
return appSettings;
|
||||
}
|
||||
|
||||
public boolean isSimilarBookRecommendationEnabled() {
|
||||
return getAppSettings().isSimilarBookRecommendation();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateSetting(String name, Object val) throws JsonProcessingException {
|
||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||
if (setting == null) {
|
||||
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));
|
||||
} else {
|
||||
setting.setVal(val.toString());
|
||||
}
|
||||
|
||||
appSettingsRepository.save(setting);
|
||||
refreshCache();
|
||||
}
|
||||
@@ -75,7 +74,6 @@ public class AppSettingService {
|
||||
private AppSettings buildAppSettings() {
|
||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||
|
||||
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
||||
|
||||
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
||||
@@ -83,36 +81,26 @@ public class AppSettingService {
|
||||
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
||||
builder.metadataRefreshOptions(options);
|
||||
} 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.coverSettings(AppSettings.CoverSettings.builder()
|
||||
.resolution(settingsMap.get(COVER_IMAGE_RESOLUTION))
|
||||
.build());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
builder.coverResolution(getOrCreateSetting(COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(getOrCreateSetting(AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(getOrCreateSetting(UPLOAD_FILE_PATTERN, ""));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
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;
|
||||
|
||||
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.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
@@ -18,16 +20,18 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@Slf4j
|
||||
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 EPUB_MIME_TYPE = "application/epub+zip";
|
||||
|
||||
@@ -35,11 +39,16 @@ public class FileUploadService {
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
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);
|
||||
|
||||
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()
|
||||
.stream()
|
||||
@@ -47,29 +56,53 @@ public class FileUploadService {
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||
|
||||
Path storagePath = Paths.get(libraryPathEntity.getPath(), Objects.requireNonNull(file.getOriginalFilename()));
|
||||
File storageFile = storagePath.toFile();
|
||||
|
||||
if (storageFile.exists()) {
|
||||
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
||||
}
|
||||
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
|
||||
UploadedFileMetadata metadata;
|
||||
|
||||
try {
|
||||
file.transferTo(storagePath); // storagePath here is required for windows, otherwise it will be resoled relative to Tomcat FS
|
||||
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
|
||||
Book book = processFile(file, libraryEntity, libraryPathEntity, storageFile);
|
||||
file.transferTo(tempPath);
|
||||
|
||||
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);
|
||||
log.info("Book processed successfully: {}", book.getMetadata().getTitle());
|
||||
return book;
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Error saving file", e);
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
} finally {
|
||||
Files.deleteIfExists(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file) {
|
||||
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();
|
||||
}
|
||||
if (file.getSize() > MAX_FILE_SIZE) {
|
||||
@@ -93,18 +126,34 @@ public class FileUploadService {
|
||||
.fileName(file.getOriginalFilename())
|
||||
.build();
|
||||
|
||||
switch (fileType) {
|
||||
case PDF -> {
|
||||
return pdfProcessor.processFile(libraryFile, false);
|
||||
}
|
||||
case EPUB -> {
|
||||
return epubProcessor.processFile(libraryFile, false);
|
||||
}
|
||||
default -> {
|
||||
log.warn("Unsupported file type for processing: {}", fileType);
|
||||
throw ApiError.INVALID_FILE_FORMAT.createException();
|
||||
}
|
||||
return switch (fileType) {
|
||||
case PDF -> pdfProcessor.processFile(libraryFile, false);
|
||||
case EPUB -> epubProcessor.processFile(libraryFile, false);
|
||||
};
|
||||
}
|
||||
|
||||
private String resolveUploadPath(String pattern, String title, String authors, String filename) {
|
||||
String path = pattern;
|
||||
boolean hasTitle = !title.isEmpty();
|
||||
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) {
|
||||
|
||||
+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 {
|
||||
String resolution = appSettingService.getAppSettings().getCoverSettings().getResolution();
|
||||
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
Reference in New Issue
Block a user