Fix: regenerate improvements (#1981)

* chore: report error on cover regeneration fail

* refactor: use RxJS forkJoin instead of Promise.all

- Replace Promise-based approach with RxJS forkJoin for better consistency
- Remove console.log debug statement
- Improve error handling with proper RxJS operators

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: cleanup

* chore: rework per development upstream

* chore: updating books on bulk cover regenerate

* chore: working

* chore: metadata regenerateCover pdate UI

* chore: review per comments

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
This commit is contained in:
farfromrefuge
2025-12-25 10:09:33 -07:00
committed by GitHub
co-authored by farfromrefug copilot-swe-agent[bot]
parent 77e06b868e
commit f5e99d52c1
8 changed files with 84 additions and 18 deletions
@@ -33,6 +33,7 @@ public enum ApiError {
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
FAILED_TO_REGENERATE_COVER(HttpStatus.BAD_REQUEST, "Failed to regenerate cover"),
FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"),
INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"),
METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata"),
@@ -8,6 +8,7 @@ import lombok.Getter;
public enum Topic {
BOOK_ADD("/queue/book-add"),
BOOK_UPDATE("/queue/book-update"),
BOOKS_COVER_UPDATE("/queue/books-cover-update"),
BOOKS_REMOVE("/queue/books-remove"),
BOOK_METADATA_UPDATE("/queue/book-metadata-update"),
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
@@ -79,10 +79,14 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
boolean saved = fileService.saveCoverImages(image, bookEntity.getId());
if (saved) {
return true;
} else {
log.warn("Could not save image extracted from CBZ as cover for '{}'", bookEntity.getFileName());
}
} finally {
image.flush(); // Release resources after processing
}
} else {
log.warn("Could not find cover image in CBZ file '{}'", bookEntity.getFileName());
}
} catch (Exception e) {
log.error("Error generating cover for '{}': {}", bookEntity.getFileName(), e.getMessage());
@@ -74,6 +74,7 @@ public class BookMetadataService {
private final CbxMetadataExtractor cbxMetadataExtractor;
private final MetadataWriterFactory metadataWriterFactory;
private final MetadataClearFlagsMapper metadataClearFlagsMapper;
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -269,8 +270,7 @@ public class BookMetadataService {
public void regenerateCoversForBooks(Set<Long> bookIds) {
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() ->
processBulkCoverRegeneration(unlockedBooks));
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
}
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
@@ -286,18 +286,48 @@ public class BookMetadataService {
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
regenerateCoverForBookId(bookInfo);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
refreshedIds.add(bookInfo.id());
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
List<Book> updatedBooks = new ArrayList<>();
if (!refreshedIds.isEmpty()) {
org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager);
List<java.util.Map<String, Object>> refreshedPatches = tx.execute(status -> {
List<BookEntity> entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds));
if (entities == null || entities.isEmpty()) return List.<java.util.Map<String, Object>>of();
entities.forEach(e -> {
if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn();
});
return entities.stream()
.map(e -> java.util.Map.<String, Object>of(
"id", e.getId(),
"coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn()
))
.toList();
});
if (refreshedPatches != null && !refreshedPatches.isEmpty()) {
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches);
}
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
@@ -356,9 +386,12 @@ public class BookMetadataService {
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title));
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
processor.generateCover(book);
boolean success = processor.generateCover(book);
log.info("{}regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success);
if (!success) {
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
}
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
}
public BookMetadata getComicInfoMetadata(long bookId) {