diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java index f1042ffec..cc089b949 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java @@ -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"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java index 5d39cc048..79b023c28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java @@ -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"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index b99e74473..90e857875 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -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()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index fa81873ed..c6ffa69ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -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 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 bookIds) { List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); - SecurityContextVirtualThread.runWithSecurityContext(() -> - processBulkCoverRegeneration(unlockedBooks)); + SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); } private List getUnlockedBookRegenerationInfos(Set 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 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 updatedBooks = new ArrayList<>(); + if (!refreshedIds.isEmpty()) { + org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager); + + List> refreshedPatches = tx.execute(status -> { + List entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds)); + if (entities == null || entities.isEmpty()) return List.>of(); + + entities.forEach(e -> { + if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn(); + }); + + return entities.stream() + .map(e -> java.util.Map.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) { diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index f35ce3914..de85f2508 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -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)) diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 04c4dfd42..7a25085b2 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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 }); } - }); + }); } }); } diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index a0cbb9162..8f6e720ba 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -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, fieldActions: Record): Observable { const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds); diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index b9256ce4f..1fa4a3aea 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -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.", + }); + }, }); }, });