Add task management panel with live task status and controls (#1322)
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@Configuration
|
||||
public class TaskExecutorConfig {
|
||||
|
||||
@Bean(name = "taskExecutor")
|
||||
public Executor taskExecutor() {
|
||||
return Executors.newVirtualThreadPerTaskExecutor();
|
||||
}
|
||||
}
|
||||
|
||||
+12
-1
@@ -4,11 +4,13 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.*;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import com.adityachandel.booklore.quartz.JobSchedulerService;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.metadata.*;
|
||||
@@ -49,7 +51,16 @@ public class MetadataController {
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookMetadata> updateMetadata(@RequestBody MetadataUpdateWrapper metadataUpdateWrapper, @PathVariable long bookId, @RequestParam(defaultValue = "true") boolean mergeCategories) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
bookMetadataUpdater.setBookMetadata(bookEntity, metadataUpdateWrapper, true, mergeCategories);
|
||||
|
||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(metadataUpdateWrapper)
|
||||
.updateThumbnail(true)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.build();
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
bookRepository.save(bookEntity);
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||
return ResponseEntity.ok(bookMetadata);
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCancelResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskStatusResponse;
|
||||
import com.adityachandel.booklore.service.TaskHistoryService;
|
||||
import com.adityachandel.booklore.service.TaskService;
|
||||
import com.adityachandel.booklore.task.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v2/tasks")
|
||||
public class TaskV2Controller {
|
||||
|
||||
private final TaskService service;
|
||||
private final TaskHistoryService taskHistoryService;
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) {
|
||||
TaskCreateResponse response = service.run(request);
|
||||
if (response.getStatus() == TaskStatus.ACCEPTED) {
|
||||
return ResponseEntity.status(HttpStatus.ACCEPTED).body(response);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{taskId}")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<TaskCancelResponse> cancelTask(@PathVariable String taskId) {
|
||||
TaskCancelResponse response = service.cancelTask(taskId);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@GetMapping("/latest")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<TaskStatusResponse> getLatestTasksForEachType() {
|
||||
TaskStatusResponse response = taskHistoryService.getLatestTasksForEachType();
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.adityachandel.booklore.convertor;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Converter
|
||||
@Slf4j
|
||||
public class JpaJsonConverter implements AttributeConverter<Map<String, Object>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map<String, Object> attribute) {
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(attribute);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error converting map to JSON", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(dbData, Map.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error converting JSON to map", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class MetadataUpdateContext {
|
||||
private BookEntity bookEntity;
|
||||
private MetadataUpdateWrapper metadataUpdateWrapper;
|
||||
private boolean updateThumbnail;
|
||||
private boolean mergeCategories;
|
||||
private MetadataReplaceMode replaceMode;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.task.tasks.options.ClearCbxCacheOptions;
|
||||
import com.adityachandel.booklore.task.tasks.options.ClearPdfCacheOptions;
|
||||
import com.adityachandel.booklore.task.tasks.options.LibraryRescanOptions;
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TaskCreateRequest {
|
||||
private String taskId;
|
||||
private TaskType taskType;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "taskType", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = ClearCbxCacheOptions.class, name = "CLEAR_CBX_CACHE"),
|
||||
@JsonSubTypes.Type(value = ClearPdfCacheOptions.class, name = "CLEAR_PDF_CACHE"),
|
||||
@JsonSubTypes.Type(value = LibraryRescanOptions.class, name = "RE_SCAN_LIBRARY")
|
||||
})
|
||||
private Object options;
|
||||
|
||||
public <T> T getOptions(Class<T> optionsClass) {
|
||||
if (options == null) {
|
||||
return null;
|
||||
}
|
||||
if (optionsClass.isInstance(options)) {
|
||||
return optionsClass.cast(options);
|
||||
}
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.convertValue(options, optionsClass);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TaskCancelResponse {
|
||||
private String taskId;
|
||||
private boolean cancelled;
|
||||
private String message;
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class TaskCreateResponse {
|
||||
private String taskId;
|
||||
private TaskType taskType;
|
||||
private TaskStatus status;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TaskStatusResponse {
|
||||
private List<TaskInfo> tasks;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class TaskInfo {
|
||||
private String id;
|
||||
private TaskType type;
|
||||
private TaskStatus status;
|
||||
private Integer progressPercentage;
|
||||
private String message;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
private LocalDateTime completedAt;
|
||||
private Map<String, Object> metadata;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.convertor.JpaJsonConverter;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Entity
|
||||
@Table(name = "tasks")
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TaskEntity {
|
||||
|
||||
@Id
|
||||
@Column(length = 36)
|
||||
private String id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false)
|
||||
private TaskType type;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false)
|
||||
private TaskStatus status;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@Column(name = "completed_at")
|
||||
private LocalDateTime completedAt;
|
||||
|
||||
@Column(name = "progress_percentage")
|
||||
private Integer progressPercentage;
|
||||
|
||||
@Column(length = 512)
|
||||
private String message;
|
||||
|
||||
@Lob
|
||||
private String errorDetails;
|
||||
|
||||
@Convert(converter = JpaJsonConverter.class)
|
||||
@Column(name = "task_options", columnDefinition = "TEXT")
|
||||
private Map<String, Object> taskOptions;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return this == o || (o instanceof TaskEntity other && id != null && id.equals(other.id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id != null ? id.hashCode() : System.identityHashCode(this);
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum MetadataReplaceMode {
|
||||
REPLACE_ALL,
|
||||
REPLACE_MISSING
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public enum TaskType {
|
||||
|
||||
CLEAR_CBX_CACHE(false, false),
|
||||
CLEAR_PDF_CACHE(false, false),
|
||||
RE_SCAN_LIBRARY(false, true);
|
||||
|
||||
@Getter
|
||||
private final boolean parallel;
|
||||
|
||||
@Getter
|
||||
private final boolean async;
|
||||
|
||||
TaskType(boolean parallel, boolean async) {
|
||||
this.parallel = parallel;
|
||||
this.async = async;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.websocket;
|
||||
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TaskProgressPayload {
|
||||
private String taskId;
|
||||
private TaskType taskType;
|
||||
private String message;
|
||||
private int progress; // 0-100 percentage
|
||||
private TaskStatus taskStatus;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@ public enum Topic {
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
DUPLICATE_FILE("/queue/duplicate-file"),
|
||||
LOG("/queue/log");
|
||||
LOG("/queue/log"),
|
||||
TASK_PROGRESS("/queue/task-progress");
|
||||
|
||||
private final String path;
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.TaskEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface TaskRepository extends JpaRepository<TaskEntity, String> {
|
||||
|
||||
@Query("SELECT t FROM TaskEntity t WHERE t.createdAt = " +
|
||||
"(SELECT MAX(t2.createdAt) FROM TaskEntity t2 WHERE t2.type = t.type) " +
|
||||
"ORDER BY t.createdAt DESC")
|
||||
List<TaskEntity> findLatestTaskForEachType();
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.repository.TaskRepository;
|
||||
import com.adityachandel.booklore.model.entity.TaskEntity;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskStatusResponse;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class TaskHistoryService {
|
||||
|
||||
private final TaskRepository taskRepository;
|
||||
private final TaskMetadataService taskMetadataService;
|
||||
|
||||
@Transactional
|
||||
public TaskEntity createTask(String taskId, TaskType type, Long userId, Map<String, Object> options) {
|
||||
TaskEntity task = TaskEntity.builder()
|
||||
.id(taskId)
|
||||
.type(type)
|
||||
.status(TaskStatus.ACCEPTED)
|
||||
.userId(userId)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.progressPercentage(0)
|
||||
.taskOptions(options)
|
||||
.build();
|
||||
|
||||
log.info("Creating task history: id={}, type={}, userId={}", taskId, type, userId);
|
||||
return taskRepository.save(task);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateTaskStatus(String taskId, TaskStatus status, String message) {
|
||||
taskRepository.findById(taskId).ifPresent(task -> {
|
||||
task.setStatus(status);
|
||||
task.setMessage(message);
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
if (status == TaskStatus.COMPLETED || status == TaskStatus.FAILED) {
|
||||
task.setCompletedAt(LocalDateTime.now());
|
||||
task.setProgressPercentage(100);
|
||||
}
|
||||
|
||||
taskRepository.save(task);
|
||||
log.info("Updated task status: id={}, status={}", taskId, status);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateTaskError(String taskId, String errorDetails) {
|
||||
taskRepository.findById(taskId).ifPresent(task -> {
|
||||
task.setStatus(TaskStatus.FAILED);
|
||||
task.setErrorDetails(errorDetails);
|
||||
task.setCompletedAt(LocalDateTime.now());
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
taskRepository.save(task);
|
||||
log.error("Task failed: id={}", taskId);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public TaskStatusResponse getLatestTasksForEachType() {
|
||||
List<TaskEntity> latestTasks = taskRepository.findLatestTaskForEachType();
|
||||
|
||||
Map<TaskType, TaskEntity> taskHistoryMap = latestTasks.stream()
|
||||
.collect(Collectors.toMap(TaskEntity::getType, task -> task));
|
||||
|
||||
List<TaskStatusResponse.TaskInfo> allTasks = new ArrayList<>();
|
||||
|
||||
for (TaskType taskType : TaskType.values()) {
|
||||
TaskEntity existingTask = taskHistoryMap.get(taskType);
|
||||
|
||||
if (existingTask != null) {
|
||||
allTasks.add(mapToTaskInfo(existingTask));
|
||||
} else {
|
||||
allTasks.add(createMetadataOnlyTaskInfo(taskType));
|
||||
}
|
||||
}
|
||||
|
||||
return TaskStatusResponse.builder()
|
||||
.tasks(allTasks)
|
||||
.build();
|
||||
}
|
||||
|
||||
private TaskStatusResponse.TaskInfo mapToTaskInfo(TaskEntity task) {
|
||||
Map<String, Object> metadata = taskMetadataService.getMetadataForTaskType(task.getType());
|
||||
|
||||
return TaskStatusResponse.TaskInfo.builder()
|
||||
.id(task.getId())
|
||||
.type(task.getType())
|
||||
.status(task.getStatus())
|
||||
.progressPercentage(task.getProgressPercentage())
|
||||
.message(task.getMessage())
|
||||
.createdAt(task.getCreatedAt())
|
||||
.updatedAt(task.getUpdatedAt())
|
||||
.completedAt(task.getCompletedAt())
|
||||
.metadata(metadata)
|
||||
.build();
|
||||
}
|
||||
|
||||
private TaskStatusResponse.TaskInfo createMetadataOnlyTaskInfo(TaskType taskType) {
|
||||
Map<String, Object> metadata = taskMetadataService.getMetadataForTaskType(taskType);
|
||||
|
||||
return TaskStatusResponse.TaskInfo.builder()
|
||||
.id(null)
|
||||
.type(taskType)
|
||||
.status(null)
|
||||
.progressPercentage(null)
|
||||
.message(null)
|
||||
.createdAt(null)
|
||||
.updatedAt(null)
|
||||
.completedAt(null)
|
||||
.metadata(metadata)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class TaskMetadataService {
|
||||
|
||||
private final FileService fileService;
|
||||
|
||||
public Map<String, Object> getMetadataForTaskType(TaskType taskType) {
|
||||
Map<String, Object> metadata = new HashMap<>();
|
||||
|
||||
switch (taskType) {
|
||||
case CLEAR_CBX_CACHE:
|
||||
metadata.putAll(getCacheMetadata(fileService.getCbxCachePath(), "CBX"));
|
||||
break;
|
||||
case CLEAR_PDF_CACHE:
|
||||
metadata.putAll(getCacheMetadata(fileService.getPdfCachePath(), "PDF"));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private Map<String, Object> getCacheMetadata(String cachePathStr, String cacheType) {
|
||||
Map<String, Object> metadata = new HashMap<>();
|
||||
|
||||
try {
|
||||
Path cachePath = Paths.get(cachePathStr);
|
||||
|
||||
if (Files.exists(cachePath) && Files.isDirectory(cachePath)) {
|
||||
long sizeInBytes = calculateDirectorySize(cachePath);
|
||||
String formattedSize = formatBytes(sizeInBytes);
|
||||
|
||||
metadata.put("currentCacheSize", formattedSize);
|
||||
metadata.put("currentCacheSizeBytes", sizeInBytes);
|
||||
} else {
|
||||
metadata.put("currentCacheSize", "0 B");
|
||||
metadata.put("currentCacheSizeBytes", 0L);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error calculating {} cache size", cacheType, e);
|
||||
metadata.put("currentCacheSize", "Unknown");
|
||||
metadata.put("currentCacheSizeBytes", -1L);
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private long calculateDirectorySize(Path path) throws IOException {
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
return walk
|
||||
.filter(Files::isRegularFile)
|
||||
.mapToLong(p -> {
|
||||
try {
|
||||
return Files.size(p);
|
||||
} catch (IOException e) {
|
||||
log.warn("Could not get size of file: {}", p, e);
|
||||
return 0L;
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
|
||||
private String formatBytes(long bytes) {
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
int exp = (int) (Math.log(bytes) / Math.log(1024));
|
||||
String pre = "KMGTPE".charAt(exp - 1) + "";
|
||||
return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCancelResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.task.*;
|
||||
import com.adityachandel.booklore.task.tasks.Task;
|
||||
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class TaskService {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final TaskHistoryService taskHistoryService;
|
||||
private final Map<TaskType, Task> taskRegistry;
|
||||
private final ConcurrentMap<TaskType, String> runningTasks = new ConcurrentHashMap<>();
|
||||
private final TaskCancellationManager cancellationManager;
|
||||
private final Executor taskExecutor;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public TaskService(AuthenticationService authenticationService, TaskHistoryService taskHistoryService, List<Task> tasks, TaskCancellationManager cancellationManager, Executor taskExecutor, ObjectMapper objectMapper) {
|
||||
this.authenticationService = authenticationService;
|
||||
this.taskHistoryService = taskHistoryService;
|
||||
this.taskRegistry = tasks.stream().collect(Collectors.toMap(Task::getTaskType, Function.identity()));
|
||||
this.cancellationManager = cancellationManager;
|
||||
this.taskExecutor = taskExecutor;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public TaskCreateResponse run(TaskCreateRequest request) {
|
||||
if (request == null || request.getTaskType() == null) {
|
||||
throw new APIException("Task request and task type cannot be null", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
TaskType taskType = request.getTaskType();
|
||||
if (taskType.isAsync()) {
|
||||
return runAsync(request, user, taskType);
|
||||
} else {
|
||||
return runSync(request, user, taskType);
|
||||
}
|
||||
}
|
||||
|
||||
private TaskCreateResponse runAsync(TaskCreateRequest request, BookLoreUser user, TaskType taskType) {
|
||||
String taskId = initializeTask(request, user, taskType);
|
||||
TaskCreateResponse response = TaskCreateResponse.builder()
|
||||
.taskId(taskId)
|
||||
.taskType(taskType)
|
||||
.status(TaskStatus.ACCEPTED)
|
||||
.build();
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
taskExecutor.execute(() ->
|
||||
SecurityContextVirtualThread.runWithSecurityContext(securityContext, () ->
|
||||
executeAsyncTask(taskId, request, taskType)
|
||||
)
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
public TaskCancelResponse cancelTask(String taskId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
boolean isRunning = runningTasks.containsValue(taskId);
|
||||
if (!isRunning) {
|
||||
throw new APIException("Task not found or not running: " + taskId, HttpStatus.NOT_FOUND);
|
||||
}
|
||||
cancellationManager.cancelTask(taskId);
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.CANCELLED, "Task cancellation requested by user");
|
||||
log.info("Task {} cancellation requested by user {}", taskId, user.getUsername());
|
||||
return TaskCancelResponse.builder()
|
||||
.taskId(taskId)
|
||||
.cancelled(true)
|
||||
.message("Task cancellation requested. The task will stop at the next checkpoint.")
|
||||
.build();
|
||||
}
|
||||
|
||||
private void executeAsyncTask(String taskId, TaskCreateRequest request, TaskType taskType) {
|
||||
try {
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.IN_PROGRESS, "Task execution started");
|
||||
request.setTaskId(taskId);
|
||||
if (cancellationManager.isTaskCancelled(taskId)) {
|
||||
log.info("Task {} was cancelled before execution", taskId);
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.CANCELLED, "Task was cancelled");
|
||||
return;
|
||||
}
|
||||
executeTask(request);
|
||||
if (cancellationManager.isTaskCancelled(taskId)) {
|
||||
log.info("Task {} was cancelled during execution", taskId);
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.CANCELLED, "Task was cancelled");
|
||||
} else {
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, "Task completed successfully");
|
||||
log.info("Async task {} of type {} completed successfully", taskId, taskType);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Async task {} of type {} failed", taskId, taskType, e);
|
||||
taskHistoryService.updateTaskError(taskId, e.getMessage());
|
||||
} finally {
|
||||
if (!taskType.isParallel()) {
|
||||
runningTasks.remove(taskType);
|
||||
}
|
||||
cancellationManager.clearCancellation(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
private TaskCreateResponse runSync(TaskCreateRequest request, BookLoreUser user, TaskType taskType) {
|
||||
String taskId = initializeTask(request, user, taskType);
|
||||
try {
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.IN_PROGRESS, "Task execution started");
|
||||
request.setTaskId(taskId);
|
||||
TaskCreateResponse response = executeTask(request);
|
||||
response.setTaskId(taskId);
|
||||
taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, "Task completed successfully");
|
||||
log.info("Sync task {} of type {} completed successfully", taskId, taskType);
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("Sync task {} of type {} failed", taskId, taskType, e);
|
||||
taskHistoryService.updateTaskError(taskId, e.getMessage());
|
||||
throw e;
|
||||
} finally {
|
||||
if (!taskType.isParallel()) {
|
||||
runningTasks.remove(taskType);
|
||||
log.info("Released lock for task type: {}", taskType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String initializeTask(TaskCreateRequest request, BookLoreUser user, TaskType taskType) {
|
||||
if (!taskType.isParallel()) {
|
||||
String existingTaskId = runningTasks.putIfAbsent(taskType, "");
|
||||
if (existingTaskId != null) {
|
||||
log.warn("Task of type {} is already running, rejecting new request", taskType);
|
||||
throw new APIException("A task of type " + taskType + " is already running. Please wait for it to complete.", HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
String taskId = UUID.randomUUID().toString();
|
||||
if (!taskType.isParallel()) {
|
||||
runningTasks.put(taskType, taskId);
|
||||
}
|
||||
Map<String, Object> options = convertOptionsToMap(request.getOptions());
|
||||
taskHistoryService.createTask(taskId, taskType, user.getId(), options);
|
||||
log.info("Initialized task: id={}, type={}, userId={}", taskId, taskType, user.getId());
|
||||
return taskId;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> convertOptionsToMap(Object options) {
|
||||
if (options == null) {
|
||||
return Map.of();
|
||||
}
|
||||
if (options instanceof Map) {
|
||||
return (Map<String, Object>) options;
|
||||
}
|
||||
try {
|
||||
return objectMapper.convertValue(options, Map.class);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Failed to convert options to map, using empty map", e);
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
|
||||
private TaskCreateResponse executeTask(TaskCreateRequest request) {
|
||||
TaskType taskType = request.getTaskType();
|
||||
log.info("Executing task of type: {}", taskType);
|
||||
Task task = taskRegistry.get(taskType);
|
||||
if (task == null) {
|
||||
throw new UnsupportedOperationException("Task type not implemented: " + taskType);
|
||||
}
|
||||
return task.execute(request);
|
||||
}
|
||||
}
|
||||
+8
-19
@@ -12,9 +12,7 @@ import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.repository.BookdropFileRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -40,9 +38,7 @@ public class BookdropMetadataService {
|
||||
private final BookdropFileRepository bookdropFileRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final MetadataExtractorFactory metadataExtractorFactory;
|
||||
private final MetadataRefreshService metadataRefreshService;
|
||||
private final FileService fileService;
|
||||
|
||||
@@ -98,23 +94,16 @@ public class BookdropMetadataService {
|
||||
|
||||
private BookMetadata extractInitialMetadata(BookdropFileEntity entity) {
|
||||
File file = new File(entity.getFilePath());
|
||||
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getName()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
|
||||
return switch (fileExt) {
|
||||
case PDF -> pdfMetadataExtractor.extractMetadata(file);
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getName())
|
||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
|
||||
return metadataExtractorFactory.extractMetadata(fileExt, file);
|
||||
}
|
||||
|
||||
private void extractAndSaveCover(BookdropFileEntity entity) {
|
||||
File file = new File(entity.getFilePath());
|
||||
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getName()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
|
||||
byte[] coverBytes;
|
||||
coverBytes = switch (fileExt) {
|
||||
case EPUB -> epubMetadataExtractor.extractCover(file);
|
||||
case PDF -> pdfMetadataExtractor.extractCover(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractCover(file);
|
||||
};
|
||||
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getName())
|
||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
|
||||
byte[] coverBytes = metadataExtractorFactory.extractCover(fileExt, file);
|
||||
if (coverBytes != null) {
|
||||
try {
|
||||
fileService.saveImage(coverBytes, fileService.getTempBookdropCoverImagePath(entity.getId()));
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Component
|
||||
public class LibraryFileHelper {
|
||||
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor));
|
||||
}
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
|
||||
|
||||
try (Stream<Path> stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) {
|
||||
return stream.filter(Files::isRegularFile)
|
||||
.map(fullPath -> {
|
||||
String fileName = fullPath.getFileName().toString();
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build();
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.filter(file -> !file.getFileName().startsWith("."))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-53
@@ -5,13 +5,11 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.adityachandel.booklore.task.RescanLibraryContext;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -20,12 +18,9 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
@@ -40,6 +35,7 @@ public class LibraryProcessingService {
|
||||
private final LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
private final BookRestorationService bookRestorationService;
|
||||
private final BookDeletionService bookDeletionService;
|
||||
private final LibraryFileHelper libraryFileHelper;
|
||||
@PersistenceContext
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@@ -48,17 +44,17 @@ public class LibraryProcessingService {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing library: " + libraryEntity.getName()));
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity, processor);
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void rescanLibrary(long libraryId) throws IOException {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
public void rescanLibrary(RescanLibraryContext context) throws IOException {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity, processor);
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
|
||||
if (!additionalFileIds.isEmpty()) {
|
||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||
@@ -72,6 +68,7 @@ public class LibraryProcessingService {
|
||||
bookRestorationService.restoreDeletedBooks(libraryFiles);
|
||||
entityManager.clear();
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
@@ -97,12 +94,10 @@ public class LibraryProcessingService {
|
||||
.map(BookEntity::getFullFilePath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Also collect paths from additional files using repository method
|
||||
Set<Path> additionalFilePaths = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()).stream()
|
||||
.map(BookAdditionalFileEntity::getFullFilePath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Combine both sets of existing paths
|
||||
existingFullPaths.addAll(additionalFilePaths);
|
||||
|
||||
return libraryFiles.stream()
|
||||
@@ -111,56 +106,15 @@ public class LibraryProcessingService {
|
||||
}
|
||||
|
||||
protected List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
// Create a set of current file names for quick lookup
|
||||
Set<String> currentFileNames = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Get all additional files from the library
|
||||
List<BookAdditionalFileEntity> allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
|
||||
|
||||
// Find additional files that no longer exist in the file system
|
||||
return allAdditionalFiles.stream()
|
||||
.filter(additionalFile -> !currentFileNames.contains(additionalFile.getFileName()))
|
||||
.map(BookAdditionalFileEntity::getId)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor));
|
||||
}
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
|
||||
|
||||
try (Stream<Path> stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) {
|
||||
return stream.filter(Files::isRegularFile)
|
||||
.map(fullPath -> {
|
||||
String fileName = fullPath.getFileName().toString();
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
// Skip files that are not recognized book files and supplementary files are not supported
|
||||
return null;
|
||||
}
|
||||
|
||||
return LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build();
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.filter(file -> !file.getFileName().startsWith("."))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.websocket.TaskProgressPayload;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
|
||||
import com.adityachandel.booklore.task.RescanLibraryContext;
|
||||
import com.adityachandel.booklore.task.TaskCancellationManager;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class LibraryRescanHelper {
|
||||
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final MetadataExtractorFactory metadataExtractorFactory;
|
||||
private final BookMetadataUpdater bookMetadataUpdater;
|
||||
private final NotificationService notificationService;
|
||||
private final TaskCancellationManager cancellationManager;
|
||||
|
||||
public LibraryRescanHelper(LibraryRepository libraryRepository, MetadataExtractorFactory metadataExtractorFactory, @Lazy BookMetadataUpdater bookMetadataUpdater, NotificationService notificationService, TaskCancellationManager cancellationManager) {
|
||||
this.libraryRepository = libraryRepository;
|
||||
this.metadataExtractorFactory = metadataExtractorFactory;
|
||||
this.bookMetadataUpdater = bookMetadataUpdater;
|
||||
this.notificationService = notificationService;
|
||||
this.cancellationManager = cancellationManager;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void handleRescanOptions(RescanLibraryContext context, String taskId) {
|
||||
|
||||
LibraryEntity library = libraryRepository.findById(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
|
||||
|
||||
List<BookEntity> bookEntities = library.getBookEntities().stream()
|
||||
.filter(b -> b != null && (b.getDeleted() == null || !b.getDeleted()))
|
||||
.toList();
|
||||
|
||||
log.info("Found {} book(s) to process in library id={}", bookEntities.size(), library.getId());
|
||||
|
||||
int totalBooks = bookEntities.size();
|
||||
int processedBooks = 0;
|
||||
|
||||
sendTaskProgressNotification(taskId, 0, String.format("Starting rescan for library: %s", library.getName()), TaskStatus.IN_PROGRESS);
|
||||
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
if (taskId != null && cancellationManager.isTaskCancelled(taskId)) {
|
||||
log.info("Library rescan for library {} was cancelled", library.getId());
|
||||
sendTaskProgressNotification(taskId, (processedBooks * 100) / totalBooks,
|
||||
String.format("Rescan cancelled for library: %s (%d/%d books processed)", library.getName(), processedBooks, totalBooks),
|
||||
TaskStatus.CANCELLED);
|
||||
break;
|
||||
}
|
||||
|
||||
log.info("Processing book: library={}, bookId={}, fileName={}", library.getName(), bookEntity.getId(), bookEntity.getFileName());
|
||||
|
||||
int progressPercentage = totalBooks > 0 ? (processedBooks * 100) / totalBooks : 0;
|
||||
|
||||
sendTaskProgressNotification(taskId, progressPercentage,
|
||||
String.format("Processing: %s (Library: %s)", bookEntity.getFileName(), library.getName()),
|
||||
TaskStatus.IN_PROGRESS);
|
||||
|
||||
try {
|
||||
BookMetadata bookMetadata = metadataExtractorFactory.extractMetadata(bookEntity.getBookType(), bookEntity.getFullFilePath().toFile());
|
||||
if (bookMetadata == null) {
|
||||
log.warn("No metadata extracted for book id={} path={}", bookEntity.getId(), bookEntity.getFullFilePath());
|
||||
continue;
|
||||
}
|
||||
MetadataUpdateContext metadataUpdateContext = MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(
|
||||
MetadataUpdateWrapper.builder()
|
||||
.metadata(bookMetadata)
|
||||
.build()
|
||||
)
|
||||
.replaceMode(context.getOptions().getMetadataReplaceMode())
|
||||
.updateThumbnail(false)
|
||||
.mergeCategories(false)
|
||||
.build();
|
||||
bookMetadataUpdater.setBookMetadata(metadataUpdateContext);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update metadata for book id={} path={}: {}", bookEntity.getId(), bookEntity.getFullFilePath(), e.getMessage(), e);
|
||||
} finally {
|
||||
processedBooks++;
|
||||
}
|
||||
}
|
||||
|
||||
if (taskId == null || !cancellationManager.isTaskCancelled(taskId)) {
|
||||
sendTaskProgressNotification(taskId, 100,
|
||||
String.format("Rescan completed for library: %s (%d books processed)", library.getName(), processedBooks),
|
||||
TaskStatus.COMPLETED);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendTaskProgressNotification(String taskId, int progress, String message, TaskStatus taskStatus) {
|
||||
try {
|
||||
TaskProgressPayload payload = TaskProgressPayload.builder()
|
||||
.taskId(taskId)
|
||||
.taskType(TaskType.RE_SCAN_LIBRARY)
|
||||
.message(message)
|
||||
.progress(progress)
|
||||
.taskStatus(taskStatus)
|
||||
.build();
|
||||
|
||||
notificationService.sendMessage(Topic.TASK_PROGRESS, payload);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send task progress notification for taskId={}: {}", taskId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -21,6 +21,7 @@ import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import com.adityachandel.booklore.task.RescanLibraryContext;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@@ -180,12 +181,14 @@ public class LibraryService {
|
||||
}
|
||||
|
||||
public void rescanLibrary(long libraryId) {
|
||||
libraryRepository.findById(libraryId)
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
||||
try {
|
||||
libraryProcessingService.rescanLibrary(libraryId);
|
||||
RescanLibraryContext context = RescanLibraryContext.builder()
|
||||
.libraryId(libraryId)
|
||||
.build();
|
||||
libraryProcessingService.rescanLibrary(context);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
|
||||
+10
-4
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.mapper.MetadataClearFlagsMapper;
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
@@ -252,12 +253,17 @@ public class BookMetadataService {
|
||||
.tags(request.getTags())
|
||||
.build();
|
||||
|
||||
MetadataUpdateWrapper metadataUpdateWrapper = MetadataUpdateWrapper.builder()
|
||||
.metadata(bookMetadata)
|
||||
.clearFlags(clearFlags)
|
||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||
.bookEntity(book)
|
||||
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
||||
.metadata(bookMetadata)
|
||||
.clearFlags(clearFlags)
|
||||
.build())
|
||||
.updateThumbnail(false)
|
||||
.mergeCategories(mergeCategories)
|
||||
.build();
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(book, metadataUpdateWrapper, false, mergeCategories);
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
}
|
||||
|
||||
return books.stream()
|
||||
|
||||
+178
-114
@@ -1,12 +1,15 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import com.adityachandel.booklore.repository.MoodRepository;
|
||||
import com.adityachandel.booklore.repository.TagRepository;
|
||||
@@ -20,7 +23,6 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@@ -32,6 +34,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -43,6 +46,7 @@ public class BookMetadataUpdater {
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final MoodRepository moodRepository;
|
||||
private final TagRepository tagRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final FileService fileService;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -50,10 +54,22 @@ public class BookMetadataUpdater {
|
||||
private final BookReviewUpdateService bookReviewUpdateService;
|
||||
private final UnifiedFileMoveService unifiedFileMoveService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void setBookMetadata(BookEntity bookEntity, MetadataUpdateWrapper wrapper, boolean setThumbnail, boolean mergeCategories) {
|
||||
@Transactional
|
||||
public void setBookMetadata(MetadataUpdateContext context) {
|
||||
BookEntity bookEntity = context.getBookEntity();
|
||||
MetadataUpdateWrapper wrapper = context.getMetadataUpdateWrapper();
|
||||
boolean mergeCategories = context.isMergeCategories();
|
||||
boolean updateThumbnail = context.isUpdateThumbnail();
|
||||
MetadataReplaceMode replaceMode = context.getReplaceMode();
|
||||
|
||||
Long bookId = bookEntity.getId();
|
||||
BookMetadata newMetadata = wrapper.getMetadata();
|
||||
|
||||
if (newMetadata == null) {
|
||||
log.warn("Metadata is null for book ID {}. Skipping update.", bookId);
|
||||
return;
|
||||
}
|
||||
|
||||
MetadataClearFlags clearFlags = wrapper.getClearFlags();
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
@@ -77,13 +93,15 @@ public class BookMetadataUpdater {
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
BookFileType bookType = bookEntity.getBookType();
|
||||
|
||||
updateBasicFields(newMetadata, metadata, clearFlags);
|
||||
updateAuthorsIfNeeded(newMetadata, metadata, clearFlags);
|
||||
updateCategoriesIfNeeded(newMetadata, metadata, clearFlags, mergeCategories);
|
||||
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories);
|
||||
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories);
|
||||
updateBasicFields(newMetadata, metadata, clearFlags, replaceMode);
|
||||
updateAuthorsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
|
||||
updateCategoriesIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
|
||||
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
|
||||
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
|
||||
bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories);
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, setThumbnail);
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail);
|
||||
|
||||
bookRepository.save(bookEntity);
|
||||
|
||||
try {
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
@@ -98,7 +116,7 @@ public class BookMetadataUpdater {
|
||||
} else {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
try {
|
||||
String thumbnailUrl = setThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
|
||||
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
|
||||
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
|
||||
@@ -146,63 +164,92 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
|
||||
|
||||
private void updateBasicFields(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear) {
|
||||
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getPublisherLocked(), clear.isPublisher(), m.getPublisher(), v -> e.setPublisher(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getPublishedDateLocked(), clear.isPublishedDate(), m.getPublishedDate(), e::setPublishedDate);
|
||||
handleFieldUpdate(e.getDescriptionLocked(), clear.isDescription(), m.getDescription(), v -> e.setDescription(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getSeriesNameLocked(), clear.isSeriesName(), m.getSeriesName(), e::setSeriesName);
|
||||
handleFieldUpdate(e.getSeriesNumberLocked(), clear.isSeriesNumber(), m.getSeriesNumber(), e::setSeriesNumber);
|
||||
handleFieldUpdate(e.getSeriesTotalLocked(), clear.isSeriesTotal(), m.getSeriesTotal(), e::setSeriesTotal);
|
||||
handleFieldUpdate(e.getIsbn13Locked(), clear.isIsbn13(), m.getIsbn13(), v -> e.setIsbn13(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getIsbn10Locked(), clear.isIsbn10(), m.getIsbn10(), v -> e.setIsbn10(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getAsinLocked(), clear.isAsin(), m.getAsin(), v -> e.setAsin(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getGoodreadsIdLocked(), clear.isGoodreadsId(), m.getGoodreadsId(), v -> e.setGoodreadsId(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getComicvineIdLocked(), clear.isComicvineId(), m.getComicvineId(), v -> e.setComicvineId(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getHardcoverIdLocked(), clear.isHardcoverId(), m.getHardcoverId(), v -> e.setHardcoverId(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getGoogleIdLocked(), clear.isGoogleId(), m.getGoogleId(), v -> e.setGoogleId(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getPageCountLocked(), clear.isPageCount(), m.getPageCount(), e::setPageCount);
|
||||
handleFieldUpdate(e.getLanguageLocked(), clear.isLanguage(), m.getLanguage(), v -> e.setLanguage(nullIfBlank(v)));
|
||||
handleFieldUpdate(e.getPersonalRatingLocked(), clear.isPersonalRating(), m.getPersonalRating(), e::setPersonalRating);
|
||||
handleFieldUpdate(e.getAmazonRatingLocked(), clear.isAmazonRating(), m.getAmazonRating(), e::setAmazonRating);
|
||||
handleFieldUpdate(e.getAmazonReviewCountLocked(), clear.isAmazonReviewCount(), m.getAmazonReviewCount(), e::setAmazonReviewCount);
|
||||
handleFieldUpdate(e.getGoodreadsRatingLocked(), clear.isGoodreadsRating(), m.getGoodreadsRating(), e::setGoodreadsRating);
|
||||
handleFieldUpdate(e.getGoodreadsReviewCountLocked(), clear.isGoodreadsReviewCount(), m.getGoodreadsReviewCount(), e::setGoodreadsReviewCount);
|
||||
handleFieldUpdate(e.getHardcoverRatingLocked(), clear.isHardcoverRating(), m.getHardcoverRating(), e::setHardcoverRating);
|
||||
handleFieldUpdate(e.getHardcoverReviewCountLocked(), clear.isHardcoverReviewCount(), m.getHardcoverReviewCount(), e::setHardcoverReviewCount);
|
||||
private void updateBasicFields(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, MetadataReplaceMode replaceMode) {
|
||||
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)), e::getTitle, replaceMode);
|
||||
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)), e::getSubtitle, replaceMode);
|
||||
handleFieldUpdate(e.getPublisherLocked(), clear.isPublisher(), m.getPublisher(), v -> e.setPublisher(nullIfBlank(v)), e::getPublisher, replaceMode);
|
||||
handleFieldUpdate(e.getPublishedDateLocked(), clear.isPublishedDate(), m.getPublishedDate(), e::setPublishedDate, e::getPublishedDate, replaceMode);
|
||||
handleFieldUpdate(e.getDescriptionLocked(), clear.isDescription(), m.getDescription(), v -> e.setDescription(nullIfBlank(v)), e::getDescription, replaceMode);
|
||||
handleFieldUpdate(e.getSeriesNameLocked(), clear.isSeriesName(), m.getSeriesName(), e::setSeriesName, e::getSeriesName, replaceMode);
|
||||
handleFieldUpdate(e.getSeriesNumberLocked(), clear.isSeriesNumber(), m.getSeriesNumber(), e::setSeriesNumber, e::getSeriesNumber, replaceMode);
|
||||
handleFieldUpdate(e.getSeriesTotalLocked(), clear.isSeriesTotal(), m.getSeriesTotal(), e::setSeriesTotal, e::getSeriesTotal, replaceMode);
|
||||
handleFieldUpdate(e.getIsbn13Locked(), clear.isIsbn13(), m.getIsbn13(), v -> e.setIsbn13(nullIfBlank(v)), e::getIsbn13, replaceMode);
|
||||
handleFieldUpdate(e.getIsbn10Locked(), clear.isIsbn10(), m.getIsbn10(), v -> e.setIsbn10(nullIfBlank(v)), e::getIsbn10, replaceMode);
|
||||
handleFieldUpdate(e.getAsinLocked(), clear.isAsin(), m.getAsin(), v -> e.setAsin(nullIfBlank(v)), e::getAsin, replaceMode);
|
||||
handleFieldUpdate(e.getGoodreadsIdLocked(), clear.isGoodreadsId(), m.getGoodreadsId(), v -> e.setGoodreadsId(nullIfBlank(v)), e::getGoodreadsId, replaceMode);
|
||||
handleFieldUpdate(e.getComicvineIdLocked(), clear.isComicvineId(), m.getComicvineId(), v -> e.setComicvineId(nullIfBlank(v)), e::getComicvineId, replaceMode);
|
||||
handleFieldUpdate(e.getHardcoverIdLocked(), clear.isHardcoverId(), m.getHardcoverId(), v -> e.setHardcoverId(nullIfBlank(v)), e::getHardcoverId, replaceMode);
|
||||
handleFieldUpdate(e.getGoogleIdLocked(), clear.isGoogleId(), m.getGoogleId(), v -> e.setGoogleId(nullIfBlank(v)), e::getGoogleId, replaceMode);
|
||||
handleFieldUpdate(e.getPageCountLocked(), clear.isPageCount(), m.getPageCount(), e::setPageCount, e::getPageCount, replaceMode);
|
||||
handleFieldUpdate(e.getLanguageLocked(), clear.isLanguage(), m.getLanguage(), v -> e.setLanguage(nullIfBlank(v)), e::getLanguage, replaceMode);
|
||||
handleFieldUpdate(e.getPersonalRatingLocked(), clear.isPersonalRating(), m.getPersonalRating(), e::setPersonalRating, e::getPersonalRating, replaceMode);
|
||||
handleFieldUpdate(e.getAmazonRatingLocked(), clear.isAmazonRating(), m.getAmazonRating(), e::setAmazonRating, e::getAmazonRating, replaceMode);
|
||||
handleFieldUpdate(e.getAmazonReviewCountLocked(), clear.isAmazonReviewCount(), m.getAmazonReviewCount(), e::setAmazonReviewCount, e::getAmazonReviewCount, replaceMode);
|
||||
handleFieldUpdate(e.getGoodreadsRatingLocked(), clear.isGoodreadsRating(), m.getGoodreadsRating(), e::setGoodreadsRating, e::getGoodreadsRating, replaceMode);
|
||||
handleFieldUpdate(e.getGoodreadsReviewCountLocked(), clear.isGoodreadsReviewCount(), m.getGoodreadsReviewCount(), e::setGoodreadsReviewCount, e::getGoodreadsReviewCount, replaceMode);
|
||||
handleFieldUpdate(e.getHardcoverRatingLocked(), clear.isHardcoverRating(), m.getHardcoverRating(), e::setHardcoverRating, e::getHardcoverRating, replaceMode);
|
||||
handleFieldUpdate(e.getHardcoverReviewCountLocked(), clear.isHardcoverReviewCount(), m.getHardcoverReviewCount(), e::setHardcoverReviewCount, e::getHardcoverReviewCount, replaceMode);
|
||||
}
|
||||
|
||||
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter) {
|
||||
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode replaceMode) {
|
||||
if (Boolean.TRUE.equals(locked)) return;
|
||||
if (shouldClear) setter.accept(null);
|
||||
else if (newValue != null) setter.accept(newValue);
|
||||
}
|
||||
|
||||
private void updateAuthorsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear) {
|
||||
if (Boolean.TRUE.equals(e.getAuthorsLocked())) {
|
||||
// Locked — do nothing
|
||||
} else if (clear.isAuthors()) {
|
||||
if (e.getAuthors() == null) {
|
||||
e.setAuthors(new HashSet<>());
|
||||
} else {
|
||||
e.getAuthors().clear();
|
||||
if (shouldClear) {
|
||||
setter.accept(null);
|
||||
return;
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
setter.accept(newValue);
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
|
||||
T currentValue = getter.get();
|
||||
if (isValueMissing(currentValue)) {
|
||||
setter.accept(newValue);
|
||||
}
|
||||
} else if (shouldUpdateField(false, m.getAuthors()) && m.getAuthors() != null) {
|
||||
if (e.getAuthors() == null) {
|
||||
e.setAuthors(new HashSet<>());
|
||||
}
|
||||
Set<AuthorEntity> newAuthors = m.getAuthors().stream()
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(name -> authorRepository.findByName(name)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
e.getAuthors().clear();
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCategoriesIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge) {
|
||||
private <T> boolean isValueMissing(T value) {
|
||||
if (value == null) return true;
|
||||
if (value instanceof String) return !StringUtils.hasText((String) value);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void updateAuthorsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
|
||||
if (Boolean.TRUE.equals(e.getAuthorsLocked())) {
|
||||
return;
|
||||
}
|
||||
if (e.getAuthors() == null) {
|
||||
e.setAuthors(new HashSet<>());
|
||||
}
|
||||
if (clear.isAuthors()) {
|
||||
e.getAuthors().clear();
|
||||
return;
|
||||
}
|
||||
if (m.getAuthors() == null) {
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
e.getAuthors().clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
Set<AuthorEntity> newAuthors = m.getAuthors().stream()
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(name -> authorRepository.findByName(name)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
if (merge) {
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
} else {
|
||||
e.getAuthors().clear();
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
}
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
|
||||
if (e.getAuthors().isEmpty()) {
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCategoriesIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
|
||||
if (Boolean.TRUE.equals(e.getCategoriesLocked())) {
|
||||
return;
|
||||
}
|
||||
@@ -211,29 +258,36 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
if (clear.isCategories()) {
|
||||
e.getCategories().clear();
|
||||
} else if (shouldUpdateField(false, m.getCategories()) && m.getCategories() != null) {
|
||||
return;
|
||||
}
|
||||
if (m.getCategories() == null) {
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
e.getCategories().clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Set<CategoryEntity> newCategories = m.getCategories().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> categoryRepository.findByName(name)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
if (merge) {
|
||||
Set<CategoryEntity> existing = e.getCategories();
|
||||
for (String name : m.getCategories()) {
|
||||
if (name == null || name.isBlank()) continue;
|
||||
CategoryEntity entity = categoryRepository.findByName(name)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(name).build()));
|
||||
existing.add(entity);
|
||||
}
|
||||
e.getCategories().addAll(newCategories);
|
||||
} else {
|
||||
Set<CategoryEntity> existing = e.getCategories();
|
||||
existing.clear();
|
||||
Set<CategoryEntity> result = m.getCategories().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> categoryRepository.findByName(name)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
existing.addAll(result);
|
||||
e.getCategories().clear();
|
||||
e.getCategories().addAll(newCategories);
|
||||
}
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
|
||||
if (e.getCategories().isEmpty()) {
|
||||
e.getCategories().addAll(newCategories);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateMoodsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge) {
|
||||
private void updateMoodsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
|
||||
if (Boolean.TRUE.equals(e.getMoodsLocked())) {
|
||||
return;
|
||||
}
|
||||
@@ -242,29 +296,36 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
if (clear.isMoods()) {
|
||||
e.getMoods().clear();
|
||||
} else if (shouldUpdateField(false, m.getMoods()) && m.getMoods() != null) {
|
||||
return;
|
||||
}
|
||||
if (m.getMoods() == null) {
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
e.getMoods().clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Set<MoodEntity> newMoods = m.getMoods().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> moodRepository.findByName(name)
|
||||
.orElseGet(() -> moodRepository.save(MoodEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
if (merge) {
|
||||
Set<MoodEntity> existing = e.getMoods();
|
||||
for (String name : m.getMoods()) {
|
||||
if (name == null || name.isBlank()) continue;
|
||||
MoodEntity entity = moodRepository.findByName(name)
|
||||
.orElseGet(() -> moodRepository.save(MoodEntity.builder().name(name).build()));
|
||||
existing.add(entity);
|
||||
}
|
||||
e.getMoods().addAll(newMoods);
|
||||
} else {
|
||||
Set<MoodEntity> existing = e.getMoods();
|
||||
existing.clear();
|
||||
Set<MoodEntity> result = m.getMoods().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> moodRepository.findByName(name)
|
||||
.orElseGet(() -> moodRepository.save(MoodEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
existing.addAll(result);
|
||||
e.getMoods().clear();
|
||||
e.getMoods().addAll(newMoods);
|
||||
}
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
|
||||
if (e.getMoods().isEmpty()) {
|
||||
e.getMoods().addAll(newMoods);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateTagsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge) {
|
||||
private void updateTagsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
|
||||
if (Boolean.TRUE.equals(e.getTagsLocked())) {
|
||||
return;
|
||||
}
|
||||
@@ -273,24 +334,31 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
if (clear.isTags()) {
|
||||
e.getTags().clear();
|
||||
} else if (shouldUpdateField(false, m.getTags()) && m.getTags() != null) {
|
||||
return;
|
||||
}
|
||||
if (m.getTags() == null) {
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
e.getTags().clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Set<TagEntity> newTags = m.getTags().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> tagRepository.findByName(name)
|
||||
.orElseGet(() -> tagRepository.save(TagEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
|
||||
if (merge) {
|
||||
Set<TagEntity> existing = e.getTags();
|
||||
for (String name : m.getTags()) {
|
||||
if (name == null || name.isBlank()) continue;
|
||||
TagEntity entity = tagRepository.findByName(name)
|
||||
.orElseGet(() -> tagRepository.save(TagEntity.builder().name(name).build()));
|
||||
existing.add(entity);
|
||||
}
|
||||
e.getTags().addAll(newTags);
|
||||
} else {
|
||||
Set<TagEntity> existing = e.getTags();
|
||||
existing.clear();
|
||||
Set<TagEntity> result = m.getTags().stream()
|
||||
.filter(n -> n != null && !n.isBlank())
|
||||
.map(name -> tagRepository.findByName(name)
|
||||
.orElseGet(() -> tagRepository.save(TagEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
existing.addAll(result);
|
||||
e.getTags().clear();
|
||||
e.getTags().addAll(newTags);
|
||||
}
|
||||
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
|
||||
if (e.getTags().isEmpty()) {
|
||||
e.getTags().addAll(newTags);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -343,10 +411,6 @@ public class BookMetadataUpdater {
|
||||
});
|
||||
}
|
||||
|
||||
private boolean shouldUpdateField(Boolean locked, Object value) {
|
||||
return (locked == null || !locked) && value != null;
|
||||
}
|
||||
|
||||
private String nullIfBlank(String value) {
|
||||
return StringUtils.hasText(value) ? value : null;
|
||||
}
|
||||
|
||||
+20
-5
@@ -2,8 +2,12 @@ package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.BookReview;
|
||||
import com.adityachandel.booklore.model.dto.MetadataBatchProgressNotification;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
@@ -12,7 +16,10 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
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.*;
|
||||
import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus;
|
||||
import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
@@ -305,10 +312,18 @@ public class MetadataRefreshService {
|
||||
|
||||
public void updateBookMetadata(BookEntity bookEntity, BookMetadata metadata, boolean replaceCover, boolean mergeCategories) {
|
||||
if (metadata != null) {
|
||||
MetadataUpdateWrapper metadataUpdateWrapper = MetadataUpdateWrapper.builder()
|
||||
.metadata(metadata)
|
||||
|
||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
||||
.metadata(metadata)
|
||||
.build())
|
||||
.updateThumbnail(replaceCover)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.build();
|
||||
bookMetadataUpdater.setBookMetadata(bookEntity, metadataUpdateWrapper, replaceCover, mergeCategories);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, book);
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class MetadataExtractorFactory {
|
||||
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
|
||||
public BookMetadata extractMetadata(BookFileType bookFileType, File file) {
|
||||
return switch (bookFileType) {
|
||||
case PDF -> pdfMetadataExtractor.extractMetadata(file);
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBX -> cbxMetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
public BookMetadata extractMetadata(BookFileExtension fileExt, File file) {
|
||||
return switch (fileExt) {
|
||||
case PDF -> pdfMetadataExtractor.extractMetadata(file);
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
public byte[] extractCover(BookFileExtension fileExt, File file) {
|
||||
return switch (fileExt) {
|
||||
case EPUB -> epubMetadataExtractor.extractCover(file);
|
||||
case PDF -> pdfMetadataExtractor.extractCover(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractCover(file);
|
||||
};
|
||||
}
|
||||
}
|
||||
+3
@@ -1,7 +1,9 @@
|
||||
package com.adityachandel.booklore.service.scheduler;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.task.RescanLibraryContext;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -17,6 +19,7 @@ public class LibraryRescanScheduler {
|
||||
@Scheduled(cron = "0 0 0 * * *") // At 00:00 every day
|
||||
public void rescanLibraries() {
|
||||
log.info("Starting scheduled library rescan at midnight");
|
||||
|
||||
for (Library library : libraryService.getAllLibraries()) {
|
||||
try {
|
||||
libraryService.rescanLibrary(library.getId());
|
||||
|
||||
+3
-9
@@ -18,8 +18,7 @@ import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.FileMovingHelper;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -50,8 +49,7 @@ public class FileUploadService {
|
||||
private final BookAdditionalFileRepository additionalFileRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final AppProperties appProperties;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
private final MetadataExtractorFactory metadataExtractorFactory;
|
||||
private final AdditionalFileMapper additionalFileMapper;
|
||||
private final FileMovingHelper fileMovingHelper;
|
||||
|
||||
@@ -228,11 +226,7 @@ public class FileUploadService {
|
||||
}
|
||||
|
||||
private BookMetadata extractMetadata(BookFileExtension fileExt, File file) throws IOException {
|
||||
return switch (fileExt) {
|
||||
case PDF -> pdfMetadataExtractor.extractMetadata(file);
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBZ, CBR, CB7 -> new BookMetadata();
|
||||
};
|
||||
return metadataExtractorFactory.extractMetadata(fileExt, file);
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.adityachandel.booklore.task;
|
||||
|
||||
import com.adityachandel.booklore.task.tasks.options.LibraryRescanOptions;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class RescanLibraryContext {
|
||||
private Long libraryId;
|
||||
private LibraryRescanOptions options;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.adityachandel.booklore.task;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class TaskCancellationManager {
|
||||
|
||||
private final Set<String> cancelledTasks = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public void cancelTask(String taskId) {
|
||||
cancelledTasks.add(taskId);
|
||||
}
|
||||
|
||||
public boolean isTaskCancelled(String taskId) {
|
||||
return cancelledTasks.contains(taskId);
|
||||
}
|
||||
|
||||
public void clearCancellation(String taskId) {
|
||||
cancelledTasks.remove(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.task;
|
||||
|
||||
public enum TaskStatus {
|
||||
ACCEPTED,
|
||||
IN_PROGRESS,
|
||||
COMPLETED,
|
||||
FAILED,
|
||||
CANCELLED
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Comparator;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class ClearCbxCacheTask implements Task {
|
||||
|
||||
private FileService fileService;
|
||||
|
||||
@Override
|
||||
public TaskCreateResponse execute(TaskCreateRequest request) {
|
||||
log.info("Starting CBX cache clearing task");
|
||||
|
||||
TaskCreateResponse.TaskCreateResponseBuilder builder = TaskCreateResponse.builder()
|
||||
.taskId(UUID.randomUUID().toString())
|
||||
.taskType(TaskType.CLEAR_CBX_CACHE);
|
||||
|
||||
try {
|
||||
String cbxCachePath = fileService.getCbxCachePath();
|
||||
Path cachePath = Paths.get(cbxCachePath);
|
||||
|
||||
if (Files.exists(cachePath) && Files.isDirectory(cachePath)) {
|
||||
try (Stream<Path> walk = Files.walk(cachePath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete file: {} - {}", path, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Files.createDirectories(cachePath);
|
||||
log.info("CBX cache cleared and directory recreated");
|
||||
} else {
|
||||
log.warn("CBX cache path does not exist or is not a directory: {}", cbxCachePath);
|
||||
}
|
||||
|
||||
builder.status(TaskStatus.COMPLETED);
|
||||
log.info("CBX cache clearing task completed successfully");
|
||||
} catch (Exception e) {
|
||||
log.error("Error clearing CBX cache", e);
|
||||
builder.status(TaskStatus.FAILED);
|
||||
throw new RuntimeException("Failed to clear CBX cache", e);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskType getTaskType() {
|
||||
return TaskType.CLEAR_CBX_CACHE;
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Comparator;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class ClearPdfCacheTask implements Task {
|
||||
|
||||
private FileService fileService;
|
||||
|
||||
@Override
|
||||
public TaskCreateResponse execute(TaskCreateRequest request) {
|
||||
log.info("Starting PDF cache clearing task");
|
||||
|
||||
TaskCreateResponse.TaskCreateResponseBuilder builder = TaskCreateResponse.builder()
|
||||
.taskId(UUID.randomUUID().toString())
|
||||
.taskType(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
try {
|
||||
String pdfCachePath = fileService.getPdfCachePath();
|
||||
Path cachePath = Paths.get(pdfCachePath);
|
||||
|
||||
if (Files.exists(cachePath) && Files.isDirectory(cachePath)) {
|
||||
try (Stream<Path> walk = Files.walk(cachePath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete file: {} - {}", path, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Files.createDirectories(cachePath);
|
||||
log.info("PDF cache cleared and directory recreated");
|
||||
} else {
|
||||
log.warn("PDF cache path does not exist or is not a directory: {}", pdfCachePath);
|
||||
}
|
||||
|
||||
builder.status(TaskStatus.COMPLETED);
|
||||
log.info("PDF cache clearing task completed successfully");
|
||||
} catch (Exception e) {
|
||||
log.error("Error clearing PDF cache", e);
|
||||
builder.status(TaskStatus.FAILED);
|
||||
throw new RuntimeException("Failed to clear PDF cache", e);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskType getTaskType() {
|
||||
return TaskType.CLEAR_PDF_CACHE;
|
||||
}
|
||||
}
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.service.library.LibraryRescanHelper;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.task.RescanLibraryContext;
|
||||
import com.adityachandel.booklore.task.TaskCancellationManager;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.task.tasks.options.LibraryRescanOptions;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class LibraryRescanTask implements Task {
|
||||
|
||||
private final LibraryService libraryService;
|
||||
private final LibraryRescanHelper libraryRescanHelper;
|
||||
private final TaskCancellationManager cancellationManager;
|
||||
|
||||
|
||||
@Override
|
||||
public TaskCreateResponse execute(TaskCreateRequest request) {
|
||||
LibraryRescanOptions options = request.getOptions(LibraryRescanOptions.class);
|
||||
String taskId = request.getTaskId();
|
||||
log.info("Starting LibraryRescanTask. TaskId: {}, Options: {}", taskId, options);
|
||||
List<Library> libraries = libraryService.getAllLibraries();
|
||||
|
||||
for (Library library : libraries) {
|
||||
if (cancellationManager.isTaskCancelled(taskId)) {
|
||||
log.info("LibraryRescanTask {} was cancelled, stopping execution", taskId);
|
||||
break;
|
||||
}
|
||||
|
||||
Long libraryId = library.getId();
|
||||
RescanLibraryContext context = RescanLibraryContext.builder()
|
||||
.libraryId(libraryId)
|
||||
.options(options)
|
||||
.build();
|
||||
try {
|
||||
libraryRescanHelper.handleRescanOptions(context, taskId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
}
|
||||
log.info("Library rescan completed for library: {}", libraryId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskType getTaskType() {
|
||||
return TaskType.RE_SCAN_LIBRARY;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
|
||||
public interface Task {
|
||||
|
||||
TaskCreateResponse execute(TaskCreateRequest request);
|
||||
|
||||
TaskType getTaskType();
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.task.tasks.options;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ClearCbxCacheOptions {
|
||||
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.task.tasks.options;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ClearPdfCacheOptions {
|
||||
// Add fields if needed in future
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.task.tasks.options;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class LibraryRescanOptions {
|
||||
|
||||
private boolean updateMetadataFromFiles;
|
||||
private MetadataReplaceMode metadataReplaceMode;
|
||||
}
|
||||
@@ -91,10 +91,6 @@ public class FileService {
|
||||
return Paths.get("/", BACKGROUNDS_DIR, filename).toString().replace("\\", "/");
|
||||
}
|
||||
|
||||
public String getMetadataBackupPath() {
|
||||
return Paths.get(appProperties.getPathConfig(), "metadata_backup").toString();
|
||||
}
|
||||
|
||||
public String getBookMetadataBackupPath(long bookId) {
|
||||
return Paths.get(appProperties.getPathConfig(), "metadata_backup", String.valueOf(bookId)).toString();
|
||||
}
|
||||
|
||||
+13
@@ -20,4 +20,17 @@ public class SecurityContextVirtualThread {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void runWithSecurityContext(SecurityContext parentContext, Runnable task) {
|
||||
Thread.startVirtualThread(() -> {
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(parentContext.getAuthentication());
|
||||
SecurityContextHolder.setContext(context);
|
||||
try {
|
||||
task.run();
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE tasks
|
||||
(
|
||||
id VARCHAR(36) NOT NULL PRIMARY KEY,
|
||||
type VARCHAR(50) NOT NULL,
|
||||
status VARCHAR(50) NOT NULL,
|
||||
user_id BIGINT NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME,
|
||||
completed_at DATETIME,
|
||||
progress_percentage INT,
|
||||
message TEXT,
|
||||
errorDetails TEXT,
|
||||
task_options TEXT,
|
||||
INDEX idx_tasks_user_id (user_id),
|
||||
INDEX idx_tasks_type (type),
|
||||
INDEX idx_tasks_status (status),
|
||||
INDEX idx_tasks_created_at (created_at)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user