diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 5ba79c346..f43bbd6e0 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -2,9 +2,11 @@ name-template: 'v$NEXT_PATCH_VERSION 🌟' tag-template: 'v$NEXT_PATCH_VERSION' categories: - - title: '🚀 Features' + - title: '🚀 New Features' labels: - 'feature' + - title: '✨ Enhancements' + labels: - 'enhancement' - title: '🐛 Bug Fixes' labels: diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 4ed8bfed8..4d7c4d4d0 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -87,4 +87,6 @@ hibernate { test { useJUnitPlatform() -} \ No newline at end of file + jvmArgs("-XX:+EnableDynamicAgentLoading") +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java new file mode 100644 index 000000000..a59f5eda3 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java @@ -0,0 +1,24 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.request.FileMoveRequest; +import com.adityachandel.booklore.service.file.FileMoveService; +import lombok.AllArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@AllArgsConstructor +@RestController +@RequestMapping("/api/v1/files") +public class FileMoveController { + + private final FileMoveService fileMoveService; + + @PostMapping("/move") + public ResponseEntity moveFiles(@RequestBody FileMoveRequest request) { + fileMoveService.moveFiles(request); + return ResponseEntity.ok().build(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java index 7ab59dae3..d6d190e7f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java @@ -1,12 +1,12 @@ package com.adityachandel.booklore.mapper; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; -import org.mapstruct.Context; -import org.mapstruct.Mapper; -import org.mapstruct.Mapping; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import org.mapstruct.*; import java.util.Set; import java.util.stream.Collectors; @@ -15,35 +15,42 @@ import java.util.stream.Collectors; public interface BookMapper { @Mapping(source = "library.id", target = "libraryId") + @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(source = "metadata", target = "metadata") @Mapping(source = "shelves", target = "shelves") Book toBook(BookEntity bookEntity); @Mapping(source = "library.id", target = "libraryId") + @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(source = "metadata", target = "metadata") @Mapping(source = "shelves", target = "shelves") Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription); @Mapping(source = "library.id", target = "libraryId") + @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(target = "metadata", ignore = true) @Mapping(target = "shelves", ignore = true) Book toBookWithoutMetadataAndShelves(BookEntity bookEntity); default Set mapAuthors(Set authors) { - if (authors == null) { - return null; - } + if (authors == null) return null; return authors.stream() .map(AuthorEntity::getName) .collect(Collectors.toSet()); } default Set mapCategories(Set categories) { - if (categories == null) { - return null; - } + if (categories == null) return null; return categories.stream() .map(CategoryEntity::getName) .collect(Collectors.toSet()); } + + @Named("mapLibraryPathIdOnly") + default LibraryPath mapLibraryPathIdOnly(LibraryPathEntity entity) { + if (entity == null) return null; + return LibraryPath.builder() + .id(entity.getId()) + .build(); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapperv2/BookMapperV2.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java similarity index 72% rename from booklore-api/src/main/java/com/adityachandel/booklore/mapperv2/BookMapperV2.java rename to booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java index 814d93c39..7d3a123e6 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapperv2/BookMapperV2.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java @@ -1,11 +1,13 @@ -package com.adityachandel.booklore.mapperv2; +package com.adityachandel.booklore.mapper.v2; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; import org.mapstruct.*; import java.util.Set; @@ -15,6 +17,7 @@ import java.util.stream.Collectors; public interface BookMapperV2 { @Mapping(source = "library.id", target = "libraryId") + @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(target = "metadata", qualifiedByName = "mapMetadata") Book toDTO(BookEntity bookEntity); @@ -34,4 +37,12 @@ public interface BookMapperV2 { return categories == null ? Set.of() : categories.stream().map(CategoryEntity::getName).collect(Collectors.toSet()); } + + @Named("mapLibraryPathIdOnly") + default LibraryPath mapLibraryPathIdOnly(LibraryPathEntity entity) { + if (entity == null) return null; + return LibraryPath.builder() + .id(entity.getId()) + .build(); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java index aabe7afe1..4aed82636 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java @@ -17,6 +17,7 @@ public class Book { private Long libraryId; private String fileName; private String filePath; + private String fileSubPath; private Long fileSizeKb; private String title; private Instant lastReadTime; @@ -28,4 +29,5 @@ public class Book { private CbxProgress cbxProgress; private Set shelves; private String readStatus; + private LibraryPath libraryPath; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java new file mode 100644 index 000000000..bd58b4cec --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.model.dto.request; + +import lombok.Data; + +import java.util.Set; + +@Data +public class FileMoveRequest { + private Set bookIds; + private String pattern; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java index 6cee1a929..65fca0b96 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java @@ -17,6 +17,7 @@ public enum AppSettingKey { COVER_IMAGE_RESOLUTION("cover_image_resolution", false), SIMILAR_BOOK_RECOMMENDATION("similar_book_recommendation", false), UPLOAD_FILE_PATTERN("upload_file_pattern", false), + MOVE_FILE_PATTERN("move_file_pattern", false), OPDS_SERVER_ENABLED("opds_server_enabled", false), OIDC_ENABLED("oidc_enabled", false), CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java index 1c2e029ea..1b30c644f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java @@ -17,6 +17,7 @@ public class AppSettings { private boolean similarBookRecommendation; private boolean opdsServerEnabled; private String uploadPattern; + private String movePattern; private Integer cbxCacheSizeInMb; private Integer pdfCacheSizeInMb; private Integer maxFileUploadSizeInMb; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java index f5d342d66..f47550fd1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java @@ -59,6 +59,18 @@ public class BookEntity { @Column(name = "added_on") private Instant addedOn; + @Column(name = "initial_hash", length = 128, updatable = false) + private String initialHash; + + @Column(name = "current_hash", length = 128) + private String currentHash; + + @Column(name = "deleted") + private Boolean deleted = Boolean.FALSE; + + @Column(name = "deleted_at") + private Instant deletedAt; + @ManyToMany @JoinTable( name = "book_shelf_mapping", diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java index 4ec3a2e28..bb31d9a95 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java @@ -25,7 +25,7 @@ public class LibraryEntity { @Convert(converter = SortConverter.class) private Sort sort; - @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true) + @OneToMany(mappedBy = "library", cascade = CascadeType.MERGE, orphanRemoval = true) private List bookEntities; @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java new file mode 100644 index 000000000..67d5f9a5c --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java @@ -0,0 +1,27 @@ +package com.adityachandel.booklore.model.enums; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.Arrays; +import java.util.Optional; + +@RequiredArgsConstructor +@Getter +public enum BookFileExtension { + PDF("pdf", BookFileType.PDF), + EPUB("epub", BookFileType.EPUB), + CBZ("cbz", BookFileType.CBX), + CBR("cbr", BookFileType.CBX), + CB7("cb7", BookFileType.CBX); + + private final String extension; + private final BookFileType type; + + public static Optional fromFileName(String fileName) { + String lower = fileName.toLowerCase(); + return Arrays.stream(values()) + .filter(e -> lower.endsWith("." + e.extension)) + .findFirst(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index 65f815f54..432d23901 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -1,10 +1,12 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.entity.BookEntity; +import jakarta.transaction.Transactional; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -13,63 +15,77 @@ import java.util.Set; @Repository public interface BookRepository extends JpaRepository, JpaSpecificationExecutor { - @Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds") - List findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection libraryPathIds); - Optional findBookByIdAndLibraryId(long id, long libraryId); Optional findBookByFileNameAndLibraryId(String fileName, long libraryId); - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId") - List findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId); + Optional findByCurrentHash(String currentHash); - @Modifying - @Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)") - void deleteByIdIn(Collection ids); + List findAllByLibraryPathIdAndFileSubPathStartingWith(Long libraryPathId, String fileSubPathPrefix); - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL") - List findAllWithMetadataByFileSizeKbIsNull(); + @Query("SELECT b FROM BookEntity b WHERE b.libraryPath.id = :libraryPathId AND b.fileSubPath = :fileSubPath AND b.fileName = :fileName AND (b.deleted IS NULL OR b.deleted = false)") + Optional findByLibraryPath_IdAndFileSubPathAndFileName(@Param("libraryPathId") Long libraryPathId, + @Param("fileSubPath") String fileSubPath, + @Param("fileName") String fileName); - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT b FROM BookEntity b") + @Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds AND (b.deleted IS NULL OR b.deleted = false)") + List findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection libraryPathIds); + + @Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)") + List findAllNonDeletedByIds(@Param("bookIds") Collection bookIds); + + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)") List findAllWithMetadata(); - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds") - List findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection libraryIds); - - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds") + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)") List findAllWithMetadataByIds(@Param("bookIds") Set bookIds); - @EntityGraph(attributePaths = {"metadata", "shelves"}) - @Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId") + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") List findAllWithMetadataByLibraryId(@Param("libraryId") Long libraryId); + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)") + List findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection libraryIds); + + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)") + List findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId); + + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL AND (b.deleted IS NULL OR b.deleted = false)") + List findAllWithMetadataByFileSizeKbIsNull(); + @Query(""" - SELECT DISTINCT b FROM BookEntity b - LEFT JOIN FETCH b.metadata m - LEFT JOIN FETCH m.authors - LEFT JOIN FETCH m.categories - LEFT JOIN FETCH b.shelves - """) + SELECT DISTINCT b FROM BookEntity b + LEFT JOIN FETCH b.metadata m + LEFT JOIN FETCH m.authors + LEFT JOIN FETCH m.categories + LEFT JOIN FETCH b.shelves + WHERE (b.deleted IS NULL OR b.deleted = false) + """) List findAllFullBooks(); -@Query(""" - SELECT DISTINCT b FROM BookEntity b - LEFT JOIN FETCH b.metadata m - LEFT JOIN FETCH m.authors a - LEFT JOIN FETCH m.categories - WHERE LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(m.description) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%')) - ORDER BY m.title ASC -""") -List findBooksContainingMetadata(@Param("text") String text); - -} + @Query(""" + SELECT DISTINCT b FROM BookEntity b + LEFT JOIN FETCH b.metadata m + LEFT JOIN FETCH m.authors a + LEFT JOIN FETCH m.categories + WHERE (b.deleted IS NULL OR b.deleted = false) AND ( + LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%')) + OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%')) + OR LOWER(m.description) LIKE LOWER(CONCAT('%', :text, '%')) + OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%')) + OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%')) + ) + ORDER BY m.title ASC + """) + List findBooksContainingMetadata(@Param("text") String text); + @Modifying + @Transactional + @Query("DELETE FROM BookEntity b WHERE b.deletedAt IS NOT NULL AND b.deletedAt < :cutoff") + int deleteAllByDeletedAtBefore(Instant cutoff); +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookQueryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookQueryService.java index 69f219c4e..6686cb935 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookQueryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookQueryService.java @@ -1,6 +1,6 @@ package com.adityachandel.booklore.service; -import com.adityachandel.booklore.mapperv2.BookMapperV2; +import com.adityachandel.booklore.mapper.v2.BookMapperV2; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.repository.BookRepository; @@ -51,7 +51,7 @@ public class BookQueryService { public List getAllFullBookEntities() { return bookRepository.findAllFullBooks(); } - + public List getBooksContainingMetadata(String text) { return bookRepository.findBooksContainingMetadata(text); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java index 9cae8b746..8bf1b535b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java @@ -73,7 +73,8 @@ public class AppSettingService { builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350")); builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true"))); - builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "")); + builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{currentFilename}")); + builder.movePattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MOVE_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title} - {authors}< ({year})>")); builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true"))); builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false"))); builder.oidcEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false"))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java new file mode 100644 index 000000000..cd6b91b25 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java @@ -0,0 +1,213 @@ +package com.adityachandel.booklore.service.file; + +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.request.FileMoveRequest; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.BookQueryService; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.library.LibraryService; +import com.adityachandel.booklore.service.monitoring.MonitoringService; +import com.adityachandel.booklore.util.PathPatternResolver; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +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.nio.file.StandardCopyOption; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Slf4j +@Service +@AllArgsConstructor +public class FileMoveService { + + private final BookQueryService bookQueryService; + private final BookRepository bookRepository; + private final BookMapper bookMapper; + private final NotificationService notificationService; + private final LibraryService libraryService; + private final MonitoringService monitoringService; + + public void moveFiles(FileMoveRequest request) { + Set bookIds = request.getBookIds(); + String pattern = request.getPattern(); + List books = bookQueryService.findAllWithMetadataByIds(bookIds); + + log.info("Starting file move for {} books using pattern: '{}'", books.size(), pattern); + + Set libraryIds = new HashSet<>(); + boolean didPause = false; + + if (!monitoringService.isPaused()) { + monitoringService.pauseMonitoring(); + didPause = true; + } + + try { + for (BookEntity book : books) { + if (book.getMetadata() == null) continue; + + if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null + || book.getFileSubPath() == null || book.getFileName() == null) { + log.error("Missing required path components for book id {}. Skipping.", book.getId()); + continue; + } + + Path oldFilePath = book.getFullFilePath(); + if (!Files.exists(oldFilePath)) { + log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath); + continue; + } + + log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle()); + + String newRelativePathStr = generatePathFromPattern(book, pattern); + if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { + newRelativePathStr = newRelativePathStr.substring(1); + } + + Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); + Path newFilePath = libraryRoot.resolve(newRelativePathStr).normalize(); + + if (oldFilePath.equals(newFilePath)) { + log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId()); + continue; + } + + try { + if (newFilePath.getParent() != null) { + Files.createDirectories(newFilePath.getParent()); + } + + log.info("Moving file from {} to {}", oldFilePath, newFilePath); + Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING); + + String newFileName = newFilePath.getFileName().toString(); + Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent()); + String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/'); + + book.setFileSubPath(newFileSubPath); + book.setFileName(newFileName); + bookRepository.save(book); + + Book updatedBookDto = bookMapper.toBook(book); + notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, updatedBookDto); + + log.info("Updated book id {} with new path", book.getId()); + deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot)); + + if (book.getLibraryPath().getLibrary().getId() != null) { + libraryIds.add(book.getLibraryPath().getLibrary().getId()); + } + } catch (IOException e) { + log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e); + } + } + + log.info("Completed file move for {} books.", books.size()); + + for (Long libraryId : libraryIds) { + try { + libraryService.rescanLibrary(libraryId); + log.info("Rescanned library id {} after file move", libraryId); + } catch (Exception e) { + log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e); + } + } + + } finally { + if (didPause && !monitoringService.isPaused()) { + log.info("Monitoring already resumed by another thread."); + } else if (didPause) { + Thread.startVirtualThread(() -> { + try { + Thread.sleep(5_000); + monitoringService.resumeMonitoring(); + log.info("Monitoring resumed after 5s delay"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.warn("Interrupted while delaying resume of monitoring"); + } + }); + } + } + } + + public String generatePathFromPattern(BookEntity book, String pattern) { + return PathPatternResolver.resolvePattern(book, pattern); + } + + public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set libraryRoots) throws IOException { + Set ignoredFilenames = Set.of(".DS_Store", "Thumbs.db"); + currentDir = currentDir.toAbsolutePath().normalize(); + + Set normalizedRoots = new HashSet<>(); + for (Path root : libraryRoots) { + normalizedRoots.add(root.toAbsolutePath().normalize()); + } + + while (currentDir != null) { + boolean isLibraryRoot = false; + for (Path root : normalizedRoots) { + try { + if (Files.isSameFile(root, currentDir)) { + isLibraryRoot = true; + break; + } + } catch (IOException e) { + log.warn("Failed to compare paths: {} and {}", root, currentDir); + } + } + + if (isLibraryRoot) { + log.debug("Reached library root: {}. Stopping cleanup.", currentDir); + break; + } + + File[] files = currentDir.toFile().listFiles(); + if (files == null) { + log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir); + break; + } + + boolean hasImportantFiles = false; + for (File file : files) { + if (!ignoredFilenames.contains(file.getName())) { + hasImportantFiles = true; + break; + } + } + + if (!hasImportantFiles) { + for (File file : files) { + try { + Files.delete(file.toPath()); + log.info("Deleted ignored file: {}", file.getAbsolutePath()); + } catch (IOException e) { + log.warn("Failed to delete ignored file: {}", file.getAbsolutePath()); + } + } + try { + Files.delete(currentDir); + log.info("Deleted empty directory: {}", currentDir); + } catch (IOException e) { + log.warn("Failed to delete directory: {}", currentDir, e); + break; + } + currentDir = currentDir.getParent(); + } else { + log.debug("Directory {} contains important files. Stopping cleanup.", currentDir); + break; + } + } + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java new file mode 100644 index 000000000..2707ddd1f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java @@ -0,0 +1,77 @@ +package com.adityachandel.booklore.service.fileprocessor; + +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.repository.BookMetadataRepository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.BookCreatorService; +import com.adityachandel.booklore.service.metadata.MetadataMatchService; +import com.adityachandel.booklore.util.FileUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.file.Path; +import java.util.Optional; + +@Slf4j +public abstract class AbstractFileProcessor implements FileProcessor { + + protected final BookRepository bookRepository; + protected final BookCreatorService bookCreatorService; + protected final BookMapper bookMapper; + protected final FileProcessingUtils fileProcessingUtils; + protected final BookMetadataRepository bookMetadataRepository; + protected final MetadataMatchService metadataMatchService; + + protected AbstractFileProcessor(BookRepository bookRepository, + BookCreatorService bookCreatorService, + BookMapper bookMapper, + FileProcessingUtils fileProcessingUtils, + BookMetadataRepository bookMetadataRepository, + MetadataMatchService metadataMatchService) { + this.bookRepository = bookRepository; + this.bookCreatorService = bookCreatorService; + this.bookMapper = bookMapper; + this.fileProcessingUtils = fileProcessingUtils; + this.bookMetadataRepository = bookMetadataRepository; + this.metadataMatchService = metadataMatchService; + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + @Override + public Book processFile(LibraryFile libraryFile, boolean forceProcess) { + Path filePath = libraryFile.getFullPath(); + String fileName = filePath.getFileName().toString(); + String hash = FileUtils.computeFileHash(filePath); + + Optional existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, forceProcess, bookRepository, bookMapper); + if (existing.isPresent()) return existing.get(); + if (!forceProcess) { + Optional byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId()); + if (byName.isPresent()) { + return bookMapper.toBook(byName.get()); + } + } + return processNewFile(libraryFile); + } + + protected abstract Book processNewFile(LibraryFile libraryFile); + + protected Book finishAndReturnBook(BookEntity bookEntity) { + String hash = FileUtils.computeFileHash(bookEntity); + bookEntity.setCurrentHash(hash); + + Float score = metadataMatchService.calculateMatchScore(bookEntity); + bookEntity.setMetadataMatchScore(score); + + bookCreatorService.saveConnections(bookEntity); + + bookEntity = bookRepository.save(bookEntity); + bookRepository.flush(); + + return bookMapper.toBook(bookEntity); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java new file mode 100644 index 000000000..cdc143b79 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java @@ -0,0 +1,10 @@ +package com.adityachandel.booklore.service.fileprocessor; + +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; + +public interface BookFileProcessor { + Book processNewFile(LibraryFile libraryFile); + boolean generateCover(BookEntity bookEntity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 41e7d225c..e56c7ea76 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -12,15 +12,12 @@ import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.util.FileUtils; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; -import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; @@ -30,62 +27,47 @@ import java.util.*; @Slf4j @Service -@AllArgsConstructor -public class CbxProcessor implements FileProcessor { +public class CbxProcessor extends AbstractFileProcessor implements BookFileProcessor { - private final BookRepository bookRepository; - private final BookCreatorService bookCreatorService; - private final BookMapper bookMapper; - private final FileProcessingUtils fileProcessingUtils; private final BookMetadataRepository bookMetadataRepository; - private final MetadataMatchService metadataMatchService; - @Transactional(propagation = Propagation.REQUIRES_NEW) - @Override - public Book processFile(LibraryFile libraryFile, boolean forceProcess) { - File bookFile = new File(libraryFile.getFileName()); - String fileName = bookFile.getName(); - if (!forceProcess) { - Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId()); - return bookOptional.map(bookMapper::toBook).orElseGet(() -> processNewFile(libraryFile)); - } else { - return processNewFile(libraryFile); - } + public CbxProcessor(BookRepository bookRepository, + BookCreatorService bookCreatorService, + BookMapper bookMapper, + FileProcessingUtils fileProcessingUtils, + BookMetadataRepository bookMetadataRepository, + MetadataMatchService metadataMatchService) { + super(bookRepository, bookCreatorService, bookMapper, fileProcessingUtils, bookMetadataRepository, metadataMatchService); + this.bookMetadataRepository = bookMetadataRepository; } - @Transactional(propagation = Propagation.REQUIRES_NEW) - protected Book processNewFile(LibraryFile libraryFile) { + @Override + public Book processNewFile(LibraryFile libraryFile) { BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX); if (generateCover(bookEntity)) { fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata()); } setMetadata(bookEntity); - Float score = metadataMatchService.calculateMatchScore(bookEntity); - bookEntity.setMetadataMatchScore(score); - bookCreatorService.saveConnections(bookEntity); - bookEntity = bookRepository.save(bookEntity); - bookRepository.flush(); - return bookMapper.toBook(bookEntity); + return finishAndReturnBook(bookEntity); } + @Override public boolean generateCover(BookEntity bookEntity) { File file = new File(FileUtils.getBookFullPath(bookEntity)); try { Optional imageOptional = extractImagesFromArchive(file); if (imageOptional.isPresent()) { - BufferedImage firstImage = imageOptional.get(); - boolean saved = fileProcessingUtils.saveCoverImage(firstImage, bookEntity.getId()); + boolean saved = fileProcessingUtils.saveCoverImage(imageOptional.get(), bookEntity.getId()); if (saved) { bookEntity.getMetadata().setCoverUpdatedOn(Instant.now()); bookMetadataRepository.save(bookEntity.getMetadata()); return true; } } - return false; } catch (Exception e) { - log.error("Error generating cover from archive {}, error: {}", bookEntity.getFileName(), e.getMessage()); - return false; + log.error("Error generating cover for '{}': {}", bookEntity.getFileName(), e.getMessage()); } + return false; } private Optional extractImagesFromArchive(File file) { @@ -97,46 +79,15 @@ public class CbxProcessor implements FileProcessor { } else if (name.endsWith(".cbr")) { return extractFirstImageFromRar(file); } else { - log.warn("Unsupported archive format: {}", name); + log.warn("Unsupported CBX format: {}", name); return Optional.empty(); } } - private Optional extractFirstImageFromRar(File file) { - try (Archive archive = new Archive(file)) { - List headers = archive.getFileHeaders(); - List imageHeaders = headers.stream() - .filter(h -> !h.isDirectory()) - .filter(h -> { - String fileName = h.getFileNameString().replace("\\", "/").toLowerCase(); - return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".webp"); - }) - .sorted(Comparator.comparing(FileHeader::getFileNameString)) - .toList(); - - for (FileHeader header : imageHeaders) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - archive.extractFile(header, baos); - byte[] imageData = baos.toByteArray(); - BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData)); - if (img != null) { - return Optional.of(img); - } - } catch (Exception e) { - log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage()); - } - } - } catch (Exception e) { - log.error("Error extracting image from RAR archive {}: {}", file.getName(), e.getMessage()); - } - return Optional.empty(); - } - private Optional extractFirstImageFromZip(File file) { try (ZipFile zipFile = new ZipFile(file)) { return Collections.list(zipFile.getEntries()).stream() - .filter(e -> !e.isDirectory()) - .filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) + .filter(e -> !e.isDirectory() && e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) .min(Comparator.comparing(ZipArchiveEntry::getName)) .map(entry -> { try (InputStream is = zipFile.getInputStream(entry)) { @@ -147,7 +98,7 @@ public class CbxProcessor implements FileProcessor { } }); } catch (Exception e) { - log.error("Error extracting image from ZIP archive {}: {}", file.getName(), e.getMessage()); + log.error("Error extracting ZIP: {}", e.getMessage()); return Optional.empty(); } } @@ -162,47 +113,57 @@ public class CbxProcessor implements FileProcessor { } } imageEntries.sort(Comparator.comparing(SevenZArchiveEntry::getName)); - sevenZFile.close(); try (SevenZFile sevenZFileReset = new SevenZFile(file)) { for (SevenZArchiveEntry imgEntry : imageEntries) { - SevenZArchiveEntry currentEntry; - while ((currentEntry = sevenZFileReset.getNextEntry()) != null) { - if (currentEntry.equals(imgEntry)) { - byte[] content = new byte[(int) currentEntry.getSize()]; + SevenZArchiveEntry current; + while ((current = sevenZFileReset.getNextEntry()) != null) { + if (current.equals(imgEntry)) { + byte[] content = new byte[(int) current.getSize()]; int offset = 0; while (offset < content.length) { int bytesRead = sevenZFileReset.read(content, offset, content.length - offset); - if (bytesRead < 0) { - break; - } + if (bytesRead < 0) break; offset += bytesRead; } - BufferedImage img = ImageIO.read(new ByteArrayInputStream(content)); - if (img != null) { - return Optional.of(img); - } else { - break; - } + return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content))); } } } } - return Optional.empty(); } catch (Exception e) { - log.error("Error extracting image from 7z archive {}: {}", file.getName(), e.getMessage()); - return Optional.empty(); + log.error("Error extracting 7z: {}", e.getMessage()); } + return Optional.empty(); + } + + private Optional extractFirstImageFromRar(File file) { + try (Archive archive = new Archive(file)) { + List imageHeaders = archive.getFileHeaders().stream() + .filter(h -> !h.isDirectory() && h.getFileNameString().toLowerCase().matches(".*\\.(jpg|jpeg|png|webp)")) + .sorted(Comparator.comparing(FileHeader::getFileNameString)) + .toList(); + + for (FileHeader header : imageHeaders) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + archive.extractFile(header, baos); + return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray()))); + } catch (Exception e) { + log.warn("Error reading RAR entry {}: {}", header.getFileNameString(), e.getMessage()); + } + } + } catch (Exception e) { + log.error("Error extracting RAR: {}", e.getMessage()); + } + return Optional.empty(); } private void setMetadata(BookEntity bookEntity) { String baseName = new File(bookEntity.getFileName()).getName(); - String title = baseName.replaceAll("(?i)\\.cb[sz7]$", "").replaceAll("[_\\-]", " ").trim(); - bookEntity.getMetadata().setTitle(truncate(title, 1000)); - } - - private String truncate(String input, int maxLength) { - if (input == null) return null; - return input.length() <= maxLength ? input : input.substring(0, maxLength); + String title = baseName + .replaceAll("(?i)\\.cb[rz7]$", "") + .replaceAll("[_\\-]", " ") + .trim(); + bookEntity.getMetadata().setTitle(FileProcessingUtils.truncate(title, 1000)); } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index bf6339d3d..b440d6fe8 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -10,80 +10,67 @@ import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.BookCreatorService; -import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; import com.adityachandel.booklore.service.metadata.MetadataMatchService; +import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; import com.adityachandel.booklore.util.FileUtils; import io.documentnode.epub4j.domain.Resource; import io.documentnode.epub4j.epub.EpubReader; -import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.time.Instant; -import java.util.Optional; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate; + @Slf4j @Service -@AllArgsConstructor -public class EpubProcessor implements FileProcessor { +public class EpubProcessor extends AbstractFileProcessor implements BookFileProcessor { - private final BookRepository bookRepository; - private final BookCreatorService bookCreatorService; - private final BookMapper bookMapper; - private final FileProcessingUtils fileProcessingUtils; - private final BookMetadataRepository bookMetadataRepository; - private final MetadataMatchService metadataMatchService; private final EpubMetadataExtractor epubMetadataExtractor; + private final BookMetadataRepository bookMetadataRepository; - @Transactional(propagation = Propagation.REQUIRES_NEW) - @Override - public Book processFile(LibraryFile libraryFile, boolean forceProcess) { - File bookFile = new File(libraryFile.getFileName()); - String fileName = bookFile.getName(); - if (!forceProcess) { - Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId()); - return bookOptional - .map(bookMapper::toBook) - .orElseGet(() -> processNewFile(libraryFile)); - } else { - return processNewFile(libraryFile); - } + public EpubProcessor(BookRepository bookRepository, + BookCreatorService bookCreatorService, + BookMapper bookMapper, + FileProcessingUtils fileProcessingUtils, + BookMetadataRepository bookMetadataRepository, + MetadataMatchService metadataMatchService, + EpubMetadataExtractor epubMetadataExtractor) { + super(bookRepository, bookCreatorService, bookMapper, fileProcessingUtils, bookMetadataRepository, metadataMatchService); + this.epubMetadataExtractor = epubMetadataExtractor; + this.bookMetadataRepository = bookMetadataRepository; } - @Transactional(propagation = Propagation.REQUIRES_NEW) - protected Book processNewFile(LibraryFile libraryFile) { + @Override + public Book processNewFile(LibraryFile libraryFile) { BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB); setBookMetadata(bookEntity); - Float score = metadataMatchService.calculateMatchScore(bookEntity); - bookEntity.setMetadataMatchScore(score); if (generateCover(bookEntity)) { fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata()); } - bookCreatorService.saveConnections(bookEntity); - bookRepository.save(bookEntity); - bookRepository.flush(); - return bookMapper.toBook(bookEntity); + return finishAndReturnBook(bookEntity); } + @Override public boolean generateCover(BookEntity bookEntity) { try { File epubFile = new File(FileUtils.getBookFullPath(bookEntity)); io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(epubFile)); Resource coverImage = epub.getCoverImage(); + if (coverImage == null) { for (Resource res : epub.getResources().getAll()) { String id = res.getId(); String href = res.getHref(); if ((id != null && id.toLowerCase().contains("cover")) || (href != null && href.toLowerCase().contains("cover"))) { - if (res.getMediaType() != null && res.getMediaType().getName().startsWith("image")) { coverImage = res; break; @@ -91,49 +78,56 @@ public class EpubProcessor implements FileProcessor { } } } + + if (coverImage == null) { + log.warn("No cover image found in EPUB '{}'", bookEntity.getFileName()); + return false; + } + boolean saved = saveCoverImage(coverImage, bookEntity.getId()); bookEntity.getMetadata().setCoverUpdatedOn(Instant.now()); bookMetadataRepository.save(bookEntity.getMetadata()); return saved; + } catch (Exception e) { - log.error("Error generating cover for epub file {}, error: {}", bookEntity.getFileName(), e.getMessage(), e); + log.error("Error generating cover for EPUB '{}': {}", bookEntity.getFileName(), e.getMessage(), e); + return false; } - return false; } private void setBookMetadata(BookEntity bookEntity) { File bookFile = new File(bookEntity.getFullFilePath().toUri()); - BookMetadata epubMetadata = epubMetadataExtractor.extractMetadata(bookFile); if (epubMetadata == null) return; - BookMetadataEntity bookMetadata = bookEntity.getMetadata(); - bookMetadata.setTitle(truncate(epubMetadata.getTitle(), 1000)); - bookMetadata.setSubtitle(truncate(epubMetadata.getSubtitle(), 1000)); - bookMetadata.setDescription(truncate(epubMetadata.getDescription(), 2000)); - bookMetadata.setPublisher(truncate(epubMetadata.getPublisher(), 1000)); - bookMetadata.setPublishedDate(epubMetadata.getPublishedDate()); - bookMetadata.setSeriesName(truncate(epubMetadata.getSeriesName(), 1000)); - bookMetadata.setSeriesNumber(epubMetadata.getSeriesNumber()); - bookMetadata.setSeriesTotal(epubMetadata.getSeriesTotal()); - bookMetadata.setIsbn13(truncate(epubMetadata.getIsbn13(), 64)); - bookMetadata.setIsbn10(truncate(epubMetadata.getIsbn10(), 64)); - bookMetadata.setPageCount(epubMetadata.getPageCount()); + BookMetadataEntity metadata = bookEntity.getMetadata(); + + metadata.setTitle(truncate(epubMetadata.getTitle(), 1000)); + metadata.setSubtitle(truncate(epubMetadata.getSubtitle(), 1000)); + metadata.setDescription(truncate(epubMetadata.getDescription(), 2000)); + metadata.setPublisher(truncate(epubMetadata.getPublisher(), 1000)); + metadata.setPublishedDate(epubMetadata.getPublishedDate()); + metadata.setSeriesName(truncate(epubMetadata.getSeriesName(), 1000)); + metadata.setSeriesNumber(epubMetadata.getSeriesNumber()); + metadata.setSeriesTotal(epubMetadata.getSeriesTotal()); + metadata.setIsbn13(truncate(epubMetadata.getIsbn13(), 64)); + metadata.setIsbn10(truncate(epubMetadata.getIsbn10(), 64)); + metadata.setPageCount(epubMetadata.getPageCount()); String lang = epubMetadata.getLanguage(); - bookMetadata.setLanguage(truncate((lang == null || lang.equalsIgnoreCase("UND")) ? "en" : lang, 1000)); + metadata.setLanguage(truncate((lang == null || lang.equalsIgnoreCase("UND")) ? "en" : lang, 1000)); - bookMetadata.setAsin(truncate(epubMetadata.getAsin(), 20)); - bookMetadata.setPersonalRating(epubMetadata.getPersonalRating()); - bookMetadata.setAmazonRating(epubMetadata.getAmazonRating()); - bookMetadata.setAmazonReviewCount(epubMetadata.getAmazonReviewCount()); - bookMetadata.setGoodreadsId(truncate(epubMetadata.getGoodreadsId(), 100)); - bookMetadata.setGoodreadsRating(epubMetadata.getGoodreadsRating()); - bookMetadata.setGoodreadsReviewCount(epubMetadata.getGoodreadsReviewCount()); - bookMetadata.setHardcoverId(truncate(epubMetadata.getHardcoverId(), 100)); - bookMetadata.setHardcoverRating(epubMetadata.getHardcoverRating()); - bookMetadata.setHardcoverReviewCount(epubMetadata.getHardcoverReviewCount()); - bookMetadata.setGoogleId(truncate(epubMetadata.getGoogleId(), 100)); + metadata.setAsin(truncate(epubMetadata.getAsin(), 20)); + metadata.setPersonalRating(epubMetadata.getPersonalRating()); + metadata.setAmazonRating(epubMetadata.getAmazonRating()); + metadata.setAmazonReviewCount(epubMetadata.getAmazonReviewCount()); + metadata.setGoodreadsId(truncate(epubMetadata.getGoodreadsId(), 100)); + metadata.setGoodreadsRating(epubMetadata.getGoodreadsRating()); + metadata.setGoodreadsReviewCount(epubMetadata.getGoodreadsReviewCount()); + metadata.setHardcoverId(truncate(epubMetadata.getHardcoverId(), 100)); + metadata.setHardcoverRating(epubMetadata.getHardcoverRating()); + metadata.setHardcoverReviewCount(epubMetadata.getHardcoverReviewCount()); + metadata.setGoogleId(truncate(epubMetadata.getGoogleId(), 100)); bookCreatorService.addAuthorsToBook(epubMetadata.getAuthors(), bookEntity); @@ -149,9 +143,4 @@ public class EpubProcessor implements FileProcessor { BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverImage.getData())); return fileProcessingUtils.saveCoverImage(originalImage, bookId); } - - private String truncate(String input, int maxLength) { - if (input == null) return null; - return input.length() <= maxLength ? input : input.substring(0, maxLength); - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/FileProcessingUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/FileProcessingUtils.java index 452f4f9dc..c3ecf10bb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/FileProcessingUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/FileProcessingUtils.java @@ -1,10 +1,17 @@ package com.adityachandel.booklore.service.fileprocessor; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.util.FileService; +import com.adityachandel.booklore.util.FileUtils; +import com.adityachandel.booklore.mapper.BookMapper; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.imageio.ImageIO; @@ -17,6 +24,8 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.Comparator; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Stream; @@ -83,4 +92,48 @@ public class FileProcessingUtils { } log.info("Deleted {} book covers", bookIds.size()); } -} + + public Optional checkForDuplicateAndUpdateMetadataIfNeeded( + LibraryFile libraryFile, + String hash, + boolean forceProcess, + BookRepository bookRepository, + BookMapper bookMapper + ) { + if (StringUtils.isBlank(hash)) { + log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath()); + return Optional.empty(); + } + + Optional existingByHash = bookRepository.findByCurrentHash(hash); + if (existingByHash.isPresent() && !forceProcess) { + BookEntity book = existingByHash.get(); + + boolean changed = false; + String fileName = libraryFile.getFullPath().getFileName().toString(); + + if (!book.getFileName().equals(fileName)) { + book.setFileName(fileName); + changed = true; + } + + if (!Objects.equals(book.getLibraryPath().getId(), libraryFile.getLibraryPathEntity().getId())) { + book.setLibraryPath(libraryFile.getLibraryPathEntity()); + book.setFileSubPath(libraryFile.getFileSubPath()); + changed = true; + } + + if (changed) { + bookRepository.save(book); + } + + return Optional.of(bookMapper.toBook(book)); + } + + return Optional.empty(); + } + + public static String truncate(String input, int maxLength) { + return input == null ? null : (input.length() <= maxLength ? input : input.substring(0, maxLength)); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java index ef0caf16e..9712aa910 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java @@ -9,10 +9,9 @@ import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.BookCreatorService; -import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; import com.adityachandel.booklore.service.metadata.MetadataMatchService; +import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; import com.adityachandel.booklore.util.FileUtils; -import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.pdfbox.Loader; @@ -20,58 +19,44 @@ import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.time.Instant; -import java.util.Optional; + +import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate; @Slf4j @Service -@AllArgsConstructor -public class PdfProcessor implements FileProcessor { +public class PdfProcessor extends AbstractFileProcessor implements BookFileProcessor { - private final BookRepository bookRepository; - private final BookCreatorService bookCreatorService; - private final BookMapper bookMapper; - private final FileProcessingUtils fileProcessingUtils; - private final BookMetadataRepository bookMetadataRepository; - private final MetadataMatchService metadataMatchService; private final PdfMetadataExtractor pdfMetadataExtractor; + private final BookMetadataRepository bookMetadataRepository; - @Transactional(propagation = Propagation.REQUIRES_NEW) - @Override - public Book processFile(LibraryFile libraryFile, boolean forceProcess) { - File bookFile = new File(libraryFile.getFileName()); - String fileName = bookFile.getName(); - if (!forceProcess) { - Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId()); - return bookOptional - .map(bookMapper::toBook) - .orElseGet(() -> processNewFile(libraryFile)); - } else { - return processNewFile(libraryFile); - } + public PdfProcessor(BookRepository bookRepository, + BookCreatorService bookCreatorService, + BookMapper bookMapper, + FileProcessingUtils fileProcessingUtils, + BookMetadataRepository bookMetadataRepository, + MetadataMatchService metadataMatchService, + PdfMetadataExtractor pdfMetadataExtractor) { + super(bookRepository, bookCreatorService, bookMapper, fileProcessingUtils, bookMetadataRepository, metadataMatchService); + this.pdfMetadataExtractor = pdfMetadataExtractor; + this.bookMetadataRepository = bookMetadataRepository; } - @Transactional(propagation = Propagation.REQUIRES_NEW) - protected Book processNewFile(LibraryFile libraryFile) { + @Override + public Book processNewFile(LibraryFile libraryFile) { BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF); if (generateCover(bookEntity)) { fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata()); } - setMetadata(bookEntity); - Float score = metadataMatchService.calculateMatchScore(bookEntity); - bookEntity.setMetadataMatchScore(score); - bookCreatorService.saveConnections(bookEntity); - bookEntity = bookRepository.save(bookEntity); - bookRepository.flush(); - return bookMapper.toBook(bookEntity); + extractAndSetMetadata(bookEntity); + return finishAndReturnBook(bookEntity); } + @Override public boolean generateCover(BookEntity bookEntity) { try (PDDocument pdf = Loader.loadPDF(new File(FileUtils.getBookFullPath(bookEntity)))) { boolean saved = generateCoverImageAndSave(bookEntity.getId(), pdf); @@ -79,14 +64,15 @@ public class PdfProcessor implements FileProcessor { bookMetadataRepository.save(bookEntity.getMetadata()); return saved; } catch (Exception e) { - log.error("Error generating cover for pdf file {}, error: {}", bookEntity.getFileName(), e.getMessage()); + log.warn("Failed to generate cover for '{}': {}", bookEntity.getFileName(), e.getMessage()); + return false; } - return false; } - private void setMetadata(BookEntity bookEntity) { + private void extractAndSetMetadata(BookEntity bookEntity) { try { BookMetadata extracted = pdfMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity))); + if (StringUtils.isNotBlank(extracted.getTitle())) { bookEntity.getMetadata().setTitle(truncate(extracted.getTitle(), 1000)); } @@ -135,8 +121,9 @@ public class PdfProcessor implements FileProcessor { if (extracted.getCategories() != null) { bookCreatorService.addCategoriesToBook(extracted.getCategories(), bookEntity); } + } catch (Exception e) { - log.error("Failed to extract advanced PDF metadata for {}: {}", bookEntity.getFileName(), e.getMessage(), e); + log.warn("Failed to extract PDF metadata for '{}': {}", bookEntity.getFileName(), e.getMessage()); } } @@ -144,9 +131,4 @@ public class PdfProcessor implements FileProcessor { BufferedImage coverImage = new PDFRenderer(document).renderImageWithDPI(0, 300, ImageType.RGB); return fileProcessingUtils.saveCoverImage(coverImage, bookId); } - - private String truncate(String input, int maxLength) { - if (input == null) return null; - return input.length() <= maxLength ? input : input.substring(0, maxLength); - } -} +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java index eca1f75a2..6b8be7736 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java @@ -6,11 +6,10 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.BookFileExtension; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryRepository; -import com.adityachandel.booklore.service.BookQueryService; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; @@ -23,19 +22,18 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionTemplate; import java.io.IOException; -import java.nio.file.*; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.*; -import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification; -@Service @AllArgsConstructor +@Service @Slf4j public class LibraryProcessingService { @@ -46,13 +44,7 @@ public class LibraryProcessingService { private final CbxProcessor cbxProcessor; private final BookRepository bookRepository; private final EntityManager entityManager; - private final TransactionTemplate transactionTemplate; private final FileService fileService; - private final BookQueryService bookQueryService; - - private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); - private final Map> deletionTasks = new ConcurrentHashMap<>(); - private static final int DELETE_DEBOUNCE_SECONDS = 3; @Transactional public void processLibrary(long libraryId) throws IOException { @@ -63,101 +55,6 @@ public class LibraryProcessingService { notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName())); } - @Transactional - public void processFile(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { - LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); - Path path = Paths.get(filePath); - String fileName = path.getFileName().toString(); - if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) { - ScheduledFuture scheduledDeletion = deletionTasks.remove(filePath); - if (scheduledDeletion != null) { - scheduledDeletion.cancel(false); - log.debug("Cancelled scheduled deletion for file: {}", filePath); - } - - notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); - - LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath); - libraryPathEntity = entityManager.merge(libraryPathEntity); - - LibraryPathEntity finalLibraryPathEntity = libraryPathEntity; - bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) - .ifPresent(existingBook -> { - Path newFullPath = path; - Path oldFullPath = existingBook.getFullFilePath(); - if (!newFullPath.equals(oldFullPath)) { - existingBook.setLibraryPath(finalLibraryPathEntity); - existingBook.setFileSubPath(FileUtils.getRelativeSubPath(finalLibraryPathEntity.getPath(), newFullPath)); - bookRepository.save(existingBook); - log.debug("Updated path for moved book: {}", fileName); - } - }); - - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path)) - .fileName(fileName) - .bookFileType(getBookFileType(fileName)) - .build(); - - processLibraryFiles(List.of(libraryFile)); - notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); - - } else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) { - ScheduledFuture scheduledDeletion = deletionTasks.putIfAbsent(filePath, scheduler.schedule(() -> { - try { - boolean fileStillExists = libraryEntity.getLibraryPaths().stream() - .anyMatch(lp -> { - Path fullPath = Path.of(lp.getPath()).resolve(fileName); - return Files.exists(fullPath); - }); - if (!fileStillExists) { - transactionTemplate.executeWithoutResult(status -> { - bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) - .ifPresent(bookEntity -> { - deleteRemovedBooks(List.of(bookEntity.getId())); - notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId())); - log.debug("Deleted book after debounce: {}", fileName); - }); - }); - } else { - log.debug("File '{}' detected to still exist after debounce, skipping delete.", fileName); - } - } catch (Exception e) { - log.error("Error during delayed deletion of file: {}", filePath, e); - } finally { - deletionTasks.remove(filePath); - } - }, DELETE_DEBOUNCE_SECONDS, TimeUnit.SECONDS)); - - // If scheduledDeletion != null, it means a task was already scheduled, so we skip scheduling again - } - } - - @Transactional - protected LibraryPathEntity getLibraryPathEntityForFile(LibraryEntity libraryEntity, String libraryPath) { - return libraryEntity.getLibraryPaths().stream().filter(l -> l.getPath().equals(libraryPath)) - .findFirst() - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(libraryPath)); - } - - @Transactional - protected BookFileType getBookFileType(String fileName) { - String lowerCaseName = fileName.toLowerCase(); - if (lowerCaseName.endsWith(".pdf")) { - return BookFileType.PDF; - } else if (lowerCaseName.endsWith(".cbz")) { - return BookFileType.CBX; - } else if (lowerCaseName.endsWith(".cbr")) { - return BookFileType.CBX; - } else if (lowerCaseName.endsWith(".cb7")) { - return BookFileType.CBX; - } else { - return BookFileType.EPUB; - } - } - @Transactional public void rescanLibrary(long libraryId) throws IOException { LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); @@ -175,9 +72,7 @@ public class LibraryProcessingService { } void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException { - List currentLibraryFiles = getLibraryFiles(libraryEntity); - Map currentFileMap = currentLibraryFiles.stream() - .collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing)); + Map currentFileMap = getLibraryFiles(libraryEntity).stream().collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing)); for (BookEntity book : libraryEntity.getBookEntities()) { Path existingPath = book.getFullFilePath(); Path updatedPath = currentFileMap.get(book.getFileName()); @@ -198,7 +93,9 @@ public class LibraryProcessingService { Set currentFileNames = getLibraryFiles(libraryEntity).stream() .map(LibraryFile::getFileName) .collect(Collectors.toSet()); + return libraryEntity.getBookEntities().stream() + .filter(book -> (book.getDeleted() == null || !book.getDeleted())) .filter(book -> !currentFileNames.contains(book.getFileName())) .map(BookEntity::getId) .collect(Collectors.toList()); @@ -219,8 +116,7 @@ public class LibraryProcessingService { for (BookEntity book : books) { try { if (book.getMetadata() != null && StringUtils.isNotBlank(book.getMetadata().getThumbnail())) { - Path thumbnailPath = Path.of(fileService.getThumbnailPath(book.getId())); - deleteDirectoryRecursively(thumbnailPath); + deleteDirectoryRecursively(Path.of(fileService.getThumbnailPath(book.getId()))); } Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId())); if (Files.exists(backupDir)) { @@ -232,28 +128,25 @@ public class LibraryProcessingService { } bookRepository.deleteAll(books); notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds); - if (bookIds.size() > 1) { - log.info("Books removed: {}", bookIds); - } + if (bookIds.size() > 1) log.info("Books removed: {}", bookIds); } private void deleteDirectoryRecursively(Path path) throws IOException { if (Files.exists(path)) { try (Stream walk = Files.walk(path)) { - walk.sorted(Comparator.reverseOrder()) - .forEach(p -> { - try { - Files.deleteIfExists(p); - } catch (IOException e) { - log.warn("Failed to delete file or directory: {}", p, e); - } - }); + walk.sorted(Comparator.reverseOrder()).forEach(p -> { + try { + Files.deleteIfExists(p); + } catch (IOException e) { + log.warn("Failed to delete file or directory: {}", p, e); + } + }); } } } @Transactional - protected void processLibraryFiles(List libraryFiles) { + public void processLibraryFiles(List libraryFiles) { for (LibraryFile libraryFile : libraryFiles) { log.info("Processing file: {}", libraryFile.getFileName()); Book book = processLibraryFile(libraryFile); @@ -267,68 +160,40 @@ public class LibraryProcessingService { @Transactional protected Book processLibraryFile(LibraryFile libraryFile) { - if (libraryFile.getBookFileType() == BookFileType.PDF) { - return pdfProcessor.processFile(libraryFile, false); - } else if (libraryFile.getBookFileType() == BookFileType.EPUB) { - return epubProcessor.processFile(libraryFile, false); - } else if (libraryFile.getBookFileType() == BookFileType.CBX) { - return cbxProcessor.processFile(libraryFile, false); - } - return null; + return switch (libraryFile.getBookFileType()) { + case PDF -> pdfProcessor.processFile(libraryFile, false); + case EPUB -> epubProcessor.processFile(libraryFile, false); + case CBX -> cbxProcessor.processFile(libraryFile, false); + }; } private List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { - List libraryFiles = new ArrayList<>(); - for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) { - libraryFiles.addAll(findLibraryFiles(libraryPathEntity, libraryEntity)); + List allFiles = new ArrayList<>(); + for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { + allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity)); } - return libraryFiles; + return allFiles; } - private List findLibraryFiles(LibraryPathEntity libraryPathEntity, LibraryEntity libraryEntity) throws IOException { - List libraryFiles = new ArrayList<>(); - Path libraryPath = Path.of(libraryPathEntity.getPath()); - try (var stream = Files.walk(libraryPath)) { - stream.filter(Files::isRegularFile) - .filter(file -> { - String fileName = file.getFileName().toString().toLowerCase(); - if (fileName.startsWith(".")) { - return false; - } - return fileName.endsWith(".pdf") || - fileName.endsWith(".epub") || - fileName.endsWith(".cbz") || - fileName.endsWith(".cbr") || - fileName.endsWith(".cb7"); + private List findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException { + Path libraryPath = Path.of(pathEntity.getPath()); + try (Stream stream = Files.walk(libraryPath)) { + return stream.filter(Files::isRegularFile) + .map(fullPath -> { + String fileName = fullPath.getFileName().toString(); + return BookFileExtension.fromFileName(fileName) + .map(ext -> LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath)) + .fileName(fileName) + .bookFileType(ext.getType()) + .build()) + .orElse(null); }) - .forEach(fullFilePath -> { - String fileName = fullFilePath.getFileName().toString().toLowerCase(); - BookFileType fileType; - if (fileName.endsWith(".pdf")) { - fileType = BookFileType.PDF; - } else if (fileName.endsWith(".epub")) { - fileType = BookFileType.EPUB; - } else if (fileName.endsWith(".cbz")) { - fileType = BookFileType.CBX; - } else if (fileName.endsWith(".cbr")) { - fileType = BookFileType.CBX; - } else if (fileName.endsWith(".cb7")) { - fileType = BookFileType.CBX; - } else { - return; - } - - String relativePath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), fullFilePath); - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileSubPath(relativePath) - .fileName(fullFilePath.getFileName().toString()) - .bookFileType(fileType) - .build(); - libraryFiles.add(libraryFile); - }); + .filter(Objects::nonNull) + .filter(file -> !file.getFileName().startsWith(".")) + .toList(); } - return libraryFiles; } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java index 28955df7d..1adf02e7a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java @@ -58,7 +58,7 @@ public class LibraryService { @PostConstruct public void initializeMonitoring() { List libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList()); - monitoringService.registerLibrariesForMonitoring(libraries); + monitoringService.registerLibraries(libraries); log.info("Monitoring initialized with {} libraries", libraries.size()); } @@ -112,14 +112,9 @@ public class LibraryService { LibraryEntity savedLibrary = libraryRepository.save(library); if (request.isWatch()) { - for (LibraryPathEntity pathEntity : savedLibrary.getLibraryPaths()) { - Path path = Paths.get(pathEntity.getPath()); - monitoringService.registerPath(path, libraryId); - } + monitoringService.registerLibraries(List.of(libraryMapper.toLibrary(savedLibrary))); } else { - for (LibraryPathEntity pathEntity : savedLibrary.getLibraryPaths()) { - monitoringService.unregisterPath(pathEntity.getPath()); - } + monitoringService.unregisterLibrary(libraryId); } if (!newPaths.isEmpty()) { @@ -212,7 +207,7 @@ public class LibraryService { LibraryEntity library = libraryRepository.findById(id).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id)); library.getLibraryPaths().forEach(libraryPath -> { Path path = Paths.get(libraryPath.getPath()); - monitoringService.unregisterPath(path.toString()); + monitoringService.unregisterLibrary(id); }); Set bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet()); fileProcessingUtils.deleteBookCovers(bookIds); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index f1401d835..5405eee81 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -16,6 +16,7 @@ import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupR import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; import com.adityachandel.booklore.util.FileService; +import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.MetadataChangeDetector; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -113,6 +114,8 @@ public class BookMetadataUpdater { File file = new File(bookEntity.getFullFilePath().toUri()); writer.writeMetadataToFile(file, metadata, thumbnailUrl, false, clearFlags); + String newHash = FileUtils.computeFileHash(bookEntity); + bookEntity.setCurrentHash(newHash); log.info("Metadata written for book ID {}", bookId); } catch (Exception e) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/backuprestore/EpubMetadataBackupRestoreService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/backuprestore/EpubMetadataBackupRestoreService.java index 6f37ea8af..6275fe6ff 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/backuprestore/EpubMetadataBackupRestoreService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/backuprestore/EpubMetadataBackupRestoreService.java @@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.documentnode.epub4j.domain.Book; import io.documentnode.epub4j.domain.Resource; import io.documentnode.epub4j.epub.EpubReader; -import io.documentnode.epub4j.epub.EpubWriter; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.FileSystemResource; import org.springframework.stereotype.Service; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java index 110646168..dce70fe01 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -16,6 +16,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.InputStream; import java.time.LocalDate; +import java.time.OffsetDateTime; import java.util.HashSet; import java.util.Set; @@ -86,11 +87,8 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } case "date" -> { - try { - builderMeta.publishedDate(LocalDate.parse(text)); - } catch (Exception e) { - log.warn("Invalid date format in OPF: {}", text); - } + LocalDate parsed = parseDate(text); + if (parsed != null) builderMeta.publishedDate(parsed); } case "meta" -> { String name = el.getAttribute("name").trim().toLowerCase(); @@ -112,10 +110,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } if (name.equals("calibre:pages") || name.equals("pagecount") || prop.equals("schema:pagecount") || prop.equals("media:pagecount") || prop.equals("booklore:page_count")) { - try { - builderMeta.pageCount(Integer.parseInt(content)); - } catch (NumberFormatException ignored) { - } + safeParseInt(content, builderMeta::pageCount); } if (name.equals("calibre:rating") || prop.equals("booklore:personal_rating")) { @@ -133,6 +128,23 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } + if (builderMeta.build().getPublishedDate() == null) { + for (int i = 0; i < children.getLength(); i++) { + if (!(children.item(i) instanceof Element el)) continue; + if (!"meta".equals(el.getLocalName())) continue; + + String prop = el.getAttribute("property").trim().toLowerCase(); + String content = el.hasAttribute("content") ? el.getAttribute("content").trim() : el.getTextContent().trim(); + if ("dcterms:modified".equals(prop)) { + LocalDate parsed = parseDate(content); + if (parsed != null) { + builderMeta.publishedDate(parsed); + break; + } + } + } + } + builderMeta.authors(authors); builderMeta.categories(categories); return builderMeta.build(); @@ -158,4 +170,26 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } catch (NumberFormatException ignored) { } } + + private LocalDate parseDate(String value) { + if (StringUtils.isBlank(value)) return null; + + try { + return LocalDate.parse(value); + } catch (Exception ignored) { + } + + try { + return OffsetDateTime.parse(value).toLocalDate(); + } catch (Exception ignored) { + } + + try { + return LocalDate.parse(value.substring(0, 10)); // fallback to prefix + } catch (Exception ignored) { + } + + log.warn("Failed to parse date from string: {}", value); + return null; + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedCbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedCbxMetadataExtractor.java deleted file mode 100644 index 6a1f6c916..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedCbxMetadataExtractor.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.adityachandel.booklore.service.metadata.upload.extractor; - -import com.adityachandel.booklore.model.UploadedFileMetadata; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.FilenameUtils; -import org.springframework.stereotype.Service; - -@Slf4j -@Service -public class UploadedCbxMetadataExtractor implements UploadedFileMetadataExtractor { - - @Override - public UploadedFileMetadata extractMetadata(String filePath) { - UploadedFileMetadata metadata = new UploadedFileMetadata(); - String title = FilenameUtils.getBaseName(filePath); - metadata.setTitle(title); - return metadata; - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedEpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedEpubMetadataExtractor.java deleted file mode 100644 index c69f7d70e..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedEpubMetadataExtractor.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.adityachandel.booklore.service.metadata.upload.extractor; - -import com.adityachandel.booklore.model.UploadedFileMetadata; -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.commons.io.FilenameUtils; -import org.springframework.stereotype.Service; - -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 UploadedEpubMetadataExtractor implements UploadedFileMetadataExtractor { - - @Override - public UploadedFileMetadata extractMetadata(String filePath) { - UploadedFileMetadata metadata = new UploadedFileMetadata(); - - try (FileInputStream fis = new FileInputStream(filePath)) { - Book epub = new EpubReader().readEpub(fis); - - String title = epub.getTitle(); - if (title != null && !title.isBlank()) { - metadata.setTitle(title); - } else { - metadata.setTitle(FilenameUtils.getBaseName(filePath)); - } - - List epubAuthors = epub.getMetadata().getAuthors(); - if (!epubAuthors.isEmpty()) { - Set 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; - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedFileMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedFileMetadataExtractor.java deleted file mode 100644 index 223aa9eb0..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedFileMetadataExtractor.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.adityachandel.booklore.service.metadata.upload.extractor; - -import com.adityachandel.booklore.model.UploadedFileMetadata; - -public interface UploadedFileMetadataExtractor { - - UploadedFileMetadata extractMetadata(String filePath); -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedPdfMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedPdfMetadataExtractor.java deleted file mode 100644 index 2cc3dae53..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/upload/extractor/UploadedPdfMetadataExtractor.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.adityachandel.booklore.service.metadata.upload.extractor; - -import com.adityachandel.booklore.model.UploadedFileMetadata; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.FilenameUtils; -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 UploadedPdfMetadataExtractor implements UploadedFileMetadataExtractor { - - @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()); - } else { - metadata.setTitle(FilenameUtils.getBaseName(filePath)); - } - 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; - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java index 8c4832916..c567a0756 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java @@ -63,4 +63,34 @@ public class AppMigrationService { log.info("Migration 'populateMetadataScores' applied to {} books.", books.size()); migrationRepository.save(new AppMigrationEntity("populateMetadataScores", LocalDateTime.now(), "Calculate and store metadata match score for all books")); } + + @Transactional + public void populateFileHashesOnce() { + if (migrationRepository.existsById("populateFileHashes")) return; + + List books = bookRepository.findAll(); + int updated = 0; + + for (BookEntity book : books) { + if (book.getCurrentHash() == null || book.getInitialHash() == null) { + String hash = FileUtils.computeFileHash(book); + if (hash != null) { + if (book.getInitialHash() == null) { + book.setInitialHash(hash); + } + book.setCurrentHash(hash); + updated++; + } + } + } + + bookRepository.saveAll(books); + + log.info("Migration 'populateFileHashes' applied to {} books.", updated); + migrationRepository.save(new AppMigrationEntity( + "populateFileHashes", + LocalDateTime.now(), + "Calculate and store initialHash and currentHash for all books" + )); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java index 540648ed0..6c82ef69c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java @@ -15,5 +15,6 @@ public class AppMigrationStartup { public void runMigrationsOnce() { appMigrationService.populateMissingFileSizesOnce(); appMigrationService.populateMetadataScoresOnce(); + appMigrationService.populateFileHashesOnce(); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/DirectoryCreateEvent.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/DirectoryCreateEvent.java new file mode 100644 index 000000000..0fbc4dd76 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/DirectoryCreateEvent.java @@ -0,0 +1,16 @@ +package com.adityachandel.booklore.service.monitoring; + +import lombok.Getter; +import org.springframework.context.ApplicationEvent; + +import java.nio.file.Path; + +@Getter +public class DirectoryCreateEvent extends ApplicationEvent { + private final Path newDirectory; + + public DirectoryCreateEvent(Object source, Path newDirectory) { + super(source); + this.newDirectory = newDirectory; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java index 72731b96e..96cf6cf06 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java @@ -1,10 +1,10 @@ package com.adityachandel.booklore.service.monitoring; import com.adityachandel.booklore.model.dto.Library; -import com.adityachandel.booklore.service.library.LibraryProcessingService; +import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.service.watcher.LibraryFileEventProcessor; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.dao.InvalidDataAccessApiUsageException; @@ -12,91 +12,270 @@ import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.file.*; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; @Slf4j @Service -@AllArgsConstructor public class MonitoringService { - private final LibraryProcessingService libraryProcessingService; + private final LibraryFileEventProcessor libraryFileEventProcessor; private final WatchService watchService; private final MonitoringTask monitoringTask; - private final Set monitoredPaths = ConcurrentHashMap.newKeySet(); - private final Map pathToLibraryIdMap = new ConcurrentHashMap<>(); - private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); + private final Set monitoredPaths = ConcurrentHashMap.newKeySet(); + private final Map pathToLibraryIdMap = new ConcurrentHashMap<>(); + private final Map libraryWatchStatusMap = new ConcurrentHashMap<>(); + private final Map registeredWatchKeys = new ConcurrentHashMap<>(); + private final Map> libraryIdToPaths = new ConcurrentHashMap<>(); + + private int pauseCount = 0; + private final Object pauseLock = new Object(); + + public MonitoringService( + LibraryFileEventProcessor libraryFileEventProcessor, + WatchService watchService, + MonitoringTask monitoringTask + ) { + this.libraryFileEventProcessor = libraryFileEventProcessor; + this.watchService = watchService; + this.monitoringTask = monitoringTask; + } + @PostConstruct public void initializeMonitoring() { monitoringTask.monitor(); startProcessingThread(); } - public void registerLibrariesForMonitoring(List libraries) { - libraries.stream() - .filter(Library::isWatch) - .forEach(library -> { - library.getPaths().forEach(libraryPath -> { - Path path = Paths.get(libraryPath.getPath()); - if (Files.isDirectory(path)) { - registerPath(path, library.getId()); - } - }); - }); - log.info("Registered libraries for monitoring: {}", libraries.size()); + @PreDestroy + public void stopMonitoring() { + log.info("Shutting down monitoring service..."); + singleThreadExecutor.shutdownNow(); + try { + watchService.close(); + } catch (IOException e) { + log.error("Failed to close WatchService", e); + } } - public synchronized void registerPath(Path path, Long libraryId) { + public synchronized void pauseMonitoring() { + pauseCount++; + if (pauseCount == 1) { + int count = 0; + for (Path path : new HashSet<>(monitoredPaths)) { + unregisterPath(path, false); + count++; + } + log.info("Monitoring paused ({} paths unregistered, pauseCount={})", count, pauseCount); + } else { + log.info("Monitoring pause requested (pauseCount={})", pauseCount); + } + } + + public synchronized void resumeMonitoring() { + if (pauseCount == 0) { + log.warn("resumeMonitoring() called but monitoring is not paused"); + return; + } + + pauseCount--; + if (pauseCount == 0) { + libraryIdToPaths.forEach((libraryId, rootPaths) -> { + for (Path rootPath : rootPaths) { + if (Files.exists(rootPath)) { + try (Stream stream = Files.walk(rootPath)) { + stream.filter(Files::isDirectory).forEach(path -> { + if (Files.exists(path)) { + registerPath(path, libraryId); + } + }); + } catch (IOException e) { + log.warn("Failed to walk path during resume: {}", rootPath, e); + } + } else { + log.debug("Skipping registration of non-existent path during resume: {}", rootPath); + } + } + }); + + synchronized (pauseLock) { + pauseLock.notifyAll(); + } + + log.info("Monitoring resumed"); + } else { + log.info("Monitoring resume requested (pauseCount={}), monitoring still paused", pauseCount); + } + } + + public synchronized boolean isPaused() { + return pauseCount > 0; + } + + public void registerLibraries(List libraries) { + libraries.forEach(lib -> libraryWatchStatusMap.put(lib.getId(), lib.isWatch())); + libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary); + log.info("Registered {} libraries for recursive monitoring", libraries.size()); + } + + public void registerLibrary(Library library) { + libraryWatchStatusMap.put(library.getId(), library.isWatch()); + if (!library.isWatch()) return; + + List registeredPaths = new ArrayList<>(); + int[] registeredCount = {0}; + + library.getPaths().forEach(libraryPath -> { + Path rootPath = Paths.get(libraryPath.getPath()); + if (Files.isDirectory(rootPath)) { + try (Stream pathStream = Files.walk(rootPath)) { + pathStream.filter(Files::isDirectory).forEach(path -> { + if (registerPath(path, library.getId())) { + registeredCount[0]++; + registeredPaths.add(path); + } + }); + } catch (IOException e) { + log.error("Failed to register paths for library '{}': {}", library.getName(), e.getMessage(), e); + } + } + }); + + libraryIdToPaths.put(library.getId(), registeredPaths); + log.info("Registered {} folders for library '{}'", registeredCount[0], library.getName()); + } + + public void unregisterLibrary(Long libraryId) { + Set pathsToRemove = pathToLibraryIdMap.entrySet().stream() + .filter(entry -> entry.getValue().equals(libraryId)) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + + for (Path path : pathsToRemove) { + unregisterPath(path); + } + + libraryWatchStatusMap.put(libraryId, false); + libraryIdToPaths.remove(libraryId); + log.info("Unregistered library {} from monitoring", libraryId); + } + + public void unregisterLibraries(Set libraryIds) { + libraryIds.forEach(this::unregisterLibrary); + } + + public boolean isLibraryWatched(Long libraryId) { + return libraryWatchStatusMap.getOrDefault(libraryId, false); + } + + public boolean isRelevantBookFile(Path path) { + return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent(); + } + + public synchronized boolean registerPath(Path path, Long libraryId) { try { if (monitoredPaths.add(path)) { - path.register(watchService, + WatchKey key = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); + registeredWatchKeys.put(path, key); pathToLibraryIdMap.put(path, libraryId); - log.info("Registered folder for monitoring: {} (Library ID: {})", path, libraryId); - } else { - log.warn("Path is already registered: {}", path); + return true; } } catch (IOException e) { log.error("Error registering path: {}", path, e); } + return false; } - public synchronized void unregisterPath(String folderPath) { - Path path = Paths.get(folderPath); + public synchronized void unregisterPath(Path path) { + unregisterPath(path, true); + } + + public synchronized void unregisterPath(Path path, boolean logUnregister) { if (monitoredPaths.remove(path)) { + WatchKey key = registeredWatchKeys.remove(path); + if (key != null) key.cancel(); pathToLibraryIdMap.remove(path); - log.info("Unregistered folder from monitoring: {}", folderPath); - } else { - log.warn("Folder not found in monitored paths: {}", folderPath); + if (logUnregister) { + log.info("Unregistered path: {}", path); + } } } @EventListener public void handleFileChangeEvent(FileChangeEvent event) { + Path fullPath = event.getFilePath(); + WatchEvent.Kind kind = event.getEventKind(); + + if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE) return; + + boolean isDir = kind == StandardWatchEventKinds.ENTRY_CREATE + ? Files.isDirectory(fullPath) + : monitoredPaths.contains(fullPath); + + boolean isRelevantFile = isRelevantBookFile(fullPath); + if (!(isDir || isRelevantFile)) return; + + if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) { + Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder()); + if (parentLibraryId != null) { + try (Stream stream = Files.walk(fullPath)) { + stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId)); + } catch (IOException e) { + log.warn("Failed to register nested paths: {}", fullPath, e); + } + } + } + + if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) { + unregisterSubPaths(fullPath); + } + if (!eventQueue.offer(event)) { - log.warn("Event queue is full, dropping event: {}", event.getFilePath()); + log.warn("Event queue full, dropping: {}", fullPath); } else { - log.debug("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size()); + log.debug("Queued: {} [{}]", fullPath, kind.name()); + } + } + + @EventListener + public void handleWatchKeyInvalidation(WatchKeyInvalidatedEvent event) { + Path invalidPath = event.getInvalidPath(); + if (monitoredPaths.remove(invalidPath)) { + log.warn("Removing invalid path from monitoring: {}", invalidPath); + pathToLibraryIdMap.remove(invalidPath); + WatchKey key = registeredWatchKeys.remove(invalidPath); + if (key != null) key.cancel(); } } private void startProcessingThread() { + log.info("Starting file change processor..."); singleThreadExecutor.submit(() -> { while (!Thread.currentThread().isInterrupted()) { try { + synchronized (pauseLock) { + while (isPaused()) { + pauseLock.wait(); + } + } + FileChangeEvent event = eventQueue.take(); processFileChangeEvent(event); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; + } catch (Exception e) { + log.error("Error in processing thread", e); } } }); @@ -109,26 +288,24 @@ public class MonitoringService { if (libraryId != null) { try { - libraryProcessingService.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString()); + libraryFileEventProcessor.processFile( + event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString() + ); } catch (InvalidDataAccessApiUsageException e) { - log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId); + log.debug("InvalidDataAccessApiUsageException for libraryId={}", libraryId); } - log.debug("Processed file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind()); } else { - log.warn("No libraryId found for watched folder: {}", watchedFolder); + log.warn("No library ID found for folder: {}", watchedFolder); } } - @PreDestroy - public void stopMonitoring() { - log.info("Shutting down monitoring service..."); - singleThreadExecutor.shutdownNow(); - if (watchService != null) { - try { - watchService.close(); - } catch (IOException e) { - log.error("Exception while closing the WatchService", e); - } + private void unregisterSubPaths(Path deletedPath) { + Set toRemove = monitoredPaths.stream() + .filter(p -> p.startsWith(deletedPath)) + .collect(Collectors.toSet()); + + for (Path path : toRemove) { + unregisterPath(path); } } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java index 7c4cf65f5..06c15cc47 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java @@ -16,9 +16,6 @@ public class MonitoringTask { private final WatchService watchService; private final ApplicationEventPublisher eventPublisher; - private static final String PDF_EXTENSION = ".pdf"; - private static final String EPUB_EXTENSION = ".epub"; - @Async public void monitor() { try { @@ -30,24 +27,26 @@ public class MonitoringTask { log.warn("WatchService has been closed. Stopping monitoring."); break; } - if (key == null) { - continue; - } + + if (key == null) continue; + + Path directory = (Path) key.watchable(); + for (WatchEvent event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); - Path fileName = (Path) event.context(); - Path directory = (Path) key.watchable(); - Path fullPath = directory.resolve(fileName); + if (kind == StandardWatchEventKinds.OVERFLOW) continue; - if (isPdfOrEpub(fileName) && (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE)) { - log.debug("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory); - eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory)); - } + Path fileName = (Path) event.context(); + Path fullPath = directory.resolve(fileName); + eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory)); } + boolean valid = key.reset(); if (!valid) { - log.warn("WatchKey is no longer valid. Stopping monitoring for {}", key.watchable()); - break; + log.warn("WatchKey is no longer valid: {}", directory); + // Clean up but DO NOT break + eventPublisher.publishEvent(new WatchKeyInvalidatedEvent(this, directory)); + continue; } } } catch (InterruptedException e) { @@ -55,9 +54,4 @@ public class MonitoringTask { Thread.currentThread().interrupt(); } } - - private boolean isPdfOrEpub(Path fileName) { - String fileNameStr = fileName.toString().toLowerCase(); - return fileNameStr.endsWith(PDF_EXTENSION) || fileNameStr.endsWith(EPUB_EXTENSION); - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/WatchKeyInvalidatedEvent.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/WatchKeyInvalidatedEvent.java new file mode 100644 index 000000000..82a03def6 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/WatchKeyInvalidatedEvent.java @@ -0,0 +1,16 @@ +package com.adityachandel.booklore.service.monitoring; + +import lombok.Getter; +import org.springframework.context.ApplicationEvent; + +import java.nio.file.Path; + +@Getter +public class WatchKeyInvalidatedEvent extends ApplicationEvent { + private final Path invalidPath; + + public WatchKeyInvalidatedEvent(Object source, Path invalidPath) { + super(source); + this.invalidPath = invalidPath; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/DeletedBooksCleanupService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/DeletedBooksCleanupService.java new file mode 100644 index 000000000..bf2859023 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/DeletedBooksCleanupService.java @@ -0,0 +1,25 @@ +package com.adityachandel.booklore.service.scheduler; + +import com.adityachandel.booklore.repository.BookRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class DeletedBooksCleanupService { + + private final BookRepository bookRepository; + + @Scheduled(cron = "0 0 0 * * MON") // At 00:00 every Monday + public void cleanupDeletedBooks() { + Instant cutoff = Instant.now().minus(7, ChronoUnit.DAYS); + int deletedCount = bookRepository.deleteAllByDeletedAtBefore(cutoff); + log.info("DeletedBooksCleanupService: Removed {} deleted books older than {}", deletedCount, cutoff); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/LibraryRescanScheduler.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/LibraryRescanScheduler.java new file mode 100644 index 000000000..10b3e83b0 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/scheduler/LibraryRescanScheduler.java @@ -0,0 +1,30 @@ +package com.adityachandel.booklore.service.scheduler; + +import com.adityachandel.booklore.model.dto.Library; +import com.adityachandel.booklore.service.library.LibraryService; +import lombok.AllArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@AllArgsConstructor +public class LibraryRescanScheduler { + + private final LibraryService libraryService; + + @Scheduled(cron = "0 0 0 * * *") // At 00:00 every day + public void rescanLibraries() { + log.info("Starting scheduled library rescan at midnight"); + for (Library library : libraryService.getLibraries()) { + try { + libraryService.rescanLibrary(library.getId()); + log.info("Rescanned library '{}'", library.getName()); + } catch (Exception e) { + log.error("Failed to rescan library '{}': {}", library.getName(), e.getMessage(), e); + } + } + log.info("Completed scheduled library rescan"); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java index 6381e2538..a8b649fc1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java @@ -1,22 +1,25 @@ package com.adityachandel.booklore.service.upload; import com.adityachandel.booklore.exception.ApiError; -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.BookFileExtension; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.LibraryRepository; -import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; -import com.adityachandel.booklore.service.metadata.upload.extractor.UploadedEpubMetadataExtractor; -import com.adityachandel.booklore.service.metadata.upload.extractor.UploadedPdfMetadataExtractor; +import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; +import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; +import com.adityachandel.booklore.service.monitoring.MonitoringService; import com.adityachandel.booklore.util.FileUtils; +import com.adityachandel.booklore.util.PathPatternResolver; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -28,33 +31,21 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; -import java.util.Optional; -import java.util.Set; @RequiredArgsConstructor @Service @Slf4j public class FileUploadService { - private static final String PDF_MIME_TYPE = "application/pdf"; - private static final String EPUB_MIME_TYPE = "application/epub+zip"; - private static final String CBZ_MIME_TYPE = "application/x-cbz"; - private static final String CBR_MIME_TYPE = "application/x-cbr"; - private static final String CB7_MIME_TYPE = "application/x-cb7"; - private static final Set SUPPORTED_MIME_TYPES = Set.of( - PDF_MIME_TYPE, EPUB_MIME_TYPE, - CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE, - "application/octet-stream" - ); - private final LibraryRepository libraryRepository; private final PdfProcessor pdfProcessor; private final EpubProcessor epubProcessor; private final CbxProcessor cbxProcessor; private final NotificationService notificationService; private final AppSettingService appSettingService; - private final UploadedPdfMetadataExtractor uploadedPdfMetadataExtractor; - private final UploadedEpubMetadataExtractor uploadedEpubMetadataExtractor; + private final PdfMetadataExtractor pdfMetadataExtractor; + private final EpubMetadataExtractor epubMetadataExtractor; + private final MonitoringService monitoringService; public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException { validateFile(file); @@ -69,16 +60,27 @@ public class FileUploadService { .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename())); + Book book; + + boolean wePaused = false; + if (!monitoringService.isPaused()) { + monitoringService.pauseMonitoring(); + wePaused = true; + } + try { file.transferTo(tempPath); - UploadedFileMetadata metadata = extractMetadata(file.getContentType(), tempPath); + BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension")); - String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim(); - String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : ""; + BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile()); String uploadPattern = appSettingService.getAppSettings().getUploadPattern(); - String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename()); + if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) { + uploadPattern += "{currentFilename}"; + } + + String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename()); Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath); File finalFile = finalPath.toFile(); @@ -92,34 +94,43 @@ public class FileUploadService { log.info("File uploaded to final location: {}", finalPath); - Book book = processFile(file, libraryEntity, libraryPathEntity, finalFile); + book = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType()); notificationService.sendMessage(Topic.BOOK_ADD, book); - log.info("Book processed successfully: {}", book.getMetadata().getTitle()); + return book; } catch (IOException e) { throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); } finally { Files.deleteIfExists(tempPath); + + if (wePaused) { + Thread.startVirtualThread(() -> { + try { + Thread.sleep(5_000); + monitoringService.resumeMonitoring(); + log.info("Monitoring resumed after 5s delay"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.warn("Interrupted while delaying resume of monitoring"); + } + }); + } } } - private UploadedFileMetadata extractMetadata(String contentType, Path tempPath) throws IOException { - if (contentType == null) { - throw ApiError.INVALID_FILE_FORMAT.createException("Content type is null."); - } - return switch (contentType.toLowerCase()) { - case PDF_MIME_TYPE -> uploadedPdfMetadataExtractor.extractMetadata(tempPath.toString()); - case EPUB_MIME_TYPE -> uploadedEpubMetadataExtractor.extractMetadata(tempPath.toString()); - case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE, "application/octet-stream" -> new UploadedFileMetadata(); - default -> throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type."); + private BookMetadata extractMetadata(BookFileExtension fileExt, File file) throws IOException { + return switch (fileExt) { + case PDF -> pdfMetadataExtractor.extractMetadata(file); + case EPUB -> epubMetadataExtractor.extractMetadata(file); + case CBZ, CBR, CB7 -> new BookMetadata(); }; } private void validateFile(MultipartFile file) { - String fileType = file.getContentType(); - if (!SUPPORTED_MIME_TYPES.contains(fileType)) { - throw ApiError.INVALID_FILE_FORMAT.createException(); + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || BookFileExtension.fromFileName(originalFilename).isEmpty()) { + throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"); } int maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb(); if (file.getSize() > maxSizeMb * 1024L * 1024L) { @@ -127,12 +138,7 @@ public class FileUploadService { } } - private Book processFile(MultipartFile file, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile) { - BookFileType fileType = determineFileType(Objects.requireNonNull(file.getContentType())); - if (fileType == null) { - throw ApiError.INVALID_FILE_FORMAT.createException(); - } - + private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType fileType) { String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath()); LibraryFile libraryFile = LibraryFile.builder() @@ -140,7 +146,7 @@ public class FileUploadService { .libraryPathEntity(libraryPathEntity) .fileSubPath(subPath) .bookFileType(fileType) - .fileName(file.getOriginalFilename()) + .fileName(fileName) .build(); return switch (fileType) { @@ -150,36 +156,4 @@ public class FileUploadService { }; } - 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) { - return switch (fileType.toLowerCase()) { - case PDF_MIME_TYPE -> BookFileType.PDF; - case EPUB_MIME_TYPE -> BookFileType.EPUB; - case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE, "application/octet-stream" -> BookFileType.CBX; - default -> null; - }; - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java new file mode 100644 index 000000000..4ea265429 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java @@ -0,0 +1,101 @@ +package com.adityachandel.booklore.service.watcher; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.util.FileUtils; +import jakarta.persistence.EntityManager; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Instant; +import java.util.*; + +@Slf4j +@Service +@AllArgsConstructor +public class BookFilePersistenceService { + + private final EntityManager entityManager; + private final BookRepository bookRepository; + private final NotificationService notificationService; + private final BookMapper bookMapper; + + @Transactional + public void updatePathIfChanged(BookEntity book, LibraryEntity libraryEntity, Path path, String currentHash) { + LibraryPathEntity newLibraryPath = getLibraryPathEntityForFile(libraryEntity, path.toString()); + newLibraryPath = entityManager.merge(newLibraryPath); + + String newSubPath = FileUtils.getRelativeSubPath(newLibraryPath.getPath(), path); + + boolean pathChanged = !Objects.equals(newSubPath, book.getFileSubPath()) || !Objects.equals(newLibraryPath.getId(), book.getLibraryPath().getId()); + + if (pathChanged) { + book.setLibraryPath(newLibraryPath); + book.setFileSubPath(newSubPath); + book.setDeleted(false); + bookRepository.save(book); + log.info("[FILE_CREATE] Updated path for existing book with hash '{}': '{}'", currentHash, path); + } else { + log.info("[FILE_CREATE] Book with hash '{}' already exists at same path. Skipping update.", currentHash); + } + notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false)); + } + + @Transactional(readOnly = true) + public Optional findByHash(String hash) { + return bookRepository.findByCurrentHash(hash); + } + + String findMatchingLibraryPath(LibraryEntity libraryEntity, Path filePath) { + return libraryEntity.getLibraryPaths().stream() + .map(lp -> Paths.get(lp.getPath()).toAbsolutePath().normalize()) + .filter(base -> filePath.toAbsolutePath().normalize().startsWith(base)) + .map(Path::toString) + .findFirst() + .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException("No matching libraryPath for: " + filePath)); + } + + LibraryPathEntity getLibraryPathEntityForFile(LibraryEntity libraryEntity, String inputPath) { + Path fullPath = Paths.get(inputPath).toAbsolutePath().normalize(); + return libraryEntity.getLibraryPaths().stream() + .map(lp -> Map.entry(lp, Paths.get(lp.getPath()).toAbsolutePath().normalize())) + .filter(entry -> fullPath.startsWith(entry.getValue())) + .max(Comparator.comparingInt(entry -> entry.getValue().getNameCount())) + .map(Map.Entry::getKey) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(inputPath)); + } + + @Transactional + public int markAllBooksUnderPathAsDeleted(long libraryPathId, String relativeFolderPath) { + String normalizedPrefix = relativeFolderPath.endsWith("/") ? relativeFolderPath : (relativeFolderPath + "/"); + + List books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, normalizedPrefix); + books.forEach(book -> { + book.setDeleted(true); + book.setDeletedAt(Instant.now()); + }); + + bookRepository.saveAll(books); + return books.size(); + } + + @Transactional(readOnly = true) + public Optional findByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) { + return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName); + } + + @Transactional + public void save(BookEntity book) { + bookRepository.save(book); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java new file mode 100644 index 000000000..023ddc127 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java @@ -0,0 +1,70 @@ +package com.adityachandel.booklore.service.watcher; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.LibraryRepository; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.library.LibraryProcessingService; +import com.adityachandel.booklore.util.FileUtils; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; + +import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification; + +@Slf4j +@Service +@RequiredArgsConstructor +public class BookFileTransactionalHandler { + + private final BookFilePersistenceService bookFilePersistenceService; + private final LibraryProcessingService libraryProcessingService; + private final NotificationService notificationService; + private final LibraryRepository libraryRepository; + + @Transactional() + public void handleNewBookFile(long libraryId, Path path, String currentHash) { + LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); + + Optional existingOpt = bookFilePersistenceService.findByHash(currentHash); + if (existingOpt.isPresent()) { + BookEntity existingBook = existingOpt.get(); + bookFilePersistenceService.updatePathIfChanged(existingBook, libraryEntity, path, currentHash); + return; + } + + String filePath = path.toString(); + String fileName = path.getFileName().toString(); + String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(libraryEntity, path); + + notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); + + LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath); + + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path)) + .fileName(fileName) + .bookFileType(BookFileExtension.fromFileName(fileName) + .map(BookFileExtension::getType) + .orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName))) + .build(); + + libraryProcessingService.processLibraryFiles(List.of(libraryFile)); + + notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); + log.info("[CREATE] Completed processing for file '{}'", filePath); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java new file mode 100644 index 000000000..c01e9213e --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java @@ -0,0 +1,173 @@ +package com.adityachandel.booklore.service.watcher; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.LibraryRepository; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.util.FileUtils; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.*; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.*; + +@Slf4j +@Service +@AllArgsConstructor +public class LibraryFileEventProcessor { + + private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final LibraryRepository libraryRepository; + private final BookFileTransactionalHandler bookFileTransactionalHandler; + private final BookFilePersistenceService bookFilePersistenceService; + private final NotificationService notificationService; + + @PostConstruct + public void init() { + Thread.ofVirtual().start(() -> { + log.info("LibraryFileEventProcessor virtual thread started."); + while (!Thread.currentThread().isInterrupted()) { + try { + handleEvent(eventQueue.take()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.warn("LibraryFileEventProcessor virtual thread interrupted."); + } catch (Exception e) { + log.error("Error while processing file event", e); + } + } + }); + } + + public void processFile(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { + eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath)); + } + + private void handleEvent(FileEvent event) { + Path path = Paths.get(event.filePath()); + String fileName = path.getFileName().toString(); + log.info("[PROCESS] '{}' event for '{}'", event.eventKind().name(), fileName); + + LibraryEntity library = libraryRepository.findById(event.libraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId())); + + if (library.getLibraryPaths().stream().noneMatch(lp -> path.toString().startsWith(lp.getPath()))) { + log.warn("[SKIP] Path outside of library: '{}'", path); + return; + } + + if (isFolder(path)) { + switch (event.eventKind().name()) { + case "ENTRY_CREATE" -> handleFolderCreate(library, path); + case "ENTRY_DELETE" -> handleFolderDelete(library, path); + default -> log.warn("[SKIP] Folder event '{}' ignored for '{}'", event.eventKind().name(), fileName); + } + return; + } + + if (!isBookFile(fileName)) { + log.debug("[SKIP] Ignored non-book file '{}'", fileName); + return; + } + + switch (event.eventKind().name()) { + case "ENTRY_CREATE" -> handleFileCreate(library, path); + case "ENTRY_DELETE" -> handleFileDelete(library, path); + default -> log.debug("[SKIP] File event '{}' ignored for '{}'", event.eventKind().name(), fileName); + } + } + + private void handleFileCreate(LibraryEntity library, Path path) { + log.info("[FILE_CREATE] '{}'", path); + String hash = FileUtils.computeFileHash(path); + if (hash == null) { + log.warn("[SKIP] Unable to compute hash for '{}'", path); + return; + } + bookFileTransactionalHandler.handleNewBookFile(library.getId(), path, hash); + } + + private void handleFileDelete(LibraryEntity library, Path path) { + log.info("[FILE_DELETE] '{}'", path); + try { + String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, path); + LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath); + + Path relPath = Paths.get(libPathEntity.getPath()).relativize(path.toAbsolutePath().normalize()); + String fileName = relPath.getFileName().toString(); + String fileSubPath = Optional.ofNullable(relPath.getParent()).map(Path::toString).orElse(""); + + bookFilePersistenceService.findByLibraryPathSubPathAndFileName(libPathEntity.getId(), fileSubPath, fileName) + .ifPresentOrElse(book -> { + book.setDeleted(true); + bookFilePersistenceService.save(book); + notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(book.getId())); + log.info("[MARKED_DELETED] Book '{}' marked as deleted", fileName); + }, () -> log.warn("[NOT_FOUND] Book for deleted path '{}' not found", path)); + + } catch (Exception e) { + log.warn("[ERROR] While handling file delete '{}': {}", path, e.getMessage()); + } + } + + private void handleFolderCreate(LibraryEntity library, Path folderPath) { + log.info("[FOLDER_CREATE] '{}'", folderPath); + try (var stream = Files.walk(folderPath)) { + stream.filter(Files::isRegularFile) + .filter(p -> isBookFile(p.getFileName().toString())) + .forEach(p -> { + try { + String hash = FileUtils.computeFileHash(p); + if (hash != null) { + bookFileTransactionalHandler.handleNewBookFile(library.getId(), p, hash); + } + } catch (Exception e) { + log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage()); + } + }); + } catch (IOException e) { + log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + } + } + + private void handleFolderDelete(LibraryEntity library, Path folderPath) { + log.info("[FOLDER_DELETE] '{}'", folderPath); + try { + String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath); + LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath); + + String relativePrefix = FileUtils.getRelativeSubPath(libPathEntity.getPath(), folderPath); + int count = bookFilePersistenceService.markAllBooksUnderPathAsDeleted(libPathEntity.getId(), relativePrefix); + log.info("[MARKED_DELETED] {} books under '{}'", count, folderPath); + } catch (Exception e) { + log.warn("[ERROR] Folder delete '{}': {}", folderPath, e.getMessage()); + } + } + + private boolean isFolder(Path path) { + return !path.getFileName().toString().contains("."); + } + + private boolean isBookFile(String fileName) { + return BookFileExtension.fromFileName(fileName).isPresent(); + } + + @PreDestroy + public void shutdown() { + worker.shutdownNow(); + log.info("LibraryFileEventProcessor worker shutdown."); + } + + public record FileEvent(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index a997634e2..9fae29f9e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -5,9 +5,13 @@ import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; +import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Comparator; +import java.util.HexFormat; import java.util.Optional; @Slf4j @@ -57,4 +61,46 @@ public class FileUtils { .forEach(File::delete); } } + + public static String computeFileHash(Path path) { + try { + return computeSHA256HeadAndTail(path, 64 * 1024); + } catch (Exception e) { + log.warn("Failed to compute hash for file '{}': {}", path, e.getMessage()); + return null; + } + } + + public static String computeFileHash(BookEntity book) { + try { + Path filePath = book.getFullFilePath(); + return computeSHA256HeadAndTail(filePath, 64 * 1024); + } catch (Exception e) { + log.warn("Failed to compute hash for book '{}': {}", book.getFileName(), e.getMessage()); + return null; + } + } + + public static String computeSHA256HeadAndTail(Path path, int sampleSize) throws IOException, NoSuchAlgorithmException { + long fileSize = Files.size(path); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + + try (RandomAccessFile raf = new RandomAccessFile(path.toFile(), "r")) { + + byte[] startBytes = new byte[(int) Math.min(sampleSize, fileSize)]; + raf.seek(0); + raf.readFully(startBytes); + digest.update(startBytes); + + if (fileSize > sampleSize) { + byte[] endBytes = new byte[(int) Math.min(sampleSize, fileSize)]; + raf.seek(fileSize - sampleSize); + raf.readFully(endBytes); + digest.update(endBytes); + } + } + + byte[] hashBytes = digest.digest(); + return HexFormat.of().formatHex(hashBytes); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java new file mode 100644 index 000000000..f34db86cb --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java @@ -0,0 +1,211 @@ +package com.adityachandel.booklore.util; + +import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.entity.AuthorEntity; +import com.adityachandel.booklore.model.entity.BookEntity; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class PathPatternResolver { + + public static String resolvePattern(BookEntity book, String pattern) { + String currentFilename = book.getFileName() != null ? book.getFileName().trim() : ""; + + if (pattern == null || pattern.isBlank()) { + return currentFilename; + } + + String title = sanitize(book.getMetadata() != null && book.getMetadata().getTitle() != null + ? book.getMetadata().getTitle() + : "Untitled"); + + String authors = sanitize( + book.getMetadata() != null && book.getMetadata().getAuthors() != null + ? book.getMetadata().getAuthors().stream() + .map(AuthorEntity::getName) + .collect(Collectors.joining(", ")) + : "" + ); + String year = sanitize( + book.getMetadata() != null && book.getMetadata().getPublishedDate() != null + ? String.valueOf(book.getMetadata().getPublishedDate().getYear()) + : "" + ); + String series = sanitize(book.getMetadata() != null ? book.getMetadata().getSeriesName() : ""); + String seriesIndex = ""; + if (book.getMetadata() != null && book.getMetadata().getSeriesNumber() != null) { + Float seriesNumber = book.getMetadata().getSeriesNumber(); + seriesIndex = (seriesNumber % 1 == 0) + ? String.valueOf(seriesNumber.intValue()) + : seriesNumber.toString(); + seriesIndex = sanitize(seriesIndex); + } + String language = sanitize(book.getMetadata() != null ? book.getMetadata().getLanguage() : ""); + String publisher = sanitize(book.getMetadata() != null ? book.getMetadata().getPublisher() : ""); + String isbn = sanitize( + book.getMetadata() != null + ? (book.getMetadata().getIsbn13() != null + ? book.getMetadata().getIsbn13() + : book.getMetadata().getIsbn10() != null + ? book.getMetadata().getIsbn10() + : "") + : "" + ); + + Map values = new LinkedHashMap<>(); + values.put("authors", authors); + values.put("title", title); + values.put("year", year); + values.put("series", series); + values.put("seriesIndex", seriesIndex); + values.put("language", language); + values.put("publisher", publisher); + values.put("isbn", isbn); + values.put("currentFilename", currentFilename); + + return resolvePatternWithValues(pattern, values, currentFilename); + } + + public static String resolvePattern(BookMetadata metadata, String pattern, String filename) { + if (pattern == null || pattern.isBlank()) { + return filename; + } + + String title = sanitize(metadata != null && metadata.getTitle() != null + ? metadata.getTitle() + : "Untitled"); + + String authors = sanitize( + metadata != null && metadata.getAuthors() != null + ? String.join(", ", metadata.getAuthors()) + : "" + ); + String year = sanitize( + metadata != null && metadata.getPublishedDate() != null + ? String.valueOf(metadata.getPublishedDate().getYear()) + : "" + ); + String series = sanitize(metadata != null ? metadata.getSeriesName() : ""); + String seriesIndex = ""; + if (metadata != null && metadata.getSeriesNumber() != null) { + Float seriesNumber = metadata.getSeriesNumber(); + seriesIndex = (seriesNumber % 1 == 0) + ? String.valueOf(seriesNumber.intValue()) + : seriesNumber.toString(); + seriesIndex = sanitize(seriesIndex); + } + String language = sanitize(metadata != null ? metadata.getLanguage() : ""); + String publisher = sanitize(metadata != null ? metadata.getPublisher() : ""); + String isbn = sanitize( + metadata != null + ? (metadata.getIsbn13() != null + ? metadata.getIsbn13() + : metadata.getIsbn10() != null + ? metadata.getIsbn10() + : "") + : "" + ); + + Map values = new LinkedHashMap<>(); + values.put("authors", authors); + values.put("title", title); + values.put("year", year); + values.put("series", series); + values.put("seriesIndex", seriesIndex); + values.put("language", language); + values.put("publisher", publisher); + values.put("isbn", isbn); + values.put("currentFilename", filename); + + return resolvePatternWithValues(pattern, values, filename); + } + + private static String resolvePatternWithValues(String pattern, Map values, String currentFilename) { + String extension = ""; + int lastDot = currentFilename.lastIndexOf("."); + if (lastDot >= 0 && lastDot < currentFilename.length() - 1) { + extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub" + } + + values.put("extension", extension); + + // Handle optional blocks enclosed in <...> + Pattern optionalBlockPattern = Pattern.compile("<([^<>]*)>"); + Matcher matcher = optionalBlockPattern.matcher(pattern); + StringBuffer resolved = new StringBuffer(); + + while (matcher.find()) { + String block = matcher.group(1); + Matcher placeholderMatcher = Pattern.compile("\\{(.*?)}").matcher(block); + boolean allHaveValues = true; + + // Check if all placeholders inside optional block have non-blank values + while (placeholderMatcher.find()) { + String key = placeholderMatcher.group(1); + String value = values.getOrDefault(key, ""); + if (value.isBlank()) { + allHaveValues = false; + break; + } + } + + if (allHaveValues) { + String resolvedBlock = block; + for (Map.Entry entry : values.entrySet()) { + resolvedBlock = resolvedBlock.replace("{" + entry.getKey() + "}", entry.getValue()); + } + matcher.appendReplacement(resolved, Matcher.quoteReplacement(resolvedBlock)); + } else { + matcher.appendReplacement(resolved, ""); + } + } + matcher.appendTail(resolved); + + String result = resolved.toString(); + + // Replace known placeholders with values, preserve unknown ones + Pattern placeholderPattern = Pattern.compile("\\{(.*?)}"); + Matcher placeholderMatcher = placeholderPattern.matcher(result); + StringBuffer finalResult = new StringBuffer(); + + while (placeholderMatcher.find()) { + String key = placeholderMatcher.group(1); + if (values.containsKey(key)) { + String replacement = values.get(key); + placeholderMatcher.appendReplacement(finalResult, Matcher.quoteReplacement(replacement)); + } else { + // Preserve unknown placeholders (e.g., {foo}) + placeholderMatcher.appendReplacement(finalResult, Matcher.quoteReplacement("{" + key + "}")); + } + } + placeholderMatcher.appendTail(finalResult); + + result = finalResult.toString(); + + if (result.isBlank()) { + result = values.getOrDefault("currentFilename", "untitled"); + } + + boolean hasExtension = result.matches(".*\\.[a-zA-Z0-9]+$"); + boolean explicitlySetExtension = pattern.contains("{extension}"); + + if (!explicitlySetExtension && !hasExtension && !extension.isBlank()) { + result += "." + extension; + } + + return result; + } + + private static String sanitize(String input) { + if (input == null) return ""; + return input + .replaceAll("[\\\\/:*?\"<>|]", "") + .replaceAll("[\\p{Cntrl}]", "") + .replaceAll("\\s+", " ") + .trim(); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/resources/db/migration/V35__Add_hash_and_deleted_columns_to_book_table.sql b/booklore-api/src/main/resources/db/migration/V35__Add_hash_and_deleted_columns_to_book_table.sql new file mode 100644 index 000000000..035dc554f --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V35__Add_hash_and_deleted_columns_to_book_table.sql @@ -0,0 +1,10 @@ +ALTER TABLE book + ADD COLUMN initial_hash TEXT, + ADD COLUMN current_hash TEXT, + ADD COLUMN deleted BOOLEAN DEFAULT FALSE, + ADD COLUMN deleted_at TIMESTAMP; + +CREATE INDEX IF NOT EXISTS idx_book_initial_hash ON book(initial_hash(255)); +CREATE INDEX IF NOT EXISTS idx_book_current_hash ON book(current_hash(255)); +CREATE INDEX IF NOT EXISTS idx_book_deleted ON book(deleted); +CREATE INDEX IF NOT EXISTS idx_book_deleted_at ON book(deleted_at); \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java new file mode 100644 index 000000000..0b6073a57 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java @@ -0,0 +1,524 @@ +package com.adityachandel.booklore; + +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.request.FileMoveRequest; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.BookQueryService; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.file.FileMoveService; +import com.adityachandel.booklore.service.monitoring.MonitoringService; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FileMoveServiceMoveFilesTest { + + @Mock + private BookQueryService bookQueryService; + + @Mock + private BookRepository bookRepository; + + @Mock + private BookMapper bookMapper; + + @Mock + private NotificationService notificationService; + + @Mock + private MonitoringService monitoringService; + + @InjectMocks + private FileMoveService fileMoveService; + + @TempDir + Path tempLibraryRoot; + + private BookEntity createBookWithFile(Path libraryRoot, String fileSubPath, String fileName) throws IOException { + LibraryEntity library = LibraryEntity.builder() + .id(42L) + .name("Test Library") + .build(); + + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(libraryRoot.toString()) + .library(library) + .build(); + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Test Book") + .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>())))) + .publishedDate(LocalDate.of(2020, 1, 1)) + .build(); + + BookEntity book = BookEntity.builder() + .id(1L) + .fileName(fileName) + .fileSubPath(fileSubPath) + .metadata(metadata) + .libraryPath(libraryPathEntity) + .build(); + + Path oldFilePath = book.getFullFilePath(); + Files.createDirectories(oldFilePath.getParent()); + Files.createFile(oldFilePath); + + return book; + } + + @Test + void testMoveFiles_successfulMove() throws IOException { + String fileName = "testbook.epub"; + String fileSubPath = "oldfolder"; + + BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(1L)); + request.setPattern("NewFolder/{title}"); + + Path oldFilePath = book.getFullFilePath(); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("Expected the file to be moved to %s", expectedNewPath) + .isTrue(); + + assertThat(Files.exists(oldFilePath)) + .withFailMessage("Original file path should no longer exist: %s", oldFilePath) + .isFalse(); + + Files.deleteIfExists(expectedNewPath); + Files.deleteIfExists(expectedNewPath.getParent()); + } + + @Test + void testMoveFiles_skipsNonexistentFile() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("NoFile") + .build(); + + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()) + .build(); + + BookEntity book = BookEntity.builder() + .id(2L) + .fileName("nofile.epub") + .fileSubPath("subfolder") + .metadata(metadata) + .libraryPath(libraryPathEntity) + .build(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(2L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(2L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NoFile.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("No file should be created for nonexistent source") + .isFalse(); + } + + @Test + void testMoveFiles_skipsBookWithoutLibraryPath() throws IOException { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("MissingLibrary") + .build(); + + BookEntity book = BookEntity.builder() + .id(3L) + .fileName("missinglibrary.epub") + .fileSubPath("subfolder") + .metadata(metadata) + .libraryPath(null) + .build(); + + Path fakeOldFile = tempLibraryRoot.resolve("subfolder").resolve("missinglibrary.epub"); + Files.createDirectories(fakeOldFile.getParent()); + Files.createFile(fakeOldFile); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(3L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(3L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("MissingLibrary.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should not be moved if library path is missing") + .isFalse(); + assertThat(Files.exists(fakeOldFile)) + .withFailMessage("Original file should remain when library path is missing") + .isTrue(); + + Files.deleteIfExists(fakeOldFile); + } + + @Test + void testMoveFiles_handlesEmptyPattern() throws IOException { + String fileName = "emptypattern.epub"; + String fileSubPath = "folder"; + + BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(4L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(4L)); + request.setPattern(""); + + Path oldFilePath = book.getFullFilePath(); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve(fileName); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should be moved to the original filename path when pattern is empty") + .isTrue(); + + assertThat(Files.exists(oldFilePath)) + .withFailMessage("Original file path should no longer exist") + .isFalse(); + + Files.deleteIfExists(expectedNewPath); + } + + @Test + void testMoveFiles_removesIllegalCharactersFromPath() throws IOException { + String fileName = "badchars.epub"; + String fileSubPath = "folder"; + + BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); + book.getMetadata().setTitle("Bad|Title:Test*?"); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(5L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(5L)); + request.setPattern("{title}"); + + Path oldFilePath = book.getFullFilePath(); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("BadTitleTest.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("Illegal characters should be removed from generated path") + .isTrue(); + + assertThat(Files.exists(oldFilePath)) + .withFailMessage("Original file path should no longer exist") + .isFalse(); + + Files.deleteIfExists(expectedNewPath); + } + + @Test + void testMoveFiles_deletesEmptyOldDirectories() throws IOException { + String fileName = "deleteold.epub"; + String fileSubPath = "folder/emptydir"; + + BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(6L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(6L)); + request.setPattern("NewFolder/{title}"); + + Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize(); + assertThat(Files.exists(oldDir)) + .withFailMessage("Precondition failed: old directory must exist before move") + .isTrue(); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("Expected file to be moved to new location") + .isTrue(); + + assertThat(Files.exists(oldDir)) + .withFailMessage("Expected old empty directory to be deleted after move") + .isFalse(); + + assertThat(Files.exists(oldDir.getParent())) + .withFailMessage("Expected parent directory of old directory to be deleted if empty") + .isFalse(); + + Files.deleteIfExists(expectedNewPath); + Files.deleteIfExists(expectedNewPath.getParent()); + } + + @Test + void testMoveFiles_keepsOldDirectoryIfNotEmpty() throws IOException { + String fileName = "keepold.epub"; + String fileSubPath = "folder/notempty"; + + BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); + + Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize(); + Files.createDirectories(oldDir); + + Path otherFile = oldDir.resolve("otherfile.txt"); + Files.createFile(otherFile); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(7L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(7L)); + request.setPattern("NewFolder/{title}"); + + Path oldFilePath = book.getFullFilePath(); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); + + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("Expected file to be moved to new location") + .isTrue(); + assertThat(Files.exists(oldFilePath)) + .withFailMessage("Original file path should no longer exist") + .isFalse(); + + assertThat(Files.exists(oldDir)) + .withFailMessage("Old directory should remain if it contains other files") + .isTrue(); + assertThat(Files.exists(otherFile)) + .withFailMessage("Other files in old directory should remain intact") + .isTrue(); + + Files.deleteIfExists(otherFile); + Files.deleteIfExists(expectedNewPath); + Files.deleteIfExists(expectedNewPath.getParent()); + } + + @Test + void testMoveFiles_handlesMultipleBooks() throws IOException { + BookEntity book1 = createBookWithFile(tempLibraryRoot, "folder1", "book1.epub"); + book1.getMetadata().setTitle("Book One"); + + BookEntity book2 = createBookWithFile(tempLibraryRoot, "folder2", "book2.epub"); + book2.getMetadata().setTitle("Book Two"); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(8L, 9L))).thenReturn(List.of(book1, book2)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(8L, 9L)); + request.setPattern("Moved/{title}"); + + Path oldPath1 = book1.getFullFilePath(); + Path oldPath2 = book2.getFullFilePath(); + + fileMoveService.moveFiles(request); + + Path expectedPath1 = tempLibraryRoot.resolve("Moved").resolve("Book One.epub"); + Path expectedPath2 = tempLibraryRoot.resolve("Moved").resolve("Book Two.epub"); + + assertThat(Files.exists(expectedPath1)) + .withFailMessage("Expected first book to be moved to new location") + .isTrue(); + assertThat(Files.exists(expectedPath2)) + .withFailMessage("Expected second book to be moved to new location") + .isTrue(); + + assertThat(Files.exists(oldPath1)) + .withFailMessage("Original path for first book should no longer exist") + .isFalse(); + assertThat(Files.exists(oldPath2)) + .withFailMessage("Original path for second book should no longer exist") + .isFalse(); + + Files.deleteIfExists(expectedPath1); + Files.deleteIfExists(expectedPath2); + Files.deleteIfExists(expectedPath1.getParent()); + } + + @Test + void testMoveFiles_skipsBookWithNullFileName() throws IOException { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("NullFileName") + .build(); + + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()) + .build(); + + BookEntity book = BookEntity.builder() + .id(10L) + .fileName(null) + .fileSubPath("folder") + .metadata(metadata) + .libraryPath(libraryPathEntity) + .build(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(10L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(10L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullFileName"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should not be moved if filename is null") + .isFalse(); + } + + @Test + void testMoveFiles_skipsBookWithEmptyFileName() throws IOException { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("EmptyFileName") + .build(); + + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()) + .build(); + + BookEntity book = BookEntity.builder() + .id(11L) + .fileName("") + .fileSubPath("folder") + .metadata(metadata) + .libraryPath(libraryPathEntity) + .build(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(11L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("EmptyFileName"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should not be moved if filename is empty") + .isFalse(); + } + + @Test + void testMoveFiles_skipsBookWithNullFileSubPath() throws IOException { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("NullSubPath") + .build(); + + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()) + .build(); + + BookEntity book = BookEntity.builder() + .id(12L) + .fileName("file.epub") + .fileSubPath(null) + .metadata(metadata) + .libraryPath(libraryPathEntity) + .build(); + + Path oldFile = tempLibraryRoot.resolve("file.epub"); + Files.createFile(oldFile); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(12L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(12L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullSubPath.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should not be moved if fileSubPath is null") + .isFalse(); + + Files.deleteIfExists(oldFile); + } + + @Test + void testMoveFiles_skipsBookWithNullMetadata() throws IOException { + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()) + .build(); + + BookEntity book = BookEntity.builder() + .id(13L) + .fileName("file.epub") + .fileSubPath("folder") + .metadata(null) + .libraryPath(libraryPathEntity) + .build(); + + Path oldFile = tempLibraryRoot.resolve("folder").resolve("file.epub"); + Files.createDirectories(oldFile.getParent()); + Files.createFile(oldFile); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(13L)); + request.setPattern("Moved/{title}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve(".epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("File should not be moved if metadata is null") + .isFalse(); + + Files.deleteIfExists(oldFile); + } + + @Disabled + @Test + void testMoveFiles_patternWithUnknownPlaceholder() throws IOException { + BookEntity book = createBookWithFile(tempLibraryRoot, "folder", "unknown.epub"); + book.getMetadata().setTitle("UnknownPlaceholder"); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(14L))).thenReturn(List.of(book)); + + FileMoveRequest request = new FileMoveRequest(); + request.setBookIds(Set.of(14L)); + request.setPattern("Moved/{title}/{foo}"); + + fileMoveService.moveFiles(request); + + Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("UnknownPlaceholder").resolve("{foo}.epub"); + assertThat(Files.exists(expectedNewPath)) + .withFailMessage("Unknown placeholders should remain in the generated path") + .isTrue(); + + Files.deleteIfExists(expectedNewPath); + Files.deleteIfExists(expectedNewPath.getParent()); + } +} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java new file mode 100644 index 000000000..b09a3ae84 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java @@ -0,0 +1,406 @@ +package com.adityachandel.booklore; + +import com.adityachandel.booklore.model.entity.AuthorEntity; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.service.BookQueryService; +import com.adityachandel.booklore.service.file.FileMoveService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(MockitoExtension.class) +class FileMoveServiceTest { + + @Mock + private BookQueryService bookQueryService; + + @InjectMocks + private FileMoveService fileMoveService; + + @Test + void testGeneratePathWithAllFieldsPresent() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Dune") + .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Frank Herbert", new ArrayList<>()))) + ) + .publishedDate(LocalDate.of(1965, 8, 1)) + .seriesName("Dune Saga") + .seriesNumber(1.0F) + .language("English") + .publisher("Chilton Books") + .isbn13("9780441172719") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("Dune.epub") + .build(); + + String pattern = "/{series}/{seriesIndex} - {title} by {authors} ({year})"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("/Dune Saga/1 - Dune by Frank Herbert (1965).epub"); + } + + @Test + void testGeneratePathWithMissingMetadata() { + BookMetadataEntity metadata = BookMetadataEntity.builder().build(); + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("unknown.pdf") + .build(); + + String result = fileMoveService.generatePathFromPattern( + book, + "/{title}_{authors}_{year}_{series}_{seriesIndex}_{language}_{publisher}_{isbn}" + ); + assertThat(result).isEqualTo("/Untitled_______.pdf"); + } + + @Test + void testGeneratePathWithMultipleAuthors() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Good Omens") + .authors(new HashSet<>(List.of( + new AuthorEntity(1L, "Neil Gaiman", new ArrayList<>()), + new AuthorEntity(2L, "Terry Pratchett", new ArrayList<>()) + ))) + .publishedDate(LocalDate.of(1990, 5, 1)) + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("goodomens.mobi") + .build(); + + String pattern = "/{title} - {authors} ({year})"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result) + .isIn( + "/Good Omens - Neil Gaiman, Terry Pratchett (1990).mobi", + "/Good Omens - Terry Pratchett, Neil Gaiman (1990).mobi" + ); // Set order is non-deterministic + } + + @Test + void testGeneratePathWithNoExtension() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("The Nameless Book") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("namelessbook") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/The Nameless Book"); + } + + @Test + void testGeneratePathWithIsbn10Fallback() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Test Book") + .isbn10("1234567890") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("testbook.pdf") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{isbn}"); + assertThat(result).isEqualTo("/1234567890.pdf"); + } + + @Test + void testGeneratePathWithEmptyFileName() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("No File") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName(null) + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/No File"); + } + + @Test + void testGeneratePathWithEmptyPattern() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Empty Pattern Book") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("empty.txt") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, ""); + assertThat(result).isEqualTo("empty.txt"); + } + + @Test + void testGeneratePathWithEmptyFileNameString() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Ghost File") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("") // explicitly empty + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/Ghost File"); + } + + @Test + void testGeneratePathWithUnknownPlaceholder() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Weird Format") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("weird.pdf") + .build(); + + String pattern = "/{title}/{unknown}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("/Weird Format/{unknown}.pdf"); + } + + @Test + void testGeneratePathWithDotOnlyFilename() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Dotfile") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName(".gitignore") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/Dotfile.gitignore"); + } + + @Test + void testGeneratePathWithOptionalBlockIncluded() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Book Title") + .seriesName("Series") + .seriesNumber(3.5F) + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("book.pdf") + .build(); + + String pattern = "<{series}/><{seriesIndex}. >{title}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("Series/3.5. Book Title.pdf"); + } + + @Test + void testGeneratePathWithOptionalBlockExcluded() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Book Title") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("book.pdf") + .build(); + + String pattern = "<{series}/><{seriesIndex}. >{title}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("Book Title.pdf"); + } + + @Test + void testOptionalBlockWithPartialMissingData() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Solo") + .seriesName("Lone") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("solo.pdf") + .build(); + + String pattern = "<{series}/><{seriesIndex}. >{title}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("Lone/Solo.pdf"); + } + + @Test + void testPatternWithMultipleOptionalBlocks() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Layered") + .seriesName("Stack") + .seriesNumber(3F) + .language("English") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("layered.epub") + .build(); + + String pattern = "<{series}/><{seriesIndex}. ><{language}/>{title}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("Stack/3. English/Layered.epub"); + } + + @Test + void testIllegalCharactersAreRemoved() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Inva|id:Name*?") + .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Au", new ArrayList<>())))) + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("bad?.pdf") + .build(); + + String pattern = "/{title}_{authors}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("/InvaidName_Author.pdf"); + } + + @Test + void testControlCharactersAreStripped() { + String titleWithControlChars = "Bad\u0000Name\u0007Here"; + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title(titleWithControlChars) + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("control.epub") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/BadNameHere.epub"); + } + + @Test + void testWhitespaceIsCollapsed() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title(" Too Many Spaces ") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("space.mobi") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/Too Many Spaces.mobi"); + } + + @Test + void testUnknownPlaceholdersAreUnchanged() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Valid Book") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("valid.pdf") + .build(); + + String pattern = "/{title}/{foo}/{bar}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("/Valid Book/{foo}/{bar}.pdf"); + } + + @Test + void testEmptyOptionalBlockIsIgnored() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("Optional") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("opt.epub") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "<>"); + assertThat(result).isEqualTo("opt.epub"); + } + + @Test + void testUnicodeCharactersArePreservedAndSanitized() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("𝔘𝔫𝔦𝔠𝔬𝔡𝔢 – 漢字 – हिंदी") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("unicode.azw3") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/𝔘𝔫𝔦𝔠𝔬𝔡𝔢 – 漢字 – हिंदी.azw3"); + } + + @Test + void testOptionalBlockDoesNotLeakSurroundingChars() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("LeakTest") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName("leaky.fb2") + .build(); + + String pattern = "<({series}) >{title}"; + String result = fileMoveService.generatePathFromPattern(book, pattern); + + assertThat(result).isEqualTo("LeakTest.fb2"); + } + + @Test + void testExtensionWithDotOnly() { + BookMetadataEntity metadata = BookMetadataEntity.builder() + .title("DotDot") + .build(); + + BookEntity book = BookEntity.builder() + .metadata(metadata) + .fileName(".") + .build(); + + String result = fileMoveService.generatePathFromPattern(book, "/{title}"); + assertThat(result).isEqualTo("/DotDot"); + } +} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/PathPatternResolverTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/PathPatternResolverTest.java new file mode 100644 index 000000000..4cc0c2e9c --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/PathPatternResolverTest.java @@ -0,0 +1,213 @@ +package com.adityachandel.booklore; + +import com.adityachandel.booklore.model.entity.AuthorEntity; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.util.PathPatternResolver; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class PathPatternResolverTest { + + private BookEntity createBook(String title, List authors, LocalDate date, + String series, Float seriesNum, String lang, + String publisher, String isbn13, String isbn10, + String fileName) { + BookEntity book = mock(BookEntity.class); + BookMetadataEntity metadata = mock(BookMetadataEntity.class); + + when(book.getMetadata()).thenReturn(metadata); + when(book.getFileName()).thenReturn(fileName); + + when(metadata.getTitle()).thenReturn(title); + + if (authors == null) { + when(metadata.getAuthors()).thenReturn(null); + } else { + LinkedHashSet authorEntities = authors.stream().map(name -> { + AuthorEntity a = new AuthorEntity(); + a.setName(name); + return a; + }).collect(Collectors.toCollection(LinkedHashSet::new)); + when(metadata.getAuthors()).thenReturn(authorEntities); + } + + when(metadata.getPublishedDate()).thenReturn(date); + when(metadata.getSeriesName()).thenReturn(series); + when(metadata.getSeriesNumber()).thenReturn(seriesNum); + when(metadata.getLanguage()).thenReturn(lang); + when(metadata.getPublisher()).thenReturn(publisher); + when(metadata.getIsbn13()).thenReturn(isbn13); + when(metadata.getIsbn10()).thenReturn(isbn10); + + return book; + } + + @Test void emptyPattern_returnsOnlyExtension() { + var book = createBook("Title", List.of("Author"), LocalDate.now(), null, null, null, null, null, null, "file.pdf"); + assertThat(PathPatternResolver.resolvePattern(book, "")).isEqualTo("file.pdf"); + } + + @Test void optionalBlockMissingPlaceholder_removed() { + var book = createBook(null, null, null, null, null, null, null, null, null, "f.epub"); + assertThat(PathPatternResolver.resolvePattern(book, "<{series}/>")).isEqualTo("f.epub"); + } + + @Test void multipleOptionalBlocks_partialValues() { + var book = createBook("Title", List.of("Author"), LocalDate.of(2020, 1, 1), + "Series", 1f, null, null, null, null, "f.epub"); + String p = "<{series}/><{seriesIndex}. ><{language}/>{title}"; + assertThat(PathPatternResolver.resolvePattern(book, p)).isEqualTo("Series/1. Title.epub"); + } + + @Test void placeholdersOutsideOptional_replacedWithEmpty() { + var book = createBook("Title", null, LocalDate.of(2020, 1, 1), null, null, null, null, null, null, "file.cbz"); + String p = "{title} - {authors} - {publisher}"; + assertThat(PathPatternResolver.resolvePattern(book, p)).isEqualTo("Title - - .cbz"); + } + + @Test void seriesNumber_decimalAndInteger() { + var book1 = createBook("Title", List.of("Author"), LocalDate.now(), "Series", 3.5f, null, null, null, null, "f.epub"); + var book2 = createBook("Title", List.of("Author"), LocalDate.now(), "Series", 3f, null, null, null, null, "f.epub"); + String p = "<{series}/><{seriesIndex}. >{title}"; + assertThat(PathPatternResolver.resolvePattern(book1, p)).isEqualTo("Series/3.5. Title.epub"); + assertThat(PathPatternResolver.resolvePattern(book2, p)).isEqualTo("Series/3. Title.epub"); + } + + @Test void sanitizes_illegalCharsAndWhitespace() { + var book = createBook(" Ti:tle/<>|*? ", List.of("Au:thor|?*"), LocalDate.of(2000, 1, 1), + "Se:ries", 1f, "Lang<>", "Pub|?", "123:456", "654|321", "file?.pdf"); + String p = "{title} - {authors} - {series} - {language} - {publisher} - {isbn}"; + String result = PathPatternResolver.resolvePattern(book, p); + assertThat(result).doesNotContain(":", "/", "*", "?", "<", ">", "|") + .contains("Title").contains("Author").contains("Series"); + } + + @Test void noExtension_returnsNoDot() { + var book = createBook("Title", List.of("Author"), LocalDate.now(), null, null, null, null, null, null, "filenameWithoutExt"); + assertThat(PathPatternResolver.resolvePattern(book, "{title}")).isEqualTo("Title"); + } + + @Test void complexPattern_allPlaceholdersPresent() { + var book = createBook("Complex Title", List.of("Author One"), LocalDate.of(2010, 5, 5), + "Complex Series", 12.5f, "English", "Publisher", "ISBN13", "ISBN10", "complex.cbz"); + String p = "<{series}/><{seriesIndex}. ><{language}/><{publisher}/>{title} - {authors} - {year} - {isbn}"; + assertThat(PathPatternResolver.resolvePattern(book, p)) + .isEqualTo("Complex Series/12.5. English/Publisher/Complex Title - Author One - 2010 - ISBN13.cbz"); + } + + @Test void missingAllMetadata_returnsExtensionOnly() { + var b = createBook(null, null, null, null, null, null, null, null, null, "f.pdf"); + assertThat(PathPatternResolver.resolvePattern(b, "")).isEqualTo("f.pdf"); + } + + @Test void optionalBlockWithEmptyValue_removesBlock() { + var b = createBook(null, null, null, null, null, null, null, null, null, "f.epub"); + assertThat(PathPatternResolver.resolvePattern(b, "<{series}/><{language}/>")).isEqualTo("f.epub"); + } + + @Test void placeholderWithEmptyValue_outsideOptional_replacedByEmpty() { + var b = createBook("T", null, null, null, null, null, null, null, null, "f.epub"); + String p = "{title} - {authors} - {language}"; + assertThat(PathPatternResolver.resolvePattern(b, p)).isEqualTo("T - - .epub"); + } + + @Test void complexPattern_someMissingOptionalBlocksSkipped() { + var b = createBook("T", List.of("A"), null, null, null, "en", null, null, null, "f.epub"); + String p = "<{series}/><{seriesIndex}. ><{language}/>{title} - {authors}"; + assertThat(PathPatternResolver.resolvePattern(b, p)).isEqualTo("en/T - A.epub"); + } + + @Test void seriesNumberDecimals_andIntegersHandledProperly() { + var b1 = createBook("T", List.of("A"), null, "S", 1f, null, null, null, null, "f.epub"); + var b2 = createBook("T", List.of("A"), null, "S", 1.5f, null, null, null, null, "f.epub"); + String p = "<{series}/><{seriesIndex}. >{title}"; + assertThat(PathPatternResolver.resolvePattern(b1, p)).isEqualTo("S/1. T.epub"); + assertThat(PathPatternResolver.resolvePattern(b2, p)).isEqualTo("S/1.5. T.epub"); + } + + @Test void sanitize_removesIllegalCharacters() { + var b = createBook("Ti:tle<>", List.of("Au:thor|?*"), null, "Se:ries", 1f, + "La<>ng", "Pub|?", "123:456", "654|321", "f?.pdf"); + String p = "{title}-{authors}-{series}-{language}-{publisher}-{isbn}"; + String result = PathPatternResolver.resolvePattern(b, p); + assertThat(result).doesNotContain(":", "/", "*", "?", "<", ">", "|") + .contains("Title").contains("Author").contains("Series"); + } + + @Test void noFileExtension_returnsNoDot() { + var b = createBook("Title", List.of("Author"), null, null, null, null, null, null, null, "fileNoExt"); + assertThat(PathPatternResolver.resolvePattern(b, "{title}")).isEqualTo("Title"); + } + + @Test void patternWithOnlyExtension_returnsExtensionOnly() { + var book = createBook(null, null, null, null, null, null, null, null, null, "sample.pdf"); + assertThat(PathPatternResolver.resolvePattern(book, ".{extension}")).isEqualTo(".pdf"); + } + + @Test void patternWithExtensionAndFilenamePlaceholder_works() { + var book = createBook("Sample", null, null, null, null, null, null, null, null, "original.epub"); + assertThat(PathPatternResolver.resolvePattern(book, "{currentFilename}")).isEqualTo("original.epub"); + } + + @Test void allPlaceholdersMissing_yieldsJustExtension() { + var book = createBook(null, null, null, null, null, null, null, null, null, "file.cbz"); + String pattern = "{title}-{authors}-{series}-{year}-{language}-{publisher}-{isbn}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("Untitled------.cbz"); + } + + @Test void patternWithBackslashes_isSanitized() { + var book = createBook("Ti\\tle", List.of("Au\\thor"), null, null, null, null, null, null, null, "f.pdf"); + assertThat(PathPatternResolver.resolvePattern(book, "{title}/{authors}")).isEqualTo("Title/Author.pdf"); + } + + @Test void optionalBlockWithMixedResolvedAndEmptyValues_skippedEntirely() { + var book = createBook("Title", null, null, null, null, null, null, null, null, "file.epub"); + String pattern = "<{authors} - {series}/>{title}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("Title.epub"); + } + + @Test void placeholderWithWhitespace_trimmedAndSanitized() { + var book = createBook(" My Book ", List.of(" John Doe "), null, null, null, null, null, null, null, "book.pdf"); + String pattern = "{title} - {authors}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("My Book - John Doe.pdf"); + } + + @Test void multipleAuthors_concatenatedProperly() { + var book = createBook("Book", List.of("Alice", "Bob", "Carol"), null, null, null, null, null, null, null, "book.pdf"); + String pattern = "{title} - {authors}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("Book - Alice, Bob, Carol.pdf"); + } + + @Test void patternWithOnlyOptional_allEmpty_resolvesToFilename() { + var book = createBook(null, null, null, null, null, null, null, null, null, "fallback.epub"); + String pattern = "<{series}/><{language}/>"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("fallback.epub"); + } + + @Test void invalidFilename_noExtension_stillResolves() { + var book = createBook("A", List.of("B"), null, null, null, null, null, null, null, "noExt"); + String pattern = "{title}-{authors}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("A-B"); + } + + @Test void patternEndsWithSlash_slashIsPreserved() { + var book = createBook("T", List.of("A"), null, "S", 1f, null, null, null, null, "b.pdf"); + String pattern = "<{series}/><{seriesIndex}/>{title}/"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("S/1/T/.pdf"); + } + + @Test void extensionDotEscaped_doubleDotsNotAdded() { + var book = createBook("X", List.of("Y"), null, null, null, null, null, null, null, "book.mobi"); + String pattern = "{title}.{extension}"; + assertThat(PathPatternResolver.resolvePattern(book, pattern)).isEqualTo("X.mobi"); + } +} \ No newline at end of file diff --git a/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts index 183ca945e..c795d65e2 100644 --- a/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts +++ b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts @@ -6,6 +6,8 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; import {BulkMetadataUpdateComponent} from '../../metadata/bulk-metadata-update-component/bulk-metadata-update-component'; import {MultiBookMetadataEditorComponent} from '../../metadata/multi-book-metadata-editor-component/multi-book-metadata-editor-component'; +import {FileMoverComponent} from '../../../file-mover-component/file-mover-component'; +import {count} from 'rxjs'; @Injectable({providedIn: 'root'}) export class BookDialogHelperService { @@ -87,4 +89,22 @@ export class BookDialogHelperService { }, }); } + + openFileMoverDialog(selectedBooks: Set) { + const count = selectedBooks.size; + return this.dialogService.open(FileMoverComponent, { + header: `Relocate Book Files (${count} book${count !== 1 ? 's' : ''})`, + showHeader: true, + modal: true, + closable: true, + closeOnEscape: false, + dismissableMask: false, + style: { + width: '90vw' + }, + data: { + bookIds: selectedBooks + }, + }); + } } diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html index 9537388ca..a84720b2a 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html @@ -259,6 +259,14 @@ pTooltip="Lock/Unlock metadata" tooltipPosition="top"> + + } } 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 39c0891b2..3c6e47201 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 @@ -33,8 +33,8 @@ .book-browser-footer { position: absolute; bottom: 0; - left: 25%; - right: 25%; + left: 10%; + right: 10%; display: flex; justify-content: center; padding: 1rem 0.5rem 0.5rem; diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts index e6bc4f7dd..36c9a870a 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts @@ -670,4 +670,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { multiBookEditMetadata(): void { this.dialogHelperService.openMultibookMetadataEditerDialog(this.selectedBooks); } + + moveFiles() { + this.dialogHelperService.openFileMoverDialog(this.selectedBooks); + } } diff --git a/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts index a32acd817..a6cd7bc91 100644 --- a/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts +++ b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts @@ -49,24 +49,38 @@ export class SeriesCollapseFilter implements BookFilter { map(isCollapsed => { if (!isCollapsed || !bookState.books) return bookState; - const seenSeries = new Set(); + const books = [...bookState.books]; + + const seriesMap = new Map(); const collapsedBooks: Book[] = []; - for (const book of bookState.books) { - const name = book.metadata?.seriesName?.trim(); - if (name && !seenSeries.has(name)) { - const count = bookState.books.filter(b => b.metadata?.seriesName?.trim() === name).length; - collapsedBooks.push({ - ...book, - seriesCount: count, - }); - seenSeries.add(name); - } else if (!name) { + for (const book of books) { + const seriesName = book.metadata?.seriesName?.trim(); + if (seriesName) { + if (!seriesMap.has(seriesName)) { + seriesMap.set(seriesName, []); + } + seriesMap.get(seriesName)!.push(book); + } else { collapsedBooks.push(book); } } + + for (const [seriesName, group] of seriesMap.entries()) { + const sortedGroup = group.slice().sort((a, b) => { + const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE; + const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE; + return aNum - bNum; + }); - return {...bookState, books: collapsedBooks}; + const firstBook = sortedGroup[0]; + collapsedBooks.push({ + ...firstBook, + seriesCount: group.length + }); + } + + return { ...bookState, books: collapsedBooks }; }) ); } diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/book-metadata-center.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/book-metadata-center.component.html index 9faddc6f0..169ab0755 100644 --- a/booklore-ui/src/app/book/metadata/book-metadata-center/book-metadata-center.component.html +++ b/booklore-ui/src/app/book/metadata/book-metadata-center/book-metadata-center.component.html @@ -18,7 +18,7 @@ } - + diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html index df6de3273..103c1f6e6 100644 --- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -371,7 +371,6 @@ } - } } diff --git a/booklore-ui/src/app/book/model/book.model.ts b/booklore-ui/src/app/book/model/book.model.ts index 40757d813..e626981e6 100644 --- a/booklore-ui/src/app/book/model/book.model.ts +++ b/booklore-ui/src/app/book/model/book.model.ts @@ -15,10 +15,13 @@ export interface Book { pdfProgress?: PdfProgress; cbxProgress?: CbxProgress; filePath?: string; + fileSubPath?: string; + fileName?: string; fileSizeKb?: number; seriesCount?: number | null; metadataMatchScore?: number | null; readStatus?: ReadStatus; + libraryPath?: { id: number }; } export interface EpubProgress { diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts index 796375ae5..f3ee8e9d1 100644 --- a/booklore-ui/src/app/book/service/book.service.ts +++ b/booklore-ui/src/app/book/service/book.service.ts @@ -420,9 +420,9 @@ export class BookService { handleBookUpdate(updatedBook: Book) { const currentState = this.bookStateSubject.value; - const updatedBooks = (currentState.books || []).map(book => { - return book.id == updatedBook.id ? {...book, metadata: updatedBook.metadata} : book - }); + const updatedBooks = (currentState.books || []).map(book => + book.id === updatedBook.id ? updatedBook : book + ); this.bookStateSubject.next({...currentState, books: updatedBooks}); } diff --git a/booklore-ui/src/app/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/book/service/library-shelf-menu.service.ts index 6992b5277..a4eaa5a60 100644 --- a/booklore-ui/src/app/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/book/service/library-shelf-menu.service.ts @@ -56,6 +56,11 @@ export class LibraryShelfMenuService { header: 'Confirmation', rejectButtonProps: { label: 'Cancel', + severity: 'secondary', + }, + acceptButtonProps: { + label: 'Yes', + severity: 'success', }, accept: () => { this.libraryService.deleteLibrary(entity?.id!).subscribe({ @@ -84,6 +89,11 @@ export class LibraryShelfMenuService { header: 'Confirmation', rejectButtonProps: { label: 'Cancel', + severity: 'secondary', + }, + acceptButtonProps: { + label: 'Yes', + severity: 'success', }, accept: () => { this.libraryService.refreshLibrary(entity?.id!).subscribe({ diff --git a/booklore-ui/src/app/book/service/library.service.ts b/booklore-ui/src/app/book/service/library.service.ts index cc52fc94f..529303431 100644 --- a/booklore-ui/src/app/book/service/library.service.ts +++ b/booklore-ui/src/app/book/service/library.service.ts @@ -120,7 +120,16 @@ export class LibraryService { return this.libraryStateSubject.value.libraries || []; } - getAllLibrariesFromAPI(): Observable { - return this.http.get (`${this.url}`); + getLibraryPathById(pathId: number): string | undefined { + const libraries = this.libraryStateSubject.value.libraries || []; + + for (const library of libraries) { + const match = library.paths.find(p => p.id === pathId); + if (match) { + return match.path; + } + } + + return undefined; } } diff --git a/booklore-ui/src/app/core/model/app-settings.model.ts b/booklore-ui/src/app/core/model/app-settings.model.ts index de5a792c3..308752bcc 100644 --- a/booklore-ui/src/app/core/model/app-settings.model.ts +++ b/booklore-ui/src/app/core/model/app-settings.model.ts @@ -79,6 +79,7 @@ export interface AppSettings { metadataRefreshOptions: MetadataRefreshOptions; coverResolution: string; uploadPattern: string; + movePattern: string; opdsServerEnabled: boolean; remoteAuthEnabled: boolean; oidcEnabled: boolean; @@ -106,5 +107,6 @@ export enum AppSettingKey { METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS', METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS', METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS', + MOVE_FILE_PATTERN = 'MOVE_FILE_PATTERN', BOOK_DELETION_ENABLED = 'BOOK_DELETION_ENABLED' } diff --git a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html index 47d3cbd7b..ff912af64 100644 --- a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html +++ b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html @@ -1,4 +1,4 @@ -
+

