Merge pull request #646 from adityachandelgit/develop
Merge Develop into Master for release
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -87,4 +87,6 @@ hibernate {
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading")
|
||||
}
|
||||
|
||||
|
||||
+24
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<String> mapAuthors(Set<AuthorEntity> authors) {
|
||||
if (authors == null) {
|
||||
return null;
|
||||
}
|
||||
if (authors == null) return null;
|
||||
return authors.stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
default Set<String> mapCategories(Set<CategoryEntity> 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();
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<Shelf> shelves;
|
||||
private String readStatus;
|
||||
private LibraryPath libraryPath;
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class FileMoveRequest {
|
||||
private Set<Long> bookIds;
|
||||
private String pattern;
|
||||
}
|
||||
+1
@@ -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),
|
||||
|
||||
+1
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
+1
-1
@@ -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<BookEntity> bookEntities;
|
||||
|
||||
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
|
||||
+27
@@ -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<BookFileExtension> fromFileName(String fileName) {
|
||||
String lower = fileName.toLowerCase();
|
||||
return Arrays.stream(values())
|
||||
.filter(e -> lower.endsWith("." + e.extension))
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
+59
-43
@@ -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<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds")
|
||||
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
||||
|
||||
Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId);
|
||||
|
||||
Optional<BookEntity> 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<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId);
|
||||
Optional<BookEntity> findByCurrentHash(String currentHash);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)")
|
||||
void deleteByIdIn(Collection<Long> ids);
|
||||
List<BookEntity> findAllByLibraryPathIdAndFileSubPathStartingWith(Long libraryPathId, String fileSubPathPrefix);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL")
|
||||
List<BookEntity> 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<BookEntity> 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<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllNonDeletedByIds(@Param("bookIds") Collection<Long> bookIds);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadata();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds")
|
||||
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> 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<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> 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<BookEntity> 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<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> 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<BookEntity> 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<BookEntity> 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<BookEntity> 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<BookEntity> 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<BookEntity> 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);
|
||||
}
|
||||
@@ -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<BookEntity> getAllFullBookEntities() {
|
||||
return bookRepository.findAllFullBooks();
|
||||
}
|
||||
|
||||
|
||||
public List<BookEntity> getBooksContainingMetadata(String text) {
|
||||
return bookRepository.findBooksContainingMetadata(text);
|
||||
}
|
||||
|
||||
+2
-1
@@ -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")));
|
||||
|
||||
+213
@@ -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<Long> bookIds = request.getBookIds();
|
||||
String pattern = request.getPattern();
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
|
||||
log.info("Starting file move for {} books using pattern: '{}'", books.size(), pattern);
|
||||
|
||||
Set<Long> 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<Path> libraryRoots) throws IOException {
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
currentDir = currentDir.toAbsolutePath().normalize();
|
||||
|
||||
Set<Path> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -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<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, forceProcess, bookRepository, bookMapper);
|
||||
if (existing.isPresent()) return existing.get();
|
||||
if (!forceProcess) {
|
||||
Optional<BookEntity> 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);
|
||||
}
|
||||
}
|
||||
+10
@@ -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);
|
||||
}
|
||||
+53
-92
@@ -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<BookEntity> 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<BufferedImage> 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<BufferedImage> 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<BufferedImage> extractFirstImageFromRar(File file) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
List<FileHeader> headers = archive.getFileHeaders();
|
||||
List<FileHeader> 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<BufferedImage> 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<BufferedImage> extractFirstImageFromRar(File file) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
List<FileHeader> 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));
|
||||
}
|
||||
}
|
||||
+56
-67
@@ -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<BookEntity> 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);
|
||||
}
|
||||
}
|
||||
+54
-1
@@ -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<Book> 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<BookEntity> 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));
|
||||
}
|
||||
}
|
||||
+27
-45
@@ -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<BookEntity> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-179
@@ -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<String, ScheduledFuture<?>> 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<LibraryFile> currentLibraryFiles = getLibraryFiles(libraryEntity);
|
||||
Map<String, Path> currentFileMap = currentLibraryFiles.stream()
|
||||
.collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing));
|
||||
Map<String, Path> 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<String> 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<Path> 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<LibraryFile> libraryFiles) {
|
||||
public void processLibraryFiles(List<LibraryFile> 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<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) {
|
||||
libraryFiles.addAll(findLibraryFiles(libraryPathEntity, libraryEntity));
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity));
|
||||
}
|
||||
return libraryFiles;
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity libraryPathEntity, LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> 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<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
try (Stream<Path> 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;
|
||||
}
|
||||
}
|
||||
+4
-9
@@ -58,7 +58,7 @@ public class LibraryService {
|
||||
@PostConstruct
|
||||
public void initializeMonitoring() {
|
||||
List<Library> 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<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
fileProcessingUtils.deleteBookCovers(bookIds);
|
||||
|
||||
+3
@@ -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) {
|
||||
|
||||
-2
@@ -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;
|
||||
|
||||
+43
-9
@@ -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;
|
||||
}
|
||||
}
|
||||
-19
@@ -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;
|
||||
}
|
||||
}
|
||||
-53
@@ -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<Author> epubAuthors = epub.getMetadata().getAuthors();
|
||||
if (!epubAuthors.isEmpty()) {
|
||||
Set<String> authors = epubAuthors.stream()
|
||||
.map(author -> author.getFirstname() + " " + author.getLastname())
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
metadata.setAuthors(authors);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to extract metadata from EPUB file {}: {}", filePath, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error while reading EPUB file {}: {}", filePath, e.getMessage());
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
-8
@@ -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);
|
||||
}
|
||||
-42
@@ -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;
|
||||
}
|
||||
}
|
||||
+30
@@ -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<BookEntity> 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"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -15,5 +15,6 @@ public class AppMigrationStartup {
|
||||
public void runMigrationsOnce() {
|
||||
appMigrationService.populateMissingFileSizesOnce();
|
||||
appMigrationService.populateMetadataScoresOnce();
|
||||
appMigrationService.populateFileHashesOnce();
|
||||
}
|
||||
}
|
||||
|
||||
+16
@@ -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;
|
||||
}
|
||||
}
|
||||
+225
-48
@@ -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<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
|
||||
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
|
||||
|
||||
private final BlockingQueue<FileChangeEvent> eventQueue = new LinkedBlockingQueue<>();
|
||||
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
|
||||
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
|
||||
private final Map<Long, Boolean> libraryWatchStatusMap = new ConcurrentHashMap<>();
|
||||
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
|
||||
private final Map<Long, List<Path>> 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<Library> 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<Path> 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<Library> 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<Path> registeredPaths = new ArrayList<>();
|
||||
int[] registeredCount = {0};
|
||||
|
||||
library.getPaths().forEach(libraryPath -> {
|
||||
Path rootPath = Paths.get(libraryPath.getPath());
|
||||
if (Files.isDirectory(rootPath)) {
|
||||
try (Stream<Path> 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<Path> 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<Long> 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<Path> 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<Path> toRemove = monitoredPaths.stream()
|
||||
.filter(p -> p.startsWith(deletedPath))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
for (Path path : toRemove) {
|
||||
unregisterPath(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-20
@@ -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);
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
}
|
||||
}
|
||||
+25
@@ -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);
|
||||
}
|
||||
}
|
||||
+30
@@ -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");
|
||||
}
|
||||
}
|
||||
+50
-76
@@ -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<String> 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;
|
||||
};
|
||||
}
|
||||
}
|
||||
+101
@@ -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<BookEntity> 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<BookEntity> 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<BookEntity> findByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
|
||||
return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void save(BookEntity book) {
|
||||
bookRepository.save(book);
|
||||
}
|
||||
}
|
||||
+70
@@ -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<BookEntity> 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);
|
||||
}
|
||||
}
|
||||
+173
@@ -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<FileEvent> 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) {
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> 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();
|
||||
}
|
||||
}
|
||||
+10
@@ -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);
|
||||
+524
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<thor>", 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");
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<AuthorEntity> 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");
|
||||
}
|
||||
}
|
||||
@@ -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<number>) {
|
||||
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
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,6 +259,14 @@
|
||||
pTooltip="Lock/Unlock metadata"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
severity="info"
|
||||
(click)="moveFiles()"
|
||||
pTooltip="Move Books"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -670,4 +670,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
multiBookEditMetadata(): void {
|
||||
this.dialogHelperService.openMultibookMetadataEditerDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
moveFiles() {
|
||||
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,24 +49,38 @@ export class SeriesCollapseFilter implements BookFilter {
|
||||
map(isCollapsed => {
|
||||
if (!isCollapsed || !bookState.books) return bookState;
|
||||
|
||||
const seenSeries = new Set<string>();
|
||||
const books = [...bookState.books];
|
||||
|
||||
const seriesMap = new Map<string, Book[]>();
|
||||
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 };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@
|
||||
</p-tab>
|
||||
}
|
||||
</p-tablist>
|
||||
<p-tabpanels class="overflow-auto" style="height: calc(100vh - 10rem);">
|
||||
<p-tabpanels class="overflow-auto" style="height: calc(100vh - 9.7rem);">
|
||||
<p-tabpanel value="view">
|
||||
<app-metadata-viewer [book$]="book$" [recommendedBooks]="recommendedBooks"></app-metadata-viewer>
|
||||
</p-tabpanel>
|
||||
|
||||
-1
@@ -371,7 +371,6 @@
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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});
|
||||
}
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -120,7 +120,16 @@ export class LibraryService {
|
||||
return this.libraryStateSubject.value.libraries || [];
|
||||
}
|
||||
|
||||
getAllLibrariesFromAPI(): Observable<Library[]> {
|
||||
return this.http.get <Library[]>(`${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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-lg gap-2 pb-4 pt-4">Internal Authentication:</p>
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
<div class="p-fluid px-4 py-2 rounded-xl flex flex-col h-[800px]">
|
||||
|
||||
<div class="px-4 mx-2 mb-4 py-3 rounded-lg border border-[var(--border-color)] transition-all">
|
||||
<p class="text-[var(--primary-color)] font-semibold mb-1">
|
||||
Customize Your File Organization
|
||||
</p>
|
||||
<p class="text-sm text-gray-300 leading-relaxed">
|
||||
Define a naming pattern to reorganize selected book files on your system. Use dynamic placeholders like
|
||||
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{title}' }}</code>
|
||||
or
|
||||
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{authors}' }}</code>
|
||||
to automatically insert metadata. <br>
|
||||
A preview below shows how files will be renamed and moved.
|
||||
Once you're satisfied, click <span class="font-semibold text-green-400">Apply</span> to proceed.
|
||||
<span class="text-yellow-500 font-medium flex items-center gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-yellow-400"></i>
|
||||
Files will be physically moved on your system when you apply changes.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-2 px-1 text-sm text-muted">
|
||||
<p-button
|
||||
size="small"
|
||||
text
|
||||
severity="info"
|
||||
(click)="placeholdersVisible = !placeholdersVisible">
|
||||
{{ placeholdersVisible ? 'Hide' : 'Show' }} available placeholders
|
||||
</p-button>
|
||||
|
||||
@if (placeholdersVisible) {
|
||||
<div class="mx-4 my-2 flex flex-wrap gap-4">
|
||||
<ul class="list-disc pl-4 min-w-[250px]">
|
||||
<li><code>{{ '{title}' }}</code> - Book title</li>
|
||||
<li><code>{{ '{authors}' }}</code> - Author(s)</li>
|
||||
<li><code>{{ '{year}' }}</code> - Full year (e.g. 2025)</li>
|
||||
<li><code>{{ '{series}' }}</code> - Series name</li>
|
||||
<li><code>{{ '{seriesIndex}' }}</code> - Series index (e.g. 01)</li>
|
||||
<li><code>{{ '{language}' }}</code> - Language (e.g. en)</li>
|
||||
<li><code>{{ '{publisher}' }}</code> - Publisher</li>
|
||||
<li><code>{{ '{isbn}' }}</code> - ISBN</li>
|
||||
<li><code>{{ '{currentFilename}' }}</code> - Original file name (with extension)</li>
|
||||
</ul>
|
||||
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
|
||||
<div class="text-sm p-3 min-w-[250px]">
|
||||
<p class="mb-1 font-medium">Tip: Optional placeholders</p>
|
||||
<p>Wrap parts of your pattern in angle brackets <code>{{ '<...>' }}</code> to make them optional.</p>
|
||||
<p>If any placeholder inside has no value, the whole block is removed.</p>
|
||||
<p class="mt-1 font-semibold">Example:</p>
|
||||
<p><code>{{ '<{seriesIndex} - >{title}' }}</code></p>
|
||||
<p class="pl-4 mt-1">• <code>{{ '01 - Dune' }}</code> (if <code>{{ '{seriesIndex}' }}</code> is present)</p>
|
||||
<p class="pl-4">• <code>{{ 'Dune' }}</code> (if <code>{{ '{seriesIndex}' }}</code> is missing)</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mb-4 px-2 items-center w-full">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="movePattern"
|
||||
(ngModelChange)="applyPattern()"
|
||||
[placeholder]="movePattern.trim() ? '' : getDefaultPattern()"
|
||||
class="flex-1"
|
||||
/>
|
||||
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
label="Make Default"
|
||||
severity="info"
|
||||
outlined
|
||||
(click)="setDefaultPattern()"
|
||||
></p-button>
|
||||
</div>
|
||||
|
||||
<div class="flex-grow overflow-y-auto mt-4">
|
||||
<p-table
|
||||
[value]="filePreviews"
|
||||
[responsiveLayout]="'scroll'"
|
||||
class="block min-w-full"
|
||||
>
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th style="width: 0.5rem; text-align: center;">ID</th>
|
||||
<th>Current Path</th>
|
||||
<th></th>
|
||||
<th>New Path</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="body" let-preview let-i="rowIndex">
|
||||
<tr>
|
||||
<td class="text-center">{{ preview.bookId }}</td>
|
||||
<td class="w-auto">
|
||||
<p>
|
||||
<span class="text-gray-400 select-none">{{ preview.libraryPathPrefix }}/</span><span>{{ preview.relativeOriginalPath }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="w-auto text-[var(--primary-color)] text-center">→</td>
|
||||
<td class="w-auto">
|
||||
<p>
|
||||
<span class="text-gray-400 select-none">{{ preview.libraryPathPrefix }}/</span><span>{{ preview.relativeNewPath }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="w-auto text-center">
|
||||
@if (preview.isMoved) {
|
||||
<i class="pi pi-check-circle text-green-600"></i>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4">
|
||||
@if (movedFileCount > 0) {
|
||||
<span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none">
|
||||
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
|
||||
<i
|
||||
class="pi pi-check-circle ml-2 text-green-500 animate-bounce"
|
||||
style="animation-duration: 1.5s;"
|
||||
aria-label="Success"
|
||||
role="img"
|
||||
></i>
|
||||
</span>
|
||||
}
|
||||
@if (movedFileCount === 0) {
|
||||
<p-button
|
||||
[label]="loading ? 'Moving...' : 'Move Files'"
|
||||
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-arrows-h'"
|
||||
severity="success"
|
||||
(click)="saveChanges()"
|
||||
[disabled]="loading || filePreviews.length === 0"
|
||||
></p-button>
|
||||
<p-button
|
||||
label="Cancel"
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
(click)="cancel()"
|
||||
></p-button>
|
||||
} @else {
|
||||
<p-button
|
||||
label="Close"
|
||||
icon="pi pi-times"
|
||||
severity="success"
|
||||
(click)="cancel()"
|
||||
></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,3 @@
|
||||
:host ::ng-deep .p-datatable-tbody > tr > td {
|
||||
padding: 0.5rem 1rem !important;
|
||||
}
|
||||
@@ -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<number> = 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<string, string> = {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/move`, request);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
|
||||
<div class="pt-2">
|
||||
<app-email-provider></app-email-provider>
|
||||
</div>
|
||||
|
||||
+222
-72
@@ -1,85 +1,235 @@
|
||||
<p class="text-lg ">
|
||||
Uploaded Files Pattern
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Define a naming pattern for future uploads using available metadata. Existing files will remain unchanged."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
File Naming Patterns
|
||||
<i
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Define custom naming patterns for uploaded files and for moving files within your library. Use metadata placeholders to automate organization."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col space-y-6 p-4 m-4 custom-border">
|
||||
|
||||
<div>
|
||||
<h2 class="mb-3 text-lg">Enter Custom File Naming Pattern:</h2>
|
||||
<h2 class="mb-3 text-lg">Enter Upload File Naming Pattern:</h2>
|
||||
<p class="mb-3 text-sm text-gray-400">
|
||||
Define how newly uploaded files are named and organized using book metadata.
|
||||
</p>
|
||||
<div class="flex gap-4 items-center">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="uploadPattern"
|
||||
class="p-inputtext w-[500px]"
|
||||
placeholder="e.g., {title} - {authors}"
|
||||
(input)="onPatternChange(uploadPattern)"
|
||||
/>
|
||||
<p-button
|
||||
label="Save"
|
||||
(onClick)="savePattern()"
|
||||
severity="primary"
|
||||
outlined="true"
|
||||
[disabled]="!!errorMessage">
|
||||
</p-button>
|
||||
<input type="text" [(ngModel)]="uploadPattern" class="p-inputtext w-[700px]" placeholder="e.g., {title} - {authors}" (input)="onUploadPatternChange(uploadPattern)"/>
|
||||
<p-button label="Save" (onClick)="savePatterns()" severity="primary" outlined="true" [disabled]="!!uploadErrorMessage || !!moveErrorMessage"></p-button>
|
||||
</div>
|
||||
@if (uploadErrorMessage) {
|
||||
<div class="text-red-500 mt-1">{{ uploadErrorMessage }}</div>
|
||||
}
|
||||
|
||||
<h3 class="mt-4 mb-2">Upload Pattern Preview:</h3>
|
||||
<p class="text-lg text-green-500">{{ generateUploadPreview() }}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 class="mb-2">Preview:</h3>
|
||||
<p class="text-lg text-green-500">{{ generatePreview() }}</p>
|
||||
</div>
|
||||
|
||||
<div class="text-gray-400">
|
||||
<h3 class="mb-1 ">Example Patterns:</h3>
|
||||
<div class="overflow-x-auto">
|
||||
<table class=" table-auto">
|
||||
<colgroup>
|
||||
<col style="width: auto;"/>
|
||||
<col style="width: 20px;"/>
|
||||
<col/>
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title} - {authors}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief - Markus Zusak/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title}/{authors}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief/Markus Zusak/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title} ({authors})/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief (Markus Zusak)/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">EMPTY</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/filename.pdf</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h2 class="mb-3 text-lg">Enter File Move Naming Pattern:</h2>
|
||||
<p class="mb-3 text-sm text-gray-400">
|
||||
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.
|
||||
</p>
|
||||
<div class="flex gap-4 items-center">
|
||||
<input type="text" [(ngModel)]="movePattern" class="p-inputtext w-[700px]" placeholder="e.g., {authors}/<{series}/><{seriesIndex}. >{title} - {authors}< ({year})>.pdf"
|
||||
(input)="onMovePatternChange(movePattern)"/>
|
||||
<p-button label="Save" (onClick)="savePatterns()" severity="primary" outlined="true" [disabled]="!!uploadErrorMessage || !!moveErrorMessage"></p-button>
|
||||
</div>
|
||||
@if (moveErrorMessage) {
|
||||
<div class="text-red-500 mt-1">{{ moveErrorMessage }}</div>
|
||||
}
|
||||
|
||||
<h3 class="mt-4 mb-2">Move Pattern Preview:</h3>
|
||||
<p class="text-lg text-green-500">{{ generateMovePreview() }}</p>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<p class="pt-4">Available Placeholders:</p>
|
||||
|
||||
<p class="text-sm text-gray-400 mb-2 mt-2">
|
||||
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 <code>{{ '{{<...>}' }}</code> to make them optional, if any placeholder inside is missing, that section will be omitted entirely.
|
||||
</p>
|
||||
|
||||
<div class="mt-2">
|
||||
<div class="mx-4 my-2 flex flex-wrap gap-4">
|
||||
<ul class="list-disc pl-4 min-w-[250px] text-gray-300">
|
||||
<li><code class="text-orange-400">{{ '{title}' }}</code> – Book title</li>
|
||||
<li><code class="text-orange-400">{{ '{authors}' }}</code> – Author(s)</li>
|
||||
<li><code class="text-orange-400">{{ '{year}' }}</code> – Full year (e.g. 2025)</li>
|
||||
<li><code class="text-orange-400">{{ '{series}' }}</code> – Series name</li>
|
||||
<li><code class="text-orange-400">{{ '{seriesIndex}' }}</code> – Series index (e.g. 01)</li>
|
||||
<li><code class="text-orange-400">{{ '{language}' }}</code> – Language code (e.g. en)</li>
|
||||
<li><code class="text-orange-400">{{ '{publisher}' }}</code> – Publisher name</li>
|
||||
<li><code class="text-orange-400">{{ '{isbn}' }}</code> – ISBN number</li>
|
||||
<li><code class="text-orange-400">{{ '{currentFilename}' }}</code> Original file name (with extension)</li>
|
||||
</ul>
|
||||
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
|
||||
<div class="text-sm p-3 min-w-[250px]">
|
||||
<p class="mb-1 font-bold text-gray-200 text">Optional blocks</p>
|
||||
<p class="text-gray-300">
|
||||
Surround parts of your pattern with angle brackets
|
||||
<code class="text-blue-400">{{ '{<...>}' }}</code>
|
||||
to make them optional. <br> If any placeholder inside the block has no value, the whole block is excluded.
|
||||
</p>
|
||||
<p class="mt-2 font-semibold text-gray-300">Example:</p>
|
||||
<p><code>{{ '{<{seriesIndex} - >{title}' }}</code></p>
|
||||
<p class="pl-4 mt-1 text-gray-300">• <code>01 - Dune</code> (if <code>{{ '{seriesIndex}' }}</code> exists)</p>
|
||||
<p class="pl-4 text-gray-300">• <code>Dune</code> (if <code>{{ '{seriesIndex}' }}</code> is missing)</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="mt-6">
|
||||
<p class="mb-4">Example Patterns & Output:</p>
|
||||
|
||||
<div class="px-4 text-sm space-y-4">
|
||||
<p class="text-base font-semibold text-gray-200 mt-6 mb-2">Examples with Full Metadata</p>
|
||||
<p class="text-gray-400 mb-4">
|
||||
<span class="block">title: <code>Harry Potter and the Sorcerer's Stone</code></span>
|
||||
<span class="block">authors: <code>J.K. Rowling</code></span>
|
||||
<span class="block">series: <code>Harry Potter</code></span>
|
||||
<span class="block">seriesIndex: <code>01</code></span>
|
||||
<span class="block">year: <code>1997</code></span>
|
||||
<span class="block">currentFilename: <code>harry1_original.epub</code></span>
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Basic pattern:</strong><code class="text-gray-400"> {{ '{authors} - {title}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> J.K. Rowling - Harry Potter and the Sorcerer's Stone.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Pattern with punctuation:</strong><code class="text-gray-400"> {{ '{title}: {series}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Harry Potter and the Sorcerer's Stone: Harry Potter.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Series in folder path:</strong><code class="text-gray-400"> {{ '{authors}/{series}/{seriesIndex} - {title}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> J.K. Rowling/Harry Potter/01 - Harry Potter and the Sorcerer's Stone.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Folder only:</strong><code class="text-gray-400"> {{ '{title}/' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> /Harry Potter and the Sorcerer's Stone/harry1_original.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Absolute path:</strong><code class="text-gray-400"> {{ '/{authors}/{title}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> /J.K. Rowling/Harry Potter and the Sorcerer's Stone.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Reuse original filename in path:</strong><code class="text-gray-400"> {{ '{authors}/{series}/{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> J.K. Rowling/Harry Potter/harry1_original.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Preserve original filename only:</strong><code class="text-gray-400"> {{ '{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> harry1_original.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Empty pattern (defaults to current filename):</strong><code class="text-gray-400"> {{ '' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> harry1_original.epub</code></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-4 text-sm space-y-4 mt-10">
|
||||
<p class="text-base font-semibold text-gray-200 mb-2">Examples with Missing Optional Fields</p>
|
||||
<p class="text-gray-400 mb-4">
|
||||
<span class="block">title: <code>Project Hail Mary</code></span>
|
||||
<span class="block">authors: <code>Andy Weir</code></span>
|
||||
<span class="block">year: <code>2021</code></span>
|
||||
<span class="block">series: <code>(not provided)</code></span>
|
||||
<span class="block">seriesIndex: <code>(not provided)</code></span>
|
||||
<span class="block">currentFilename: <code>project_hail_mary_final.epub</code></span>
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Pattern with optional blocks:</strong><code
|
||||
class="text-gray-400"> {{ '{authors}/<{series}/><{seriesIndex}. >{title}< ({year})>' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/Project Hail Mary (2021).epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Fallback with seriesIndex and dash:</strong><code
|
||||
class="text-gray-400"> {{ '<{seriesIndex}. >{title}< - {authors}>' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Project Hail Mary - Andy Weir.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Brackets & punctuation fallback:</strong><code class="text-gray-400"> {{ '<[{series}] >{title} - {authors}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Project Hail Mary - Andy Weir.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Series + punctuation fallback:</strong><code class="text-gray-400"> {{ '<{series}: >{title} by {authors}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Project Hail Mary by Andy Weir.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Only folders, no filename:</strong><code class="text-gray-400"> {{ '{authors}/' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Deep nested folders:</strong><code class="text-gray-400"> {{ '{authors}/books/<{series}/>{title}/' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/books/Project Hail Mary/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">With static folder prefix:</strong><code class="text-gray-400"> {{ 'Books/<{series}/>{authors} - {title}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Books/Andy Weir - Project Hail Mary.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Use original filename in path:</strong><code
|
||||
class="text-gray-400"> {{ '{authors}/books/<{series}/>{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/books/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Prefix current filename manually:</strong><code class="text-gray-400"> {{ '{authors}/final__{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/final__project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Filename preserved, renamed folder:</strong><code class="text-gray-400"> {{ '{title}/source/{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Project Hail Mary/source/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Use current filename with year suffix:</strong><code
|
||||
class="text-gray-400"> {{ '{authors}/{year}__{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/2021__project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Fallback with optional + extras folder:</strong><code
|
||||
class="text-gray-400"> {{ '<{series}/>{authors}/extras/{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/extras/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Archive structure using original name:</strong><code
|
||||
class="text-gray-400"> {{ 'archive/<{series}/>{year}/{currentFilename}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> archive/2021/project_hail_mary_final.epub</code></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p class="mb-1"><strong class="text-gray-300">Structured folder + renamed file:</strong><code
|
||||
class="text-gray-400"> {{ '{authors}/<{series}/>{title} ({year}) by {authors}' }}</code></p>
|
||||
<p><strong class="text-gray-300">Output:</strong><code class="text-gray-400"> Andy Weir/Project Hail Mary (2021) by Andy Weir.epub</code></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text text-gray-400">
|
||||
<strong>Note:</strong>
|
||||
<ul class="list-disc pl-6">
|
||||
<li>Only the placeholders {title} and {authors} are supported. These values will be extracted from the metadata of the uploaded PDF or EPUB file.</li>
|
||||
<li>Multiple authors will be joined using commas.</li>
|
||||
<li>If <code>{title}</code> is used but is missing in uploaded book's metadata, the path will fall back to <code>/filename.pdf</code>.</li>
|
||||
<li>If <code>{authors}</code> is used but is missing in uploaded book's metadata, the path will fall back to <code>{title}/filename.pdf</code> if the title exists, otherwise <code>/filename.pdf</code>.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+101
-32
@@ -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<string, string> = {
|
||||
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<AppSettings | null> = 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, string>): 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 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
|
||||
<div class="p-4">
|
||||
<div class="px-4 pt-4 pb-2">
|
||||
<div class="flex items-center gap-2 pb-4 pt-4">
|
||||
<p class="text-lg ">Book Cover Image</p>
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
@@ -130,7 +130,7 @@
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
|
||||
<div class="p-4">
|
||||
<div class="px-4 py-2">
|
||||
<app-opds-settings></app-opds-settings>
|
||||
</div>
|
||||
|
||||
@@ -138,7 +138,7 @@
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
|
||||
<div class="p-4">
|
||||
<div class="px-4 py-2">
|
||||
<app-file-upload-pattern></app-file-upload-pattern>
|
||||
</div>
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
OPDS Server Settings
|
||||
<i
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
|
||||
<div class="p-4 pt-6">
|
||||
<p class="text-lg pb-4 pt-2">Metadata Persistence:</p>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="p-4">
|
||||
<p class="text-lg pb-4 pt-4 ">
|
||||
Book Reader Settings: Global or Per-Book
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
|
||||
|
||||
<div class="flex justify-between items-center pb-2 pt-2">
|
||||
<h2 class="text-lg flex items-center gap-2">
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<div class="w-full h-[calc(100vh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
<app-view-preferences></app-view-preferences>
|
||||
<p-divider></p-divider>
|
||||
<app-sidebar-sorting-preferences></app-sidebar-sorting-preferences>
|
||||
|
||||
Reference in New Issue
Block a user