Audiobook enhancement (#2611)

* Audiobook enhancement

* Fix choppy virtual scroller with mixed audiobook/ebook cards by using uniform heights

* Fix audiobook cover regeneration for combined books and improve error messages

* Fix cover extraction when attaching audiobook files during rescan

* Set audiobookCoverUpdatedOn for cache busting when generating cover

* Add support for regenerating covers from specific book files

* Fix Continue Reading/Listening scrollers to filter by actual progress instead of primary file type

* Show ebook cover and open ebook reader in Continue Reading scroller for combined books

* Prevent read status from being downgraded when saving audiobook progress

* Fix BookCoverServiceTest to match updated regenerateCover method signature
---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-02-05 13:33:08 -07:00
committed by GitHub
co-authored by acx10
parent 92d1334f25
commit d38271de9c
121 changed files with 5078 additions and 909 deletions
+3 -3
View File
@@ -25,7 +25,7 @@ import {UserStatsGuard} from './core/security/guards/user-stats.guard';
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
import {EbookReaderComponent} from './features/readers/ebook-reader';
import {LibraryStatsComponent} from './features/stats/component/library-stats/library-stats.component';
import {AudiobookReaderComponent} from './features/readers/audiobook-reader/audiobook-reader.component';
import {AudiobookPlayerComponent} from './features/readers/audiobook-player';
export const routes: Routes = [
{
@@ -75,8 +75,8 @@ export const routes: Routes = [
canActivate: [AuthGuard]
},
{
path: 'audiobook-reader/book/:bookId',
component: AudiobookReaderComponent,
path: 'audiobook-player/book/:bookId',
component: AudiobookPlayerComponent,
canActivate: [AuthGuard]
},
{
@@ -207,15 +207,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return this.coverScalePreferenceService.gridColumnMinWidth;
}
getCardHeight(book: Book): number {
getCardHeight(_book: Book): number {
// Use uniform height for all book types to ensure smooth virtual scrolling.
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
// cannot accurately estimate positions when item heights vary.
if (this.isMobile) {
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
if (isAudiobook) {
return this.mobileCardSize.width + this.MOBILE_TITLE_BAR_HEIGHT;
}
return this.mobileCardSize.height;
}
return this.coverScalePreferenceService.getCardHeight(book);
return this.coverScalePreferenceService.getCardHeight(_book);
}
get viewIcon(): string {
@@ -39,7 +39,7 @@
}
@if (!_isSeriesViewActive && hasDigitalFile()) {
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
<p-button [rounded]="true" [icon]="_isAudiobook ? 'pi pi-play' : 'pi pi-book'" class="read-btn" (click)="readBook(book)"></p-button>
}
@if (isCheckboxEnabled) {
@@ -3,6 +3,9 @@
border-radius: 8px 8px 8px 8px;
position: relative;
overflow: hidden;
height: 100%;
display: flex;
flex-direction: column;
&.selected {
border: 2px solid var(--primary-color);
@@ -22,7 +25,9 @@
}
.cover-container.audiobook-cover {
aspect-ratio: 1/1;
// Use same aspect-ratio as ebooks for uniform virtual scroller row heights.
// The square audiobook cover image will be centered via object-fit: contain.
aspect-ratio: 5/7;
background-color: var(--surface-ground);
}
@@ -1,6 +1,6 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {TooltipModule} from "primeng/tooltip";
import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model';
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
import {Button} from 'primeng/button';
import {MenuModule} from 'primeng/menu';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
@@ -49,6 +49,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
@Input() seriesViewEnabled: boolean = false;
@Input() isSeriesCollapsed: boolean = false;
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
@Input() forceEbookMode: boolean = false;
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
@@ -128,9 +129,9 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['book']) {
if (changes['book'] || changes['forceEbookMode']) {
this.computeAllMemoizedValues();
if (!changes['book'].firstChange && this.menuInitialized) {
if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) {
this.additionalFilesLoaded = false;
this.initMenu();
}
@@ -158,7 +159,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
? this.book.metadata?.seriesName
: this.book.metadata?.title;
this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode;
this._coverImageUrl = this._isAudiobook
? this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus);
@@ -167,7 +171,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books';
this._titleTooltip = 'Title: ' + this._displayTitle;
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK';
}
get hasProgress(): boolean {
@@ -200,9 +203,26 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
readBook(book: Book): void {
if (this.forceEbookMode && book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(book);
if (ebookType) {
this.bookService.readBook(book.id, undefined, ebookType);
return;
}
}
this.bookService.readBook(book.id);
}
private getEbookType(book: Book): BookType | undefined {
if (book.epubProgress) return 'EPUB';
if (book.pdfProgress) return 'PDF';
if (book.cbxProgress) return 'CBX';
const alternativeFormat = book.alternativeFormats?.find(f =>
f.bookType && ['EPUB', 'PDF', 'CBX', 'FB2', 'MOBI', 'AZW3'].includes(f.bookType)
);
return alternativeFormat?.bookType;
}
onMenuShow(): void {
this.menuToggled.emit(true);
}
@@ -425,10 +445,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
summary: 'Success',
detail: 'Cover regeneration started'
}),
error: () => this.messageService.add({
error: (err) => this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to regenerate cover'
detail: err?.error?.message || 'Failed to regenerate cover'
})
});
}
@@ -443,10 +463,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
summary: 'Success',
detail: 'Cover generated successfully'
}),
error: () => this.messageService.add({
error: (err) => this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to generate cover'
detail: err?.error?.message || 'Failed to generate cover'
})
});
}
@@ -740,6 +760,12 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
if (!this.book?.primaryFile) {
return 'PHYSICAL';
}
if (this.forceEbookMode && this.book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(this.book);
if (ebookType) {
return ebookType;
}
}
const ext = this.book?.primaryFile?.extension;
if (ext) {
return ext.toUpperCase();
@@ -124,12 +124,13 @@ export class BookDialogHelperService {
});
}
openCoverSearchDialog(bookId: number): DynamicDialogRef | null {
openCoverSearchDialog(bookId: number, coverType?: 'ebook' | 'audiobook'): DynamicDialogRef | null {
return this.openDialog(CoverSearchComponent, {
showHeader: false,
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
data: {
bookId: bookId,
coverType: coverType,
},
});
}
@@ -52,11 +52,10 @@ export class CoverScalePreferenceService {
return `${this.currentCardSize.width}px`;
}
getCardHeight(book: Book): number {
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
if (isAudiobook) {
return Math.round((this.BASE_WIDTH + this.TITLE_BAR_HEIGHT) * this.scaleFactor);
}
getCardHeight(_book: Book): number {
// Use uniform height for all book types to ensure smooth virtual scrolling.
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
// cannot accurately estimate positions when item heights vary.
return this.currentCardSize.height;
}
@@ -1,6 +1,6 @@
<div class="book-cover-wrapper" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
<div class="book-cover-wrapper" [class.audiobook-only]="isAudiobookOnly()" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
<img
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
[src]="getThumbnailUrl()"
class="book-cover"
alt="Cover of {{ book.metadata?.title }}"
loading="lazy"/>
@@ -10,6 +10,13 @@
border-radius: 0.5rem;
}
&.audiobook-only {
.book-cover {
aspect-ratio: 1 / 1;
object-fit: cover;
}
}
.info-btn {
position: absolute;
top: 50%;
@@ -35,6 +35,19 @@ export class BookCardLiteComponent implements OnInit, OnDestroy {
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
isHovered: boolean = false;
isAudiobookOnly(): boolean {
const primaryIsAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK';
const hasEbookAlternative = this.book.alternativeFormats?.some(f => f.bookType !== 'AUDIOBOOK') ?? false;
return primaryIsAudiobook && !hasEbookAlternative;
}
getThumbnailUrl(): string {
if (this.isAudiobookOnly()) {
return this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn);
}
return this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
}
ngOnInit(): void {
this.userService.userState$
.pipe(
@@ -97,6 +97,19 @@ export interface BookFileProgress {
progressPercent: number;
}
export interface AudiobookMetadata {
narrator?: string;
abridged?: boolean | null;
durationSeconds?: number;
bitrate?: number;
sampleRate?: number;
channels?: number;
codec?: string;
chapterCount?: number;
narratorLocked?: boolean;
abridgedLocked?: boolean;
}
export interface BookMetadata {
bookId: number;
title?: string;
@@ -129,7 +142,16 @@ export interface BookMetadata {
ranobedbId?: string;
ranobedbRating?: number | null;
hardcoverRating?: number | null;
audibleId?: string;
audibleRating?: number | null;
audibleReviewCount?: number | null;
narrator?: string;
abridged?: boolean | null;
narratorLocked?: boolean;
abridgedLocked?: boolean;
audiobookMetadata?: AudiobookMetadata;
coverUpdatedOn?: string;
audiobookCoverUpdatedOn?: string;
authors?: string[];
categories?: string[];
moods?: string[];
@@ -166,12 +188,16 @@ export interface BookMetadata {
lubimyczytacRatingLocked?: boolean;
ranobedbIdLocked?: boolean;
ranobedbRatingLocked?: boolean;
audibleIdLocked?: boolean;
audibleRatingLocked?: boolean;
audibleReviewCountLocked?: boolean;
coverUpdatedOnLocked?: boolean;
authorsLocked?: boolean;
categoriesLocked?: boolean;
moodsLocked?: boolean;
tagsLocked?: boolean;
coverLocked?: boolean;
audiobookCoverLocked?: boolean;
reviewsLocked?: boolean;
[key: string]: unknown;
@@ -206,11 +232,17 @@ export interface MetadataClearFlags {
lubimyczytacRating?: boolean;
ranobedbId?: boolean;
ranobedbRating?: boolean;
audibleId?: boolean;
audibleRating?: boolean;
audibleReviewCount?: boolean;
narrator?: boolean;
abridged?: boolean;
authors?: boolean;
categories?: boolean;
moods?: boolean;
tags?: boolean;
cover?: boolean;
audiobookCover?: boolean;
}
export interface MetadataUpdateWrapper {
@@ -11,6 +11,7 @@ export interface Library {
sort?: SortOption;
paths: LibraryPath[];
formatPriority?: BookType[];
allowedFormats?: BookType[];
}
export interface LibraryPath {
@@ -310,7 +310,7 @@ export class BookService {
break;
case 'AUDIOBOOK':
baseUrl = 'audiobook-reader';
baseUrl = 'audiobook-player';
break;
}
@@ -700,6 +700,35 @@ export class BookService {
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds});
}
uploadAudiobookCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url});
}
uploadAudiobookCoverFromFile(bookId: number, file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData);
}
getUploadAudiobookCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/audiobook-cover/upload";
}
regenerateAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {});
}
generateCustomAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {});
}
supportsDualCovers(book: Book): boolean {
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
const hasAudiobook = allFiles.some(f => f!.bookType === 'AUDIOBOOK');
const hasEbook = allFiles.some(f => f!.bookType !== 'AUDIOBOOK');
return hasAudiobook && hasEbook;
}
bulkUploadCover(bookIds: number[], file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
@@ -165,4 +165,8 @@ export class LibraryService {
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoadingSubject.next({ isLoading, expectedCount });
}
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
return this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`);
}
}
@@ -23,10 +23,11 @@
#scrollContainer
[horizontal]="true">
@for (book of books; track book.id) {
<div class="dashboard-scroller-card" [class.menu-open]="openMenuBookId === book.id">
<div class="dashboard-scroller-card" [ngClass]="{'menu-open': openMenuBookId === book.id, 'square-card': useSquareCovers}">
<app-book-card
[book]="book"
[isCheckboxEnabled]="false"
[forceEbookMode]="forceEbookMode"
(menuToggled)="handleMenuToggle(book.id, $event)"
[overlayPreferenceService]="bookCardOverlayPreferenceService"
></app-book-card>
@@ -96,6 +96,17 @@
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
&.square-card {
width: 160px;
height: auto;
flex-basis: 160px;
::ng-deep .cover-container.audiobook-cover {
aspect-ratio: 1/1 !important;
flex: none;
}
}
&:hover, &.menu-open {
transform: translateY(-4px) scale(1.04);
filter: drop-shadow(0 25px 50px rgba(0, 0, 0, 0.4));
@@ -180,6 +191,12 @@
height: 184px;
width: 108px;
flex-basis: 108px;
&.square-card {
width: 150px;
height: auto;
flex-basis: 150px;
}
}
.dashboard-scroller-no-books {
@@ -1,6 +1,7 @@
import {Component, ElementRef, Input, ViewChild, inject} from '@angular/core';
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {NgClass} from '@angular/common';
import {ProgressSpinnerModule} from 'primeng/progressspinner';
import {Book} from '../../../book/model/book.model';
@@ -14,7 +15,8 @@ import { BookCardOverlayPreferenceService } from '../../../book/components/book-
imports: [
InfiniteScrollDirective,
BookCardComponent,
ProgressSpinnerModule
ProgressSpinnerModule,
NgClass
],
standalone: true
})
@@ -24,12 +26,17 @@ export class DashboardScrollerComponent {
@Input() title!: string;
@Input() books!: Book[] | null;
@Input() isMagicShelf: boolean = false;
@Input() useSquareCovers: boolean = false;
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
openMenuBookId: number | null = null;
public bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
get forceEbookMode(): boolean {
return this.bookListType === ScrollerType.LAST_READ;
}
handleMenuToggle(bookId: number, isOpen: boolean) {
this.openMenuBookId = isOpen ? bookId : null;
}
@@ -41,6 +41,7 @@ export class DashboardSettingsComponent implements OnInit {
availableScrollerTypes = [
{label: 'Continue Reading', value: ScrollerType.LAST_READ},
{label: 'Continue Listening', value: ScrollerType.LAST_LISTENED},
{label: 'Recently Added', value: ScrollerType.LATEST_ADDED},
{label: 'Discover Something New', value: ScrollerType.RANDOM},
{label: 'Magic Shelf', value: ScrollerType.MAGIC_SHELF}
@@ -102,6 +103,8 @@ export class DashboardSettingsComponent implements OnInit {
switch (scroller.type) {
case ScrollerType.LAST_READ:
return 'Continue Reading';
case ScrollerType.LAST_LISTENED:
return 'Continue Listening';
case ScrollerType.LATEST_ADDED:
return 'Recently Added';
case ScrollerType.RANDOM:
@@ -57,6 +57,7 @@
[bookListType]="scroller.type"
[title]="scroller.title"
[isMagicShelf]="scroller.type === ScrollerType.MAGIC_SHELF"
[useSquareCovers]="scroller.type === ScrollerType.LAST_LISTENED"
[books]="getBooksForScroller(scroller) | async">
</app-dashboard-scroller>
}
@@ -74,7 +74,11 @@ export class MainDashboardComponent implements OnInit {
private getLastReadBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
let books = (state.books || []).filter(book => book.lastReadTime && (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED));
let books = (state.books || []).filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
this.hasEbookProgress(book)
);
books = books.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
@@ -85,6 +89,28 @@ export class MainDashboardComponent implements OnInit {
);
}
private getLastListenedBooks(maxItems: number): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
let books = (state.books || []).filter(book =>
book.lastReadTime &&
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
book.audiobookProgress
);
books = books.sort((a, b) => {
const aTime = new Date(a.lastReadTime!).getTime();
const bTime = new Date(b.lastReadTime!).getTime();
return bTime - aTime;
});
return books.slice(0, maxItems);
})
);
}
private hasEbookProgress(book: Book): boolean {
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
}
private getLatestAddedBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
return this.bookService.bookState$.pipe(
map((state: BookState) => {
@@ -156,6 +182,9 @@ export class MainDashboardComponent implements OnInit {
case ScrollerType.LAST_READ:
books$ = this.getLastReadBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.LAST_LISTENED:
books$ = this.getLastListenedBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
case ScrollerType.LATEST_ADDED:
books$ = this.getLatestAddedBooks(config.maxItems || DEFAULT_MAX_ITEMS);
break;
@@ -2,6 +2,7 @@ import {DEFAULT_MAX_ITEMS} from '../components/dashboard-settings/dashboard-sett
export enum ScrollerType {
LAST_READ = 'lastRead',
LAST_LISTENED = 'lastListened',
LATEST_ADDED = 'latestAdded',
RANDOM = 'random',
MAGIC_SHELF = 'magicShelf'
@@ -25,8 +26,9 @@ export interface DashboardConfig {
export const DEFAULT_DASHBOARD_CONFIG: DashboardConfig = {
scrollers: [
{id: '1', type: ScrollerType.LAST_READ, title: 'Continue Reading', enabled: true, order: 1, maxItems: DEFAULT_MAX_ITEMS},
{id: '2', type: ScrollerType.LATEST_ADDED, title: 'Recently Added', enabled: true, order: 2, maxItems: DEFAULT_MAX_ITEMS},
{id: '3', type: ScrollerType.RANDOM, title: 'Discover Something New', enabled: true, order: 3, maxItems: DEFAULT_MAX_ITEMS}
{id: '1', type: ScrollerType.LAST_LISTENED, title: 'Continue Listening', enabled: true, order: 1, maxItems: DEFAULT_MAX_ITEMS},
{id: '2', type: ScrollerType.LAST_READ, title: 'Continue Reading', enabled: true, order: 2, maxItems: DEFAULT_MAX_ITEMS},
{id: '3', type: ScrollerType.LATEST_ADDED, title: 'Recently Added', enabled: true, order: 3, maxItems: DEFAULT_MAX_ITEMS},
{id: '4', type: ScrollerType.RANDOM, title: 'Discover Something New', enabled: true, order: 4, maxItems: DEFAULT_MAX_ITEMS}
]
};
@@ -155,6 +155,60 @@
}
</div>
</div>
<div class="option-item allowed-formats-option">
<div class="option-label">
<span>Allowed formats</span>
<i
class="pi pi-question-circle info-icon"
pTooltip="Select which book formats this library should accept. Files of other formats will be ignored during scans."
tooltipPosition="right"
></i>
</div>
<div class="allowed-formats-container">
<div class="allow-all-toggle">
<p-checkbox
[(ngModel)]="allowAllFormats"
[binary]="true"
inputId="allowAll"
(onChange)="onAllowAllFormatsChange()"
/>
<label for="allowAll" class="allow-all-label">Allow all formats</label>
</div>
@if (!allowAllFormats) {
<div class="format-checkboxes">
@for (format of allBookFormats; track format.type) {
<div class="format-checkbox-item" [class.has-warning]="getFormatWarning(format.type)">
<p-checkbox
[ngModel]="isFormatSelected(format.type)"
[binary]="true"
[inputId]="'format-' + format.type"
(onChange)="onFormatCheckboxChange(format.type, $event.checked)"
/>
<label [for]="'format-' + format.type" class="format-checkbox-label">
{{ format.label }}
</label>
@if (getFormatWarning(format.type); as warning) {
<i
class="pi pi-exclamation-triangle warning-icon"
[pTooltip]="warning"
tooltipPosition="top"
></i>
}
</div>
}
</div>
@if (hasAnyFormatWarning()) {
<div class="format-warning-message">
<i class="pi pi-info-circle"></i>
<span>Deselected formats with existing books will not be affected, but won't appear in future scans</span>
</div>
}
}
</div>
</div>
</div>
</section>
</div>
@@ -2,7 +2,7 @@
max-width: 90vw;
display: flex;
flex-direction: column;
max-height: 85vh;
max-height: 90vh;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 12px;
@@ -88,7 +88,7 @@
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1.125rem;
margin-bottom: 0.75rem;
font-size: 0.85rem;
font-weight: 600;
text-transform: uppercase;
@@ -408,7 +408,8 @@
--p-toggleswitch-checked-hover-background: var(--p-green-600);
}
&.format-priority-option {
&.format-priority-option,
&.allowed-formats-option {
flex-direction: column;
align-items: flex-start;
}
@@ -434,6 +435,78 @@
}
}
// Allowed formats
.allowed-formats-container {
display: flex;
flex-direction: column;
gap: 0.875rem;
width: 100%;
}
.allow-all-toggle {
display: flex;
align-items: center;
gap: 0.5rem;
.allow-all-label {
font-size: 0.875rem;
color: var(--text-color);
cursor: pointer;
}
}
.format-checkboxes {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1.25rem;
padding: 0.75rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 6px;
}
.format-checkbox-item {
display: flex;
align-items: center;
gap: 0.375rem;
min-width: 100px;
.format-checkbox-label {
font-size: 0.8rem;
color: var(--text-color);
cursor: pointer;
}
.warning-icon {
font-size: 0.75rem;
color: var(--p-orange-400);
margin-left: 0.25rem;
}
&.has-warning {
.format-checkbox-label {
color: var(--p-orange-400);
}
}
}
.format-warning-message {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.625rem 0.75rem;
background: rgba(234, 179, 8, 0.1);
border: 1px solid var(--p-orange-400);
border-radius: 6px;
font-size: 0.8rem;
color: var(--p-orange-400);
i {
flex-shrink: 0;
margin-top: 0.125rem;
}
}
// Format chips
.format-chips {
display: flex;
@@ -16,12 +16,13 @@ import {DialogLauncherService} from '../../shared/services/dialog-launcher.servi
import {switchMap} from 'rxjs/operators';
import {map} from 'rxjs';
import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop';
import {Checkbox} from 'primeng/checkbox';
@Component({
selector: 'app-library-creator',
standalone: true,
templateUrl: './library-creator.component.html',
imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule],
imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule, Checkbox],
styleUrl: './library-creator.component.scss'
})
export class LibraryCreatorComponent implements OnInit {
@@ -34,6 +35,9 @@ export class LibraryCreatorComponent implements OnInit {
editModeLibraryName: string = '';
watch: boolean = false;
formatPriority: {type: BookType, label: string}[] = [];
allowAllFormats: boolean = true;
selectedAllowedFormats: Set<BookType> = new Set();
formatCounts: Record<string, number> = {};
readonly allBookFormats: {type: BookType, label: string}[] = [
{type: 'EPUB', label: 'EPUB'},
@@ -55,13 +59,14 @@ export class LibraryCreatorComponent implements OnInit {
ngOnInit(): void {
this.initializeFormatPriority();
this.initializeAllowedFormats();
const data = this.dynamicDialogConfig?.data;
if (data?.mode === 'edit') {
this.mode = data.mode;
this.library = this.libraryService.findLibraryById(data.libraryId);
if (this.library) {
const {name, icon, iconType, paths, watch, formatPriority} = this.library;
const {name, icon, iconType, paths, watch, formatPriority, allowedFormats} = this.library;
this.chosenLibraryName = name;
this.editModeLibraryName = name;
@@ -84,6 +89,19 @@ export class LibraryCreatorComponent implements OnInit {
}
});
}
if (allowedFormats && allowedFormats.length > 0) {
this.allowAllFormats = false;
this.selectedAllowedFormats = new Set(allowedFormats);
} else {
this.allowAllFormats = true;
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type));
}
this.libraryService.getBookCountsByFormat(this.library.id!).subscribe(counts => {
this.formatCounts = counts;
});
this.folders = paths.map(path => path.path);
}
}
@@ -93,6 +111,43 @@ export class LibraryCreatorComponent implements OnInit {
this.formatPriority = [...this.allBookFormats];
}
private initializeAllowedFormats(): void {
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type));
}
onAllowAllFormatsChange(): void {
if (this.allowAllFormats) {
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type));
}
}
onFormatCheckboxChange(formatType: BookType, checked: boolean): void {
if (checked) {
this.selectedAllowedFormats.add(formatType);
} else {
this.selectedAllowedFormats.delete(formatType);
}
this.allowAllFormats = this.selectedAllowedFormats.size === this.allBookFormats.length;
}
isFormatSelected(formatType: BookType): boolean {
return this.selectedAllowedFormats.has(formatType);
}
getFormatWarning(formatType: BookType): string | null {
if (this.mode !== 'edit') return null;
const count = this.formatCounts[formatType];
if (count && count > 0 && !this.selectedAllowedFormats.has(formatType)) {
return `${count} existing book${count > 1 ? 's' : ''} will not appear in future scans`;
}
return null;
}
hasAnyFormatWarning(): boolean {
if (this.mode !== 'edit') return false;
return this.allBookFormats.some(f => this.getFormatWarning(f.type) !== null);
}
closeDialog(): void {
this.dynamicDialogRef.close();
}
@@ -161,7 +216,8 @@ export class LibraryCreatorComponent implements OnInit {
iconType: iconType,
paths: this.folders.map(folder => ({path: folder})),
watch: this.watch,
formatPriority: this.formatPriority.map(f => f.type)
formatPriority: this.formatPriority.map(f => f.type),
allowedFormats: this.allowAllFormats ? [] : Array.from(this.selectedAllowedFormats)
};
if (this.mode === 'edit') {
@@ -8,73 +8,161 @@
}
<div class="form-content">
<div class="main-section">
<div class="cover-section">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Cover Image"
width="250"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
<div class="covers-section" [class.dual-covers]="supportsDualCovers(book)">
<!-- Ebook Cover Section -->
@if (hasEbookFormat(book)) {
<div class="cover-section">
@if (supportsDualCovers(book)) {
<div class="cover-type-label ebook">
<i class="pi pi-book"></i> Ebook Cover
</div>
}
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Cover Image"
width="200"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
<div class="cover-actions">
@if (!book.isPhysical) {
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['coverLocked']">
</p-button>
}
<p-button
icon="pi pi-palette"
(onClick)="generateCustomCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingCover"
[disabled]="book.metadata!['coverLocked'] || isGeneratingCover">
</p-button>
<p-button
[disabled]="book.metadata!['coverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openCoverSearch()"
pTooltip="Search for cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload cover"
tooltipPosition="top"
[disabled]="book.metadata!['coverLocked']"
name="file"
[url]="getUploadCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['coverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (book.metadata!['coverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
</div>
</div>
}
<!-- Audiobook Cover Section -->
@if (hasAudiobookFormat(book)) {
<div class="cover-section audiobook-cover-section">
<div class="cover-type-label audiobook">
<i class="pi pi-headphones"></i> Audiobook Cover
</div>
<p-image
[src]="urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)"
alt="Audiobook Cover"
width="200"
appendTo="body"
lazyLoad
[preview]="true"
class="square-cover">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
<div class="cover-actions">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateAudiobookCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['audiobookCoverLocked']">
</p-button>
<p-button
icon="pi pi-palette"
(onClick)="generateCustomAudiobookCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingAudiobookCover"
[disabled]="book.metadata!['audiobookCoverLocked'] || isGeneratingAudiobookCover">
</p-button>
<p-button
[disabled]="book.metadata!['audiobookCoverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openAudiobookCoverSearch()"
pTooltip="Search for audiobook cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload audiobook cover"
tooltipPosition="top"
[disabled]="book.metadata!['audiobookCoverLocked']"
name="file"
[url]="getUploadAudiobookCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onAudiobookCoverUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['audiobookCoverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audiobookCover')" severity="success"></p-button>
}
@if (book.metadata!['audiobookCoverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audiobookCover')" severity="warn"></p-button>
}
</div>
</div>
}
<div class="cover-actions">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['coverLocked']">
</p-button>
<p-button
icon="pi pi-palette"
(onClick)="generateCustomCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingCover"
[disabled]="book.metadata!['coverLocked'] || isGeneratingCover">
</p-button>
<p-button
[disabled]="book.metadata!['coverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openCoverSearch()"
pTooltip="Search for cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload cover"
tooltipPosition="top"
[disabled]="book.metadata!['coverLocked']"
name="file"
[url]="getUploadCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['coverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (book.metadata!['coverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
</div>
</div>
<div class="fields-section">
@@ -596,6 +684,48 @@
</div>
</div>
}
@if (isFieldVisible('audibleId')) {
<div class="field-group metadata-id-field">
<label for="audibleId">Audible ID</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleId" formControlName="audibleId"/>
@if (!book.metadata!['audibleIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="success"></p-button>
}
@if (book.metadata!['audibleIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="warn"></p-button>
}
</div>
</div>
}
@if (isFieldVisible('audibleRating')) {
<div class="field-group metadata-id-field">
<label for="audibleRating">Audible ★</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleRating" formControlName="audibleRating"/>
@if (!book.metadata!['audibleRatingLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="success"></p-button>
}
@if (book.metadata!['audibleRatingLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="warn"></p-button>
}
</div>
</div>
}
@if (isFieldVisible('audibleReviewCount')) {
<div class="field-group metadata-id-field">
<label for="audibleReviewCount">Audible #</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleReviewCount" formControlName="audibleReviewCount"/>
@if (!book.metadata!['audibleReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="success"></p-button>
}
@if (book.metadata!['audibleReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="warn"></p-button>
}
</div>
</div>
}
</div>
<div class="description-section">
@@ -6,10 +6,6 @@
}
}
::ng-deep p-image {
width: 250px;
}
::ng-deep .cover-item p-image {
width: 150px;
}
@@ -120,15 +116,64 @@ label {
}
}
.covers-section {
display: flex;
flex-direction: column;
gap: 1.5rem;
flex-shrink: 0;
margin: 0 auto;
&.dual-covers {
flex-direction: row;
gap: 1rem;
@media (max-width: 767px) {
flex-direction: column;
align-items: center;
}
}
}
.cover-section {
display: flex;
flex-direction: column;
align-items: center;
gap: 0;
gap: 0.5rem;
position: relative;
width: 250px;
flex-shrink: 0;
margin: 0 auto;
&.audiobook-cover-section {
::ng-deep .square-cover img {
aspect-ratio: 1;
object-fit: cover;
border-radius: 0.5rem;
}
}
}
.cover-type-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.8rem;
font-weight: 600;
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
margin-bottom: 0.25rem;
i {
font-size: 0.9rem;
}
&.ebook {
color: var(--primary-color);
background: color-mix(in srgb, var(--primary-color) 15%, transparent);
}
&.audiobook {
color: var(--purple-500);
background: color-mix(in srgb, var(--purple-500) 15%, transparent);
}
}
.upload-spinner {
@@ -80,6 +80,7 @@ export class MetadataEditorComponent implements OnInit {
isLoading = false;
isSaving = false;
isGeneratingCover = false;
isGeneratingAudiobookCover = false;
refreshingBookIds = new Set<number>();
isAutoFetching = false;
@@ -118,6 +119,9 @@ export class MetadataEditorComponent implements OnInit {
lubimyczytacRating: true,
ranobedbId: true,
ranobedbRating: true,
audibleId: true,
audibleRating: true,
audibleReviewCount: true,
};
navigationState$ = this.bookNavigationService.getNavigationState();
@@ -195,10 +199,14 @@ export class MetadataEditorComponent implements OnInit {
ranobedbId: new FormControl(""),
ranobedbRating: new FormControl(""),
googleId: new FormControl(""),
audibleId: new FormControl(""),
audibleRating: new FormControl(""),
audibleReviewCount: new FormControl(""),
seriesName: new FormControl(""),
seriesNumber: new FormControl(""),
seriesTotal: new FormControl(""),
thumbnailUrl: new FormControl(""),
audiobookCover: new FormControl(""),
titleLocked: new FormControl(false),
subtitleLocked: new FormControl(false),
@@ -229,10 +237,14 @@ export class MetadataEditorComponent implements OnInit {
ranobedbIdLocked: new FormControl(""),
ranobedbRatingLocked: new FormControl(false),
googleIdLocked: new FormControl(false),
audibleIdLocked: new FormControl(false),
audibleRatingLocked: new FormControl(false),
audibleReviewCountLocked: new FormControl(false),
seriesNameLocked: new FormControl(false),
seriesNumberLocked: new FormControl(false),
seriesTotalLocked: new FormControl(false),
coverLocked: new FormControl(false),
audiobookCoverLocked: new FormControl(false),
reviewsLocked: new FormControl(false),
});
}
@@ -345,6 +357,9 @@ export class MetadataEditorComponent implements OnInit {
ranobedbId: metadata.ranobedbId ?? null,
ranobedbRating: metadata.ranobedbRating ?? null,
googleId: metadata.googleId ?? null,
audibleId: metadata.audibleId ?? null,
audibleRating: metadata.audibleRating ?? null,
audibleReviewCount: metadata.audibleReviewCount ?? null,
seriesName: metadata.seriesName ?? null,
seriesNumber: metadata.seriesNumber ?? null,
seriesTotal: metadata.seriesTotal ?? null,
@@ -377,10 +392,14 @@ export class MetadataEditorComponent implements OnInit {
ranobedbIdLocked: metadata.ranobedbIdLocked ?? false,
ranobedbRatingLocked: metadata.ranobedbRatingLocked ?? false,
googleIdLocked: metadata.googleIdLocked ?? false,
audibleIdLocked: metadata.audibleIdLocked ?? false,
audibleRatingLocked: metadata.audibleRatingLocked ?? false,
audibleReviewCountLocked: metadata.audibleReviewCountLocked ?? false,
seriesNameLocked: metadata.seriesNameLocked ?? false,
seriesNumberLocked: metadata.seriesNumberLocked ?? false,
seriesTotalLocked: metadata.seriesTotalLocked ?? false,
coverLocked: metadata.coverLocked ?? false,
audiobookCoverLocked: metadata.audiobookCoverLocked ?? false,
reviewsLocked: metadata.reviewsLocked ?? false,
});
@@ -413,12 +432,16 @@ export class MetadataEditorComponent implements OnInit {
{key: "ranobedbIdLocked", control: "ranobedbId"},
{key: "ranobedbRatingLocked", control: "ranobedbRating"},
{key: "googleIdLocked", control: "googleId"},
{key: "audibleIdLocked", control: "audibleId"},
{key: "audibleRatingLocked", control: "audibleRating"},
{key: "audibleReviewCountLocked", control: "audibleReviewCount"},
{key: "pageCountLocked", control: "pageCount"},
{key: "descriptionLocked", control: "description"},
{key: "seriesNameLocked", control: "seriesName"},
{key: "seriesNumberLocked", control: "seriesNumber"},
{key: "seriesTotalLocked", control: "seriesTotal"},
{key: "coverLocked", control: "thumbnailUrl"},
{key: "audiobookCoverLocked", control: "audiobookCover"},
{key: "reviewsLocked", control: "reviews"},
];
@@ -496,6 +519,7 @@ export class MetadataEditorComponent implements OnInit {
const isLocked = this.metadataForm.get(field + "Locked")?.value;
const updatedLockedState = !isLocked;
this.metadataForm.get(field + "Locked")?.setValue(updatedLockedState);
if (updatedLockedState) {
this.metadataForm.get(field)?.disable();
} else {
@@ -561,11 +585,15 @@ export class MetadataEditorComponent implements OnInit {
ranobedbId: form.get("ranobedbId")?.value,
ranobedbRating: form.get("ranobedbRating")?.value,
googleId: form.get("googleId")?.value,
audibleId: form.get("audibleId")?.value,
audibleRating: form.get("audibleRating")?.value,
audibleReviewCount: form.get("audibleReviewCount")?.value,
language: form.get("language")?.value,
seriesName: form.get("seriesName")?.value,
seriesNumber: form.get("seriesNumber")?.value,
seriesTotal: form.get("seriesTotal")?.value,
thumbnailUrl: form.get("thumbnailUrl")?.value,
audiobookCover: form.get("audiobookCover")?.value,
// Locks
titleLocked: form.get("titleLocked")?.value,
@@ -597,10 +625,14 @@ export class MetadataEditorComponent implements OnInit {
ranobedbIdLocked: form.get("ranobedbIdLocked")?.value,
ranobedbRatingLocked: form.get("ranobedbRatingLocked")?.value,
googleIdLocked: form.get("googleIdLocked")?.value,
audibleIdLocked: form.get("audibleIdLocked")?.value,
audibleRatingLocked: form.get("audibleRatingLocked")?.value,
audibleReviewCountLocked: form.get("audibleReviewCountLocked")?.value,
seriesNameLocked: form.get("seriesNameLocked")?.value,
seriesNumberLocked: form.get("seriesNumberLocked")?.value,
seriesTotalLocked: form.get("seriesTotalLocked")?.value,
coverLocked: form.get("coverLocked")?.value,
audiobookCoverLocked: form.get("audiobookCoverLocked")?.value,
reviewsLocked: form.get("reviewsLocked")?.value,
...(shouldLockAllFields !== undefined && {
@@ -650,9 +682,13 @@ export class MetadataEditorComponent implements OnInit {
ranobedbId: wasCleared("ranobedbId"),
ranobedbRating: wasCleared("ranobedbRating"),
googleId: wasCleared("googleId"),
audibleId: wasCleared("audibleId"),
audibleRating: wasCleared("audibleRating"),
audibleReviewCount: wasCleared("audibleReviewCount"),
seriesName: wasCleared("seriesName"),
seriesNumber: wasCleared("seriesNumber"),
seriesTotal: wasCleared("seriesTotal"),
audiobookCover: wasCleared("audiobookCover"),
cover: false,
};
@@ -742,6 +778,13 @@ export class MetadataEditorComponent implements OnInit {
},
});
},
error: (err) => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: err?.error?.message || "Failed to regenerate cover",
});
}
});
}
@@ -779,6 +822,71 @@ export class MetadataEditorComponent implements OnInit {
});
}
regenerateAudiobookCover(bookId: number) {
this.bookService.regenerateAudiobookCover(bookId).subscribe({
next: () => {
this.bookService.getBookByIdFromAPI(bookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
this.messageService.add({
severity: "success",
summary: "Success",
detail: "Audiobook cover regenerated successfully.",
});
},
error: () => {
this.messageService.add({
severity: "warning",
summary: "Partial Success",
detail: "Cover regenerated but failed to refresh display. Please refresh the page.",
});
},
});
},
error: (err) => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: err?.error?.message || "Failed to regenerate audiobook cover",
});
}
});
}
generateCustomAudiobookCover(bookId: number) {
this.isGeneratingAudiobookCover = true;
this.bookService.generateCustomAudiobookCover(bookId)
.pipe(finalize(() => this.isGeneratingAudiobookCover = false))
.subscribe({
next: () => {
this.bookService.getBookByIdFromAPI(bookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
this.messageService.add({
severity: "success",
summary: "Success",
detail: "Custom audiobook cover generated successfully.",
});
},
error: () => {
this.messageService.add({
severity: "warning",
summary: "Partial Success",
detail: "Cover generated but failed to refresh display. Please refresh the page.",
});
},
});
},
error: (err) => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: "Failed to generate custom audiobook cover",
});
}
});
}
autoFetch(bookId: number) {
this.refreshingBookIds.add(bookId);
this.isAutoFetching = true;
@@ -818,11 +926,14 @@ export class MetadataEditorComponent implements OnInit {
}
openCoverSearch() {
const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId);
const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId, 'ebook');
ref?.onClose.subscribe((result) => {
if (result) {
this.metadataForm.get("thumbnailUrl")?.setValue(result);
this.onSave();
this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
},
});
}
});
}
@@ -882,4 +993,60 @@ export class MetadataEditorComponent implements OnInit {
onFieldChange(): void {
this.metadataForm.markAsDirty();
}
// Cover type detection methods
hasEbookFormat(book: Book): boolean {
if (book.isPhysical) {
return true;
}
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
return allFiles.some(f => f!.bookType !== 'AUDIOBOOK');
}
hasAudiobookFormat(book: Book): boolean {
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
return allFiles.some(f => f!.bookType === 'AUDIOBOOK');
}
supportsDualCovers(book: Book): boolean {
return this.bookService.supportsDualCovers(book);
}
getUploadAudiobookCoverUrl(): string {
return this.bookService.getUploadAudiobookCoverUrl(this.currentBookId);
}
openAudiobookCoverSearch() {
const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId, 'audiobook');
ref?.onClose.subscribe((result) => {
if (result) {
this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
},
});
}
});
}
onAudiobookCoverUpload(event: FileUploadEvent): void {
const response: HttpResponse<unknown> =
event.originalEvent as HttpResponse<unknown>;
if (response && response.status === 200) {
this.isUploading = false;
this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({
next: (updatedBook) => {
this.bookService.handleBookUpdate(updatedBook);
},
});
} else {
this.isUploading = false;
this.messageService.add({
severity: 'error',
summary: 'Upload Failed',
detail: 'An error occurred while uploading the audiobook cover',
life: 3000,
});
}
}
}
@@ -40,62 +40,143 @@
<span>Cover Image</span>
</div>
<div class="section-content">
<div class="field-row cover-field-row">
<label class="field-label">Cover</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="metadataForm.get('thumbnailUrl')?.value"
alt="Current cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('coverLocked')?.value"
(click)="toggleLock('thumbnailUrl')"
[pTooltip]="metadataForm.get('coverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('coverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<div class="section-content" [class.dual-covers-section]="currentBook && supportsDualCovers(currentBook)">
<!-- Ebook Cover Row -->
@if (!currentBook || hasEbookFormat(currentBook)) {
<div class="field-row cover-field-row">
<label class="field-label">
@if (currentBook && supportsDualCovers(currentBook)) {
<i class="pi pi-book cover-type-icon"></i> Ebook
} @else {
Cover
}
</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="metadataForm.get('thumbnailUrl')?.value"
alt="Current cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('coverLocked')?.value"
(click)="toggleLock('thumbnailUrl')"
[pTooltip]="metadataForm.get('coverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('coverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
</div>
</div>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('thumbnailUrl')"
[class.copied]="isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl']"
[class.reset]="isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']"
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
(mouseenter)="onMouseEnter('thumbnailUrl')"
(mouseleave)="onMouseLeave('thumbnailUrl')"
>
<i [class]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('thumbnailUrl')"
[class.copied]="isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl']"
[class.reset]="isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']"
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
(mouseenter)="onMouseEnter('thumbnailUrl')"
(mouseleave)="onMouseLeave('thumbnailUrl')"
>
<i [class]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
</div>
</div>
</div>
</div>
</div>
}
<!-- Audiobook Cover Row -->
@if (currentBook && hasAudiobookFormat(currentBook)) {
<div class="field-row cover-field-row audiobook-cover-row">
<label class="field-label">
<i class="pi pi-headphones cover-type-icon"></i> Audiobook
</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image square-cover"
[src]="metadataForm.get('audiobookThumbnailUrl')?.value"
alt="Current audiobook cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('audiobookCoverLocked')?.value"
(click)="toggleLock('audiobookThumbnailUrl')"
[pTooltip]="metadataForm.get('audiobookCoverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('audiobookCoverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
</div>
</div>
@if (isAudibleProvider()) {
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('audiobookThumbnailUrl')"
[class.copied]="isValueCopied('audiobookThumbnailUrl') && !hoveredFields['audiobookThumbnailUrl']"
[class.reset]="isValueCopied('audiobookThumbnailUrl') && hoveredFields['audiobookThumbnailUrl']"
(click)="hoveredFields['audiobookThumbnailUrl'] && isValueCopied('audiobookThumbnailUrl') ? resetField('audiobookThumbnailUrl') : copyFetchedToCurrent('audiobookThumbnailUrl')"
(mouseenter)="onMouseEnter('audiobookThumbnailUrl')"
(mouseleave)="onMouseLeave('audiobookThumbnailUrl')"
>
<i [class]="isValueSaved('audiobookThumbnailUrl') ? 'pi pi-check' : (hoveredFields['audiobookThumbnailUrl'] && isValueCopied('audiobookThumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
} @else {
<div class="transfer-btn-placeholder"></div>
}
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
@if (isAudibleProvider()) {
<p-image
class="cover-image square-cover"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched audiobook cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
} @else {
<div class="no-cover-placeholder">
<i class="pi pi-image"></i>
<span>N/A</span>
</div>
}
</div>
</div>
</div>
</div>
}
</div>
</section>
@@ -261,16 +342,108 @@
</div>
</section>
<!-- Additional Details Section -->
@if (metadataFieldsBottom.length > 0) {
<!-- Series Information Section -->
<section class="form-section">
<div class="section-header">
<i class="pi pi-book"></i>
<span>Series Information</span>
</div>
<div class="section-content">
@for (field of metadataSeriesFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
</div>
</div>
</div>
}
</div>
</section>
<!-- Book Details Section -->
<section class="form-section">
<div class="section-header">
<i class="pi pi-id-card"></i>
<span>Book Details</span>
</div>
<div class="section-content">
@for (field of metadataBookDetailsFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
</div>
</div>
</div>
}
</div>
</section>
<!-- Provider Metadata Section -->
@if (metadataProviderFields.length > 0) {
<section class="form-section">
<div class="section-header">
<i class="pi pi-list"></i>
<span>Additional Details</span>
<i class="pi pi-cloud"></i>
<span>Provider Metadata</span>
</div>
<div class="section-content">
@for (field of metadataFieldsBottom; track field) {
@for (field of metadataProviderFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
@@ -308,6 +481,72 @@
</div>
</section>
}
<!-- Audiobook Details Section -->
@if (currentBook && hasAudiobookFormat(currentBook)) {
<section class="form-section">
<div class="section-header">
<i class="pi pi-headphones"></i>
<span>Audiobook Details</span>
</div>
<div class="section-content">
@for (field of audiobookMetadataFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
@if (field.type === 'boolean') {
<p-checkbox
formControlName="{{field.controlName}}"
[binary]="true"
class="field-checkbox"
/>
} @else {
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
}
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
@if (field.type === 'boolean') {
<p-checkbox
[ngModel]="getFetchedAudiobookValue(field.fetchedKey)"
[ngModelOptions]="{ standalone: true }"
[binary]="true"
[disabled]="true"
class="field-checkbox"
/>
} @else {
<input pInputText [value]="getFetchedAudiobookValue(field.fetchedKey) ?? ''" class="field-input" readonly/>
}
</div>
</div>
</div>
}
</div>
</section>
}
</div>
@if (!reviewMode) {
@@ -144,21 +144,20 @@
}
.cover-image {
width: 100px;
height: 150px;
width: 120px;
height: auto;
border-radius: 6px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
@media (min-width: 768px) {
width: 120px;
height: 180px;
width: 150px;
}
::ng-deep img {
width: 100%;
height: 100%;
object-fit: cover;
height: auto;
display: block;
}
}
@@ -199,6 +198,65 @@
color: var(--text-secondary-color);
}
// Cover type icon in label
.cover-type-icon {
font-size: 0.8rem;
margin-right: 0.25rem;
}
// Square cover for audiobooks
.square-cover {
aspect-ratio: 1;
::ng-deep img {
object-fit: cover;
aspect-ratio: 1;
}
}
// Audiobook cover row
.audiobook-cover-row {
background: rgba(var(--p-primary-500-rgb), 0.03);
}
// Transfer button placeholder (same width as button)
.transfer-btn-placeholder {
width: 32px;
height: 32px;
flex-shrink: 0;
}
// No cover placeholder
.no-cover-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 120px;
height: 120px;
background: var(--surface-ground);
border: 1px dashed var(--border-color);
border-radius: 6px;
color: var(--text-secondary-color);
@media (min-width: 768px) {
width: 150px;
height: 150px;
}
i {
font-size: 1.75rem;
margin-bottom: 0.5rem;
opacity: 0.5;
}
span {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
// Field Rows
.field-row {
@@ -221,7 +279,7 @@
// Cover field row specific styles
.cover-field-row {
padding: 1.25rem 1rem;
padding: 1rem;
.field-label {
text-align: center;
@@ -255,7 +313,7 @@
// Position covers towards the arrow on desktop only
@media (min-width: 768px) {
padding: 1.5rem 1rem;
padding: 1rem;
.field-side.current {
justify-content: flex-end;
@@ -5,19 +5,20 @@ import {Button} from 'primeng/button';
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {AsyncPipe} from '@angular/common';
import {Observable} from 'rxjs';
import {forkJoin, Observable} from 'rxjs';
import {Tooltip} from 'primeng/tooltip';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {BookService} from '../../../../book/service/book.service';
import {Textarea} from 'primeng/textarea';
import {filter, map, take} from 'rxjs/operators';
import {filter, take} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {AutoComplete, AutoCompleteSelectEvent} from 'primeng/autocomplete';
import {Image} from 'primeng/image';
import {Checkbox} from 'primeng/checkbox';
import {LazyLoadImageModule} from 'ng-lazyload-image';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-settings.model';
import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata';
import {ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, getArrayFields, getBookDetailsFields, getBottomFields, getProviderFields, getSeriesFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata';
@Component({
selector: 'app-metadata-picker',
@@ -34,7 +35,8 @@ import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields,
Textarea,
AutoComplete,
Image,
LazyLoadImageModule
LazyLoadImageModule,
Checkbox
]
})
export class MetadataPickerComponent implements OnInit {
@@ -43,13 +45,19 @@ export class MetadataPickerComponent implements OnInit {
metadataFieldsTop: MetadataFieldConfig[] = [];
metadataChips: MetadataFieldConfig[] = [];
metadataDescription: MetadataFieldConfig[] = [];
metadataSeriesFields: MetadataFieldConfig[] = [];
metadataBookDetailsFields: MetadataFieldConfig[] = [];
metadataProviderFields: MetadataFieldConfig[] = [];
metadataFieldsBottom: MetadataFieldConfig[] = [];
audiobookMetadataFields: MetadataFieldConfig[] = [];
@Input() reviewMode!: boolean;
@Input() fetchedMetadata!: BookMetadata;
@Input() book$!: Observable<Book | null>;
@Output() goBack = new EventEmitter<boolean>();
currentBook: Book | null = null;
private allItems: Record<string, string[]> = {};
filteredItems: Record<string, string[]> = {};
@@ -80,7 +88,15 @@ export class MetadataPickerComponent implements OnInit {
this.metadataFieldsTop = getTopFields();
this.metadataChips = getArrayFields();
this.metadataDescription = getTextareaFields();
this.metadataSeriesFields = getSeriesFields();
this.metadataBookDetailsFields = getBookDetailsFields();
this.updateProviderFields();
this.updateBottomFields();
this.audiobookMetadataFields = AUDIOBOOK_METADATA_FIELDS;
}
private updateProviderFields(): void {
this.metadataProviderFields = getProviderFields(this.enabledProviderFields);
}
private updateBottomFields(): void {
@@ -106,6 +122,7 @@ export class MetadataPickerComponent implements OnInit {
.subscribe(settings => {
if (settings?.metadataProviderSpecificFields) {
this.enabledProviderFields = settings.metadataProviderSpecificFields;
this.updateProviderFields();
this.updateBottomFields();
}
});
@@ -138,9 +155,8 @@ export class MetadataPickerComponent implements OnInit {
this.book$
.pipe(
filter((book): book is Book => !!book && !!book.metadata),
map(book => book.metadata),
takeUntilDestroyed(this.destroyRef)
).subscribe((metadata) => {
).subscribe((book) => {
if (this.reviewMode) {
this.metadataForm.reset();
this.copiedFields = {};
@@ -148,16 +164,16 @@ export class MetadataPickerComponent implements OnInit {
this.hoveredFields = {};
}
if (metadata) {
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn);
this.currentBookId = metadata.bookId;
this.patchMetadataToForm(metadata);
}
this.currentBook = book;
const metadata = book.metadata!;
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn);
this.currentBookId = metadata.bookId;
this.patchMetadataToForm(metadata, book);
});
}
private patchMetadataToForm(metadata: BookMetadata): void {
private patchMetadataToForm(metadata: BookMetadata, book: Book): void {
const patchData: Record<string, unknown> = {};
for (const field of ALL_METADATA_FIELDS) {
@@ -173,10 +189,26 @@ export class MetadataPickerComponent implements OnInit {
patchData[field.lockedKey] = metadata[lockedKey] ?? false;
}
// Handle special fields
// Handle special fields - ebook cover
patchData['thumbnailUrl'] = this.urlHelper.getCoverUrl(metadata.bookId, metadata.coverUpdatedOn);
patchData['coverLocked'] = metadata.coverLocked ?? false;
// Handle audiobook cover
patchData['audiobookThumbnailUrl'] = this.urlHelper.getAudiobookCoverUrl(metadata.bookId, metadata.audiobookCoverUpdatedOn);
patchData['audiobookCoverLocked'] = metadata.audiobookCoverLocked ?? false;
// Handle audiobook-specific metadata fields
// narrator/abridged are now at top-level of BookMetadata, but we also check nested for backward compatibility
for (const field of AUDIOBOOK_METADATA_FIELDS) {
const key = field.controlName as keyof BookMetadata;
const lockedKey = field.lockedKey as keyof BookMetadata;
// Prefer top-level fields, fallback to nested audiobookMetadata
const topLevelValue = metadata[key];
const topLevelLocked = metadata[lockedKey];
patchData[field.controlName] = topLevelValue ?? (field.type === 'boolean' ? null : '');
patchData[field.lockedKey] = topLevelLocked ?? false;
}
this.metadataForm.patchValue(patchData);
this.applyLockStates(metadata);
}
@@ -186,6 +218,10 @@ export class MetadataPickerComponent implements OnInit {
for (const field of ALL_METADATA_FIELDS) {
lockedFields[field.lockedKey] = !!metadata[field.lockedKey as keyof BookMetadata];
}
// Also handle audiobook metadata lock states (now at top-level of BookMetadata)
for (const field of AUDIOBOOK_METADATA_FIELDS) {
lockedFields[field.lockedKey] = !!metadata[field.lockedKey as keyof BookMetadata];
}
this.formBuilder.applyLockStates(this.metadataForm, lockedFields);
}
@@ -214,7 +250,20 @@ export class MetadataPickerComponent implements OnInit {
onSave(): void {
this.isSaving = true;
const updatedBookMetadata = this.buildMetadataWrapper(undefined);
this.bookService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false).subscribe({
const requests: Observable<unknown>[] = [
this.bookService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false)
];
// Handle audiobook cover upload when fetched from Audible provider
if (this.isAudibleProvider() && this.copiedFields['audiobookThumbnailUrl']) {
const audiobookCoverUrl = this.fetchedMetadata.thumbnailUrl;
if (audiobookCoverUrl) {
requests.push(this.bookService.uploadAudiobookCoverFromUrl(this.currentBookId, audiobookCoverUrl));
}
}
forkJoin(requests).subscribe({
next: () => {
this.isSaving = false;
for (const field of Object.keys(this.copiedFields)) {
@@ -254,6 +303,8 @@ export class MetadataPickerComponent implements OnInit {
metadata[field.controlName] = this.getArrayValue(field.controlName);
} else if (field.type === 'number') {
metadata[field.controlName] = this.getNumberValue(field.controlName);
} else if (field.type === 'boolean') {
metadata[field.controlName] = this.getBooleanValue(field.controlName);
} else {
metadata[field.controlName] = this.getStringValue(field.controlName);
}
@@ -263,6 +314,17 @@ export class MetadataPickerComponent implements OnInit {
metadata['thumbnailUrl'] = this.getThumbnail();
metadata['coverLocked'] = this.metadataForm.get('coverLocked')?.value;
metadata['audiobookCoverLocked'] = this.metadataForm.get('audiobookCoverLocked')?.value;
// Set audiobook content metadata (narrator/abridged) at top level
for (const field of AUDIOBOOK_METADATA_FIELDS) {
if (field.type === 'boolean') {
metadata[field.controlName] = this.getBooleanValue(field.controlName);
} else {
metadata[field.controlName] = this.getStringValue(field.controlName);
}
metadata[field.lockedKey] = this.metadataForm.get(field.lockedKey)?.value ?? false;
}
return metadata as BookMetadata;
}
@@ -304,6 +366,17 @@ export class MetadataPickerComponent implements OnInit {
return Array.isArray(fieldValue) ? fieldValue as string[] : [];
}
private getBooleanValue(field: string): boolean | null {
const formValue = this.metadataForm.get(field)?.value;
if (formValue === null || formValue === undefined) {
if (this.copiedFields[field]) {
return (this.fetchedMetadata[field as keyof BookMetadata] as boolean | null) ?? null;
}
return null;
}
return !!formValue;
}
private inferClearFlags(current: BookMetadata, original: BookMetadata): MetadataClearFlags {
const flags: Record<string, boolean> = {};
@@ -316,16 +389,36 @@ export class MetadataPickerComponent implements OnInit {
flags[key] = !(curr as string[])?.length && !!(orig as string[])?.length;
} else if (field.type === 'number') {
flags[key] = curr === null && orig !== null;
} else if (field.type === 'boolean') {
flags[key] = curr === null && orig !== null;
} else {
flags[key] = !curr && !!orig;
}
}
flags['cover'] = !current.thumbnailUrl && !!original.thumbnailUrl;
// Handle audiobook metadata clear flags (now at top-level of BookMetadata)
for (const field of AUDIOBOOK_METADATA_FIELDS) {
const key = field.controlName as keyof BookMetadata;
const curr = current[key];
const orig = original[key];
if (field.type === 'boolean') {
flags[key] = curr === null && orig !== null;
} else {
flags[key] = !curr && !!orig;
}
}
return flags as MetadataClearFlags;
}
getThumbnail(): string | null {
// For Audible provider, cover is handled separately via uploadAudiobookCoverFromUrl
if (this.isAudibleProvider()) {
return null;
}
const thumbnailUrl = this.metadataForm.get('thumbnailUrl')?.value;
if (thumbnailUrl?.includes('api/v1')) {
return null;
@@ -360,16 +453,20 @@ export class MetadataPickerComponent implements OnInit {
}
toggleLock(field: string): void {
const controlName = field;
let lockField = field;
if (field === 'thumbnailUrl') {
field = 'cover';
lockField = 'cover';
} else if (field === 'audiobookThumbnailUrl') {
lockField = 'audiobookCover';
}
const isLocked = this.metadataForm.get(field + 'Locked')?.value;
const isLocked = this.metadataForm.get(lockField + 'Locked')?.value;
const updatedLockedState = !isLocked;
this.metadataForm.get(field + 'Locked')?.setValue(updatedLockedState);
this.metadataForm.get(lockField + 'Locked')?.setValue(updatedLockedState);
if (updatedLockedState) {
this.metadataForm.get(field)?.disable();
this.metadataForm.get(controlName)?.disable();
} else {
this.metadataForm.get(field)?.enable();
this.metadataForm.get(controlName)?.enable();
}
this.updateMetadata(undefined);
}
@@ -392,20 +489,26 @@ export class MetadataPickerComponent implements OnInit {
}
copyFetchedToCurrent(field: string): void {
let lockField = field;
if (field === 'thumbnailUrl') {
field = 'cover';
lockField = 'cover';
} else if (field === 'audiobookThumbnailUrl') {
lockField = 'audiobookCover';
}
const isLocked = this.metadataForm.get(`${field}Locked`)?.value;
const isLocked = this.metadataForm.get(`${lockField}Locked`)?.value;
if (isLocked) {
this.messageService.add({
severity: 'warn',
summary: 'Action Blocked',
detail: `${field} is locked and cannot be updated.`
detail: `${lockField} is locked and cannot be updated.`
});
return;
}
if (field === 'cover') {
field = 'thumbnailUrl';
// For audiobook cover from Audible, use the thumbnailUrl from fetched metadata
if (field === 'audiobookThumbnailUrl') {
this.metadataForm.get('audiobookThumbnailUrl')?.setValue(this.fetchedMetadata.thumbnailUrl);
this.highlightCopiedInput(field);
return;
}
if (this.metadataUtils.copyFieldToForm(field, this.fetchedMetadata, this.metadataForm, this.copiedFields)) {
this.highlightCopiedInput(field);
@@ -451,4 +554,30 @@ export class MetadataPickerComponent implements OnInit {
resetField(field: string): void {
this.metadataUtils.resetField(field, this.metadataForm, this.originalMetadata, this.copiedFields, this.hoveredFields);
}
isAudibleProvider(): boolean {
return this.fetchedMetadata?.provider?.toLowerCase() === 'audible';
}
getFetchedAudiobookValue(key: string): unknown {
return this.fetchedMetadata?.[key as keyof BookMetadata];
}
// Cover type detection methods
hasEbookFormat(book: Book): boolean {
if (book.isPhysical) {
return true;
}
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
return allFiles.some(f => f!.bookType !== 'AUDIOBOOK');
}
hasAudiobookFormat(book: Book): boolean {
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
return allFiles.some(f => f!.bookType === 'AUDIOBOOK');
}
supportsDualCovers(book: Book): boolean {
return this.hasEbookFormat(book) && this.hasAudiobookFormat(book);
}
}
@@ -266,6 +266,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
if (metadata['lubimyczytacId']) return 'lubimyczytac';
if (metadata.comicvineId) return 'comicvine';
if (metadata.ranobedbId) return 'ranobedb';
if (metadata.audibleId) return 'audible';
return null;
}
@@ -378,13 +379,15 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
return `<a href="https://comicvine.gamespot.com/volume/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
} else if (metadata.ranobedbId) {
return `<a href="https://ranobedb.org/book/${metadata.ranobedbId}" target="_blank">RanobeDB</a>`;
} else if (metadata.audibleId) {
return `<a href="https://www.audible.com/pd/${metadata.audibleId}" target="_blank">Audible</a>`;
}
throw new Error("No provider ID found in metadata.");
}
trackByMetadata(index: number, metadata: BookMetadata): string {
return metadata.googleId || metadata.goodreadsId || metadata.asin ||
metadata.hardcoverId || metadata.comicvineId || index.toString();
metadata.hardcoverId || metadata.comicvineId || metadata.audibleId || index.toString();
}
onProviderClick(event: MouseEvent) {
@@ -8,6 +8,11 @@
<p-tab value="similar">
<i class="pi pi-bookmark"></i> Similar Books
</p-tab>
@if (supportsDualCovers()) {
<p-tab value="covers">
<i class="pi pi-images"></i> Covers
</p-tab>
}
<p-tab value="files">
<i class="pi pi-folder-open"></i> Files
</p-tab>
@@ -54,6 +59,39 @@
</div>
</ng-template>
</p-tabpanel>
<p-tabpanel value="covers">
<ng-template #content>
<div class="covers-tab-content">
<div class="covers-grid">
<div class="cover-item">
<div class="cover-label">
<i class="pi pi-book"></i> Ebook Cover
</div>
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Ebook Cover"
width="200"
appendTo="body"
[preview]="true">
</p-image>
</div>
<div class="cover-item">
<div class="cover-label audiobook">
<i class="pi pi-headphones"></i> Audiobook Cover
</div>
<p-image
[src]="urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)"
alt="Audiobook Cover"
width="200"
appendTo="body"
[preview]="true"
styleClass="square-cover">
</p-image>
</div>
</div>
</div>
</ng-template>
</p-tabpanel>
<p-tabpanel value="notes">
<ng-template #content>
<app-book-notes-component [bookId]="book.id"></app-book-notes-component>
@@ -214,3 +214,53 @@
margin: 0;
opacity: 0.8;
}
// Covers tab styles
.covers-tab-content {
padding: 1rem 0;
}
.covers-grid {
display: flex;
flex-wrap: wrap;
gap: 2rem;
justify-content: center;
@media (min-width: 768px) {
justify-content: flex-start;
}
}
.cover-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
::ng-deep .square-cover img {
aspect-ratio: 1;
object-fit: cover;
border-radius: 0.5rem;
}
}
.cover-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
font-weight: 600;
color: var(--primary-color);
padding: 0.25rem 0.75rem;
background: color-mix(in srgb, var(--primary-color) 15%, transparent);
border-radius: 0.5rem;
i {
font-size: 1rem;
}
&.audiobook {
color: var(--purple-500);
background: color-mix(in srgb, var(--purple-500) 15%, transparent);
}
}
@@ -1,4 +1,4 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {Component, EventEmitter, inject, Input, Output} from '@angular/core';
import {UpperCasePipe} from '@angular/common';
import {Book, BookRecommendation, BookType, FileInfo} from '../../../../../book/model/book.model';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
@@ -9,6 +9,9 @@ import {BookNotesComponent} from '../../../../../book/components/book-notes/book
import {BookReadingSessionsComponent} from '../../book-reading-sessions/book-reading-sessions.component';
import {Button} from 'primeng/button';
import {Tooltip} from 'primeng/tooltip';
import {Image} from 'primeng/image';
import {UrlHelperService} from '../../../../../../shared/service/url-helper.service';
import {BookService} from '../../../../../book/service/book.service';
export interface ReadEvent {
bookId: number;
@@ -59,7 +62,8 @@ export interface DeleteSupplementaryFileEvent {
BookReadingSessionsComponent,
Button,
Tooltip,
UpperCasePipe
UpperCasePipe,
Image
],
templateUrl: './metadata-tabs.component.html',
styleUrl: './metadata-tabs.component.scss'
@@ -69,6 +73,9 @@ export class MetadataTabsComponent {
@Input() bookInSeries: Book[] = [];
@Input() recommendedBooks: BookRecommendation[] = [];
protected urlHelper = inject(UrlHelperService);
private bookService = inject(BookService);
@Output() readBook = new EventEmitter<ReadEvent>();
@Output() downloadBook = new EventEmitter<DownloadEvent>();
@Output() downloadFile = new EventEmitter<DownloadAdditionalFileEvent>();
@@ -161,4 +168,8 @@ export class MetadataTabsComponent {
isPhysicalBook(): boolean {
return !this.book?.primaryFile && (!this.book?.alternativeFormats || this.book.alternativeFormats.length === 0);
}
supportsDualCovers(): boolean {
return this.bookService.supportsDualCovers(this.book);
}
}
@@ -6,7 +6,7 @@
<div class="cover-wrapper">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
[src]="getBookCoverUrl(book)"
alt="Image"
width="250"
appendTo="body"
@@ -96,12 +96,12 @@
<div class="title-group">
@if (book?.metadata?.seriesName) {
<p class="series-link" (click)="goToSeries(book?.metadata?.seriesName!)">
<div class="series-link" (click)="goToSeries(book?.metadata?.seriesName!)">
{{ book?.metadata?.seriesName }}
@if (book?.metadata?.seriesNumber) {
#{{ book?.metadata?.seriesNumber }}
}
</p>
</div>
}
<div class="title-wrapper">
@@ -154,7 +154,7 @@
</p-button>
</div>
@if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.lubimyczytacRating || book?.metadata?.ranobedbRating || book?.metadata?.googleId) {
@if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.lubimyczytacRating || book?.metadata?.ranobedbRating || book?.metadata?.audibleRating || book?.metadata?.googleId) {
<div class="gradient-divider"></div>
}
@@ -229,6 +229,20 @@
</a>
}
@if (book?.metadata?.audibleRating) {
<a
class="rating-link"
[href]="'https://www.audible.com/pd/' + (book.metadata?.audibleId ?? '')"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="getRatingTooltip(book, 'audible')"
tooltipPosition="top"
>
<img src="https://www.audible.com/favicon.ico" alt="Audible" class="rating-favicon"/>
<span class="rating-value">{{ getRatingPercent(book.metadata!.audibleRating) }}%</span>
</a>
}
@if (book?.metadata?.googleId) {
<a
class="rating-link"
@@ -1078,7 +1078,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return p != null ? Math.round(p * 10) / 10 : null;
}
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover' | 'lubimyczytac' | 'ranobedb'): string {
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover' | 'lubimyczytac' | 'ranobedb' | 'audible'): string {
const meta = book?.metadata;
if (!meta) return '';
@@ -1103,6 +1103,10 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return meta.ranobedbRating != null
? `★ ${meta.ranobedbRating}`
: '';
case 'audible':
return meta.audibleRating != null
? `★ ${meta.audibleRating} | ${meta.audibleReviewCount?.toLocaleString() ?? '0'} reviews`
: '';
default:
return '';
}
@@ -1231,4 +1235,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
isPhysicalBook(book: Book): boolean {
return !this.hasAnyFiles(book);
}
getBookCoverUrl(book: Book): string {
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
return isAudiobook
? this.urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn);
}
}
@@ -1,10 +1,10 @@
<div class="cover-search-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-image header-icon"></i>
<i class="pi {{ coverType === 'audiobook' ? 'pi-headphones' : 'pi-image' }} header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Search Cover Images</h2>
<h2 class="panel-title">Search {{ coverType === 'audiobook' ? 'Audiobook' : 'Ebook' }} Cover</h2>
<p class="panel-description">Find and select a cover for your book</p>
</div>
<p-button
@@ -31,7 +31,7 @@ export class CoverSearchComponent implements OnInit {
coverImages: CoverImage[] = [];
loading = false;
hasSearched = false;
isAudiobook = false;
coverType: 'ebook' | 'audiobook' = 'ebook';
private fb = inject(FormBuilder);
private bookCoverService = inject(BookCoverService);
@@ -51,8 +51,16 @@ export class CoverSearchComponent implements OnInit {
this.bookId = this.dynamicDialogConfig.data.bookId;
const book = this.bookService.getBookByIdFromState(this.bookId);
// Use explicitly provided coverType, or auto-detect based on primary file
if (this.dynamicDialogConfig.data.coverType) {
this.coverType = this.dynamicDialogConfig.data.coverType;
} else if (book?.primaryFile?.bookType === 'AUDIOBOOK') {
this.coverType = 'audiobook';
} else {
this.coverType = 'ebook';
}
if (book) {
this.isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
this.searchForm.patchValue({
title: book.metadata?.title || '',
author: book.metadata?.authors && book.metadata?.authors.length > 0 ? book.metadata?.authors[0] : ''
@@ -70,7 +78,7 @@ export class CoverSearchComponent implements OnInit {
const request: CoverFetchRequest = {
title: this.searchForm.value.title,
author: this.searchForm.value.author,
squareCover: this.isAudiobook
coverType: this.coverType
};
this.bookCoverService.fetchBookCovers(request)
@@ -95,24 +103,27 @@ export class CoverSearchComponent implements OnInit {
}
selectAndSave(image: CoverImage) {
this.bookService.uploadCoverFromUrl(this.bookId, image.url)
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Cover Updated',
detail: 'Cover image updated successfully.'
});
this.dynamicDialogRef.close();
},
error: err => {
this.messageService.add({
severity: 'error',
summary: 'Cover Update Failed',
detail: err?.message || 'Failed to update cover image.'
});
}
});
const uploadObservable = this.coverType === 'audiobook'
? this.bookService.uploadAudiobookCoverFromUrl(this.bookId, image.url)
: this.bookService.uploadCoverFromUrl(this.bookId, image.url);
uploadObservable.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Cover Updated',
detail: `${this.coverType === 'audiobook' ? 'Audiobook' : 'Ebook'} cover image updated successfully.`
});
this.dynamicDialogRef.close(true);
},
error: err => {
this.messageService.add({
severity: 'error',
summary: 'Cover Update Failed',
detail: err?.message || 'Failed to update cover image.'
});
}
});
}
onClear() {
@@ -35,7 +35,8 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
'hardcoverId', 'hardcoverRating', 'hardcoverReviewCount', 'moods', 'tags',
'comicvineId',
'lubimyczytacId', 'lubimyczytacRating',
'ranobedbId', 'ranobedbRating'
'ranobedbId', 'ranobedbRating',
'audibleId', 'audibleRating', 'audibleReviewCount'
];
providerSpecificFields: (keyof FieldOptions)[] = [
@@ -46,6 +47,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
'comicvineId',
'lubimyczytacId', 'lubimyczytacRating',
'ranobedbId', 'ranobedbRating',
'audibleId', 'audibleRating', 'audibleReviewCount',
];
nonProviderSpecificFields: (keyof FieldOptions)[] = [
@@ -54,8 +56,8 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
'language', 'categories', 'cover', 'pageCount',
];
providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb'];
providersWithClear: string[] = ['Clear All', 'Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb'];
providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb', 'Audible'];
providersWithClear: string[] = ['Clear All', 'Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb', 'Audible'];
refreshCovers: boolean = false;
mergeCategories: boolean = false;
@@ -102,6 +104,9 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
// Ranobedb
'ranobedbId', 'ranobedbRating',
// Audible
'audibleId', 'audibleRating', 'audibleReviewCount',
// Generic provider-specific
'moods', 'tags'
];
@@ -274,6 +279,9 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
'lubimyczytacRating': 'Lubimyczytac Rating',
'ranobedbId': 'Ranobedb ID',
'ranobedbRating': 'Ranobedb Rating',
'audibleId': 'Audible ID',
'audibleRating': 'Audible Rating',
'audibleReviewCount': 'Audible Review Count',
'moods': 'Moods (Hardcover)',
'tags': 'Tags (Hardcover)'
};
@@ -45,6 +45,10 @@ export class MetadataProviderFieldSelectorComponent implements OnInit {
{
label: 'Ranobedb',
fields: ['ranobedbId', 'ranobedbRating']
},
{
label: 'Audible',
fields: ['audibleId', 'audibleRating', 'audibleReviewCount']
}
];
@@ -65,6 +69,9 @@ export class MetadataProviderFieldSelectorComponent implements OnInit {
'lubimyczytacRating': 'Lubimyczytac Rating',
'ranobedbId': 'Ranobedb ID',
'ranobedbRating': 'Ranobedb Rating',
'audibleId': 'Audible ID',
'audibleRating': 'Audible Rating',
'audibleReviewCount': 'Audible Review Count',
};
private readonly allFieldNames: (keyof MetadataProviderSpecificFields)[] = [
@@ -74,7 +81,8 @@ export class MetadataProviderFieldSelectorComponent implements OnInit {
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount',
'comicvineId',
'lubimyczytacId', 'lubimyczytacRating',
'ranobedbId', 'ranobedbRating'
'ranobedbId', 'ranobedbRating',
'audibleId', 'audibleRating', 'audibleReviewCount'
];
ngOnInit(): void {
@@ -53,6 +53,9 @@ export interface FieldOptions {
lubimyczytacRating: FieldProvider;
ranobedbId: FieldProvider;
ranobedbRating: FieldProvider;
audibleId: FieldProvider;
audibleRating: FieldProvider;
audibleReviewCount: FieldProvider;
moods: FieldProvider;
tags: FieldProvider;
}
@@ -4,7 +4,7 @@
<span class="loading-text">Loading audiobook...</span>
</div>
} @else {
<div class="audiobook-reader">
<div class="audiobook-player">
<!-- Hidden audio element -->
<audio
#audioElement
@@ -53,7 +53,7 @@ $border-color: rgba(255, 255, 255, 0.1);
}
// Main container
.audiobook-reader {
.audiobook-player {
display: flex;
flex-direction: column;
height: 100vh;
@@ -436,9 +436,10 @@ $border-color: rgba(255, 255, 255, 0.1);
.audio-details {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 1.25rem;
padding: 1rem 1rem 0;
padding: 1rem;
color: $text-tertiary;
font-size: 0.8rem;
background: rgba(255, 255, 255, 0.03);
@@ -23,7 +23,7 @@ import {AuthService} from '../../../shared/service/auth.service';
import {API_CONFIG} from '../../../core/config/api-config';
@Component({
selector: 'app-audiobook-reader',
selector: 'app-audiobook-player',
standalone: true,
imports: [
CommonModule,
@@ -35,10 +35,10 @@ import {API_CONFIG} from '../../../core/config/api-config';
SelectButton,
Menu
],
templateUrl: './audiobook-reader.component.html',
styleUrls: ['./audiobook-reader.component.scss']
templateUrl: './audiobook-player.component.html',
styleUrls: ['./audiobook-player.component.scss']
})
export class AudiobookReaderComponent implements OnInit, OnDestroy {
export class AudiobookPlayerComponent implements OnInit, OnDestroy {
@ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>;
private destroy$ = new Subject<void>();
@@ -161,10 +161,10 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
}
}
// Load cover URLs
// Load cover URLs - prefer stored audiobook cover, fall back to embedded, then book cover
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`;
this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${this.bookId}/cover?token=${encodeURIComponent(token || '')}`;
this.coverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${this.bookId}/audiobook-cover?token=${encodeURIComponent(token || '')}`;
this.isLoading = false;
@@ -789,7 +789,13 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
}
onCoverError(): void {
if (this.coverUrl !== this.bookCoverUrl) {
// Fallback chain: stored audiobook cover -> embedded cover -> book cover
const embeddedCoverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
if (this.coverUrl && !this.coverUrl.includes('/audiobook/') && this.coverUrl !== this.bookCoverUrl) {
// First fallback: try embedded cover from file
this.coverUrl = embeddedCoverUrl;
} else if (this.coverUrl !== this.bookCoverUrl) {
// Second fallback: try book cover
this.coverUrl = this.bookCoverUrl;
} else {
this.coverUrl = undefined;
@@ -1,3 +1,3 @@
export * from './audiobook-reader.component';
export * from './audiobook-player.component';
export * from './audiobook.service';
export * from './audiobook.model';
@@ -44,6 +44,8 @@ export class MetadataMatchWeightsComponent implements OnInit {
hardcoverRating: 'Hardcover Rating',
hardcoverReviewCount: 'Hardcover Rating #',
ranobedbRating: 'Ranobedb Rating',
audibleRating: 'Audible Rating',
audibleReviewCount: 'Audible Rating #',
};
form!: FormGroup;
@@ -79,6 +81,8 @@ export class MetadataMatchWeightsComponent implements OnInit {
hardcoverRating: [0, [Validators.required, Validators.min(0)]],
hardcoverReviewCount: [0, [Validators.required, Validators.min(0)]],
ranobedbRating: [0, [Validators.required, Validators.min(0)]],
audibleRating: [0, [Validators.required, Validators.min(0)]],
audibleReviewCount: [0, [Validators.required, Validators.min(0)]],
coverImage: [0, [Validators.required, Validators.min(0)]],
});
this.appSettings$
@@ -114,6 +114,26 @@
</div>
}
</div>
<div class="setting-item">
<div class="setting-header">
<p-toggleswitch [(ngModel)]="audibleEnabled"></p-toggleswitch>
<label class="setting-label">Audible</label>
</div>
@if (audibleEnabled) {
<div class="setting-options">
<div class="config-field">
<label class="config-label">Region</label>
<p-select
[options]="audibleDomains"
[(ngModel)]="selectedAudibleDomain"
placeholder="Select Domain"
class="config-select">
</p-select>
</div>
</div>
}
</div>
</div>
</div>
@@ -68,6 +68,22 @@ export class MetadataProviderSettingsComponent implements OnInit {
selectedGoogleLanguage = '';
audibleDomains = [
{label: 'audible.com', value: 'com'},
{label: 'audible.co.uk', value: 'co.uk'},
{label: 'audible.de', value: 'de'},
{label: 'audible.fr', value: 'fr'},
{label: 'audible.it', value: 'it'},
{label: 'audible.es', value: 'es'},
{label: 'audible.ca', value: 'ca'},
{label: 'audible.com.au', value: 'com.au'},
{label: 'audible.co.jp', value: 'co.jp'},
{label: 'audible.in', value: 'in'}
];
selectedAudibleDomain = 'com';
audibleEnabled: boolean = false;
hardcoverToken: string = '';
amazonCookie: string = '';
hardcoverEnabled: boolean = false;
@@ -107,6 +123,8 @@ export class MetadataProviderSettingsComponent implements OnInit {
this.doubanEnabled = metadataProviderSettings?.douban?.enabled ?? false;
this.lubimyCzytacEnabled = metadataProviderSettings?.lubimyczytac?.enabled ?? false;
this.ranobedbEnabled = metadataProviderSettings?.ranobedb?.enabled ?? false;
this.audibleEnabled = metadataProviderSettings?.audible?.enabled ?? false;
this.selectedAudibleDomain = metadataProviderSettings?.audible?.domain ?? 'com';
});
}
@@ -146,7 +164,11 @@ export class MetadataProviderSettingsComponent implements OnInit {
},
douban: {enabled: this.doubanEnabled},
lubimyczytac: {enabled: this.lubimyCzytacEnabled},
ranobedb: {enabled: this.ranobedbEnabled}
ranobedb: {enabled: this.ranobedbEnabled},
audible: {
enabled: this.audibleEnabled,
domain: this.selectedAudibleDomain
}
}
}
];
@@ -224,6 +224,9 @@ export class LibraryMetadataSettingsComponent implements OnInit {
lubimyczytacRating: {p1: null, p2: null, p3: null, p4: null},
ranobedbId: {p1: null, p2: null, p3: null, p4: null},
ranobedbRating: {p1: null, p2: null, p3: null, p4: null},
audibleId: {p1: null, p2: null, p3: null, p4: null},
audibleRating: {p1: null, p2: null, p3: null, p4: null},
audibleReviewCount: {p1: null, p2: null, p3: null, p4: null},
moods: {p1: null, p2: null, p3: null, p4: null},
tags: {p1: null, p2: null, p3: null, p4: null}
}
@@ -122,6 +122,40 @@
}
</div>
<div class="setting-item">
<div class="setting-header">
<p-toggleswitch
[ngModel]="metadataPersistence.saveToOriginalFile.audiobook.enabled"
(onChange)="onSaveToOriginalFileToggle('audiobook')">
</p-toggleswitch>
<label class="setting-label">Write Metadata to Audiobooks</label>
</div>
<p class="setting-description">
Write metadata directly into audiobook files (M4B, M4A, MP3, etc.) when editing book information.
<span class="setting-note">Supports title, authors, narrator, description, publisher, categories, series, language, and cover art. For folder-based audiobooks, cover is saved as cover.jpg in the folder.</span>
</p>
@if (metadataPersistence.saveToOriginalFile.audiobook.enabled) {
<div class="setting-options">
<div class="filesize-input">
<label>Max file size:</label>
<input
type="number"
[(ngModel)]="metadataPersistence.saveToOriginalFile.audiobook.maxFileSizeInMb"
(change)="onFilesizeChange('audiobook')"
min="1"
max="2000"
class="filesize-field">
<span class="filesize-unit">MB</span>
<i
class="pi pi-info-circle"
pTooltip="Only files up to this size will be updated. Larger files are ignored."
tooltipPosition="right">
</i>
</div>
</div>
}
</div>
@if ((appSettings$ | async)?.diskType === 'LOCAL') {
<div class="setting-item">
<div class="setting-header">
@@ -35,6 +35,10 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
cbx: {
enabled: false,
maxFileSizeInMb: 250
},
audiobook: {
enabled: false,
maxFileSizeInMb: 1000
}
},
convertCbrCb7ToCbz: false,
@@ -98,6 +102,10 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
cbx: {
enabled: persistenceSettings.saveToOriginalFile?.cbx?.enabled ?? false,
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.cbx?.maxFileSizeInMb ?? 250
},
audiobook: {
enabled: persistenceSettings.saveToOriginalFile?.audiobook?.enabled ?? false,
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.audiobook?.maxFileSizeInMb ?? 1000
}
}
};
@@ -7,6 +7,7 @@ import {Component, Input} from '@angular/core';
export class CoverGeneratorComponent {
@Input() title: string = '';
@Input() author: string = '';
@Input() isSquare: boolean = false;
private wrapText(text: string, maxLineLength: number): string[] {
const words = text.split(' ');
@@ -40,26 +41,159 @@ export class CoverGeneratorComponent {
return text.substring(0, maxLength - 3) + '...';
}
private calculateTitleFontSize(lineCount: number): number {
if (lineCount <= 2) return 36;
if (lineCount === 3) return 30;
return 24;
private escapeXml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
private calculateAuthorFontSize(lineCount: number): number {
if (lineCount <= 2) return 28;
return 22;
private hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return Math.abs(hash);
}
generateCover(): string {
const width = 250;
const height = this.isSquare ? 250 : 350;
const hash = this.hashString(this.title + this.author);
if (this.isSquare) {
return this.generateAudiobookCover(width, height, hash);
} else {
return this.generateEbookCover(width, height, hash);
}
}
private generateEbookCover(width: number, height: number, hash: number): string {
const palettes = [
{bg1: '#1a1a2e', bg2: '#16213e', accent: '#e94560', text: '#eaeaea', textSecondary: '#b8b8b8'},
{bg1: '#2d3436', bg2: '#636e72', accent: '#74b9ff', text: '#ffffff', textSecondary: '#dfe6e9'},
{bg1: '#0c3547', bg2: '#1a5276', accent: '#f39c12', text: '#ecf0f1', textSecondary: '#bdc3c7'},
{bg1: '#1e3d59', bg2: '#17263a', accent: '#ffc13b', text: '#f5f0e1', textSecondary: '#c7b198'},
{bg1: '#2c2c54', bg2: '#474787', accent: '#ff793f', text: '#f8f8f8', textSecondary: '#d1ccc0'},
{bg1: '#1b262c', bg2: '#0f4c75', accent: '#3282b8', text: '#bbe1fa', textSecondary: '#8fbdd3'},
];
const palette = palettes[hash % palettes.length];
const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(false);
const titleLineHeight = titleFontSize * 1.3;
const titleStartY = 80;
const titleElements = titleLines.map((line, index) => {
const y = titleStartY + (index * titleLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Georgia, serif" font-weight="600" font-size="${titleFontSize}" fill="${palette.text}">${this.escapeXml(line)}</text>`;
}).join('\n');
const authorLineHeight = authorFontSize * 1.3;
const authorStartY = height - 50 - ((authorLines.length - 1) * authorLineHeight);
const authorElements = authorLines.map((line, index) => {
const y = authorStartY + (index * authorLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="${authorFontSize}" fill="${palette.textSecondary}">${this.escapeXml(line)}</text>`;
}).join('\n');
const decorY = titleStartY + (titleLines.length * titleLineHeight) + 20;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
<defs>
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${palette.bg1}"/>
<stop offset="100%" style="stop-color:${palette.bg2}"/>
</linearGradient>
<linearGradient id="spineGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgba(0,0,0,0.4)"/>
<stop offset="100%" style="stop-color:rgba(0,0,0,0)"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#bgGrad)"/>
<rect x="0" y="0" width="12" height="100%" fill="url(#spineGrad)"/>
<rect x="20" y="20" width="${width - 40}" height="${height - 40}" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.4" rx="2"/>
<rect x="25" y="25" width="${width - 50}" height="${height - 50}" fill="none" stroke="${palette.accent}" stroke-width="0.5" opacity="0.2" rx="1"/>
${titleElements}
<line x1="80" y1="${decorY}" x2="170" y2="${decorY}" stroke="${palette.accent}" stroke-width="2" stroke-linecap="round"/>
<circle cx="125" cy="${decorY}" r="3" fill="${palette.accent}"/>
${authorElements}
<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>
</svg>`;
return this.svgToDataUrl(svg);
}
private generateAudiobookCover(width: number, height: number, hash: number): string {
const palettes = [
{bg1: '#667eea', bg2: '#764ba2', accent: '#ffffff', text: '#ffffff', textSecondary: '#e8e8e8'},
{bg1: '#f093fb', bg2: '#f5576c', accent: '#ffffff', text: '#ffffff', textSecondary: '#ffeaea'},
{bg1: '#4facfe', bg2: '#00f2fe', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#43e97b', bg2: '#38f9d7', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#fa709a', bg2: '#fee140', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#a18cd1', bg2: '#fbc2eb', accent: '#ffffff', text: '#2d3436', textSecondary: '#4a4a4a'},
];
const palette = palettes[hash % palettes.length];
const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(true);
const titleLineHeight = titleFontSize * 1.3;
const titleStartY = 70;
const titleElements = titleLines.map((line, index) => {
const y = titleStartY + (index * titleLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-weight="700" font-size="${titleFontSize}" fill="${palette.text}">${this.escapeXml(line)}</text>`;
}).join('\n');
const authorLineHeight = authorFontSize * 1.3;
const authorStartY = height - 40 - ((authorLines.length - 1) * authorLineHeight);
const authorElements = authorLines.map((line, index) => {
const y = authorStartY + (index * authorLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="${authorFontSize}" fill="${palette.textSecondary}">${this.escapeXml(line)}</text>`;
}).join('\n');
const iconY = titleStartY + (titleLines.length * titleLineHeight) + 25;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
<defs>
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${palette.bg1}"/>
<stop offset="100%" style="stop-color:${palette.bg2}"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#bgGrad)"/>
<circle cx="125" cy="125" r="100" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.15"/>
<circle cx="125" cy="125" r="80" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.1"/>
${titleElements}
<g transform="translate(125, ${iconY})" opacity="0.9">
<circle cx="0" cy="0" r="18" fill="none" stroke="${palette.accent}" stroke-width="2" opacity="0.6"/>
<path d="M-6,-8 L-6,8 L8,0 Z" fill="${palette.accent}" opacity="0.8"/>
</g>
${authorElements}
</svg>`;
return this.svgToDataUrl(svg);
}
private processText(isSquare: boolean): {
titleLines: string[];
authorLines: string[];
titleFontSize: number;
authorFontSize: number;
} {
const maxTitleLength = 60;
const maxAuthorLength = 40;
const truncatedTitle = this.truncateText(this.title, maxTitleLength);
const truncatedAuthor = this.truncateText(this.author, maxAuthorLength);
const maxLineLength = 12;
const maxTitleLines = 4;
const maxAuthorLines = 3;
const maxLineLength = 14;
const maxTitleLines = isSquare ? 3 : 4;
const maxAuthorLines = isSquare ? 2 : 3;
let titleLines = this.wrapText(truncatedTitle, maxLineLength);
let authorLines = this.wrapText(truncatedAuthor, maxLineLength);
@@ -77,49 +211,24 @@ export class CoverGeneratorComponent {
const titleFontSize = this.calculateTitleFontSize(titleLines.length);
const authorFontSize = this.calculateAuthorFontSize(authorLines.length);
const titleLineHeight = titleFontSize * 1.2;
const titlePadding = 15;
const titleBoxHeight = titleLines.length * titleLineHeight + (titlePadding * 2);
return {titleLines, authorLines, titleFontSize, authorFontSize};
}
const titleElements = titleLines.map((line, index) => {
const y = 40 + titlePadding + titleFontSize + (index * titleLineHeight);
return `<text x="20" y="${y}" font-family="serif" font-size="${titleFontSize}" fill="#000000">${line}</text>`;
}).join('\n');
private calculateTitleFontSize(lineCount: number): number {
if (lineCount <= 2) return 28;
if (lineCount === 3) return 24;
return 20;
}
const titleWithBackground = `
<rect x="0" y="40" width="100%" height="${titleBoxHeight}" fill="url(#titleGradient)" />
${titleElements}
`;
private calculateAuthorFontSize(lineCount: number): number {
if (lineCount <= 2) return 18;
return 16;
}
const authorLineHeight = authorFontSize * 1.2;
const authorStartY = 330 - (authorLines.length - 1) * authorLineHeight;
const authorElements = authorLines.map((line, index) => {
const y = authorStartY + index * authorLineHeight;
return `<text x="230" y="${y}" text-anchor="end" font-family="sans-serif" font-size="${authorFontSize}" fill="#000000">${line}</text>`;
}).join('\n');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="250" height="350" viewBox="0 0 250 350">
<defs>
<linearGradient id="titleGradient" >
<stop style="stop-color:#dddddd;stop-opacity:1;" offset="0" id="stop1" />
<stop style="stop-color:#dfdfdf;stop-opacity:0.6;" offset="1" id="stop2" />
</linearGradient>
<linearGradient id="pageGradient">
<stop style="stop-color:#557766;stop-opacity:1;" offset="0" id="stop8" />
<stop style="stop-color:#669988;stop-opacity:1;" offset="1" id="stop9" />
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#pageGradient)" />
${titleWithBackground}
${authorElements}
</svg>
`;
const base64 = btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (match, p1) => {
private svgToDataUrl(svg: string): string {
const base64 = btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (_, p1) => {
return String.fromCharCode(parseInt(p1, 16));
}));
return `data:image/svg+xml;base64,${base64}`;
}
}
@@ -1,6 +1,6 @@
import {MetadataProviderSpecificFields} from '../model/app-settings.model';
export type FieldType = 'string' | 'number' | 'array' | 'textarea';
export type FieldType = 'string' | 'number' | 'array' | 'textarea' | 'boolean';
export interface MetadataFieldConfig {
label: string;
@@ -43,12 +43,23 @@ export const ALL_METADATA_FIELDS: MetadataFieldConfig[] = [
{label: 'LB ID', controlName: 'lubimyczytacId', lockedKey: 'lubimyczytacIdLocked', fetchedKey: 'lubimyczytacId', type: 'string', providerKey: 'lubimyczytacId'},
{label: 'LB ★', controlName: 'lubimyczytacRating', lockedKey: 'lubimyczytacRatingLocked', fetchedKey: 'lubimyczytacRating', type: 'number', providerKey: 'lubimyczytacRating'},
{label: 'Ranobedb ID', controlName: 'ranobedbId', lockedKey: 'ranobedbIdLocked', fetchedKey: 'ranobedbId', type: 'string', providerKey: 'ranobedbId'},
{label: 'Ranobedb ★', controlName: 'ranobedbRating', lockedKey: 'ranobedbRatingLocked', fetchedKey: 'ranobedbRating', type: 'number', providerKey: 'ranobedbRating'}
{label: 'Ranobedb ★', controlName: 'ranobedbRating', lockedKey: 'ranobedbRatingLocked', fetchedKey: 'ranobedbRating', type: 'number', providerKey: 'ranobedbRating'},
{label: 'Audible ID', controlName: 'audibleId', lockedKey: 'audibleIdLocked', fetchedKey: 'audibleId', type: 'string', providerKey: 'audibleId'},
{label: 'Audible ★', controlName: 'audibleRating', lockedKey: 'audibleRatingLocked', fetchedKey: 'audibleRating', type: 'number', providerKey: 'audibleRating'},
{label: 'Audible #', controlName: 'audibleReviewCount', lockedKey: 'audibleReviewCountLocked', fetchedKey: 'audibleReviewCount', type: 'number', providerKey: 'audibleReviewCount'}
];
// Audiobook content metadata fields (narrator/abridged) - now stored at top level of BookMetadata
export const AUDIOBOOK_METADATA_FIELDS: MetadataFieldConfig[] = [
{label: 'Narrator', controlName: 'narrator', lockedKey: 'narratorLocked', fetchedKey: 'narrator', type: 'string'},
{label: 'Abridged', controlName: 'abridged', lockedKey: 'abridgedLocked', fetchedKey: 'abridged', type: 'boolean'}
];
export const TOP_FIELD_NAMES = ['title', 'subtitle', 'publisher', 'publishedDate'];
export const ARRAY_FIELD_NAMES = ['authors', 'categories', 'moods', 'tags'];
export const TEXTAREA_FIELD_NAMES = ['description'];
export const SERIES_FIELD_NAMES = ['seriesName', 'seriesNumber', 'seriesTotal'];
export const BOOK_DETAILS_FIELD_NAMES = ['language', 'isbn10', 'isbn13', 'pageCount'];
export function getTopFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => TOP_FIELD_NAMES.includes(f.controlName));
@@ -62,6 +73,26 @@ export function getTextareaFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => f.type === 'textarea');
}
export function getSeriesFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => SERIES_FIELD_NAMES.includes(f.controlName));
}
export function getBookDetailsFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => BOOK_DETAILS_FIELD_NAMES.includes(f.controlName));
}
export function getProviderFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] {
const providerFields = ALL_METADATA_FIELDS.filter(f => !!f.providerKey);
if (enabledProviderFields) {
return providerFields.filter(field =>
!field.providerKey || enabledProviderFields[field.providerKey]
);
}
return providerFields;
}
export function getBottomFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] {
const bottomFields = ALL_METADATA_FIELDS.filter(f =>
!TOP_FIELD_NAMES.includes(f.controlName) &&
@@ -1,6 +1,6 @@
import {Injectable} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
import {ALL_METADATA_FIELDS, MetadataFieldConfig} from './metadata-field.config';
import {ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, MetadataFieldConfig} from './metadata-field.config';
@Injectable({
providedIn: 'root'
@@ -22,9 +22,20 @@ export class MetadataFormBuilder {
}
}
// Add audiobook-specific metadata fields
for (const field of AUDIOBOOK_METADATA_FIELDS) {
const defaultValue = this.getDefaultValue(field.type);
controls[field.controlName] = new FormControl(defaultValue);
if (includeLockedControls) {
controls[field.lockedKey] = new FormControl(false);
}
}
controls['thumbnailUrl'] = new FormControl('');
controls['audiobookThumbnailUrl'] = new FormControl('');
if (includeLockedControls) {
controls['coverLocked'] = new FormControl(false);
controls['audiobookCoverLocked'] = new FormControl(false);
}
return new FormGroup(controls);
@@ -36,6 +47,8 @@ export class MetadataFormBuilder {
return [];
case 'number':
return null;
case 'boolean':
return null;
default:
return '';
}
@@ -52,11 +65,19 @@ export class MetadataFormBuilder {
}
}
// Apply locks for standard fields
for (const field of fields) {
if (lockedFields[field.lockedKey]) {
metadataForm.get(field.controlName)?.disable({emitEvent: false});
}
}
// Apply locks for audiobook metadata fields
for (const field of AUDIOBOOK_METADATA_FIELDS) {
if (lockedFields[field.lockedKey]) {
metadataForm.get(field.controlName)?.disable({emitEvent: false});
}
}
}
setAllFieldsLocked(metadataForm: FormGroup, locked: boolean): void {
@@ -117,6 +117,7 @@ export class MetadataUtilsService {
copiedFields: Record<string, boolean>,
hoveredFields?: Record<string, boolean>
): void {
// All fields including narrator/abridged are now at top level of BookMetadata
metadataForm.get(field)?.setValue(originalMetadata?.[field as keyof BookMetadata]);
copiedFields[field] = false;
if (hoveredFields) {
@@ -54,6 +54,7 @@ export interface MetadataProviderSettings {
comicvine: Comicvine;
douban: Douban;
lubimyczytac: Lubimyczytac;
audible: Audible;
}
export interface Amazon {
@@ -93,6 +94,11 @@ export interface Lubimyczytac {
enabled: boolean;
}
export interface Audible {
enabled: boolean;
domain: string;
}
export interface FormatWriteSettings {
enabled: boolean;
maxFileSizeInMb: number;
@@ -102,6 +108,7 @@ export interface SaveToOriginalFileSettings {
epub: FormatWriteSettings;
pdf: FormatWriteSettings;
cbx: FormatWriteSettings;
audiobook: FormatWriteSettings;
}
export interface MetadataPersistenceSettings {
@@ -181,6 +188,9 @@ export interface MetadataProviderSpecificFields {
lubimyczytacRating: boolean;
ranobedbId: boolean;
ranobedbRating: boolean;
audibleId: boolean;
audibleRating: boolean;
audibleReviewCount: boolean;
}
export enum AppSettingKey {
@@ -72,6 +72,42 @@ export class UrlHelperService {
return this.appendToken(url);
}
getAudiobookCoverUrl(bookId: number, audiobookCoverUpdatedOn?: string): string {
if (!audiobookCoverUpdatedOn) {
const book = this.bookService.getBookByIdFromState(bookId);
if (book && book.metadata) {
const coverGenerator = new CoverGeneratorComponent();
coverGenerator.title = book.metadata.title || '';
coverGenerator.author = (book.metadata.authors || []).join(', ');
coverGenerator.isSquare = true;
return coverGenerator.generateCover();
}
}
let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-cover`;
if (audiobookCoverUpdatedOn) {
url += `?${audiobookCoverUpdatedOn}`;
}
return this.appendToken(url);
}
getAudiobookThumbnailUrl(bookId: number, audiobookCoverUpdatedOn?: string): string {
if (!audiobookCoverUpdatedOn) {
const book = this.bookService.getBookByIdFromState(bookId);
if (book && book.metadata) {
const coverGenerator = new CoverGeneratorComponent();
coverGenerator.title = book.metadata.title || '';
coverGenerator.author = (book.metadata.authors || []).join(', ');
coverGenerator.isSquare = true;
return coverGenerator.generateCover();
}
}
let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-thumbnail`;
if (audiobookCoverUpdatedOn) {
url += `?${audiobookCoverUpdatedOn}`;
}
return this.appendToken(url);
}
getBookdropCoverUrl(bookdropId: number): string {
const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`;
return this.appendToken(url);
@@ -14,7 +14,7 @@ export interface CoverImage {
export interface CoverFetchRequest {
title?: string;
author?: string;
squareCover?: boolean;
coverType?: 'ebook' | 'audiobook';
}
@Injectable({