Merge pull request #867 from booklore-app/develop

Merge Develop into Master for release
This commit is contained in:
Aditya Chandel
2025-08-10 11:40:52 -06:00
committed by GitHub
68 changed files with 2185 additions and 3522 deletions
+2 -2
View File
@@ -27,7 +27,7 @@ RUN gradle clean build
# Stage 3: Final image # Stage 3: Final image
FROM eclipse-temurin:21-jre-alpine FROM eclipse-temurin:21-jre-alpine
RUN apk update && apk add nginx RUN apk update && apk add nginx su-exec
COPY ./nginx.conf /etc/nginx/nginx.conf COPY ./nginx.conf /etc/nginx/nginx.conf
COPY --from=angular-build /angular-app/dist/booklore/browser /usr/share/nginx/html COPY --from=angular-build /angular-app/dist/booklore/browser /usr/share/nginx/html
@@ -36,4 +36,4 @@ COPY --from=springboot-build /springboot-app/build/libs/booklore-api-0.0.1-SNAPS
EXPOSE 8080 80 EXPOSE 8080 80
CMD /usr/sbin/nginx -g "daemon off;" & \ CMD /usr/sbin/nginx -g "daemon off;" & \
java -jar /app/app.jar su-exec ${PUID:-0}:${PGID:-0} java -jar /app/app.jar
+10 -10
View File
@@ -1,8 +1,8 @@
plugins { plugins {
id 'java' id 'java'
id 'org.springframework.boot' version '3.5.0' id 'org.springframework.boot' version '3.5.1'
id 'io.spring.dependency-management' version '1.1.7' id 'io.spring.dependency-management' version '1.1.7'
id 'org.hibernate.orm' version '7.0.0.Final' id 'org.hibernate.orm' version '7.1.0.Final'
id 'com.github.ben-manes.versions' version '0.52.0' id 'com.github.ben-manes.versions' version '0.52.0'
} }
@@ -39,8 +39,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
// --- Database & Migration --- // --- Database & Migration ---
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.3' implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.4'
implementation 'org.flywaydb:flyway-mysql:11.9.0' implementation 'org.flywaydb:flyway-mysql:11.11.0'
implementation 'jakarta.persistence:jakarta.persistence-api:3.2.0' implementation 'jakarta.persistence:jakarta.persistence-api:3.2.0'
// --- Security & Authentication --- // --- Security & Authentication ---
@@ -61,22 +61,22 @@ dependencies {
implementation 'io.documentnode:epub4j-core:4.2.2' implementation 'io.documentnode:epub4j-core:4.2.2'
// --- JSON & Web Scraping --- // --- JSON & Web Scraping ---
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.19.0' implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.19.2'
implementation 'org.jsoup:jsoup:1.20.1' implementation 'org.jsoup:jsoup:1.21.1'
// --- Mapping (DTOs & Entities) --- // --- Mapping (DTOs & Entities) ---
implementation 'org.mapstruct:mapstruct:1.6.3' implementation 'org.mapstruct:mapstruct:1.6.3'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3' annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'
// --- API Documentation --- // --- API Documentation ---
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
implementation 'org.apache.commons:commons-compress:1.27.1' implementation 'org.apache.commons:commons-compress:1.28.0'
implementation 'com.github.junrar:junrar:7.5.5' implementation 'com.github.junrar:junrar:7.5.5'
implementation 'org.apache.commons:commons-text:1.13.1' implementation 'org.apache.commons:commons-text:1.14.0'
// --- Test Dependencies --- // --- Test Dependencies ---
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.assertj:assertj-core:3.26.3' testImplementation 'org.assertj:assertj-core:3.27.3'
testImplementation "org.mockito:mockito-inline:5.2.0" testImplementation "org.mockito:mockito-inline:5.2.0"
} }
@@ -28,4 +28,13 @@ public class FileUploadController {
} }
return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId)); return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId));
} }
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload/bookdrop", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
return ResponseEntity.ok(fileUploadService.uploadFileBookDrop(file));
}
} }
@@ -11,6 +11,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
import java.util.Map;
@RestController @RestController
@RequestMapping("/api/v1/libraries") @RequestMapping("/api/v1/libraries")
@@ -72,4 +73,13 @@ public class LibraryController {
libraryService.rescanLibrary(libraryId); libraryService.rescanLibrary(libraryId);
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@PatchMapping("/{libraryId}/file-naming-pattern")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> setFileNamingPattern(@PathVariable long libraryId, @RequestBody Map<String, String> body) {
String pattern = body.get("fileNamingPattern");
Library updated = libraryService.setFileNamingPattern(libraryId, pattern);
return ResponseEntity.ok(updated);
}
} }
@@ -0,0 +1,30 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.quartz.JobSchedulerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/v1/tasks")
@RequiredArgsConstructor
public class TaskController {
private final JobSchedulerService jobSchedulerService;
@DeleteMapping("/{taskId}")
public ResponseEntity<?> cancelTask(@PathVariable String taskId) {
log.info("Received request to cancel task: {}", taskId);
boolean cancelled = jobSchedulerService.cancelJob(taskId);
if (cancelled) {
return ResponseEntity.ok(Map.of("message", "Task cancellation scheduled"));
} else {
return ResponseEntity.badRequest().body(Map.of("error", "Failed to cancel task or task not found"));
}
}
}
@@ -14,5 +14,3 @@ public class APIException extends RuntimeException {
this.message = formattedMessage; this.message = formattedMessage;
} }
} }
@@ -85,6 +85,14 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(errorResponse, HttpStatus.OK); return new ResponseEntity<>(errorResponse, HttpStatus.OK);
} }
@ExceptionHandler(InterruptedException.class)
public ResponseEntity<ErrorResponse> handleInterruptedException(InterruptedException ex) {
log.info("Request was interrupted: {}", ex.getMessage() != null ? ex.getMessage() : "Thread interrupted");
Thread.currentThread().interrupt();
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.OK.value(), "Request was cancelled.");
return new ResponseEntity<>(errorResponse, HttpStatus.OK);
}
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) { public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred."); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
@@ -14,6 +14,7 @@ public class Library {
private String name; private String name;
private Sort sort; private Sort sort;
private String icon; private String icon;
private String fileNamingPattern;
private boolean watch; private boolean watch;
private List<LibraryPath> paths; private List<LibraryPath> paths;
} }
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.EventTaskType;
import com.adityachandel.booklore.model.enums.TaskStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TaskMessage {
private String taskId;
@Builder.Default
private Instant timestamp = Instant.now();
private String message;
private EventTaskType taskType;
private TaskStatus status;
@JsonProperty
public String getTitle() {
return taskType != null ? taskType.getTitle() : null;
}
@JsonProperty
public boolean isCancellable() {
return taskType != null && taskType.isCancellable();
}
}
@@ -7,7 +7,6 @@ import java.util.List;
@Data @Data
public class BookdropFinalizeRequest { public class BookdropFinalizeRequest {
private String uploadPattern;
private Boolean selectAll; private Boolean selectAll;
private List<Long> excludedIds; private List<Long> excludedIds;
private List<BookdropFinalizeFile> files; private List<BookdropFinalizeFile> files;
@@ -37,4 +37,7 @@ public class LibraryEntity {
private boolean watch; private boolean watch;
private String icon; private String icon;
@Column(name = "file_naming_pattern")
private String fileNamingPattern;
} }
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.model.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum EventTaskType {
METADATA_REFRESH("Metadata Refresh", true);
private final String title;
private final boolean cancellable;
}
@@ -0,0 +1,9 @@
package com.adityachandel.booklore.model.enums;
public enum TaskStatus {
IN_PROGRESS,
CANCELLED,
COMPLETED,
FAILED
}
@@ -10,7 +10,7 @@ public enum Topic {
BOOK_METADATA_BATCH_UPDATE("/topic/book-metadata-batch-update"), BOOK_METADATA_BATCH_UPDATE("/topic/book-metadata-batch-update"),
BOOK_METADATA_BATCH_PROGRESS("/topic/book-metadata-batch-progress"), BOOK_METADATA_BATCH_PROGRESS("/topic/book-metadata-batch-progress"),
BOOKDROP_FILE("/topic/bookdrop-file"), BOOKDROP_FILE("/topic/bookdrop-file"),
TASK("/topic/task"),
LOG("/topic/log"); LOG("/topic/log");
private final String path; private final String path;
@@ -9,7 +9,9 @@ import org.quartz.*;
import org.quartz.impl.matchers.KeyMatcher; import org.quartz.impl.matchers.KeyMatcher;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@Slf4j @Slf4j
@@ -20,6 +22,7 @@ public class JobSchedulerService {
private final Scheduler scheduler; private final Scheduler scheduler;
private final BlockingQueue<RefreshJobWrapper> jobQueue = new LinkedBlockingQueue<>(); private final BlockingQueue<RefreshJobWrapper> jobQueue = new LinkedBlockingQueue<>();
private final Map<String, String> runningJobs = new ConcurrentHashMap<>();
private boolean isJobRunning = false; private boolean isJobRunning = false;
public synchronized void scheduleMetadataRefresh(MetadataRefreshRequest request, Long userId) { public synchronized void scheduleMetadataRefresh(MetadataRefreshRequest request, Long userId) {
@@ -47,7 +50,6 @@ public class JobSchedulerService {
log.info("Processing job from queue. Remaining queue size: {}", jobQueue.size()); log.info("Processing job from queue. Remaining queue size: {}", jobQueue.size());
String jobId = generateUniqueJobId(request); String jobId = generateUniqueJobId(request);
try { try {
log.info("Scheduling job with ID: {}", jobId);
scheduleJob(request, userId, jobId); scheduleJob(request, userId, jobId);
} catch (Exception e) { } catch (Exception e) {
isJobRunning = false; isJobRunning = false;
@@ -57,11 +59,39 @@ public class JobSchedulerService {
} }
} }
public synchronized boolean cancelJob(String jobId) {
try {
String quartzJobId = runningJobs.get(jobId);
if (quartzJobId == null) {
log.warn("Job with ID {} not found in running jobs", jobId);
return false;
}
JobKey jobKey = new JobKey(quartzJobId, "metadataRefreshJobGroup");
boolean cancelled = scheduler.interrupt(jobKey);
if (cancelled) {
runningJobs.remove(jobId);
isJobRunning = false;
log.info("Job {} cancellation scheduled", jobId);
processQueue();
} else {
log.warn("Failed to cancel job {}", jobId);
}
return cancelled;
} catch (UnableToInterruptJobException e) {
log.error("Job {} cannot be interrupted: {}", jobId, e.getMessage());
return false;
}
}
private void scheduleJob(MetadataRefreshRequest request, Long userId, String jobId) { private void scheduleJob(MetadataRefreshRequest request, Long userId, String jobId) {
try { try {
JobDataMap jobDataMap = new JobDataMap(); JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("request", request); jobDataMap.put("request", request);
jobDataMap.put("userId", userId); jobDataMap.put("userId", userId);
jobDataMap.put("jobId", jobId);
JobDetail jobDetail = JobBuilder.newJob(RefreshMetadataJob.class) JobDetail jobDetail = JobBuilder.newJob(RefreshMetadataJob.class)
.withIdentity(jobId, "metadataRefreshJobGroup") .withIdentity(jobId, "metadataRefreshJobGroup")
@@ -74,6 +104,8 @@ public class JobSchedulerService {
.startNow() .startNow()
.build(); .build();
runningJobs.put(jobId, jobId);
scheduler.scheduleJob(jobDetail, trigger); scheduler.scheduleJob(jobDetail, trigger);
log.info("Job scheduled successfully with ID: {}", jobId); log.info("Job scheduled successfully with ID: {}", jobId);
@@ -99,6 +131,7 @@ public class JobSchedulerService {
if (jobException != null) { if (jobException != null) {
log.error("Job execution encountered an error: {}", jobException.getMessage(), jobException); log.error("Job execution encountered an error: {}", jobException.getMessage(), jobException);
} }
runningJobs.remove(jobId);
isJobRunning = false; isJobRunning = false;
log.debug("Job completion handled. Processing next job in the queue."); log.debug("Job completion handled. Processing next job in the queue.");
processQueue(); processQueue();
@@ -1,32 +1,57 @@
package com.adityachandel.booklore.quartz; package com.adityachandel.booklore.quartz;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest; import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
import com.adityachandel.booklore.service.metadata.BookMetadataService;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService; import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution; import org.quartz.*;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Slf4j @Slf4j
@Component @Component
@AllArgsConstructor @RequiredArgsConstructor
@DisallowConcurrentExecution @DisallowConcurrentExecution
public class RefreshMetadataJob implements Job { public class RefreshMetadataJob implements InterruptableJob {
private MetadataRefreshService metadataRefreshService; private final MetadataRefreshService metadataRefreshService;
private volatile Thread executionThread;
@Override @Override
public void execute(JobExecutionContext context) throws JobExecutionException { public void execute(JobExecutionContext context) throws JobExecutionException {
executionThread = Thread.currentThread();
try { try {
MetadataRefreshRequest request = (MetadataRefreshRequest) context.getMergedJobDataMap().get("request"); MetadataRefreshRequest request = (MetadataRefreshRequest) context.getMergedJobDataMap().get("request");
Long userId = (Long) context.getMergedJobDataMap().get("userId"); Long userId = (Long) context.getMergedJobDataMap().get("userId");
metadataRefreshService.refreshMetadata(request, userId); String jobId = (String) context.getMergedJobDataMap().get("jobId");
} catch (Exception e) { log.info("Starting metadata refresh job with ID: {}", jobId);
metadataRefreshService.refreshMetadata(request, userId, jobId);
log.info("Completed metadata refresh job with ID: {}", jobId);
} catch (RuntimeException e) {
if (e.getCause() instanceof InterruptedException) {
log.info("Metadata refresh job with ID was interrupted: {}", context.getMergedJobDataMap().get("jobId"));
Thread.currentThread().interrupt();
return;
}
throw new JobExecutionException("Error occurred while executing metadata refresh job", e); throw new JobExecutionException("Error occurred while executing metadata refresh job", e);
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
log.info("Metadata refresh job was interrupted");
Thread.currentThread().interrupt();
return;
}
throw new JobExecutionException("Error occurred while executing metadata refresh job", e);
} finally {
executionThread = null;
}
}
@Override
public void interrupt() throws UnableToInterruptJobException {
Thread thread = executionThread;
if (thread != null) {
thread.interrupt();
} else {
log.warn("No execution thread found to interrupt");
} }
} }
} }
@@ -14,13 +14,15 @@ import java.util.Set;
@Repository @Repository
public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> { public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId); Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId);
Optional<BookEntity> findBookByFileNameAndLibraryId(String fileName, long libraryId); Optional<BookEntity> findBookByFileNameAndLibraryId(String fileName, long libraryId);
Optional<BookEntity> findByCurrentHash(String currentHash); Optional<BookEntity> findByCurrentHash(String currentHash);
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
List<BookEntity> findAllByLibraryPathIdAndFileSubPathStartingWith(Long libraryPathId, String fileSubPathPrefix); List<BookEntity> findAllByLibraryPathIdAndFileSubPathStartingWith(Long libraryPathId, String fileSubPathPrefix);
@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)") @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)")
@@ -31,9 +33,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds AND (b.deleted IS NULL OR b.deleted = false)") @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); 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"}) @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadata(); List<BookEntity> findAllWithMetadata();
@@ -22,6 +22,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository; import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService; import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
@@ -70,6 +71,7 @@ public class BookDropService {
private final AppProperties appProperties; private final AppProperties appProperties;
private final BookdropFileMapper mapper; private final BookdropFileMapper mapper;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
AppSettingService appSettingService;
public BookdropFileNotification getFileNotificationSummary() { public BookdropFileNotification getFileNotificationSummary() {
long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW); long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
@@ -127,7 +129,7 @@ public class BookDropService {
failedCount.incrementAndGet(); failedCount.incrementAndGet();
continue; continue;
} }
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount); processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
} }
} }
} else { } else {
@@ -156,7 +158,7 @@ public class BookDropService {
failedCount.incrementAndGet(); failedCount.incrementAndGet();
continue; continue;
} }
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount); processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
} }
} }
} }
@@ -188,7 +190,6 @@ public class BookDropService {
BookdropFinalizeRequest.BookdropFinalizeFile fileReq, BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId, Long defaultLibraryId,
Long defaultPathId, Long defaultPathId,
String uploadPattern,
BookdropFinalizeResult results, BookdropFinalizeResult results,
AtomicInteger failedCount AtomicInteger failedCount
) { ) {
@@ -217,13 +218,7 @@ public class BookDropService {
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId); log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} }
BookdropFileResult result = moveFile( BookdropFileResult result = moveFile(libraryId, pathId, metadata, fileEntity);
libraryId,
pathId,
uploadPattern,
metadata,
fileEntity
);
results.getResults().add(result); results.getResults().add(result);
if (!result.isSuccess()) { if (!result.isSuccess()) {
@@ -241,7 +236,7 @@ public class BookDropService {
} }
} }
private BookdropFileResult moveFile(long libraryId, long pathId, String filePattern, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception { private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
LibraryEntity library = libraryRepository.findById(libraryId) LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -250,6 +245,11 @@ public class BookDropService {
.findFirst() .findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
String filePattern = library.getFileNamingPattern();
if (filePattern == null || filePattern.isBlank()) {
filePattern = appSettingService.getAppSettings().getUploadPattern();
}
if (filePattern.endsWith("/") || filePattern.endsWith("\\")) { if (filePattern.endsWith("/") || filePattern.endsWith("\\")) {
filePattern += "{currentFilename}"; filePattern += "{currentFilename}";
} }
@@ -39,28 +39,42 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
@Transactional(propagation = Propagation.REQUIRES_NEW) @Transactional(propagation = Propagation.REQUIRES_NEW)
@Override @Override
public Book processFile(LibraryFile libraryFile) { public Book processFile(LibraryFile libraryFile) {
Path filePath = libraryFile.getFullPath(); Path path = libraryFile.getFullPath();
String fileName = filePath.getFileName().toString(); String fileName = path.getFileName().toString();
String hash = FileFingerprint.generateHash(filePath); String hash = FileFingerprint.generateHash(path);
Optional<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookMapper); Optional<Book> duplicate = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookMapper);
if (existing.isPresent()) { if (duplicate.isPresent()) {
return existing.get(); return handleDuplicate(duplicate.get(), libraryFile);
}
Optional<BookEntity> byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
if (byName.isPresent()) {
return bookMapper.toBook(byName.get());
} }
BookEntity book = processNewFile(libraryFile); Long libraryId = libraryFile.getLibraryEntity().getId();
book.setCurrentHash(hash); return bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
.map(bookMapper::toBook)
.orElseGet(() -> createAndMapBook(libraryFile, hash));
}
Float score = metadataMatchService.calculateMatchScore(book); private Book handleDuplicate(Book bookDto, LibraryFile libraryFile) {
book.setMetadataMatchScore(score); bookRepository.findById(bookDto.getId())
.ifPresent(entity -> {
entity.setFileSubPath(libraryFile.getFileSubPath());
entity.setFileName(libraryFile.getFileName());
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
log.info("Duplicate file handled: bookId={} fileName='{}' libraryId={} subPath='{}'",
entity.getId(),
libraryFile.getFileName(),
libraryFile.getLibraryEntity().getId(),
libraryFile.getFileSubPath());
});
return bookDto;
}
bookCreatorService.saveConnections(book); private Book createAndMapBook(LibraryFile libraryFile, String hash) {
BookEntity entity = processNewFile(libraryFile);
return bookMapper.toBook(book); entity.setCurrentHash(hash);
entity.setMetadataMatchScore(metadataMatchService.calculateMatchScore(entity));
bookCreatorService.saveConnections(entity);
return bookMapper.toBook(entity);
} }
protected abstract BookEntity processNewFile(LibraryFile libraryFile); protected abstract BookEntity processNewFile(LibraryFile libraryFile);
@@ -1,6 +1,7 @@
package com.adityachandel.booklore.service.library; package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryEntity;
@@ -21,6 +22,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -36,6 +38,7 @@ public class LibraryProcessingService {
private final NotificationService notificationService; private final NotificationService notificationService;
private final BookRepository bookRepository; private final BookRepository bookRepository;
private final FileService fileService; private final FileService fileService;
private final BookMapper bookMapper;
private final LibraryFileProcessorRegistry fileProcessorRegistry; private final LibraryFileProcessorRegistry fileProcessorRegistry;
@Transactional @Transactional
@@ -53,12 +56,47 @@ public class LibraryProcessingService {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName())); notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity); List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
deleteRemovedBooks(detectDeletedBookIds(libraryFiles, libraryEntity)); List<Long> bookIds = detectDeletedBookIds(libraryFiles, libraryEntity);
if (!bookIds.isEmpty()) {
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
deleteRemovedBooks(bookIds);
}
restoreDeletedBooks(libraryFiles);
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity); processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName())); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
} }
private void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
if (libraryFiles.isEmpty()) return;
LibraryEntity libraryEntity = libraryFiles.get(0).getLibraryEntity();
Set<Path> currentPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
.filter(book -> currentPaths.contains(book.getFullFilePath()))
.collect(Collectors.toList());
if (toRestore.isEmpty()) return;
toRestore.forEach(book -> {
book.setDeleted(false);
book.setDeletedAt(null);
book.setAddedOn(Instant.now());
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
});
bookRepository.saveAll(toRestore);
List<Long> restoredIds = toRestore.stream()
.map(BookEntity::getId)
.toList();
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
}
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) { public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(libraryFiles, libraryEntity); processor.processLibraryFiles(libraryFiles, libraryEntity);
@@ -150,4 +188,4 @@ public class LibraryProcessingService {
.toList(); .toList();
} }
} }
} }
@@ -231,4 +231,10 @@ public class LibraryService {
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId); List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
return bookEntities.stream().map(bookMapper::toBook).toList(); return bookEntities.stream().map(bookMapper::toBook).toList();
} }
public Library setFileNamingPattern(long libraryId, String pattern) {
LibraryEntity library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
library.setFileNamingPattern(pattern);
return libraryMapper.toLibrary(libraryRepository.save(library));
}
} }
@@ -5,44 +5,44 @@ import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.MetadataUpdateWrapper; import com.adityachandel.booklore.model.MetadataUpdateWrapper;
import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.TaskMessage;
import com.adityachandel.booklore.model.dto.MetadataBatchProgressNotification; import com.adityachandel.booklore.model.dto.MetadataBatchProgressNotification;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions; import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest; import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension; import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.MetadataFetchJobEntity;
import com.adityachandel.booklore.model.entity.MetadataFetchProposalEntity;
import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus; import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus;
import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus; import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus;
import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.model.enums.EventTaskType;
import com.adityachandel.booklore.model.enums.TaskStatus;
import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookdropFileRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.MetadataFetchJobRepository; import com.adityachandel.booklore.repository.MetadataFetchJobRepository;
import com.adityachandel.booklore.repository.MetadataFetchProposalRepository; import com.adityachandel.booklore.repository.MetadataFetchProposalRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.metadata.parser.BookParser; import com.adityachandel.booklore.service.metadata.parser.BookParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.File;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.entity.BookdropFileEntity.Status.PENDING_REVIEW;
import static com.adityachandel.booklore.model.enums.MetadataProvider.*; import static com.adityachandel.booklore.model.enums.MetadataProvider.*;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@Slf4j @Slf4j
@AllArgsConstructor @AllArgsConstructor
@@ -56,92 +56,193 @@ public class MetadataRefreshService {
private final BookMetadataUpdater bookMetadataUpdater; private final BookMetadataUpdater bookMetadataUpdater;
private final NotificationService notificationService; private final NotificationService notificationService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
private final BookQueryService bookQueryService;
private final Map<MetadataProvider, BookParser> parserMap; private final Map<MetadataProvider, BookParser> parserMap;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final BookRepository bookRepository;
private final PlatformTransactionManager transactionManager;
@Transactional public void refreshMetadata(MetadataRefreshRequest request, Long userId, String jobId) {
public void refreshMetadata(MetadataRefreshRequest request, Long userId) {
log.info("Refresh Metadata task started!");
if (Boolean.TRUE.equals(request.getQuick())) {
AppSettings appSettings = appSettingService.getAppSettings();
request.setRefreshOptions(appSettings.getMetadataRefreshOptions());
}
List<MetadataProvider> providers = prepareProviders(request);
List<BookEntity> books = getBookEntities(request);
boolean isReviewMode = Boolean.TRUE.equals(request.getRefreshOptions().getReviewBeforeApply());
MetadataFetchJobEntity task = null;
String taskId = null;
if (isReviewMode) {
taskId = UUID.randomUUID().toString();
task = MetadataFetchJobEntity.builder()
.taskId(taskId)
.userId(userId)
.status(MetadataFetchTaskStatus.IN_PROGRESS)
.startedAt(Instant.now())
.totalBooksCount(books.size())
.completedBooks(0)
.build();
metadataFetchJobRepository.save(task);
}
int completedCount = 0;
try { try {
for (BookEntity book : books) { if (Boolean.TRUE.equals(request.getQuick())) {
try { AppSettings appSettings = appSettingService.getAppSettings();
if (book.getMetadata().areAllFieldsLocked()) { request.setRefreshOptions(appSettings.getMetadataRefreshOptions());
log.info("Skipping locked book: {}", book.getFileName());
notificationService.sendMessage(Topic.LOG, createLogNotification("Book '" + book.getMetadata().getTitle() + "' is locked."));
continue;
}
reportProgressIfNeeded(task, taskId, completedCount, books.size(), book);
Map<MetadataProvider, BookMetadata> metadataMap = fetchMetadataForBook(providers, book);
if (providers.contains(GoodReads)) {
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1500));
}
BookMetadata fetched = buildFetchMetadata(book.getId(), request, metadataMap);
if (isReviewMode) {
saveProposal(taskId, book.getId(), fetched);
} else {
updateBookMetadata(book, fetched, request.getRefreshOptions().isRefreshCovers(), request.getRefreshOptions().isMergeCategories());
}
completedCount++;
} catch (Exception e) {
log.error("Metadata update failed for book: {}", book.getFileName(), e);
}
} }
List<MetadataProvider> providers = prepareProviders(request);
Set<Long> bookIds = getBookEntities(request);
boolean isReviewMode = Boolean.TRUE.equals(request.getRefreshOptions().getReviewBeforeApply());
MetadataFetchJobEntity task;
if (isReviewMode) { if (isReviewMode) {
completeTask(task, completedCount, books.size()); task = MetadataFetchJobEntity.builder()
.taskId(jobId)
.userId(userId)
.status(MetadataFetchTaskStatus.IN_PROGRESS)
.startedAt(Instant.now())
.totalBooksCount(bookIds.size())
.completedBooks(0)
.build();
metadataFetchJobRepository.save(task);
} else {
task = null;
} }
TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
int completedCount = 0;
for (Long bookId : bookIds) {
checkForInterruption(jobId, task, bookIds.size());
int finalCompletedCount = completedCount;
txTemplate.execute(status -> {
BookEntity book = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId))
.stream().findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
try {
checkForInterruption(jobId, task, bookIds.size());
if (book.getMetadata().areAllFieldsLocked()) {
log.info("Skipping locked book: {}", book.getFileName());
sendTaskNotification(jobId, "Skipped locked book: " + book.getMetadata().getTitle(), TaskStatus.IN_PROGRESS);
return null;
}
reportProgressIfNeeded(task, jobId, finalCompletedCount, bookIds.size(), book);
Map<MetadataProvider, BookMetadata> metadataMap = fetchMetadataForBook(providers, book);
if (providers.contains(GoodReads)) {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1500));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
status.setRollbackOnly();
return null;
}
}
BookMetadata fetched = buildFetchMetadata(book.getId(), request, metadataMap);
if (isReviewMode) {
saveProposal(task.getTaskId(), book.getId(), fetched);
} else {
updateBookMetadata(book, fetched, request.getRefreshOptions().isRefreshCovers(), request.getRefreshOptions().isMergeCategories());
sendTaskProgressNotification(jobId, finalCompletedCount + 1, bookIds.size(), "Metadata updated: " + book.getMetadata().getTitle());
}
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
log.info("Processing interrupted for book: {}", book.getFileName());
status.setRollbackOnly();
return null;
}
log.error("Metadata update failed for book: {}", book.getFileName(), e);
sendTaskNotification(jobId, String.format("Failed to process: %s - %s", book.getMetadata().getTitle(), e.getMessage()), TaskStatus.FAILED);
}
bookRepository.saveAndFlush(book);
return null;
});
completedCount++;
}
if (isReviewMode) completeTask(task, completedCount, bookIds.size());
log.info("Metadata refresh task {} completed successfully", jobId);
sendTaskNotification(jobId, String.format("Metadata refresh completed successfully - processed %d books", completedCount), TaskStatus.COMPLETED);
} catch (RuntimeException e) {
if (e.getCause() instanceof InterruptedException) {
log.info("Metadata refresh task {} cancelled successfully", jobId);
return;
}
log.error("Fatal error during metadata refresh", e);
sendTaskNotification(jobId, "Fatal error during metadata refresh: " + e.getMessage(), TaskStatus.FAILED);
throw e;
} catch (Exception fatal) { } catch (Exception fatal) {
log.error("Fatal error during metadata refresh", fatal); log.error("Fatal error during metadata refresh", fatal);
if (isReviewMode) { sendTaskNotification(jobId, "Fatal error during metadata refresh: " + fatal.getMessage(), TaskStatus.FAILED);
failTask(task, books.size(), fatal.getMessage());
}
throw fatal; throw fatal;
} }
}
log.info("Metadata refresh task completed!"); public Map<MetadataProvider, BookMetadata> fetchMetadataForBook(List<MetadataProvider> providers, Book book) {
return providers.stream()
.map(provider -> createInterruptibleMetadataFuture(() -> fetchTopMetadataFromAProvider(provider, book)))
.map(this::joinFutureSafely)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
BookMetadata::getProvider,
metadata -> metadata,
(existing, replacement) -> existing
));
}
protected Map<MetadataProvider, BookMetadata> fetchMetadataForBook(List<MetadataProvider> providers, BookEntity bookEntity) {
Book book = bookMapper.toBook(bookEntity);
return providers.stream()
.map(provider -> createInterruptibleMetadataFuture(() -> fetchTopMetadataFromAProvider(provider, book)))
.map(this::joinFutureSafely)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
BookMetadata::getProvider,
metadata -> metadata,
(existing, replacement) -> existing
));
}
private CompletableFuture<BookMetadata> createInterruptibleMetadataFuture(java.util.function.Supplier<BookMetadata> metadataSupplier) {
return CompletableFuture.supplyAsync(() -> {
if (Thread.currentThread().isInterrupted()) {
log.info("Skipping metadata fetch due to interruption");
return null;
}
return metadataSupplier.get();
}).exceptionally(e -> {
if (e.getCause() instanceof InterruptedException) {
log.info("Metadata fetch was interrupted");
Thread.currentThread().interrupt();
return null;
}
log.error("Error fetching metadata from provider", e);
return null;
});
}
private BookMetadata joinFutureSafely(CompletableFuture<BookMetadata> future) {
try {
return future.join();
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
log.info("Future join interrupted");
return null;
}
throw e;
}
}
private void checkForInterruption(String jobId, MetadataFetchJobEntity task, int totalBooks) {
if (Thread.currentThread().isInterrupted()) {
log.info("Metadata refresh task {} cancelled by user request", jobId);
sendTaskNotification(jobId, "Task cancelled by user", TaskStatus.CANCELLED);
if (task != null) {
failTask(task, totalBooks);
}
throw new RuntimeException(new InterruptedException("Task was cancelled"));
}
}
private void sendTaskNotification(String taskId, String message, TaskStatus status) {
notificationService.sendMessage(Topic.TASK, TaskMessage.builder()
.taskId(taskId)
.taskType(EventTaskType.METADATA_REFRESH)
.message(message)
.status(status)
.build());
}
private void sendTaskProgressNotification(String taskId, int current, int total, String message) {
sendTaskNotification(taskId, String.format("(%d/%d) %s", current, total, message), TaskStatus.IN_PROGRESS);
} }
private void reportProgressIfNeeded(MetadataFetchJobEntity task, String taskId, int completedCount, int total, BookEntity book) { private void reportProgressIfNeeded(MetadataFetchJobEntity task, String taskId, int completedCount, int total, BookEntity book) {
if (task == null) return; if (task == null) return;
task.setCompletedBooks(completedCount); task.setCompletedBooks(completedCount);
metadataFetchJobRepository.save(task); metadataFetchJobRepository.save(task);
String message = String.format("Processing '%s'", book.getMetadata().getTitle()); String message = String.format("Processing '%s'", book.getMetadata().getTitle());
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS, notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS,
new MetadataBatchProgressNotification( new MetadataBatchProgressNotification(
taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS.name() taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS.name()
@@ -161,14 +262,14 @@ public class MetadataRefreshService {
)); ));
} }
private void failTask(MetadataFetchJobEntity task, int total, String errorMessage) { private void failTask(MetadataFetchJobEntity task, int total) {
task.setStatus(MetadataFetchTaskStatus.ERROR); task.setStatus(MetadataFetchTaskStatus.ERROR);
task.setCompletedAt(Instant.now()); task.setCompletedAt(Instant.now());
metadataFetchJobRepository.save(task); metadataFetchJobRepository.save(task);
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS, notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS,
new MetadataBatchProgressNotification( new MetadataBatchProgressNotification(
task.getTaskId(), 0, total, "Error: " + errorMessage, task.getTaskId(), 0, total, "Error: " + "Task was cancelled",
MetadataFetchTaskStatus.ERROR.name() MetadataFetchTaskStatus.ERROR.name()
)); ));
} }
@@ -188,7 +289,7 @@ public class MetadataRefreshService {
metadataFetchProposalRepository.save(proposal); metadataFetchProposalRepository.save(proposal);
} }
@Transactional
public void updateBookMetadata(BookEntity bookEntity, BookMetadata metadata, boolean replaceCover, boolean mergeCategories) { public void updateBookMetadata(BookEntity bookEntity, BookMetadata metadata, boolean replaceCover, boolean mergeCategories) {
if (metadata != null) { if (metadata != null) {
MetadataUpdateWrapper metadataUpdateWrapper = MetadataUpdateWrapper.builder() MetadataUpdateWrapper metadataUpdateWrapper = MetadataUpdateWrapper.builder()
@@ -198,17 +299,14 @@ public class MetadataRefreshService {
Book book = bookMapper.toBook(bookEntity); Book book = bookMapper.toBook(bookEntity);
notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, book); notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, book);
notificationService.sendMessage(Topic.LOG, createLogNotification("Book metadata updated: " + book.getMetadata().getTitle()));
} }
} }
@Transactional
public List<MetadataProvider> prepareProviders(MetadataRefreshRequest request) { public List<MetadataProvider> prepareProviders(MetadataRefreshRequest request) {
Set<MetadataProvider> allProviders = new HashSet<>(getAllProvidersUsingIndividualFields(request)); Set<MetadataProvider> allProviders = new HashSet<>(getAllProvidersUsingIndividualFields(request));
return new ArrayList<>(allProviders); return new ArrayList<>(allProviders);
} }
@Transactional
protected Set<MetadataProvider> getAllProvidersUsingIndividualFields(MetadataRefreshRequest request) { protected Set<MetadataProvider> getAllProvidersUsingIndividualFields(MetadataRefreshRequest request) {
MetadataRefreshOptions.FieldOptions fieldOptions = request.getRefreshOptions().getFieldOptions(); MetadataRefreshOptions.FieldOptions fieldOptions = request.getRefreshOptions().getFieldOptions();
Set<MetadataProvider> uniqueProviders = new HashSet<>(); Set<MetadataProvider> uniqueProviders = new HashSet<>();
@@ -224,7 +322,6 @@ public class MetadataRefreshService {
return uniqueProviders; return uniqueProviders;
} }
@Transactional
protected void addProviderToSet(MetadataRefreshOptions.FieldProvider fieldProvider, Set<MetadataProvider> providerSet) { protected void addProviderToSet(MetadataRefreshOptions.FieldProvider fieldProvider, Set<MetadataProvider> providerSet) {
if (fieldProvider != null) { if (fieldProvider != null) {
if (fieldProvider.getP4() != null) providerSet.add(fieldProvider.getP4()); if (fieldProvider.getP4() != null) providerSet.add(fieldProvider.getP4());
@@ -234,39 +331,6 @@ public class MetadataRefreshService {
} }
} }
@Transactional
public Map<MetadataProvider, BookMetadata> fetchMetadataForBook(List<MetadataProvider> providers, Book book) {
return providers.stream()
.map(provider -> CompletableFuture.supplyAsync(() -> fetchTopMetadataFromAProvider(provider, book))
.exceptionally(e -> {
log.error("Error fetching metadata from provider: {}", provider, e);
return null;
}))
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
BookMetadata::getProvider,
metadata -> metadata,
(existing, replacement) -> existing
));
}
@Transactional
protected Map<MetadataProvider, BookMetadata> fetchMetadataForBook(List<MetadataProvider> providers, BookEntity bookEntity) {
return providers.stream()
.map(provider -> CompletableFuture.supplyAsync(() -> fetchTopMetadataFromAProvider(provider, bookMapper.toBook(bookEntity)))
.exceptionally(e -> {
log.error("Error fetching metadata from provider: {}", provider, e);
return null;
}))
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
BookMetadata::getProvider,
metadata -> metadata,
(existing, replacement) -> existing
));
}
public BookMetadata fetchTopMetadataFromAProvider(MetadataProvider provider, Book book) { public BookMetadata fetchTopMetadataFromAProvider(MetadataProvider provider, Book book) {
return getParser(provider).fetchTopMetadata(book, buildFetchMetadataRequestFromBook(book)); return getParser(provider).fetchTopMetadata(book, buildFetchMetadataRequestFromBook(book));
@@ -291,7 +355,6 @@ public class MetadataRefreshService {
.build(); .build();
} }
@Transactional
public BookMetadata buildFetchMetadata(Long bookId, MetadataRefreshRequest request, Map<MetadataProvider, BookMetadata> metadataMap) { public BookMetadata buildFetchMetadata(Long bookId, MetadataRefreshRequest request, Map<MetadataProvider, BookMetadata> metadataMap) {
BookMetadata metadata = BookMetadata.builder().bookId(bookId).build(); BookMetadata metadata = BookMetadata.builder().bookId(bookId).build();
MetadataRefreshOptions.FieldOptions fieldOptions = request.getRefreshOptions().getFieldOptions(); MetadataRefreshOptions.FieldOptions fieldOptions = request.getRefreshOptions().getFieldOptions();
@@ -309,11 +372,10 @@ public class MetadataRefreshService {
if (metadataMap.containsKey(Google)) { if (metadataMap.containsKey(Google)) {
metadata.setGoogleId(metadataMap.get(Google).getGoogleId()); metadata.setGoogleId(metadataMap.get(Google).getGoogleId());
} }
if (metadataMap.containsKey(Comicvine)){ if (metadataMap.containsKey(Comicvine)) {
metadata.setComicvineId(metadataMap.get(Comicvine).getComicvineId()); metadata.setComicvineId(metadataMap.get(Comicvine).getComicvineId());
} }
if (request.getRefreshOptions().isMergeCategories()) { if (request.getRefreshOptions().isMergeCategories()) {
metadata.setCategories(getAllCategories(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories)); metadata.setCategories(getAllCategories(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories));
@@ -338,7 +400,7 @@ public class MetadataRefreshService {
return metadata; return metadata;
} }
@Transactional
protected void setOtherUnspecifiedMetadata(Map<MetadataProvider, BookMetadata> metadataMap, BookMetadata metadataCombined, MetadataProvider provider) { protected void setOtherUnspecifiedMetadata(Map<MetadataProvider, BookMetadata> metadataMap, BookMetadata metadataCombined, MetadataProvider provider) {
if (metadataMap.containsKey(provider)) { if (metadataMap.containsKey(provider)) {
BookMetadata metadata = metadataMap.get(provider); BookMetadata metadata = metadataMap.get(provider);
@@ -373,7 +435,7 @@ public class MetadataRefreshService {
Set<String> extract(BookMetadata metadata); Set<String> extract(BookMetadata metadata);
} }
@Transactional
protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) { protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) {
String value = null; String value = null;
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) { if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
@@ -395,7 +457,7 @@ public class MetadataRefreshService {
return value; return value;
} }
@Transactional
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) { protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
Set<String> values = new HashSet<>(); Set<String> values = new HashSet<>();
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) { if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
@@ -439,23 +501,18 @@ public class MetadataRefreshService {
} }
@Transactional protected Set<Long> getBookEntities(MetadataRefreshRequest request) {
protected List<BookEntity> getBookEntities(MetadataRefreshRequest request) {
MetadataRefreshRequest.RefreshType refreshType = request.getRefreshType(); MetadataRefreshRequest.RefreshType refreshType = request.getRefreshType();
if (refreshType != MetadataRefreshRequest.RefreshType.LIBRARY && refreshType != MetadataRefreshRequest.RefreshType.BOOKS) { if (refreshType != MetadataRefreshRequest.RefreshType.LIBRARY && refreshType != MetadataRefreshRequest.RefreshType.BOOKS) {
throw ApiError.INVALID_REFRESH_TYPE.createException(); throw ApiError.INVALID_REFRESH_TYPE.createException();
} }
return switch (refreshType) {
List<BookEntity> books = switch (refreshType) {
case LIBRARY -> { case LIBRARY -> {
LibraryEntity libraryEntity = libraryRepository.findById(request.getLibraryId()) LibraryEntity libraryEntity = libraryRepository.findById(request.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(request.getLibraryId()));
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(request.getLibraryId())); yield bookRepository.findBookIdsByLibraryId(libraryEntity.getId());
yield libraryEntity.getBookEntities();
} }
case BOOKS -> bookQueryService.findAllWithMetadataByIds(request.getBookIds()); case BOOKS -> request.getBookIds();
}; };
books.sort(Comparator.comparing(BookEntity::getFileName, Comparator.nullsLast(String::compareTo)));
return books;
} }
} }
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.service.upload; package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.BookMetadata;
@@ -48,6 +49,7 @@ public class FileUploadService {
private final BookFileProcessorRegistry processorRegistry; private final BookFileProcessorRegistry processorRegistry;
private final NotificationService notificationService; private final NotificationService notificationService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
private final AppProperties appProperties;
private final PdfMetadataExtractor pdfMetadataExtractor; private final PdfMetadataExtractor pdfMetadataExtractor;
private final EpubMetadataExtractor epubMetadataExtractor; private final EpubMetadataExtractor epubMetadataExtractor;
private final MonitoringService monitoringService; private final MonitoringService monitoringService;
@@ -61,8 +63,7 @@ public class FileUploadService {
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException { public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
validateFile(file); validateFile(file);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId) LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths() LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
.stream() .stream()
@@ -81,20 +82,15 @@ public class FileUploadService {
try { try {
file.transferTo(tempPath); file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath); setTemporaryFileOwnership(tempPath);
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension")); BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile()); BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile());
String uploadPattern = appSettingService.getAppSettings().getUploadPattern(); String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) { if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) {
uploadPattern += "{currentFilename}"; uploadPattern += "{currentFilename}";
} }
String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename()); String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename());
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath); Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
File finalFile = finalPath.toFile(); File finalFile = finalPath.toFile();
@@ -132,6 +128,33 @@ public class FileUploadService {
} }
} }
public Book uploadFileBookDrop(MultipartFile file) throws IOException {
validateFile(file);
Path dropFolder = Paths.get(appProperties.getBookdropFolder());
Files.createDirectories(dropFolder);
String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
Path tempPath = Files.createTempFile("bookdrop-", originalFilename);
try {
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
Path finalPath = dropFolder.resolve(originalFilename);
if (Files.exists(finalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
Files.move(tempPath, finalPath);
log.info("File moved to book-drop folder: {}", finalPath);
return null;
} finally {
Files.deleteIfExists(tempPath);
}
}
private BookMetadata extractMetadata(BookFileExtension fileExt, File file) throws IOException { private BookMetadata extractMetadata(BookFileExtension fileExt, File file) throws IOException {
return switch (fileExt) { return switch (fileExt) {
case PDF -> pdfMetadataExtractor.extractMetadata(file); case PDF -> pdfMetadataExtractor.extractMetadata(file);
@@ -153,7 +176,7 @@ public class FileUploadService {
private void setTemporaryFileOwnership(Path tempPath) throws IOException { private void setTemporaryFileOwnership(Path tempPath) throws IOException {
UserPrincipalLookupService lookupService = FileSystems.getDefault() UserPrincipalLookupService lookupService = FileSystems.getDefault()
.getUserPrincipalLookupService(); .getUserPrincipalLookupService();
if (!userId.equals("0")) { if (!userId.equals("0")) {
UserPrincipal user = lookupService.lookupPrincipalByName(userId); UserPrincipal user = lookupService.lookupPrincipalByName(userId);
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setOwner(user); Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setOwner(user);
@@ -178,5 +201,4 @@ public class FileUploadService {
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type); BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile); return processor.processFile(libraryFile);
} }
} }
@@ -0,0 +1,3 @@
ALTER TABLE library
ADD COLUMN IF NOT EXISTS file_naming_pattern VARCHAR(1000);
@@ -0,0 +1,212 @@
package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
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.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class FileUploadServiceTest {
@TempDir
Path tempDir;
@Mock
LibraryRepository libraryRepository;
@Mock
BookFileProcessorRegistry processorRegistry;
@Mock
NotificationService notificationService;
@Mock
AppSettingService appSettingService;
@Mock
PdfMetadataExtractor pdfMetadataExtractor;
@Mock
EpubMetadataExtractor epubMetadataExtractor;
@Mock
MonitoringService monitoringService;
AppProperties appProperties;
FileUploadService service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
appProperties = new AppProperties();
appProperties.setBookdropFolder(tempDir.toString());
AppSettings settings = new AppSettings();
settings.setMaxFileUploadSizeInMb(10);
settings.setUploadPattern("{currentFilename}");
when(appSettingService.getAppSettings()).thenReturn(settings);
service = new FileUploadService(
libraryRepository, processorRegistry, notificationService,
appSettingService, appProperties, pdfMetadataExtractor,
epubMetadataExtractor, monitoringService
);
ReflectionTestUtils.setField(service, "userId", "0");
ReflectionTestUtils.setField(service, "groupId", "0");
}
@Test
void uploadFileBookDrop_succeeds_and_copiesFile() throws IOException {
byte[] content = "hello".getBytes();
MockMultipartFile file = new MockMultipartFile("file", "test.pdf", "application/pdf", content);
assertThat(service.uploadFileBookDrop(file)).isNull();
Path dropped = tempDir.resolve("test.pdf");
assertThat(Files.exists(dropped)).isTrue();
assertThat(Files.readAllBytes(dropped)).isEqualTo(content);
}
@Test
void uploadFileBookDrop_throws_when_duplicate() throws IOException {
byte[] content = "data".getBytes();
MockMultipartFile file = new MockMultipartFile("file", "dup.epub", "application/epub+zip", content);
Files.write(tempDir.resolve("dup.epub"), new byte[]{1, 2, 3});
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFileBookDrop(file))
.satisfies(ex -> {
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getStatus());
assertThat(ex.getMessage()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getMessage());
});
}
@Test
void uploadFileBookDrop_throws_on_invalid_extension() {
MockMultipartFile file = new MockMultipartFile("file", "bad.txt", "text/plain", "x".getBytes());
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFileBookDrop(file))
.satisfies(ex -> {
assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_FILE_FORMAT.getStatus());
assertThat(ex.getMessage()).contains("Invalid file format, only pdf and epub are supported");
});
}
@Test
void uploadFileBookDrop_throws_when_too_large() {
byte[] content = new byte[2 * 1024 * 1024];
MockMultipartFile file = new MockMultipartFile("file", "big.pdf", "application/pdf", content);
AppSettings small = new AppSettings();
small.setMaxFileUploadSizeInMb(1);
when(appSettingService.getAppSettings()).thenReturn(small);
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFileBookDrop(file))
.satisfies(ex -> {
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_TOO_LARGE.getStatus());
assertThat(ex.getMessage()).contains("1");
});
}
@Test
void uploadFile_throws_when_library_not_found() {
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", new byte[]{1});
when(libraryRepository.findById(42L)).thenReturn(Optional.empty());
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFile(file, 42L, 1L))
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.LIBRARY_NOT_FOUND.getStatus()));
}
@Test
void uploadFile_throws_when_invalid_library_path() {
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", new byte[]{1});
LibraryEntity lib = new LibraryEntity();
lib.setId(42L);
lib.setLibraryPaths(List.of());
when(libraryRepository.findById(42L)).thenReturn(Optional.of(lib));
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFile(file, 42L, 99L))
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_LIBRARY_PATH.getStatus()));
}
@Test
void uploadFile_throws_on_transfer_io_exception() throws IOException {
MultipartFile file = mock(MultipartFile.class);
when(file.getOriginalFilename()).thenReturn("book.cbz");
when(file.getSize()).thenReturn(100L);
when(file.getName()).thenReturn("file");
doThrow(new IOException("disk error")).when(file).transferTo(any(Path.class));
LibraryEntity lib = new LibraryEntity();
lib.setId(1L);
LibraryPathEntity path = new LibraryPathEntity();
path.setId(1L);
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(lib));
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
.satisfies(ex -> {
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_READ_ERROR.getStatus());
assertThat(ex.getMessage()).contains("Error reading files from path");
});
}
@Test
void uploadFile_succeeds_and_processes() throws IOException {
byte[] data = "content".getBytes();
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", data);
LibraryEntity lib = new LibraryEntity();
lib.setId(7L);
LibraryPathEntity path = new LibraryPathEntity();
path.setId(2L);
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(7L)).thenReturn(Optional.of(lib));
BookFileProcessor proc = mock(BookFileProcessor.class);
Book stubBook = Book.builder().build();
stubBook.setTitle("X");
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(proc);
when(proc.processFile(any())).thenReturn(stubBook);
Book result = service.uploadFile(file, 7L, 2L);
assertThat(result).isSameAs(stubBook);
Path moved = tempDir.resolve("book.cbz");
assertThat(Files.exists(moved)).isTrue();
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(stubBook));
verifyNoInteractions(pdfMetadataExtractor, epubMetadataExtractor);
}
}
+570 -2807
View File
File diff suppressed because it is too large Load Diff
+18 -18
View File
@@ -12,16 +12,16 @@
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "^20.0.1", "@angular/animations": "^20.1.6",
"@angular/common": "^20.0.1", "@angular/common": "^20.1.6",
"@angular/compiler": "^20.0.1", "@angular/compiler": "^20.1.6",
"@angular/core": "^20.0.1", "@angular/core": "^20.1.6",
"@angular/forms": "^20.0.1", "@angular/forms": "^20.1.6",
"@angular/platform-browser": "^20.0.1", "@angular/platform-browser": "^20.1.6",
"@angular/platform-browser-dynamic": "^20.0.1", "@angular/platform-browser-dynamic": "^20.1.6",
"@angular/router": "^20.0.1", "@angular/router": "^20.1.6",
"@iharbeck/ngx-virtual-scroller": "^19.0.1", "@iharbeck/ngx-virtual-scroller": "^19.0.1",
"@primeng/themes": "^19.1.3", "@primeng/themes": "^19.1.4",
"@stomp/rx-stomp": "^2.0.1", "@stomp/rx-stomp": "^2.0.1",
"@stomp/stompjs": "^7.1.1", "@stomp/stompjs": "^7.1.1",
"@tailwindcss/postcss": "^4.1.8", "@tailwindcss/postcss": "^4.1.8",
@@ -30,9 +30,9 @@
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"ng-lazyload-image": "^9.1.3", "ng-lazyload-image": "^9.1.3",
"ngx-extended-pdf-viewer": "^23.3.1", "ngx-extended-pdf-viewer": "^23.3.1",
"ngx-infinite-scroll": "^19.0.0", "ngx-infinite-scroll": "^20.0.0",
"primeicons": "^7.0.0", "primeicons": "^7.0.0",
"primeng": "19.1.2", "primeng": "19.1.4",
"quill": "^2.0.3", "quill": "^2.0.3",
"rxjs": "^7.8.2", "rxjs": "^7.8.2",
"showdown": "^2.1.0", "showdown": "^2.1.0",
@@ -42,15 +42,15 @@
"zone.js": "^0.15.1" "zone.js": "^0.15.1"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "^20.0.1", "@angular-devkit/build-angular": "^20.1.5",
"@angular/cli": "^20.0.1", "@angular/cli": "^20.1.5",
"@angular/compiler-cli": "^20.0.1", "@angular/compiler-cli": "^20.1.6",
"@tailwindcss/typography": "^0.5.16", "@tailwindcss/typography": "^0.5.16",
"@types/jasmine": "^5.1.8", "@types/jasmine": "^5.1.8",
"@types/showdown": "^2.0.6", "@types/showdown": "^2.0.6",
"angular-eslint": "^19.7.1", "angular-eslint": "^20.1.1",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"eslint": "^9.28.0", "eslint": "^9.33.0",
"jasmine-core": "^5.7.1", "jasmine-core": "^5.7.1",
"karma": "^6.4.4", "karma": "^6.4.4",
"karma-chrome-launcher": "^3.2.0", "karma-chrome-launcher": "^3.2.0",
@@ -58,7 +58,7 @@
"karma-jasmine": "^5.1.0", "karma-jasmine": "^5.1.0",
"karma-jasmine-html-reporter": "^2.1.0", "karma-jasmine-html-reporter": "^2.1.0",
"tailwindcss": "3.4.17", "tailwindcss": "3.4.17",
"typescript": "^5.8.3", "typescript": "^5.8.2",
"typescript-eslint": "^8.33.1" "typescript-eslint": "^8.39.0"
} }
} }
+8 -1
View File
@@ -3,7 +3,7 @@ import {RxStompService} from './shared/websocket/rx-stomp.service';
import {Message} from '@stomp/stompjs'; import {Message} from '@stomp/stompjs';
import {BookService} from './book/service/book.service'; import {BookService} from './book/service/book.service';
import {NotificationEventService} from './shared/websocket/notification-event.service'; import {NotificationEventService} from './shared/websocket/notification-event.service';
import {parseLogNotification} from './shared/websocket/model/log-notification.model'; import {parseLogNotification, parseTaskMessage, TaskMessage} from './shared/websocket/model/log-notification.model';
import {ConfirmDialog} from 'primeng/confirmdialog'; import {ConfirmDialog} from 'primeng/confirmdialog';
import {Toast} from 'primeng/toast'; import {Toast} from 'primeng/toast';
import {RouterOutlet} from '@angular/router'; import {RouterOutlet} from '@angular/router';
@@ -12,6 +12,7 @@ import {AppConfigService} from './core/service/app-config.service';
import {MetadataBatchProgressNotification} from './core/model/metadata-batch-progress.model'; import {MetadataBatchProgressNotification} from './core/model/metadata-batch-progress.model';
import {MetadataProgressService} from './core/service/metadata-progress-service'; import {MetadataProgressService} from './core/service/metadata-progress-service';
import {BookdropFileService, BookdropFileNotification} from './bookdrop/bookdrop-file.service'; import {BookdropFileService, BookdropFileNotification} from './bookdrop/bookdrop-file.service';
import {TaskEventService} from './shared/websocket/task-event.service';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -29,6 +30,7 @@ export class AppComponent implements OnInit {
private notificationEventService = inject(NotificationEventService); private notificationEventService = inject(NotificationEventService);
private metadataProgressService = inject(MetadataProgressService); private metadataProgressService = inject(MetadataProgressService);
private bookdropFileService = inject(BookdropFileService); private bookdropFileService = inject(BookdropFileService);
private taskEventService = inject(TaskEventService);
private appConfigService = inject(AppConfigService); private appConfigService = inject(AppConfigService);
ngOnInit(): void { ngOnInit(): void {
@@ -64,6 +66,11 @@ export class AppComponent implements OnInit {
this.notificationEventService.handleNewNotification(logNotification); this.notificationEventService.handleNewNotification(logNotification);
}); });
this.rxStompService.watch('/topic/task').subscribe((message: Message) => {
const taskMessage: TaskMessage = parseTaskMessage(message.body);
this.taskEventService.handleTaskMessage(taskMessage);
});
this.rxStompService.watch('/topic/bookdrop-file').subscribe((message: Message) => { this.rxStompService.watch('/topic/bookdrop-file').subscribe((message: Message) => {
const notification = JSON.parse(message.body) as BookdropFileNotification; const notification = JSON.parse(message.body) as BookdropFileNotification;
this.bookdropFileService.handleIncomingFile(notification); this.bookdropFileService.handleIncomingFile(notification);
@@ -5,6 +5,7 @@ export interface Library {
name: string; name: string;
icon: string; icon: string;
watch: boolean; watch: boolean;
fileNamingPattern?: string;
sort?: SortOption; sort?: SortOption;
paths: LibraryPath[]; paths: LibraryPath[];
} }
@@ -122,14 +122,27 @@ export class LibraryService {
getLibraryPathById(pathId: number): string | undefined { getLibraryPathById(pathId: number): string | undefined {
const libraries = this.libraryStateSubject.value.libraries || []; const libraries = this.libraryStateSubject.value.libraries || [];
for (const library of libraries) { for (const library of libraries) {
const match = library.paths.find(p => p.id === pathId); const match = library.paths.find(p => p.id === pathId);
if (match) { if (match) {
return match.path; return match.path;
} }
} }
return undefined; return undefined;
} }
updateLibraryFileNamingPattern(libraryId: number, fileNamingPattern: string): Observable<Library> {
return this.http.patch<Library>(`${this.url}/${libraryId}/file-naming-pattern`, { fileNamingPattern }).pipe(
map(updatedLibrary => {
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary =>
existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
return updatedLibrary;
}),
catchError(error => {
throw error;
})
);
}
} }
@@ -27,7 +27,7 @@ import {Textarea} from 'primeng/textarea';
export class BookdropFileMetadataPickerComponent { export class BookdropFileMetadataPickerComponent {
@Input() fetchedMetadata!: BookMetadata; @Input() fetchedMetadata!: BookMetadata;
@Input() originalMetadata!: BookMetadata; @Input() originalMetadata?: BookMetadata;
@Input() metadataForm!: FormGroup; @Input() metadataForm!: FormGroup;
@Input() copiedFields: Record<string, boolean> = {}; @Input() copiedFields: Record<string, boolean> = {};
@Input() savedFields: Record<string, boolean> = {}; @Input() savedFields: Record<string, boolean> = {};
@@ -127,7 +127,7 @@ export class BookdropFileMetadataPickerComponent {
} }
resetField(field: string) { resetField(field: string) {
this.metadataForm.get(field)?.setValue(this.originalMetadata[field]); this.metadataForm.get(field)?.setValue(this.originalMetadata?.[field]);
this.copiedFields[field] = false; this.copiedFields[field] = false;
this.hoveredFields[field] = false; this.hoveredFields[field] = false;
} }
@@ -33,25 +33,6 @@
} }
@if (bookdropFileUis.length !== 0) { @if (bookdropFileUis.length !== 0) {
<div class="flex gap-2 items-center px-1 pb-4 w-full">
<label for="uploadPatternInput" class="text-sm text-gray-300 font-medium">File Naming Pattern:</label>
<input
id="uploadPatternInput"
fluid
class="min-w-[20rem] max-w-[45.5rem]"
pSize="small"
type="text"
pInputText
[(ngModel)]="uploadPattern"
placeholder="e.g., {title} - {authors}"/>
<i
class="pi pi-info-circle text-blue-500 cursor-help"
pTooltip="Sets the filename pattern used when moving files from bookdrop folder to the library, using metadata placeholders like {title}, {authors}, etc."
tooltipPosition="top"
style="font-size: 1rem; margin-left: 0.25rem;"></i>
</div>
<div class="flex justify-between items-center gap-4 px-1"> <div class="flex justify-between items-center gap-4 px-1">
<div class="flex gap-4 items-center"> <div class="flex gap-4 items-center">
@@ -126,7 +107,7 @@
} }
</div> </div>
<div class="flex-1 overflow-y-auto px-6 space-y-2 pb-4"> <div class="flex-1 overflow-y-auto px-6 pt-4 space-y-2 pb-4">
@if (bookdropFileUis.length === 0) { @if (bookdropFileUis.length === 0) {
<div class="h-full w-full flex items-center justify-center text-gray-400 italic py-8"> <div class="h-full w-full flex items-center justify-center text-gray-400 italic py-8">
No bookdrop files to review. No bookdrop files to review.
@@ -11,7 +11,6 @@ import {DropdownModule} from 'primeng/dropdown';
import {FormControl, FormGroup, FormsModule} from '@angular/forms'; import {FormControl, FormGroup, FormsModule} from '@angular/forms';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {Select} from 'primeng/select'; import {Select} from 'primeng/select';
import {InputText} from 'primeng/inputtext';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {ConfirmationService, MessageService} from 'primeng/api'; import {ConfirmationService, MessageService} from 'primeng/api';
@@ -55,7 +54,6 @@ export interface BookdropFileUI {
BookdropFileMetadataPickerComponent, BookdropFileMetadataPickerComponent,
Tooltip, Tooltip,
Divider, Divider,
InputText,
Checkbox, Checkbox,
NgStyle, NgStyle,
NgClass, NgClass,
@@ -231,31 +229,31 @@ export class BookdropFileReviewComponent implements OnInit {
Object.values(this.fileUiCache).forEach(fileUi => { Object.values(this.fileUiCache).forEach(fileUi => {
const original = fileUi.file.originalMetadata; const original = fileUi.file.originalMetadata;
fileUi.metadataForm.patchValue({ fileUi.metadataForm.patchValue({
title: original.title || null, title: original?.title || null,
subtitle: original.subtitle || null, subtitle: original?.subtitle || null,
authors: [...(original.authors ?? [])].sort(), authors: [...(original?.authors ?? [])].sort(),
categories: [...(original.categories ?? [])].sort(), categories: [...(original?.categories ?? [])].sort(),
publisher: original.publisher || null, publisher: original?.publisher || null,
publishedDate: original.publishedDate || null, publishedDate: original?.publishedDate || null,
isbn10: original.isbn10 ?? null, isbn10: original?.isbn10 ?? null,
isbn13: original.isbn13 ?? null, isbn13: original?.isbn13 ?? null,
description: original.description ?? null, description: original?.description ?? null,
pageCount: original.pageCount ?? null, pageCount: original?.pageCount ?? null,
language: original.language ?? null, language: original?.language ?? null,
asin: original.asin ?? null, asin: original?.asin ?? null,
amazonRating: original.amazonRating ?? null, amazonRating: original?.amazonRating ?? null,
amazonReviewCount: original.amazonReviewCount ?? null, amazonReviewCount: original?.amazonReviewCount ?? null,
goodreadsId: original.goodreadsId ?? null, goodreadsId: original?.goodreadsId ?? null,
goodreadsRating: original.goodreadsRating ?? null, goodreadsRating: original?.goodreadsRating ?? null,
goodreadsReviewCount: original.goodreadsReviewCount ?? null, goodreadsReviewCount: original?.goodreadsReviewCount ?? null,
hardcoverId: original.hardcoverId ?? null, hardcoverId: original?.hardcoverId ?? null,
hardcoverRating: original.hardcoverRating ?? null, hardcoverRating: original?.hardcoverRating ?? null,
hardcoverReviewCount: original.hardcoverReviewCount ?? null, hardcoverReviewCount: original?.hardcoverReviewCount ?? null,
googleId: original.googleId ?? null, googleId: original?.googleId ?? null,
comicvineId: original.comicvineId ?? null, comicvineId: original?.comicvineId ?? null,
seriesName: original.seriesName ?? null, seriesName: original?.seriesName ?? null,
seriesNumber: original.seriesNumber ?? null, seriesNumber: original?.seriesNumber ?? null,
seriesTotal: original.seriesTotal ?? null, seriesTotal: original?.seriesTotal ?? null,
thumbnailUrl: this.urlHelper.getBookdropCoverUrl(fileUi.file.id), thumbnailUrl: this.urlHelper.getBookdropCoverUrl(fileUi.file.id),
}); });
fileUi.copiedFields = {}; fileUi.copiedFields = {};
@@ -425,7 +423,6 @@ export class BookdropFileReviewComponent implements OnInit {
}); });
const payload: BookdropFinalizePayload = { const payload: BookdropFinalizePayload = {
uploadPattern: this.uploadPattern,
selectAll: this.selectAllAcrossPages, selectAll: this.selectAllAcrossPages,
excludedIds: this.selectAllAcrossPages ? Array.from(this.excludedFiles) : undefined, excludedIds: this.selectAllAcrossPages ? Array.from(this.excludedFiles) : undefined,
defaultLibraryId: this.defaultLibraryId ? Number(this.defaultLibraryId) : undefined, defaultLibraryId: this.defaultLibraryId ? Number(this.defaultLibraryId) : undefined,
@@ -473,33 +470,33 @@ export class BookdropFileReviewComponent implements OnInit {
}); });
} }
private createMetadataForm(original: BookMetadata, bookdropFileId: number): FormGroup { private createMetadataForm(original: BookMetadata | undefined, bookdropFileId: number): FormGroup {
return new FormGroup({ return new FormGroup({
title: new FormControl(original.title ?? ''), title: new FormControl(original?.title ?? ''),
subtitle: new FormControl(original.subtitle ?? ''), subtitle: new FormControl(original?.subtitle ?? ''),
authors: new FormControl([...(original.authors ?? [])].sort()), authors: new FormControl([...(original?.authors ?? [])].sort()),
categories: new FormControl([...(original.categories ?? [])].sort()), categories: new FormControl([...(original?.categories ?? [])].sort()),
publisher: new FormControl(original.publisher ?? ''), publisher: new FormControl(original?.publisher ?? ''),
publishedDate: new FormControl(original.publishedDate ?? ''), publishedDate: new FormControl(original?.publishedDate ?? ''),
isbn10: new FormControl(original.isbn10 ?? ''), isbn10: new FormControl(original?.isbn10 ?? ''),
isbn13: new FormControl(original.isbn13 ?? ''), isbn13: new FormControl(original?.isbn13 ?? ''),
description: new FormControl(original.description ?? ''), description: new FormControl(original?.description ?? ''),
pageCount: new FormControl(original.pageCount ?? ''), pageCount: new FormControl(original?.pageCount ?? ''),
language: new FormControl(original.language ?? ''), language: new FormControl(original?.language ?? ''),
asin: new FormControl(original.asin ?? ''), asin: new FormControl(original?.asin ?? ''),
amazonRating: new FormControl(original.amazonRating ?? ''), amazonRating: new FormControl(original?.amazonRating ?? ''),
amazonReviewCount: new FormControl(original.amazonReviewCount ?? ''), amazonReviewCount: new FormControl(original?.amazonReviewCount ?? ''),
goodreadsId: new FormControl(original.goodreadsId ?? ''), goodreadsId: new FormControl(original?.goodreadsId ?? ''),
goodreadsRating: new FormControl(original.goodreadsRating ?? ''), goodreadsRating: new FormControl(original?.goodreadsRating ?? ''),
goodreadsReviewCount: new FormControl(original.goodreadsReviewCount ?? ''), goodreadsReviewCount: new FormControl(original?.goodreadsReviewCount ?? ''),
hardcoverId: new FormControl(original.hardcoverId ?? ''), hardcoverId: new FormControl(original?.hardcoverId ?? ''),
hardcoverRating: new FormControl(original.hardcoverRating ?? ''), hardcoverRating: new FormControl(original?.hardcoverRating ?? ''),
hardcoverReviewCount: new FormControl(original.hardcoverReviewCount ?? ''), hardcoverReviewCount: new FormControl(original?.hardcoverReviewCount ?? ''),
googleId: new FormControl(original.googleId ?? ''), googleId: new FormControl(original?.googleId ?? ''),
comicvineId: new FormControl(original.comicvineId ?? ''), comicvineId: new FormControl(original?.comicvineId ?? ''),
seriesName: new FormControl(original.seriesName ?? ''), seriesName: new FormControl(original?.seriesName ?? ''),
seriesNumber: new FormControl(original.seriesNumber ?? ''), seriesNumber: new FormControl(original?.seriesNumber ?? ''),
seriesTotal: new FormControl(original.seriesTotal ?? ''), seriesTotal: new FormControl(original?.seriesTotal ?? ''),
thumbnailUrl: new FormControl(this.urlHelper.getBookdropCoverUrl(bookdropFileId)), thumbnailUrl: new FormControl(this.urlHelper.getBookdropCoverUrl(bookdropFileId)),
}); });
} }
@@ -5,13 +5,11 @@ import {BookMetadata} from '../book/model/book.model';
import {API_CONFIG} from '../config/api-config'; import {API_CONFIG} from '../config/api-config';
export enum BookdropFileStatus { export enum BookdropFileStatus {
PENDING_REVIEW = 'PENDING_REVIEW',
ACCEPTED = 'ACCEPTED', ACCEPTED = 'ACCEPTED',
REJECTED = 'REJECTED', REJECTED = 'REJECTED',
} }
export interface BookdropFinalizePayload { export interface BookdropFinalizePayload {
uploadPattern: string;
selectAll?: boolean; selectAll?: boolean;
excludedIds?: number[]; excludedIds?: number[];
defaultLibraryId?: number; defaultLibraryId?: number;
@@ -30,7 +28,7 @@ export interface BookdropFile {
fileName: string; fileName: string;
filePath: string; filePath: string;
fileSize: number; fileSize: number;
originalMetadata: BookMetadata; originalMetadata?: BookMetadata;
fetchedMetadata?: BookMetadata; fetchedMetadata?: BookMetadata;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
@@ -1,7 +1,8 @@
import {inject, Injectable, OnDestroy} from '@angular/core'; import {inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subscription} from 'rxjs'; import {BehaviorSubject, Subscription} from 'rxjs';
import {map} from 'rxjs/operators'; import {map, filter, take} from 'rxjs/operators';
import {BookdropFileApiService} from './bookdrop-file-api.service'; import {BookdropFileApiService} from './bookdrop-file-api.service';
import {AuthService} from '../core/service/auth.service';
export interface BookdropFileNotification { export interface BookdropFileNotification {
pendingCount: number; pendingCount: number;
@@ -25,14 +26,13 @@ export class BookdropFileService implements OnDestroy {
); );
private apiService = inject(BookdropFileApiService); private apiService = inject(BookdropFileApiService);
private authService = inject(AuthService);
private subscriptions = new Subscription(); private subscriptions = new Subscription();
constructor() { constructor() {
const sub = this.apiService.getNotification().subscribe({ this.authService.token$
next: summary => this.summarySubject.next(summary), .pipe(filter(t => !!t), take(1))
error: err => console.warn('Failed to fetch bookdrop file summary:', err) .subscribe(() => this.refresh());
});
this.subscriptions.add(sub);
} }
handleIncomingFile(summary: BookdropFileNotification): void { handleIncomingFile(summary: BookdropFileNotification): void {
@@ -1,23 +1,24 @@
<div class="staging-border p-4 mt-6 rounded"> <div class="staging-border p-4 rounded">
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<div class="flex flex-col justify-center"> <div class="flex flex-col justify-center">
<p class="text-sm font-medium text-gray-200">Pending Bookdrop Files</p> <p class="text font-bold text-zinc-300">Pending Bookdrop Files</p>
<p class="text-lg font-bold text-primary">{{ pendingCount }}</p> <p class="text-lg font-bold text-primary">{{ pendingCount }}</p>
@if (lastUpdatedAt) { @if (lastUpdatedAt) {
<p class="text-xs text-gray-400 mt-1"> <p class="text-xs text-zinc-400 mt-1">
Last updated: {{ lastUpdatedAt | date: 'short' }} Last updated: {{ lastUpdatedAt | date: 'short' }}
</p> </p>
} }
</div> </div>
<div class="flex items-center"> <div class="flex items-center">
<button <p-button
type="button" size="small"
class="p-button p-button-sm p-button-outlined p-button-info" outlined
severity="info"
(click)="openReviewDialog()"> (click)="openReviewDialog()">
Review Review
</button> </p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -4,6 +4,7 @@ import {takeUntil} from 'rxjs/operators';
import {BookdropFileNotification, BookdropFileService} from '../bookdrop-file.service'; import {BookdropFileNotification, BookdropFileService} from '../bookdrop-file.service';
import {DatePipe} from '@angular/common'; import {DatePipe} from '@angular/common';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {Button} from 'primeng/button';
@Component({ @Component({
selector: 'app-bookdrop-files-widget-component', selector: 'app-bookdrop-files-widget-component',
@@ -11,7 +12,8 @@ import {Router} from '@angular/router';
templateUrl: './bookdrop-files-widget.component.html', templateUrl: './bookdrop-files-widget.component.html',
styleUrl: './bookdrop-files-widget.component.scss', styleUrl: './bookdrop-files-widget.component.scss',
imports: [ imports: [
DatePipe DatePipe,
Button
] ]
}) })
export class BookdropFilesWidgetComponent implements OnInit, OnDestroy { export class BookdropFilesWidgetComponent implements OnInit, OnDestroy {
@@ -1,4 +1,4 @@
<div class="flex flex-col px-4 py-6 live-border"> <div class="flex flex-col p-4 space-y-2 live-border">
<p class="text-sm text-gray-400">{{ latestNotification.timestamp }}</p> <p class="text-xs text-zinc-400">{{ latestNotification.timestamp }}</p>
<p>{{ latestNotification.message }}</p> <p class="font-normal text-zinc-200">{{ latestNotification.message }}</p>
</div> </div>
@@ -1,6 +1,6 @@
import {Component, inject} from '@angular/core'; import {Component, inject} from '@angular/core';
import {LogNotification} from '../../../shared/websocket/model/log-notification.model';
import {NotificationEventService} from '../../../shared/websocket/notification-event.service'; import {NotificationEventService} from '../../../shared/websocket/notification-event.service';
import {LogNotification} from '../../../shared/websocket/model/log-notification.model';
@Component({ @Component({
selector: 'app-live-notification-box', selector: 'app-live-notification-box',
@@ -0,0 +1,43 @@
<div class="flex flex-col p-4 live-border">
@if (tasks$ | async; as tasks) {
@if (tasks.length === 0) {
<div class="text-center text-zinc-400">
<p class="text-sm">No active tasks</p>
</div>
} @else {
@for (task of tasks; track task.taskId; let i = $index) {
@if (i > 0) {
<div class="border-t border-zinc-700 my-4"></div>
}
<div class="flex flex-col space-y-1.5">
<p class="text-xs text-zinc-400">{{ task.timestamp }}</p>
<div class="flex flex-col space-y-0.5">
<div class="flex justify-between items-center">
<div class="flex items-center space-x-1.5">
<span class="px-1.5 py-0.5 text-xs rounded-xl font-bold" [class]="getStatusClasses(task.status)">
{{ getStatusText(task.status) }}
</span>
@if (task.title) {
<h4 class="font-bold text-zinc-200">Task: {{ task.title }}</h4>
}
</div>
<div class="flex items-center space-x-1">
@if (task.status === TaskStatus.IN_PROGRESS && task.cancellable) {
<p-button
(onClick)="cancelTask(task.taskId)" icon="pi pi-ban" severity="danger" size="small" rounded text>
</p-button>
}
<p-button
(onClick)="removeTask(task.taskId)" icon="pi pi-times" severity="secondary" size="small" rounded text>
</p-button>
</div>
</div>
<p class="font-normal text-zinc-300">{{ task.message }}</p>
</div>
</div>
}
}
}
</div>
@@ -0,0 +1,6 @@
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
@@ -0,0 +1,84 @@
import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TaskMessage, TaskStatus} from '../../../shared/websocket/model/log-notification.model';
import {TaskEventService} from '../../../shared/websocket/task-event.service';
import {TaskService} from '../../../shared/services/task.service';
import {Observable, take} from 'rxjs';
import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api';
@Component({
selector: 'app-live-task-event-box',
standalone: true,
imports: [CommonModule, Button],
templateUrl: './live-task-event-box.component.html',
styleUrls: ['./live-task-event-box.component.scss'],
host: {
class: 'config-panel'
}
})
export class LiveTaskEventBoxComponent {
tasks$: Observable<TaskMessage[]>;
TaskStatus = TaskStatus;
private taskEventService = inject(TaskEventService);
private taskService = inject(TaskService);
private messageService = inject(MessageService);
constructor() {
this.tasks$ = this.taskEventService.tasks$;
}
cancelTask(taskId: string): void {
this.taskService.cancelTask(taskId).pipe(take(1)).subscribe({
next: (response) => {
this.messageService.add({
severity: 'success',
summary: 'Success',
detail: `Task cancellation scheduled`
});
},
error: (error) => {
this.messageService.add({
severity: 'error',
summary: 'Cancellation failed',
detail: error.error?.error || 'Failed to cancel task'
});
}
});
}
removeTask(taskId: string): void {
this.taskEventService.removeTask(taskId);
}
getStatusClasses(status: TaskStatus): string {
switch (status) {
case TaskStatus.IN_PROGRESS:
return 'bg-blue-700 text-zinc-100';
case TaskStatus.COMPLETED:
return 'bg-green-700 text-zinc-100';
case TaskStatus.FAILED:
return 'bg-red-700 text-zinc-100';
case TaskStatus.CANCELLED:
return 'bg-gray-700 text-zinc-100';
default:
return 'bg-zinc-700 text-zinc-100';
}
}
getStatusText(status: TaskStatus): string {
switch (status) {
case TaskStatus.IN_PROGRESS:
return 'Running';
case TaskStatus.COMPLETED:
return 'Completed';
case TaskStatus.FAILED:
return 'Failed';
case TaskStatus.CANCELLED:
return 'Cancelled';
default:
return 'Unknown';
}
}
}
@@ -1,5 +1,8 @@
<div class="metadata-progress-box flex flex-col w-[25rem] max-h-[60vh] overflow-y-auto"> <div class="metadata-progress-box flex gap-4 flex-col w-[25rem] max-h-[60vh] overflow-y-auto">
<app-live-notification-box/> <app-live-notification-box/>
@if (hasActiveTasks$ | async) {
<app-live-task-event-box/>
}
@if (hasMetadataTasks$ | async) { @if (hasMetadataTasks$ | async) {
<app-metadata-progress-widget/> <app-metadata-progress-widget/>
} }
@@ -1,7 +1,9 @@
import {Component, inject} from '@angular/core'; import {Component, inject} from '@angular/core';
import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component'; import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component';
import {LiveTaskEventBoxComponent} from '../live-task-event-box/live-task-event-box.component';
import {MetadataProgressWidgetComponent} from '../metadata-progress-widget-component/metadata-progress-widget-component'; import {MetadataProgressWidgetComponent} from '../metadata-progress-widget-component/metadata-progress-widget-component';
import {MetadataProgressService} from '../../service/metadata-progress-service'; import {MetadataProgressService} from '../../service/metadata-progress-service';
import {TaskEventService} from '../../../shared/websocket/task-event.service';
import {map} from 'rxjs/operators'; import {map} from 'rxjs/operators';
import {AsyncPipe} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {BookdropFilesWidgetComponent} from '../../../bookdrop/bookdrop-files-widget-component/bookdrop-files-widget.component'; import {BookdropFilesWidgetComponent} from '../../../bookdrop/bookdrop-files-widget-component/bookdrop-files-widget.component';
@@ -11,6 +13,7 @@ import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
selector: 'app-unified-notification-popover-component', selector: 'app-unified-notification-popover-component',
imports: [ imports: [
LiveNotificationBoxComponent, LiveNotificationBoxComponent,
LiveTaskEventBoxComponent,
MetadataProgressWidgetComponent, MetadataProgressWidgetComponent,
AsyncPipe, AsyncPipe,
BookdropFilesWidgetComponent BookdropFilesWidgetComponent
@@ -22,10 +25,15 @@ import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
export class UnifiedNotificationBoxComponent { export class UnifiedNotificationBoxComponent {
metadataProgressService = inject(MetadataProgressService); metadataProgressService = inject(MetadataProgressService);
bookdropFileService = inject(BookdropFileService); bookdropFileService = inject(BookdropFileService);
taskEventService = inject(TaskEventService);
hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe( hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe(
map(tasks => Object.keys(tasks).length > 0) map(tasks => Object.keys(tasks).length > 0)
); );
hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$; hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$;
hasActiveTasks$ = this.taskEventService.tasks$.pipe(
map(tasks => tasks.length > 0)
);
} }
@@ -1,11 +1,10 @@
import {inject, Injectable, Injector} from '@angular/core'; import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable, tap} from 'rxjs'; import {BehaviorSubject, Observable, tap} from 'rxjs';
import {RxStompService} from '../../shared/websocket/rx-stomp.service'; import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {API_CONFIG} from '../../config/api-config'; import {API_CONFIG} from '../../config/api-config';
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config'; import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
import {OAuthService} from 'angular-oauth2-oidc'; import {OAuthService} from 'angular-oauth2-oidc';
import {AppSettingsService} from './app-settings.service';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
@Injectable({ @Injectable({
@@ -21,6 +20,9 @@ export class AuthService {
private oAuthService = inject(OAuthService); private oAuthService = inject(OAuthService);
private router = inject(Router); private router = inject(Router);
private tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
public token$ = this.tokenSubject.asObservable();
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> { internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe( return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => { tap((response) => {
@@ -57,6 +59,7 @@ export class AuthService {
saveInternalTokens(accessToken: string, refreshToken: string): void { saveInternalTokens(accessToken: string, refreshToken: string): void {
localStorage.setItem('accessToken_Internal', accessToken); localStorage.setItem('accessToken_Internal', accessToken);
localStorage.setItem('refreshToken_Internal', refreshToken); localStorage.setItem('refreshToken_Internal', refreshToken);
this.tokenSubject.next(accessToken);
} }
getInternalAccessToken(): string | null { getInternalAccessToken(): string | null {
@@ -74,6 +77,7 @@ export class AuthService {
logout(): void { logout(): void {
localStorage.removeItem('accessToken_Internal'); localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal'); localStorage.removeItem('refreshToken_Internal');
this.tokenSubject.next(null);
this.getRxStompService().deactivate(); this.getRxStompService().deactivate();
if (this.oAuthService.clientId) { if (this.oAuthService.clientId) {
this.oAuthService.logOut(); this.oAuthService.logOut();
@@ -0,0 +1,26 @@
import { Injectable, inject } from '@angular/core';
import { AuthService } from './auth.service';
import { UserService } from '../../settings/user-management/user.service';
import { filter, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class StartupService {
private auth = inject(AuthService);
private userSvc = inject(UserService);
load(): Promise<void> {
this.auth.token$
.pipe(filter(t => !!t))
.subscribe(() => {
this.userSvc.getMyself()
.pipe(catchError(() => of(null)))
.subscribe(user => {
if (user) {
this.userSvc.setInitialUser(user);
}
});
});
return Promise.resolve();
}
}
@@ -42,8 +42,8 @@ export class DialogLauncherService {
openGithubSupportDialog(): void { openGithubSupportDialog(): void {
this.open({ this.open({
component: GithubSupportDialog, component: GithubSupportDialog,
header: 'Support BookLore on GitHub', header: 'Support Booklore',
top: '25%' top: '15%'
}); });
} }
@@ -83,13 +83,13 @@
</p-popover> </p-popover>
</li> </li>
<li class="relative group overflow-hidden !border-transparent topbar-item" pTooltip="Love BookLore?" tooltipPosition="bottom" (click)="openGithubSupportDialog()"> <li class="relative group overflow-hidden !border-transparent topbar-item" (click)="openGithubSupportDialog()">
<span <span
style="animation-duration: 2s; background: conic-gradient(from 90deg, #f97316, #f59e0b, #eab308, #84cc16, #22c55e, #10b981, #14a8a6, #06b6d4, #0ea5e9, #3b82f6, #6366f1, #8b5cf6, #a855f7, #d946ef, #ec4899, #f43f5e)" style="animation-duration: 2s; background: conic-gradient(from 90deg, #f97316, #f59e0b, #eab308, #84cc16, #22c55e, #10b981, #14a8a6, #06b6d4, #0ea5e9, #3b82f6, #6366f1, #8b5cf6, #a855f7, #d946ef, #ec4899, #f43f5e)"
class="absolute -top-5 -left-5 w-20 h-20 animate-spin"> class="absolute -top-5 -left-5 w-20 h-20 animate-spin">
</span> </span>
<span style="inset: 1px; border-radius: 4px" class="absolute z-2 bg-surface-900 transition-all"></span> <span style="inset: 1px; border-radius: 4px" class="absolute z-2 bg-surface-900 transition-all"></span>
<i class="pi pi-thumbs-up z-10"></i> <i class="pi pi-heart z-10"></i>
</li> </li>
<li class="relative"> <li class="relative">
<button type="button" <button type="button"
@@ -23,6 +23,7 @@ import {MetadataBatchProgressNotification} from '../../../core/model/metadata-ba
import {UnifiedNotificationBoxComponent} from '../../../core/component/unified-notification-popover-component/unified-notification-popover-component'; import {UnifiedNotificationBoxComponent} from '../../../core/component/unified-notification-popover-component/unified-notification-popover-component';
import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service'; import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
import {DialogLauncherService} from '../../../dialog-launcher.service'; import {DialogLauncherService} from '../../../dialog-launcher.service';
import {TaskEventService} from '../../../shared/websocket/task-event.service';
@Component({ @Component({
selector: 'app-topbar', selector: 'app-topbar',
@@ -77,10 +78,12 @@ export class AppTopBarComponent implements OnDestroy {
protected userService: UserService, protected userService: UserService,
private metadataProgressService: MetadataProgressService, private metadataProgressService: MetadataProgressService,
private bookdropFileService: BookdropFileService, private bookdropFileService: BookdropFileService,
private dialogLauncher: DialogLauncherService private dialogLauncher: DialogLauncherService,
private taskEventService: TaskEventService
) { ) {
this.subscribeToMetadataProgress(); this.subscribeToMetadataProgress();
this.subscribeToNotifications(); this.subscribeToNotifications();
this.subscribeToTaskEvents();
this.metadataProgressService.activeTasks$ this.metadataProgressService.activeTasks$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
@@ -153,6 +156,16 @@ export class AppTopBarComponent implements OnDestroy {
}); });
} }
private subscribeToTaskEvents() {
this.taskEventService.tasks$
.pipe(takeUntil(this.destroy$))
.subscribe((tasks) => {
if (tasks.length > 0) {
this.triggerPulseEffect();
}
});
}
private triggerPulseEffect() { private triggerPulseEffect() {
this.showPulse = true; this.showPulse = true;
clearTimeout(this.eventTimer); clearTimeout(this.eventTimer);
@@ -333,6 +333,7 @@
</span> </span>
</p> </p>
} }
<p><strong>Page Count:</strong> {{ book?.metadata!.pageCount || '-' }}</p>
</div> </div>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
@@ -0,0 +1,262 @@
<div class="w-full h-[calc(100dvh-10.5rem)] md:h-[calc(100dvh-11.65rem)] overflow-y-auto border rounded-lg enclosing-container">
<div class="pt-8 px-4">
<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-2 text-lg">Default File Naming Pattern:</h2>
<p class="mb-3 text-sm text-gray-400">
Define the default naming pattern for files. This pattern applies to all libraries unless overridden.
</p>
<div class="flex gap-4 items-center">
<input type="text" [(ngModel)]="defaultPattern" class="p-inputtext w-[700px]" placeholder="e.g., {title} - {authors}" (input)="onDefaultPatternChange(defaultPattern)"/>
<p-button label="Save" (onClick)="savePatterns()" severity="primary" outlined="true" [disabled]="!!defaultErrorMessage"></p-button>
</div>
@if (defaultErrorMessage) {
<div class="text-red-500 mt-1">{{ defaultErrorMessage }}</div>
}
<div class="flex gap-2 pt-2">
<p class="text-zinc-400">Preview:</p>
<p class="text-green-500">{{ generateDefaultPreview() }}</p>
</div>
</div>
<div>
<h2 class="py-2 text-lg">Overrides for Libraries:</h2>
<p class="mb-3 text-sm text-gray-400">
Define custom naming patterns for specific libraries. Leave empty to use the default pattern.
</p>
@for (library of libraries; track library.id) {
<div class="flex flex-col gap-2 p-3">
<div class="flex gap-3 items-center">
<i [class]="'pi pi-' + library.icon"></i>
<span class="min-w-[100px] font-medium">{{ library.name }}</span>
<input
type="text"
[(ngModel)]="library.fileNamingPattern"
class="p-inputtext flex-1"
placeholder="Leave empty to use default pattern"
(input)="onLibraryPatternChange(library)"/>
<p-button
label="Clear"
(onClick)="clearLibraryPattern(library)"
severity="secondary"
outlined="true"
size="small"
[disabled]="!library.fileNamingPattern">
</p-button>
</div>
<div class="ml-8 flex gap-2">
<p class="text-sm text-zinc-400">Preview:</p>
<p class="text-sm text-green-500">{{ generateLibraryPreview(library) }}</p>
</div>
</div>
}
<div class="flex justify-end">
<p-button label="Save All Library Patterns" (onClick)="saveLibraryPatterns()" severity="primary" outlined="true"></p-button>
</div>
</div>
<div>
<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>
</div>
</div>
@@ -1,3 +1,7 @@
.enclosing-container {
border-color: var(--p-content-border-color);
}
.custom-border { .custom-border {
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: var(--card-border); border-radius: var(--card-border);
@@ -2,21 +2,23 @@ import {Component, inject, OnInit} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {AppSettingsService} from '../../../core/service/app-settings.service'; import {AppSettingsService} from '../../core/service/app-settings.service';
import {Observable} from 'rxjs'; import {forkJoin, Observable, of} from 'rxjs';
import {AppSettingKey, AppSettings} from '../../../core/model/app-settings.model'; import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model';
import {filter, take} from 'rxjs/operators'; import {catchError, filter, take} from 'rxjs/operators';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {Library} from '../../book/model/library.model';
import {LibraryService} from '../../book/service/library.service';
@Component({ @Component({
selector: 'app-file-upload-pattern', selector: 'app-file-naming-pattern',
templateUrl: './file-upload-pattern.component.html', templateUrl: './file-naming-pattern.component.html',
standalone: true, standalone: true,
imports: [FormsModule, Button, Divider, Tooltip], imports: [FormsModule, Button, Divider, Tooltip],
styleUrls: ['./file-upload-pattern.component.scss'], styleUrls: ['./file-naming-pattern.component.scss'],
}) })
export class FileUploadPatternComponent implements OnInit { export class FileNamingPatternComponent implements OnInit {
readonly exampleMetadata: Record<string, string> = { readonly exampleMetadata: Record<string, string> = {
title: 'The Fellowship of the Ring', title: 'The Fellowship of the Ring',
authors: 'J.R.R. Tolkien', authors: 'J.R.R. Tolkien',
@@ -28,14 +30,13 @@ export class FileUploadPatternComponent implements OnInit {
isbn: '9780618574940', isbn: '9780618574940',
}; };
uploadPattern = ''; defaultPattern = '';
movePattern = ''; libraries: Library[] = [];
defaultErrorMessage = '';
uploadErrorMessage = '';
moveErrorMessage = '';
private appSettingsService = inject(AppSettingsService); private appSettingsService = inject(AppSettingsService);
private messageService = inject(MessageService); private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$; appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
@@ -43,8 +44,13 @@ export class FileUploadPatternComponent implements OnInit {
this.appSettings$ this.appSettings$
.pipe(filter((settings) => settings != null), take(1)) .pipe(filter((settings) => settings != null), take(1))
.subscribe((settings) => { .subscribe((settings) => {
this.uploadPattern = settings?.uploadPattern ?? ''; this.defaultPattern = settings?.uploadPattern ?? '';
this.movePattern = settings?.movePattern ?? ''; });
this.libraryService.libraryState$
.pipe(filter(state => state.loaded && !!state.libraries))
.subscribe(state => {
this.libraries = state.libraries ?? [];
}); });
} }
@@ -65,77 +71,77 @@ export class FileUploadPatternComponent implements OnInit {
return hasExtension ? path : path + ext; return hasExtension ? path : path + ext;
} }
generateUploadPreview(): string { private generatePreview(pattern: string): string {
let path = this.replacePlaceholders(this.uploadPattern || '', this.exampleMetadata); let path = this.replacePlaceholders(pattern || '', this.exampleMetadata);
if (!path) return '/original_filename.pdf'; if (!path) return '/original_filename.pdf';
if (path.endsWith('/')) return path + '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}')) { if (path.includes('{originalFilename}')) {
path = path.replace('{originalFilename}', 'original_filename.pdf'); path = path.replace('{originalFilename}', 'original_filename.pdf');
return path.startsWith('/') ? path : `/${path}`; return path.startsWith('/') ? path : `/${path}`;
} }
path = this.appendExtensionIfMissing(path); path = this.appendExtensionIfMissing(path);
return path.startsWith('/') ? path : `/${path}`; return path.startsWith('/') ? path : `/${path}`;
} }
generateMovePreview(): string { generateDefaultPreview(): string {
let path = this.replacePlaceholders(this.movePattern || '', this.exampleMetadata); return this.generatePreview(this.defaultPattern);
}
if (!path) return '/original_filename.pdf'; generateLibraryPreview(library: Library): string {
return this.generatePreview(library.fileNamingPattern || this.defaultPattern);
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 { validatePattern(pattern: string): boolean {
// Allow letters, numbers, whitespace, common punctuation and placeholders syntax
const validPatternRegex = /^[\w\s\-{}\/().<>.,:'"]*$/; const validPatternRegex = /^[\w\s\-{}\/().<>.,:'"]*$/;
return validPatternRegex.test(pattern); return validPatternRegex.test(pattern);
} }
onUploadPatternChange(pattern: string): void { onDefaultPatternChange(pattern: string): void {
this.uploadPattern = pattern; this.defaultPattern = pattern;
this.uploadErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; this.defaultErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.';
} }
onMovePatternChange(pattern: string): void { onLibraryPatternChange(library: Library): void {
this.movePattern = pattern; // Optionally add per-library validation here
this.moveErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; }
clearLibraryPattern(library: Library): void {
library.fileNamingPattern = '';
} }
savePatterns(): void { savePatterns(): void {
if (this.uploadErrorMessage || this.moveErrorMessage) { if (this.defaultErrorMessage) {
this.showMessage('error', 'Invalid Pattern', 'Please fix errors before saving.'); this.showMessage('error', 'Invalid Pattern', 'Please fix errors before saving.');
return; return;
} }
this.appSettingsService this.appSettingsService
.saveSettings([ .saveSettings([
{key: AppSettingKey.UPLOAD_FILE_PATTERN, newValue: this.uploadPattern}, { key: AppSettingKey.UPLOAD_FILE_PATTERN, newValue: this.defaultPattern },
{key: AppSettingKey.MOVE_FILE_PATTERN, newValue: this.movePattern},
]) ])
.subscribe({ .subscribe({
next: () => this.showMessage('success', 'Settings Saved', 'The patterns were successfully saved!'), next: () => this.showMessage('success', 'Settings Saved', 'The default pattern was successfully saved!'),
error: () => this.showMessage('error', 'Error', 'There was an error saving the settings.'), error: () => this.showMessage('error', 'Error', 'There was an error saving the settings.'),
}); });
} }
saveLibraryPatterns(): void {
const patchRequests = this.libraries.map(library =>
this.libraryService.updateLibraryFileNamingPattern(library.id!, library.fileNamingPattern || '').pipe(
catchError(() => of(null))
)
);
forkJoin(patchRequests).subscribe(results => {
const failures = results.filter(result => result === null);
if (failures.length === 0) {
this.showMessage('success', 'Library Patterns Saved', 'Library-specific patterns were successfully saved!');
} else {
this.showMessage('error', 'Error', `Failed to save ${failures.length} library pattern(s).`);
}
});
}
private showMessage(severity: 'success' | 'error', summary: string, detail: string): void { private showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
this.messageService.add({severity, summary, detail}); this.messageService.add({ severity, summary, detail });
} }
} }
@@ -1,235 +0,0 @@
<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 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-[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>
<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>
@@ -130,8 +130,4 @@
<p-divider></p-divider> <p-divider></p-divider>
</div> </div>
<div class="px-4 py-2">
<app-file-upload-pattern></app-file-upload-pattern>
</div>
</div> </div>
@@ -14,7 +14,6 @@ import {AppSettingsService} from '../../core/service/app-settings.service';
import {BookService} from '../../book/service/book.service'; import {BookService} from '../../book/service/book.service';
import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model'; import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model';
import {filter, take} from 'rxjs/operators'; import {filter, take} from 'rxjs/operators';
import {FileUploadPatternComponent} from './file-upload-pattern/file-upload-pattern.component';
import {InputText} from 'primeng/inputtext'; import {InputText} from 'primeng/inputtext';
@Component({ @Component({
@@ -28,7 +27,6 @@ import {InputText} from 'primeng/inputtext';
Tooltip, Tooltip,
ToggleSwitch, ToggleSwitch,
FormsModule, FormsModule,
FileUploadPatternComponent,
InputText InputText
], ],
templateUrl: './global-preferences.component.html', templateUrl: './global-preferences.component.html',
@@ -22,6 +22,9 @@
<p-tab [value]="SettingsTab.EmailSettings"> <p-tab [value]="SettingsTab.EmailSettings">
<i class="pi pi-envelope"></i> Email <i class="pi pi-envelope"></i> Email
</p-tab> </p-tab>
<p-tab [value]="SettingsTab.NamingPattern">
<i class="pi pi-sitemap"></i> Patterns
</p-tab>
<p-tab [value]="SettingsTab.AuthenticationSettings"> <p-tab [value]="SettingsTab.AuthenticationSettings">
<i class="pi pi-lock"></i> Authentication <i class="pi pi-lock"></i> Authentication
</p-tab> </p-tab>
@@ -55,6 +58,9 @@
<p-tabpanel [value]="SettingsTab.EmailSettings"> <p-tabpanel [value]="SettingsTab.EmailSettings">
<app-email></app-email> <app-email></app-email>
</p-tabpanel> </p-tabpanel>
<p-tabpanel [value]="SettingsTab.NamingPattern">
<app-file-naming-pattern></app-file-naming-pattern>
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.AuthenticationSettings"> <p-tabpanel [value]="SettingsTab.AuthenticationSettings">
<app-authentication-settings></app-authentication-settings> <app-authentication-settings></app-authentication-settings>
</p-tabpanel> </p-tabpanel>
@@ -13,17 +13,19 @@ import {ReaderPreferences} from './reader-preferences/reader-preferences.compone
import {MetadataSettingsComponent} from './metadata-settings-component/metadata-settings-component'; import {MetadataSettingsComponent} from './metadata-settings-component/metadata-settings-component';
import {OpdsSettingsComponent} from './global-preferences/opds-settings/opds-settings.component'; import {OpdsSettingsComponent} from './global-preferences/opds-settings/opds-settings.component';
import {DeviceSettingsComponent} from './device-settings-component/device-settings-component'; import {DeviceSettingsComponent} from './device-settings-component/device-settings-component';
import {FileNamingPatternComponent} from './file-naming-pattern/file-naming-pattern.component';
export enum SettingsTab { export enum SettingsTab {
ReaderSettings = 'reader-settings', ReaderSettings = 'reader',
ViewPreferences = 'view-settings', ViewPreferences = 'view',
DeviceSettings = 'device-settings', DeviceSettings = 'device',
UserManagement = 'user-management', UserManagement = 'user',
EmailSettings = 'email-settings', EmailSettings = 'email',
MetadataSettings = 'metadata-settings', NamingPattern = 'naming-pattern',
ApplicationSettings = 'app-settings', MetadataSettings = 'metadata',
AuthenticationSettings = 'auth-settings', ApplicationSettings = 'application',
Opds = 'opds-settings' AuthenticationSettings = 'authentication',
Opds = 'opds'
} }
@Component({ @Component({
@@ -43,7 +45,8 @@ export enum SettingsTab {
ReaderPreferences, ReaderPreferences,
MetadataSettingsComponent, MetadataSettingsComponent,
OpdsSettingsComponent, OpdsSettingsComponent,
DeviceSettingsComponent DeviceSettingsComponent,
FileNamingPatternComponent
], ],
templateUrl: './settings.component.html', templateUrl: './settings.component.html',
styleUrl: './settings.component.scss' styleUrl: './settings.component.scss'
@@ -6,6 +6,8 @@ import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {Library} from '../../book/model/library.model'; import {Library} from '../../book/model/library.model';
import {catchError} from 'rxjs/operators'; import {catchError} from 'rxjs/operators';
import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model'; import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model';
import {filter, take} from 'rxjs/operators';
import {AuthService} from '../../core/service/auth.service';
export interface EntityViewPreferences { export interface EntityViewPreferences {
global: EntityViewPreference; global: EntityViewPreference;
@@ -119,18 +121,12 @@ export class UserService {
private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`; private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
private http = inject(HttpClient); private http = inject(HttpClient);
private injector = inject(Injector);
private rxStompService?: RxStompService;
private userStateSubject = new BehaviorSubject<User | null>(null); private userStateSubject = new BehaviorSubject<User | null>(null);
userState$ = this.userStateSubject.asObservable(); userState$ = this.userStateSubject.asObservable();
constructor() { public setInitialUser(user: User): void {
this.getMyself().subscribe(user => { this.userStateSubject.next(user);
this.userStateSubject.next(user);
this.startWebSocket();
});
} }
getCurrentUser(): User | null { getCurrentUser(): User | null {
@@ -200,29 +196,4 @@ export class UserService {
} }
}); });
} }
updateUserSettingV2(userId: number, key: string, value: any): Observable<void> {
const payload = { key, value };
return this.http.put<void>(`${this.userUrl}/${userId}/settings`, payload);
}
private startWebSocket(): void {
const token = this.getToken();
if (token) {
const rxStompService = this.getRxStompService();
rxStompService.activate();
}
}
private getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
}
getToken(): string | null {
return localStorage.getItem('accessToken');
}
} }
@@ -0,0 +1,17 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
@Injectable({
providedIn: 'root'
})
export class TaskService {
private http = inject(HttpClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/tasks`;
cancelTask(taskId: string): Observable<{ message: string }> {
return this.http.delete<{ message: string }>(`${this.url}/${taskId}`);
}
}
@@ -1,3 +1,10 @@
export enum TaskStatus {
IN_PROGRESS = 'IN_PROGRESS',
CANCELLED = 'CANCELLED',
COMPLETED = 'COMPLETED',
FAILED = 'FAILED'
}
export interface LogNotification { export interface LogNotification {
timestamp?: string; timestamp?: string;
message: string; message: string;
@@ -5,10 +12,25 @@ export interface LogNotification {
export function parseLogNotification(messageBody: string): LogNotification { export function parseLogNotification(messageBody: string): LogNotification {
const raw = JSON.parse(messageBody); const raw = JSON.parse(messageBody);
const localTime = new Date(raw.timestamp).toLocaleTimeString();
return { return {
timestamp: localTime, timestamp: raw.timestamp ? new Date(raw.timestamp).toLocaleTimeString() : undefined,
message: raw.message, message: raw.message,
}; };
} }
export interface TaskMessage {
taskId: string;
timestamp: string;
title?: string;
message: string;
cancellable: boolean;
status: TaskStatus;
}
export function parseTaskMessage(messageBody: string): TaskMessage {
const raw = JSON.parse(messageBody) as TaskMessage;
return {
...raw,
timestamp: new Date(raw.timestamp).toLocaleTimeString()
};
}
@@ -0,0 +1,42 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { TaskMessage } from './model/log-notification.model';
@Injectable({
providedIn: 'root'
})
export class TaskEventService {
private tasksSubject = new BehaviorSubject<Map<string, TaskMessage>>(new Map());
tasks$: Observable<TaskMessage[]> = this.tasksSubject.asObservable().pipe(
map(taskMap => Array.from(taskMap.values()))
);
handleTaskMessage(taskMessage: TaskMessage): void {
const currentTasks = new Map(this.tasksSubject.value);
currentTasks.set(taskMessage.taskId, taskMessage);
this.tasksSubject.next(currentTasks);
}
removeTask(taskId: string): void {
const currentTasks = new Map(this.tasksSubject.value);
currentTasks.delete(taskId);
this.tasksSubject.next(currentTasks);
}
getTask(taskId: string): TaskMessage | undefined {
return this.tasksSubject.value.get(taskId);
}
getTaskById$(taskId: string): Observable<TaskMessage | undefined> {
return this.tasksSubject.asObservable().pipe(
map(taskMap => taskMap.get(taskId))
);
}
clearAllTasks(): void {
this.tasksSubject.next(new Map());
}
}
@@ -1,26 +1,38 @@
@if ((libraryState$ | async)?.libraries; as libraries) { @if ((libraryState$ | async)?.libraries; as libraries) {
<div <div
class="flex flex-col gap-10 p-4 items-center justify-center w-full max-w-[700px]"> class="flex flex-col gap-8 p-4 items-center justify-center w-full max-w-[700px]">
<p-select <div class="flex flex-col items-center gap-2 w-full">
[options]="libraries" <label class="text-sm text-stone-400">Upload Destination</label>
optionLabel="name" <p-selectbutton
placeholder="Select Library" [options]="stateOptions"
[(ngModel)]="selectedLibrary" [(ngModel)]="value"
class="w-full"></p-select> [allowEmpty]="false"
<p-select optionLabel="label"
[options]="selectedLibrary?.paths" optionValue="value">
optionLabel="path" </p-selectbutton>
placeholder="Select Upload Location" </div>
[(ngModel)]="selectedPath" @if (value === 'library') {
[disabled]="!selectedLibrary" <p-select
class="w-full"></p-select> [options]="libraries"
optionLabel="name"
placeholder="Select Library"
[(ngModel)]="selectedLibrary"
class="w-full"></p-select>
<p-select
[options]="selectedLibrary?.paths"
optionLabel="path"
placeholder="Select Subpath"
[(ngModel)]="selectedPath"
[disabled]="!selectedLibrary"
class="w-full"></p-select>
}
<p-fileupload class="w-full" name="file" <p-fileupload class="w-full" name="file"
[maxFileSize]="maxFileSizeBytes" [maxFileSize]="maxFileSizeBytes"
[customUpload]="true" [customUpload]="true"
[multiple]="true" accept=".pdf,.epub,.cbz,.cbr,.cb7" [multiple]="true" accept=".pdf,.epub,.cbz,.cbr,.cb7"
(onSelect)="onFilesSelect($event)" (onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)" (uploadHandler)="uploadFiles($event)"
[disabled]="!selectedLibrary || !selectedPath"> [disabled]="value === 'library' ? (!selectedLibrary || !selectedPath) : false">
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback"> <ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
<div class="flex flex-col items-center justify-center flex-1 gap-4"> <div class="flex flex-col items-center justify-center flex-1 gap-4">
<div class="flex gap-4"> <div class="flex gap-4">
@@ -1,7 +1,7 @@
import {Component, inject, OnInit} from '@angular/core'; import {Component, inject, OnInit} from '@angular/core';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload'; import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import { AsyncPipe } from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {Select} from 'primeng/select'; import {Select} from 'primeng/select';
@@ -17,6 +17,7 @@ import {Tooltip} from 'primeng/tooltip';
import {AppSettingsService} from '../../../core/service/app-settings.service'; import {AppSettingsService} from '../../../core/service/app-settings.service';
import {filter, take} from 'rxjs/operators'; import {filter, take} from 'rxjs/operators';
import {AppSettings} from '../../../core/model/app-settings.model'; import {AppSettings} from '../../../core/model/app-settings.model';
import {SelectButton} from 'primeng/selectbutton';
interface UploadingFile { interface UploadingFile {
file: File; file: File;
@@ -34,8 +35,9 @@ interface UploadingFile {
FormsModule, FormsModule,
Select, Select,
Badge, Badge,
Tooltip Tooltip,
], SelectButton
],
templateUrl: './book-uploader.component.html', templateUrl: './book-uploader.component.html',
styleUrl: './book-uploader.component.scss' styleUrl: './book-uploader.component.scss'
}) })
@@ -53,6 +55,11 @@ export class BookUploaderComponent implements OnInit {
readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$; readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$; appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
maxFileSizeBytes?: number; maxFileSizeBytes?: number;
stateOptions = [
{label: 'Library', value: 'library'},
{label: 'Bookdrop', value: 'bookdrop'}
];
value = 'library';
ngOnInit(): void { ngOnInit(): void {
this.appSettings$ this.appSettings$
@@ -101,7 +108,7 @@ export class BookUploaderComponent implements OnInit {
} }
uploadFiles(event: FileUploadHandlerEvent): void { uploadFiles(event: FileUploadHandlerEvent): void {
if (!this.selectedLibrary || !this.selectedPath) { if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
this.messageService.add({ this.messageService.add({
severity: 'warn', severity: 'warn',
summary: 'Missing Data', summary: 'Missing Data',
@@ -111,34 +118,52 @@ export class BookUploaderComponent implements OnInit {
return; return;
} }
const libraryId = this.selectedLibrary.id!.toString();
const pathId = this.selectedPath.id!.toString();
const filesToUpload = this.files.filter(f => f.status === 'Pending'); const filesToUpload = this.files.filter(f => f.status === 'Pending');
if (filesToUpload.length === 0) return; if (filesToUpload.length === 0) return;
this.isUploading = true; this.isUploading = true;
let pending = filesToUpload.length; this.uploadBatch(filesToUpload, 0, 5);
}
for (const uploadFile of filesToUpload) { private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number): void {
const batch = files.slice(startIndex, startIndex + batchSize);
if (batch.length === 0) {
this.isUploading = false;
return;
}
let pending = batch.length;
for (const uploadFile of batch) {
uploadFile.status = 'Uploading'; uploadFile.status = 'Uploading';
const formData = new FormData(); const formData = new FormData();
formData.append('file', uploadFile.file); formData.append('file', uploadFile.file);
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
this.http.post<Book>(`${API_CONFIG.BASE_URL}/api/v1/files/upload`, formData).subscribe({ let uploadUrl: string;
if (this.value === 'library') {
const libraryId = this.selectedLibrary!.id!.toString();
const pathId = this.selectedPath!.id!.toString();
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
} else {
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload/bookdrop`;
}
this.http.post<Book>(uploadUrl, formData).subscribe({
next: () => { next: () => {
uploadFile.status = 'Uploaded'; uploadFile.status = 'Uploaded';
if (--pending === 0) this.isUploading = false; if (--pending === 0) {
this.uploadBatch(files, startIndex + batchSize, batchSize);
}
}, },
error: (err) => { error: (err) => {
uploadFile.status = 'Failed'; uploadFile.status = 'Failed';
uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.'; uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.';
console.error('Upload failed for', uploadFile.file.name, err); console.error('Upload failed for', uploadFile.file.name, err);
if (--pending === 0) { if (--pending === 0) {
this.isUploading = false; this.uploadBatch(files, startIndex + batchSize, batchSize);
} }
} }
}); });
@@ -146,11 +171,14 @@ export class BookUploaderComponent implements OnInit {
} }
isChooseDisabled(): boolean { isChooseDisabled(): boolean {
if (this.value === 'bookdrop') {
return this.isUploading;
}
return !this.selectedLibrary || !this.selectedPath || this.isUploading; return !this.selectedLibrary || !this.selectedPath || this.isUploading;
} }
isUploadDisabled(): boolean { isUploadDisabled(): boolean {
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles; return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
} }
formatSize(bytes: number): string { formatSize(bytes: number): string {
@@ -11,7 +11,7 @@
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{authors}' }}</code> <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> to automatically insert metadata. <br>
A preview below shows how files will be renamed and moved. 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. Once you're satisfied, click <span class="font-semibold text-green-400">Move Files</span> to proceed.
<span class="text-yellow-500 font-medium flex items-center gap-2"> <span class="text-yellow-500 font-medium flex items-center gap-2">
<i class="pi pi-exclamation-triangle text-yellow-400"></i> <i class="pi pi-exclamation-triangle text-yellow-400"></i>
Files will be physically moved on your system when you apply changes. Files will be physically moved on your system when you apply changes.
@@ -57,7 +57,7 @@
} }
</div> </div>
<div class="flex gap-2 mb-4 px-2 items-center w-full"> <div class="flex gap-4 mb-4 px-2 items-center w-full">
<input <input
type="text" type="text"
pInputText pInputText
@@ -116,7 +116,7 @@
<p-divider></p-divider> <p-divider></p-divider>
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4"> <div class="flex justify-end items-center gap-4 flex-shrink-0 px-4 pt-4">
@if (movedFileCount > 0) { @if (movedFileCount > 0) {
<span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none"> <span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none">
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved {{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
@@ -1,14 +1,61 @@
<p class="mb-4" style="max-width: 450px; word-wrap: break-word; line-height: 1.5; font-size: 1rem;"> <div class="flex flex-col items-center justify-center p-2 md:p-6 rounded-lg border border-neutral-700" style="max-width: 700px; margin: auto;">
I hope <strong>Booklore</strong> has made managing your book collection easier and more enjoyable. <div class="mb-4 w-full text-center">
If you appreciate the project, please consider giving it a ⭐ on GitHub. Your support truly means a lot and motivates me to keep improving. <span class="inline-block px-3 py-1 rounded-full bg-blue-800/60 text-blue-200 text-xs font-semibold tracking-wide mb-2">
</p> Open Source & Community Driven
<p class="mb-4 text-left italic text-gray-300" style="max-width: 450px; font-size: 0.9rem;"> </span>
— Aditya (Creator of BookLore) <h2 class="text-2xl font-bold text-white mb-2 tracking-tight">
</p> Booklore
<div class="flex justify-center" style="max-width: 450px; margin: auto;"> </h2>
<p-button <p class="text-base text-zinc-200 leading-relaxed">
label="Go to GitHub" Booklore is designed to help you manage your book collection with ease and enjoyment.<br>
icon="pi pi-github" If you find Booklore valuable, please consider supporting its continued development.
(click)="openGithub()"> </p>
</p-button> </div>
<div class="mb-4 w-full text-center">
<p class="text-zinc-200 italic text-sm">
Your feedback and support help me keep Booklore improving for everyone.<br>
<span class="text-zinc-300">- Aditya (Creator of Booklore)</span>
</p>
</div>
<div class="flex md:flex-row flex-col justify-center items-center gap-3 w-full mb-4">
<a href="https://github.com/booklore-app/booklore" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Star on GitHub"
icon="pi pi-github"
outlined
severity="success"
[style]="{ 'min-width': '160px' }">
</p-button>
</a>
<a href="https://opencollective.com/booklore" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Open Collective"
icon="pi pi-globe"
severity="info"
outlined>
</p-button>
</a>
<a href="https://account.venmo.com/u/AdityaChandel" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Buy me a coffee"
icon="pi pi-heart"
outlined
severity="danger">
</p-button>
</a>
</div>
<div class="w-full text-center mt-2">
<span class="block mb-1 font-medium text-green-300 text-sm">Booklore will always remain free for everyone. That is my commitment to you.</span>
<div class="text-gray-400 text-sm space-y-2 mt-2">
<p>
<span class="font-semibold text-blue-300">Open Collective</span> contributions directly support development, infrastructure, and ongoing improvements.
</p>
<p>
<span class="font-semibold text-red-300">Venmo</span> is a wonderful way to show personal appreciation, think of it as buying me a coffee for my hard work.
</p>
<p class="text-yellow-200 pt-2">
Every contribution, no matter the size, helps keep Booklore open, growing, and accessible to all.
</p>
</div>
</div>
</div> </div>
+7
View File
@@ -16,6 +16,7 @@ import {AuthService, websocketInitializer} from './app/core/service/auth.service
import {provideOAuthClient} from 'angular-oauth2-oidc'; import {provideOAuthClient} from 'angular-oauth2-oidc';
import {APP_INITIALIZER, provideAppInitializer} from '@angular/core'; import {APP_INITIALIZER, provideAppInitializer} from '@angular/core';
import {initializeAuthFactory} from './app/auth-initializer'; import {initializeAuthFactory} from './app/auth-initializer';
import {StartupService} from './app/core/service/startup.service';
bootstrapApplication(AppComponent, { bootstrapApplication(AppComponent, {
providers: [ providers: [
@@ -25,6 +26,12 @@ bootstrapApplication(AppComponent, {
deps: [AuthService], deps: [AuthService],
multi: true multi: true
}, },
{
provide: APP_INITIALIZER,
useFactory: (startup: StartupService) => () => startup.load(),
deps: [StartupService],
multi: true
},
provideHttpClient(withInterceptors([AuthInterceptorService])), provideHttpClient(withInterceptors([AuthInterceptorService])),
provideOAuthClient(), provideOAuthClient(),
provideAppInitializer(initializeAuthFactory()), provideAppInitializer(initializeAuthFactory()),
+1
View File
@@ -5,6 +5,7 @@ BOOKLORE_IMAGE_TAG=latest
# User and Timezone Settings # User and Timezone Settings
# PUID and PGID define the user/group running the container. # PUID and PGID define the user/group running the container.
# Avoid using "user" property because system won't work with it.
# TZ sets the timezone for correct time-related operations. # TZ sets the timezone for correct time-related operations.
PUID=1000 # Default user ID (Check with `id -u` on Linux/Mac) PUID=1000 # Default user ID (Check with `id -u` on Linux/Mac)
PGID=1000 # Default group ID (Check with `id -g` on Linux/Mac) PGID=1000 # Default group ID (Check with `id -g` on Linux/Mac)