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) {
+5
View File
@@ -57,6 +57,11 @@ export class AppComponent implements OnInit, OnDestroy {
this.bookService.handleBookUpdate(JSON.parse(msg.body))
)
);
this.subscriptions.push(
this.rxStompService.watch('/user/queue/books-cover-update').subscribe(msg =>
this.bookService.handleMultipleBookCoverPatches(JSON.parse(msg.body))
)
);
this.subscriptions.push(
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
@@ -5,7 +5,7 @@ import {PageTitleService} from "../../../../shared/service/page-title.service";
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject} from 'rxjs';
import {BehaviorSubject, combineLatest, finalize, forkJoin, Observable, of, Subject} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
@@ -696,7 +696,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
life: 3000
});
}
});
});
}
});
}
@@ -632,6 +632,24 @@ export class BookService {
this.bookStateSubject.next({...currentState, books: updatedBooks})
}
/**
* Incoming payload: [{ id: number, coverUpdatedOn: "2025-12-25T00:48:17Z" }, ...]
* Apply minimal patch to local state so UI updates the cover image (and can use cache-busting).
*/
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
if (!patches || patches.length === 0) return;
const currentState = this.bookStateSubject.value;
const books = currentState.books || [];
patches.forEach(p => {
const index = books.findIndex(b=>b.id === p.id);
if (index !== -1 && books[index].metadata) {
books[index].metadata.coverUpdatedOn = p.coverUpdatedOn;
}
});
this.bookStateSubject.next({...currentState, books});
}
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
@@ -654,18 +654,22 @@ export class MetadataEditorComponent implements OnInit {
regenerateCover(bookId: number) {
this.bookService.regenerateCover(bookId).subscribe({
next: () => {
this.messageService.add({
severity: "success",
summary: "Success",
detail:
"Book cover regenerated successfully. Refresh page to see the new cover.",
});
},
error: () => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: "Failed to start cover regeneration",
this.bookService.getBookByIdFromAPI(bookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
this.messageService.add({
severity: "success",
summary: "Success",
detail: "Book cover regenerated successfully.",
});
},
error: () => {
this.messageService.add({
severity: "warning",
summary: "Partial Success",
detail: "Cover regenerated but failed to refresh display. Please refresh the page.",
});
},
});
},
});