Internal Authentication:

diff --git a/booklore-ui/src/app/file-mover-component/file-mover-component.html b/booklore-ui/src/app/file-mover-component/file-mover-component.html new file mode 100644 index 000000000..ec83f41e5 --- /dev/null +++ b/booklore-ui/src/app/file-mover-component/file-mover-component.html @@ -0,0 +1,154 @@ +
+ +
+

+ Customize Your File Organization +

+

+ Define a naming pattern to reorganize selected book files on your system. Use dynamic placeholders like + {{ '{title}' }} + or + {{ '{authors}' }} + to automatically insert metadata.
+ A preview below shows how files will be renamed and moved. + Once you're satisfied, click Apply to proceed. + + + Files will be physically moved on your system when you apply changes. + +

+
+ +
+ + {{ placeholdersVisible ? 'Hide' : 'Show' }} available placeholders + + + @if (placeholdersVisible) { +
+
    +
  • {{ '{title}' }} - Book title
  • +
  • {{ '{authors}' }} - Author(s)
  • +
  • {{ '{year}' }} - Full year (e.g. 2025)
  • +
  • {{ '{series}' }} - Series name
  • +
  • {{ '{seriesIndex}' }} - Series index (e.g. 01)
  • +
  • {{ '{language}' }} - Language (e.g. en)
  • +
  • {{ '{publisher}' }} - Publisher
  • +
  • {{ '{isbn}' }} - ISBN
  • +
  • {{ '{currentFilename}' }} - Original file name (with extension)
  • +
+ + + +
+

Tip: Optional placeholders

+

Wrap parts of your pattern in angle brackets {{ '<...>' }} to make them optional.

+

If any placeholder inside has no value, the whole block is removed.

+

Example:

+

{{ '<{seriesIndex} - >{title}' }}

+

• {{ '01 - Dune' }} (if {{ '{seriesIndex}' }} is present)

+

• {{ 'Dune' }} (if {{ '{seriesIndex}' }} is missing)

+
+
+ } +
+ +
+ + + +
+ +
+ + + + ID + Current Path + + New Path + + + + + {{ preview.bookId }} + +

