feat(custom-covers): add functionality to generate custom covers for selected books (#2355)

* feat(custom-covers): add functionality to generate custom covers for selected books

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(book-menu): add option to generate custom covers in metadata menu

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-20 08:56:18 -07:00
committed by GitHub
parent b7c0d7050d
commit 691845adb8
8 changed files with 149 additions and 2 deletions
@@ -85,6 +85,14 @@ public class BookCoverController {
bookCoverService.regenerateCoversForBooks(request.getBookIds());
}
@Operation(summary = "Generate custom covers for selected books", description = "Generate custom covers for a list of books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Custom cover generation started successfully")
@PostMapping("/bulk-generate-custom-covers")
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
public void generateCustomCoversForBooks(@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) {
bookCoverService.generateCustomCoversForBooks(request.getBookIds());
}
@Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Cover upload started successfully")
@PostMapping("/bulk-upload-cover")
@@ -157,6 +157,14 @@ public class BookCoverService {
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
}
/**
* Generate custom covers for a set of books.
*/
public void generateCustomCoversForBooks(Set<Long> bookIds) {
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCustomCoverGeneration(unlockedBooks));
}
/**
* Regenerate covers for all books.
*/
@@ -294,6 +302,49 @@ public class BookCoverService {
}
}
private void processBulkCustomCoverGeneration(List<BookCoverInfo> books) {
try {
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started generating custom covers for " + total + " selected book(s)"));
int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookCoverInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Generating custom cover for: " + bookInfo.title()));
transactionTemplate.execute(status -> {
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
String title = book.getMetadata().getTitle();
String author = getAuthorNames(book);
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
fileService.createThumbnailFromBytes(book.getId(), coverBytes);
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
updateBookCoverMetadata(book);
bookRepository.save(book);
refreshedIds.add(book.getId());
});
return null;
});
log.info("{}Successfully generated custom cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
} catch (Exception e) {
log.error("Failed to generate custom cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
current++;
}
notifyBulkCoverUpdate(refreshedIds);
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
} catch (Exception e) {
log.error("Error during custom cover generation: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during custom cover generation"));
}
}
// =========================
// SECTION: INTERNAL HELPERS
// =========================
@@ -289,6 +289,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
userState.user
);
});
@@ -619,6 +620,38 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
generateCustomCoversForSelected(): void {
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
const count = this.selectedBooks.size;
this.confirmationService.confirm({
message: `Are you sure you want to generate custom covers for ${count} book(s)?`,
header: 'Confirm Custom Cover Generation',
icon: 'pi pi-palette',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
this.bookService.generateCustomCoversForBooks(Array.from(this.selectedBooks)).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Custom Cover Generation Started',
detail: `Generating custom covers for ${count} book(s).`,
life: 3000
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not start custom cover generation.',
life: 3000
});
}
});
}
});
}
moveFiles(): void {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
}
@@ -24,7 +24,7 @@
display: flex;
align-items: center;
padding: 1rem 0.5rem 0.5rem;
z-index: 1;
z-index: 100;
border-radius: 10px 10px 0 0;
border: 1px solid rgba(255, 255, 255, 0.5);
border-width: 1px 1px 0px 1px;
@@ -201,6 +201,7 @@ export class SeriesPageComponent implements OnDestroy {
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata(),
() => this.regenerateCoversForSelected(),
() => this.generateCustomCoversForSelected(),
userState.user
);
this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user());
@@ -454,6 +455,38 @@ export class SeriesPageComponent implements OnDestroy {
});
}
generateCustomCoversForSelected(): void {
if (!this.selectedBooks || this.selectedBooks.size === 0) return;
const count = this.selectedBooks.size;
this.confirmationService.confirm({
message: `Are you sure you want to generate custom covers for ${count} book(s)?`,
header: 'Confirm Custom Cover Generation',
icon: 'pi pi-palette',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
this.bookService.generateCustomCoversForBooks(Array.from(this.selectedBooks)).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Custom Cover Generation Started',
detail: `Generating custom covers for ${count} book(s).`,
life: 3000
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not start custom cover generation.',
life: 3000
});
}
});
}
});
}
moveFiles() {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
}
@@ -93,6 +93,7 @@ describe('BookMenuService', () => {
const bulkEdit = vi.fn();
const multiEdit = vi.fn();
const regenerate = vi.fn();
const generateCustomCovers = vi.fn();
const items = service.getMetadataMenuItems(
autoFetch,
@@ -100,10 +101,11 @@ describe('BookMenuService', () => {
bulkEdit,
multiEdit,
regenerate,
generateCustomCovers,
mockUser
);
expect(items).toHaveLength(5);
expect(items).toHaveLength(6);
expect(items[0].label).toBe('Auto Fetch Metadata');
expect(items[0].icon).toBe('pi pi-bolt');
expect(items[1].label).toBe('Custom Fetch Metadata');
@@ -114,6 +116,8 @@ describe('BookMenuService', () => {
expect(items[3].icon).toBe('pi pi-clone');
expect(items[4].label).toBe('Regenerate Covers');
expect(items[4].icon).toBe('pi pi-image');
expect(items[5].label).toBe('Generate Custom Covers');
expect(items[5].icon).toBe('pi pi-palette');
});
it('should return empty array when user has no permissions', () => {
@@ -123,6 +127,7 @@ describe('BookMenuService', () => {
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
mockUserNoPermissions
);
@@ -136,6 +141,7 @@ describe('BookMenuService', () => {
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
null
);
@@ -148,6 +154,7 @@ describe('BookMenuService', () => {
const bulkEdit = vi.fn();
const multiEdit = vi.fn();
const regenerate = vi.fn();
const generateCustomCovers = vi.fn();
const items = service.getMetadataMenuItems(
autoFetch,
@@ -155,6 +162,7 @@ describe('BookMenuService', () => {
bulkEdit,
multiEdit,
regenerate,
generateCustomCovers,
mockUser
);
@@ -172,6 +180,9 @@ describe('BookMenuService', () => {
items[4].command!({} as any);
expect(regenerate).toHaveBeenCalledOnce();
items[5].command!({} as any);
expect(generateCustomCovers).toHaveBeenCalledOnce();
});
it('should return only items for granted permissions', () => {
@@ -192,6 +203,7 @@ describe('BookMenuService', () => {
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
partialUser
);
@@ -26,6 +26,7 @@ export class BookMenuService {
bulkEditMetadata: () => void,
multiBookEditMetadata: () => void,
regenerateCovers: () => void,
generateCustomCovers: () => void,
user: User | null): MenuItem[] {
const permissions = user?.permissions;
@@ -66,6 +67,11 @@ export class BookMenuService {
icon: 'pi pi-image',
command: regenerateCovers
});
items.push({
label: 'Generate Custom Covers',
icon: 'pi pi-palette',
command: generateCustomCovers
});
}
return items;
@@ -581,6 +581,10 @@ export class BookService {
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-cover`, {});
}
generateCustomCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-generate-custom-covers`, {bookIds});
}
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds});
}