+ {{ preview.libraryPathPrefix }}/{{ preview.relativeOriginalPath }} +

+ + → + +

+ {{ preview.libraryPathPrefix }}/{{ preview.relativeNewPath }} +

+ + + @if (preview.isMoved) { + + } + + +
+
+
+ + + +
+ @if (movedFileCount > 0) { + + {{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved + + + } + @if (movedFileCount === 0) { + + + } @else { + + } +
+
diff --git a/booklore-ui/src/app/file-mover-component/file-mover-component.scss b/booklore-ui/src/app/file-mover-component/file-mover-component.scss new file mode 100644 index 000000000..a62a09f59 --- /dev/null +++ b/booklore-ui/src/app/file-mover-component/file-mover-component.scss @@ -0,0 +1,3 @@ +:host ::ng-deep .p-datatable-tbody > tr > td { + padding: 0.5rem 1rem !important; +} diff --git a/booklore-ui/src/app/file-mover-component/file-mover-component.ts b/booklore-ui/src/app/file-mover-component/file-mover-component.ts new file mode 100644 index 000000000..ee93f8bf8 --- /dev/null +++ b/booklore-ui/src/app/file-mover-component/file-mover-component.ts @@ -0,0 +1,219 @@ +import {Component, inject} from '@angular/core'; +import {FormsModule} from '@angular/forms'; +import {Button} from 'primeng/button'; +import {TableModule} from 'primeng/table'; +import {InputText} from 'primeng/inputtext'; +import {Divider} from 'primeng/divider'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {MessageService} from 'primeng/api'; +import {filter, take} from 'rxjs/operators'; + +import {BookService} from '../book/service/book.service'; +import {Book} from '../book/model/book.model'; +import {FileMoveRequest, FileOperationsService} from '../file-operations-service'; +import {LibraryService} from "../book/service/library.service"; +import {AppSettingsService} from '../core/service/app-settings.service'; +import {AppSettingKey} from '../core/model/app-settings.model'; + +@Component({ + selector: 'app-file-mover-component', + standalone: true, + imports: [Button, FormsModule, TableModule, InputText, Divider], + templateUrl: './file-mover-component.html', + styleUrl: './file-mover-component.scss' +}) +export class FileMoverComponent { + private config = inject(DynamicDialogConfig); + private ref = inject(DynamicDialogRef); + private bookService = inject(BookService); + private libraryService = inject(LibraryService); + private fileOperationsService = inject(FileOperationsService); + private messageService = inject(MessageService); + private appSettingsService = inject(AppSettingsService); + + movePattern = ''; + placeholdersVisible = false; + loading = false; + + bookIds: Set = new Set(); + books: Book[] = []; + filePreviews: { originalPath: string; newPath: string; isMoved?: boolean }[] = []; + + constructor() { + this.bookIds = new Set(this.config.data?.bookIds ?? []); + this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]); + + this.appSettingsService.appSettings$.pipe( + filter(settings => settings != null), + take(1) + ).subscribe(settings => { + this.movePattern = settings?.movePattern; + this.applyPattern(); + }); + } + + applyPattern(): void { + this.filePreviews = this.books.map(book => { + const meta = book.metadata!; + const fileName = book.fileName ?? ''; + const extension = fileName.match(/\.[^.]+$/)?.[0] ?? ''; + const fileSubPath = book.fileSubPath ? `${book.fileSubPath.replace(/\/+$/g, '')}/` : ''; + + const relativeOriginalPath = `${fileSubPath}${fileName}`; + const libraryPathPrefix = + book.libraryPath?.id != null + ? this.libraryService.getLibraryPathById(book.libraryPath.id)?.replace(/\/+$/g, '') ?? '' + : ''; + const originalPath = `${libraryPathPrefix}/${relativeOriginalPath}`.replace(/\/\/+/g, '/'); + + const values: Record = { + authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'), + title: this.sanitize(meta.title || 'Untitled'), + year: this.formatYear(meta.publishedDate), + series: this.sanitize(meta.seriesName || ''), + seriesIndex: this.formatSeriesIndex(meta.seriesNumber ?? undefined), + language: this.sanitize(meta.language || ''), + publisher: this.sanitize(meta.publisher || ''), + isbn: this.sanitize(meta.isbn13 || meta.isbn10 || ''), + currentFilename: this.sanitize(fileName) + }; + + let newPath: string; + + if (!this.movePattern?.trim()) { + // If pattern empty, just use current filename as the new path + newPath = `${fileSubPath}${fileName}`; // preserve subpath + filename + } else { + newPath = this.movePattern.replace(/<([^<>]+)>/g, (_, block) => { + const placeholders = [...block.matchAll(/{(.*?)}/g)].map(m => m[1]); + const allHaveValues = placeholders.every(key => values[key]?.trim()); + return allHaveValues + ? block.replace(/{(.*?)}/g, (_: string, key: string) => values[key] ?? '') + : ''; + }); + + newPath = newPath.replace(/{(.*?)}/g, (_, key) => values[key] ?? ''); + + // Append extension if not already present (most patterns won't include extension) + if (!newPath.endsWith(extension)) { + newPath += extension; + } + } + + const relativeNewPath = newPath; + const fullNewPath = `${libraryPathPrefix}/${relativeNewPath}`.replace(/\/\/+/g, '/'); + + return { + bookId: book.id, + originalPath, + relativeOriginalPath, + libraryPathPrefix, + newPath: fullNewPath, + relativeNewPath + }; + }); + } + + get movedFileCount(): number { + return this.filePreviews.filter(p => p.isMoved).length; + } + + sanitize(input: string | undefined): string { + return input?.replace(/[\\/:*?"<>|]/g, '') + .replace(/[\x00-\x1F\x7F]/g, '') + .replace(/\s+/g, ' ') + .trim() ?? ''; + } + + formatYear(dateStr?: string): string { + if (!dateStr) return ''; + const date = new Date(dateStr); + return isNaN(date.getTime()) ? '' : date.getFullYear().toString(); + } + + formatSeriesIndex(seriesNumber?: number): string { + if (seriesNumber == null) return ''; + return this.sanitize(seriesNumber.toString()); + } + + getDefaultPattern(): string { + return 'e.g. {authors}/<{series}/><{seriesIndex}. >{title} - {authors}< ({year})>'; + } + + saveChanges(): void { + if (!this.movePattern?.trim()) { + this.messageService.add({ + severity: 'error', + summary: 'Missing Pattern', + detail: 'Move pattern cannot be empty. Please enter a valid pattern.', + life: 3000 + }); + return; + } + + this.loading = true; + const request: FileMoveRequest = { + bookIds: [...this.bookIds], + pattern: this.movePattern + }; + + this.fileOperationsService.moveFiles(request).subscribe({ + next: () => { + this.loading = false; + this.filePreviews.forEach(p => (p.isMoved = true)); + this.messageService.add({ + severity: 'success', + summary: 'Files Moved', + detail: `${this.filePreviews.length} file(s) successfully relocated.`, + life: 3000 + }); + }, + error: () => { + this.loading = false; + this.messageService.add({ + severity: 'error', + summary: 'Move Failed', + detail: 'An error occurred while moving the files.', + life: 3000 + }); + } + }); + } + + setDefaultPattern(): void { + const trimmedPattern = this.movePattern?.trim(); + + if (!trimmedPattern) { + this.messageService.add({ + severity: 'error', + summary: 'Cannot Save', + detail: 'Move pattern cannot be empty.' + }); + return; + } + + const payload = [ + { + key: AppSettingKey.MOVE_FILE_PATTERN, + newValue: trimmedPattern + } + ]; + + this.appSettingsService.saveSettings(payload).subscribe({ + next: () => this.messageService.add({ + severity: 'success', + summary: 'Saved', + detail: 'Move pattern saved as default.' + }), + error: () => this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to save default move pattern.' + }) + }); + } + + cancel(): void { + this.ref.close(); + } +} diff --git a/booklore-ui/src/app/file-operations-service.ts b/booklore-ui/src/app/file-operations-service.ts new file mode 100644 index 000000000..2044f8414 --- /dev/null +++ b/booklore-ui/src/app/file-operations-service.ts @@ -0,0 +1,22 @@ +import {inject, Injectable} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from './config/api-config'; + +export interface FileMoveRequest { + bookIds: number[]; + pattern: string; +} + +@Injectable({ + providedIn: 'root' +}) +export class FileOperationsService { + private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/files`; + + private http = inject(HttpClient); + + moveFiles(request: FileMoveRequest): Observable { + return this.http.post(`${this.baseUrl}/move`, request); + } +} diff --git a/booklore-ui/src/app/settings/email/email.component.html b/booklore-ui/src/app/settings/email/email.component.html index bb367f87a..789297c1a 100644 --- a/booklore-ui/src/app/settings/email/email.component.html +++ b/booklore-ui/src/app/settings/email/email.component.html @@ -1,4 +1,4 @@ -
+
diff --git a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html b/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html index ce88bd0fe..536216e01 100644 --- a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html +++ b/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html @@ -1,85 +1,235 @@ -

- Uploaded Files Pattern - +

+ File Naming Patterns +

+
+
-

Enter Custom File Naming Pattern:

+

Enter Upload File Naming Pattern:

+

+ Define how newly uploaded files are named and organized using book metadata. +

- - - + +
+ @if (uploadErrorMessage) { +
{{ uploadErrorMessage }}
+ } + +

Upload Pattern Preview:

+

{{ generateUploadPreview() }}

-

Preview:

-

{{ generatePreview() }}

-
- -
-

Example Patterns:

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{title} - {authors}/filename.pdf→/The Book Thief - Markus Zusak/filename.pdf
{title}/{authors}/filename.pdf→/The Book Thief/Markus Zusak/filename.pdf
{title} ({authors})/filename.pdf→/The Book Thief (Markus Zusak)/filename.pdf
{title}/filename.pdf→/The Book Thief/filename.pdf
EMPTY→/filename.pdf
+

Enter File Move Naming Pattern:

+

+ Specify how book files should be renamed and relocated using metadata such as title, authors, or series. This pattern is applied when using the Move Files feature. +

+
+ + +
+ @if (moveErrorMessage) { +
{{ moveErrorMessage }}
+ } + +

Move Pattern Preview:

+

{{ generateMovePreview() }}

+ + + +

Available Placeholders:

+ +

+ Use placeholders to dynamically insert book metadata into file names and folder paths. These will be replaced with actual values when uploading or moving files. + You can also wrap parts of the pattern in {{ '{{<...>}' }} to make them optional, if any placeholder inside is missing, that section will be omitted entirely. +

+ +
+
+
    +
  • {{ '{title}' }} – Book title
  • +
  • {{ '{authors}' }} – Author(s)
  • +
  • {{ '{year}' }} – Full year (e.g. 2025)
  • +
  • {{ '{series}' }} – Series name
  • +
  • {{ '{seriesIndex}' }} – Series index (e.g. 01)
  • +
  • {{ '{language}' }} – Language code (e.g. en)
  • +
  • {{ '{publisher}' }} – Publisher name
  • +
  • {{ '{isbn}' }} – ISBN number
  • +
  • {{ '{currentFilename}' }} Original file name (with extension)
  • +
+ + + +
+

Optional blocks

+

+ Surround parts of your pattern with angle brackets + {{ '{<...>}' }} + to make them optional.
If any placeholder inside the block has no value, the whole block is excluded. +

+

Example:

+

{{ '{<{seriesIndex} - >{title}' }}

+

• 01 - Dune (if {{ '{seriesIndex}' }} exists)

+

• Dune (if {{ '{seriesIndex}' }} is missing)

+
+
+
+ + + +
+

Example Patterns & Output:

+ +
+

Examples with Full Metadata

+

+ title: Harry Potter and the Sorcerer's Stone + authors: J.K. Rowling + series: Harry Potter + seriesIndex: 01 + year: 1997 + currentFilename: harry1_original.epub +

+ +
+

Basic pattern: {{ '{authors} - {title}' }}

+

Output: J.K. Rowling - Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Pattern with punctuation: {{ '{title}: {series}' }}

+

Output: Harry Potter and the Sorcerer's Stone: Harry Potter.epub

+
+ +
+

Series in folder path: {{ '{authors}/{series}/{seriesIndex} - {title}' }}

+

Output: J.K. Rowling/Harry Potter/01 - Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Folder only: {{ '{title}/' }}

+

Output: /Harry Potter and the Sorcerer's Stone/harry1_original.epub

+
+ +
+

Absolute path: {{ '/{authors}/{title}' }}

+

Output: /J.K. Rowling/Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Reuse original filename in path: {{ '{authors}/{series}/{currentFilename}' }}

+

Output: J.K. Rowling/Harry Potter/harry1_original.epub

+
+ +
+

Preserve original filename only: {{ '{currentFilename}' }}

+

Output: harry1_original.epub

+
+ +
+

Empty pattern (defaults to current filename): {{ '' }}

+

Output: harry1_original.epub

+
+
+ +
+

Examples with Missing Optional Fields

+

+ title: Project Hail Mary + authors: Andy Weir + year: 2021 + series: (not provided) + seriesIndex: (not provided) + currentFilename: project_hail_mary_final.epub +

+ +
+

Pattern with optional blocks: {{ '{authors}/<{series}/><{seriesIndex}. >{title}< ({year})>' }}

+

Output: Andy Weir/Project Hail Mary (2021).epub

+
+ +
+

Fallback with seriesIndex and dash: {{ '<{seriesIndex}. >{title}< - {authors}>' }}

+

Output: Project Hail Mary - Andy Weir.epub

+
+ +
+

Brackets & punctuation fallback: {{ '<[{series}] >{title} - {authors}' }}

+

Output: Project Hail Mary - Andy Weir.epub

+
+ +
+

Series + punctuation fallback: {{ '<{series}: >{title} by {authors}' }}

+

Output: Project Hail Mary by Andy Weir.epub

+
+ +
+

Only folders, no filename: {{ '{authors}/' }}

+

Output: Andy Weir/project_hail_mary_final.epub

+
+ +
+

Deep nested folders: {{ '{authors}/books/<{series}/>{title}/' }}

+

Output: Andy Weir/books/Project Hail Mary/project_hail_mary_final.epub

+
+ +
+

With static folder prefix: {{ 'Books/<{series}/>{authors} - {title}' }}

+

Output: Books/Andy Weir - Project Hail Mary.epub

+
+ +
+

Use original filename in path: {{ '{authors}/books/<{series}/>{currentFilename}' }}

+

Output: Andy Weir/books/project_hail_mary_final.epub

+
+ +
+

Prefix current filename manually: {{ '{authors}/final__{currentFilename}' }}

+

Output: Andy Weir/final__project_hail_mary_final.epub

+
+ +
+

Filename preserved, renamed folder: {{ '{title}/source/{currentFilename}' }}

+

Output: Project Hail Mary/source/project_hail_mary_final.epub

+
+ +
+

Use current filename with year suffix: {{ '{authors}/{year}__{currentFilename}' }}

+

Output: Andy Weir/2021__project_hail_mary_final.epub

+
+ +
+

Fallback with optional + extras folder: {{ '<{series}/>{authors}/extras/{currentFilename}' }}

+

Output: Andy Weir/extras/project_hail_mary_final.epub

+
+ +
+

Archive structure using original name: {{ 'archive/<{series}/>{year}/{currentFilename}' }}

+

Output: archive/2021/project_hail_mary_final.epub

+
+ +
+

Structured folder + renamed file: {{ '{authors}/<{series}/>{title} ({year}) by {authors}' }}

+

Output: Andy Weir/Project Hail Mary (2021) by Andy Weir.epub

+
+
-
-
- Note: -
    -
  • Only the placeholders {title} and {authors} are supported. These values will be extracted from the metadata of the uploaded PDF or EPUB file.
  • -
  • Multiple authors will be joined using commas.
  • -
  • If {title} is used but is missing in uploaded book's metadata, the path will fall back to /filename.pdf.
  • -
  • If {authors} is used but is missing in uploaded book's metadata, the path will fall back to {title}/filename.pdf if the title exists, otherwise /filename.pdf. -
  • -
diff --git a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts b/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts index 762293020..b35a09c87 100644 --- a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts +++ b/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts @@ -4,22 +4,35 @@ 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 {AppSettingKey, AppSettings} from '../../../core/model/app-settings.model'; import {filter, take} from 'rxjs/operators'; +import {Divider} from 'primeng/divider'; import {Tooltip} from 'primeng/tooltip'; @Component({ selector: 'app-file-upload-pattern', templateUrl: './file-upload-pattern.component.html', standalone: true, - imports: [FormsModule, Button, Tooltip], - styleUrls: ['./file-upload-pattern.component.scss'] + imports: [FormsModule, Button, Divider, Tooltip], + styleUrls: ['./file-upload-pattern.component.scss'], }) export class FileUploadPatternComponent implements OnInit { - title: string = 'The Book Thief'; - authors: string = 'Markus Zusak'; - uploadPattern: string = ''; - errorMessage: string = ''; + readonly exampleMetadata: Record = { + title: 'The Fellowship of the Ring', + authors: 'J.R.R. Tolkien', + year: '1954', + series: 'The Lord of the Rings', + seriesIndex: '01', + language: 'en', + publisher: 'Allen & Unwin', + isbn: '9780618574940', + }; + + uploadPattern = ''; + movePattern = ''; + + uploadErrorMessage = ''; + moveErrorMessage = ''; private appSettingsService = inject(AppSettingsService); private messageService = inject(MessageService); @@ -27,43 +40,99 @@ export class FileUploadPatternComponent implements OnInit { appSettings$: Observable = this.appSettingsService.appSettings$; ngOnInit(): void { - this.appSettings$.pipe( - filter(settings => settings != null), - take(1) - ).subscribe(settings => { - this.uploadPattern = settings?.uploadPattern || ''; + this.appSettings$ + .pipe(filter((settings) => settings != null), take(1)) + .subscribe((settings) => { + this.uploadPattern = settings?.uploadPattern ?? ''; + this.movePattern = settings?.movePattern ?? ''; + }); + } + + private replacePlaceholders(pattern: string, values: Record): string { + pattern = pattern.replace(/<([^<>]+)>/g, (_, block) => { + const placeholders = [...block.matchAll(/{(.*?)}/g)].map((m) => m[1]); + const allHaveValues = placeholders.every((key) => values[key]?.trim()); + return allHaveValues + ? block.replace(/{(.*?)}/g, (_: string, key: string) => values[key] ?? '') + : ''; }); + return pattern.replace(/{(.*?)}/g, (_, key) => values[key] ?? '').trim(); } - generatePreview(): string { - let path = this.uploadPattern - .replace('{title}', this.title) - .replace('{authors}', this.authors) - .replace(/\/+$/, '') - .trim(); - - return path ? `/${path}/filename.pdf` : '/filename.pdf'; + private appendExtensionIfMissing(path: string, ext = '.pdf'): string { + const lastSegment = path.split('/').pop() ?? ''; + const hasExtension = /\.[a-z0-9]{2,5}$/i.test(lastSegment); + return hasExtension ? path : path + ext; } - validatePattern(pattern: string): void { - const isValid = /^[\w\s\-{}\/().]*$/.test(pattern); - this.errorMessage = isValid ? '' : 'Pattern contains invalid characters.'; + generateUploadPreview(): string { + let path = this.replacePlaceholders(this.uploadPattern || '', this.exampleMetadata); + + if (!path) return '/original_filename.pdf'; + + // If pattern ends with slash, append original filename + if (path.endsWith('/')) { + return path + 'original_filename.pdf'; + } + + // Replace {originalFilename} placeholder if present + if (path.includes('{originalFilename}')) { + path = path.replace('{originalFilename}', 'original_filename.pdf'); + return path.startsWith('/') ? path : `/${path}`; + } + + path = this.appendExtensionIfMissing(path); + return path.startsWith('/') ? path : `/${path}`; } - onPatternChange(pattern: string): void { + generateMovePreview(): string { + let path = this.replacePlaceholders(this.movePattern || '', this.exampleMetadata); + + if (!path) return '/original_filename.pdf'; + + if (path.endsWith('/')) { + return path + 'original_filename.pdf'; + } + + if (path.includes('{originalFilename}')) { + path = path.replace('{originalFilename}', 'original_filename.pdf'); + return path.startsWith('/') ? path : `/${path}`; + } + + path = this.appendExtensionIfMissing(path); + return path.startsWith('/') ? path : `/${path}`; + } + + validatePattern(pattern: string): boolean { + // Allow letters, numbers, whitespace, common punctuation and placeholders syntax + const validPatternRegex = /^[\w\s\-{}\/().<>.,:'"]*$/; + return validPatternRegex.test(pattern); + } + + onUploadPatternChange(pattern: string): void { this.uploadPattern = pattern; - this.validatePattern(pattern); + this.uploadErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; } - savePattern(): void { - this.saveSetting('UPLOAD_FILE_PATTERN', this.uploadPattern); + onMovePatternChange(pattern: string): void { + this.movePattern = pattern; + this.moveErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; } - 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.') - }); + savePatterns(): void { + if (this.uploadErrorMessage || this.moveErrorMessage) { + this.showMessage('error', 'Invalid Pattern', 'Please fix errors before saving.'); + return; + } + this.appSettingsService + .saveSettings([ + {key: AppSettingKey.UPLOAD_FILE_PATTERN, newValue: this.uploadPattern}, + {key: AppSettingKey.MOVE_FILE_PATTERN, newValue: this.movePattern}, + ]) + .subscribe({ + next: () => this.showMessage('success', 'Settings Saved', 'The patterns 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 { diff --git a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html index 82a16af68..89948fb6c 100644 --- a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html +++ b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html @@ -1,6 +1,6 @@ -
+
-
+

Book Cover Image

-
+
@@ -138,7 +138,7 @@
-
+
diff --git a/booklore-ui/src/app/settings/global-preferences/opds-settings/opds-settings.component.html b/booklore-ui/src/app/settings/global-preferences/opds-settings/opds-settings.component.html index 07606b94b..41d16f95c 100644 --- a/booklore-ui/src/app/settings/global-preferences/opds-settings/opds-settings.component.html +++ b/booklore-ui/src/app/settings/global-preferences/opds-settings/opds-settings.component.html @@ -1,4 +1,4 @@ -

+

OPDS Server Settings +

Metadata Persistence:

diff --git a/booklore-ui/src/app/settings/reader-preferences/reader-preferences.component.html b/booklore-ui/src/app/settings/reader-preferences/reader-preferences.component.html index 177abd9a0..c791d8c99 100644 --- a/booklore-ui/src/app/settings/reader-preferences/reader-preferences.component.html +++ b/booklore-ui/src/app/settings/reader-preferences/reader-preferences.component.html @@ -1,4 +1,4 @@ -
+

Book Reader Settings: Global or Per-Book diff --git a/booklore-ui/src/app/settings/user-management/user-management.component.html b/booklore-ui/src/app/settings/user-management/user-management.component.html index 006b66d92..0351f31d3 100644 --- a/booklore-ui/src/app/settings/user-management/user-management.component.html +++ b/booklore-ui/src/app/settings/user-management/user-management.component.html @@ -1,4 +1,4 @@ -

+

diff --git a/booklore-ui/src/app/settings/view-preferences-parent/view-preferences-parent.component.html b/booklore-ui/src/app/settings/view-preferences-parent/view-preferences-parent.component.html index 1e1aa452d..cf3519f62 100644 --- a/booklore-ui/src/app/settings/view-preferences-parent/view-preferences-parent.component.html +++ b/booklore-ui/src/app/settings/view-preferences-parent/view-preferences-parent.component.html @@ -1,4 +1,4 @@ -
+