Organize code

This commit is contained in:
aditya.chandel
2025-10-12 02:09:57 -06:00
parent 7c9bd56f63
commit 4453115149
50 changed files with 30 additions and 30 deletions
@@ -0,0 +1,37 @@
<div class="rounded-xl overflow-hidden">
<p-tabs [value]="tab" lazy="true" scrollable>
<p-tablist>
<p-tab value="view">
<i [class]="'pi pi-book'"></i>
Book Details
</p-tab>
@if (admin || canEditMetadata) {
<p-tab value="edit">
<i [class]="'pi pi-pencil'"></i>
Edit Metadata
</p-tab>
}
@if (admin || canEditMetadata) {
<p-tab value="match">
<i [class]="'pi pi-search'"></i>
Search Metadata
</p-tab>
}
</p-tablist>
<p-tabpanels class="tabpanels-responsive overflow-auto">
<p-tabpanel value="view">
<app-metadata-viewer [book$]="book$" [recommendedBooks]="recommendedBooks"></app-metadata-viewer>
</p-tabpanel>
@if (admin || canEditMetadata) {
<p-tabpanel value="edit">
<app-metadata-editor [book$]="book$"></app-metadata-editor>
</p-tabpanel>
}
@if (admin || canEditMetadata) {
<p-tabpanel value="match">
<app-metadata-searcher [book$]="book$"></app-metadata-searcher>
</p-tabpanel>
}
</p-tabpanels>
</p-tabs>
</div>
@@ -0,0 +1,9 @@
.tabpanels-responsive {
height: calc(100dvh - 9.7rem);
}
@media (max-width: 768px) {
.tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
}
@@ -0,0 +1,148 @@
import {Component, inject, OnDestroy, OnInit, Optional} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {UserService} from '../../../settings/user-management/user.service';
import {Book, BookRecommendation} from '../../../book/model/book.model';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {distinctUntilChanged, filter, map, shareReplay, switchMap, take, takeUntil,} from 'rxjs/operators';
import {BookService} from '../../../book/service/book.service';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {Tab, TabList, TabPanel, TabPanels, Tabs,} from 'primeng/tabs';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host-service';
import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component';
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
@Component({
selector: 'app-book-metadata-center',
standalone: true,
templateUrl: './book-metadata-center.component.html',
imports: [
Tabs,
TabList,
Tab,
TabPanels,
TabPanel,
MetadataViewerComponent,
MetadataEditorComponent,
MetadataSearcherComponent
],
styleUrls: ['./book-metadata-center.component.scss'],
})
export class BookMetadataCenterComponent implements OnInit, OnDestroy {
private route = inject(ActivatedRoute);
private bookService = inject(BookService);
private userService = inject(UserService);
private appSettingsService = inject(AppSettingsService);
private metadataHostService = inject(BookMetadataHostService);
private destroy$ = new Subject<void>();
book$!: Observable<Book>;
recommendedBooks: BookRecommendation[] = [];
tab: string = 'view';
canEditMetadata: boolean = false;
admin: boolean = false;
private appSettings$ = this.appSettingsService.appSettings$;
private currentBookId$ = new BehaviorSubject<number | null>(null);
constructor(
@Optional() private config?: DynamicDialogConfig,
@Optional() private ref?: DynamicDialogRef
) {
}
ngOnInit(): void {
const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
if (bookIdFromDialog != null) {
this.currentBookId$.next(bookIdFromDialog);
} else {
this.route.paramMap
.pipe(
map(params => Number(params.get('bookId'))),
filter(bookId => !isNaN(bookId)),
takeUntil(this.destroy$)
)
.subscribe(bookId => this.currentBookId$.next(bookId));
}
this.metadataHostService.bookSwitches$
.pipe(
filter((bookId): bookId is number => !!bookId),
distinctUntilChanged(),
takeUntil(this.destroy$)
)
.subscribe(bookId => {
this.currentBookId$.next(bookId);
});
this.book$ = this.currentBookId$.pipe(
filter((bookId): bookId is number => bookId != null),
distinctUntilChanged(),
switchMap(bookId =>
this.bookService.bookState$.pipe(
map(state => state.books?.find(b => b.id === bookId)),
filter((book): book is Book => !!book && !!book.metadata),
switchMap(book =>
this.bookService.getBookByIdFromAPI(book.id, true)
)
)
),
takeUntil(this.destroy$),
shareReplay(1)
);
this.currentBookId$
.pipe(
filter((id): id is number => id != null),
takeUntil(this.destroy$)
)
.subscribe(bookId => this.fetchBookRecommendationsIfNeeded(bookId));
this.route.queryParamMap
.pipe(
map(params => params.get('tab') ?? 'view'),
distinctUntilChanged(),
takeUntil(this.destroy$)
)
.subscribe(tab => {
const validTabs = ['view', 'edit', 'match'];
this.tab = validTabs.includes(tab) ? tab : 'view';
});
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
)
.subscribe(userState => {
this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false;
this.admin = userState.user?.permissions?.admin ?? false;
});
}
private fetchBookRecommendationsIfNeeded(bookId: number): void {
this.appSettings$
.pipe(
filter(settings => settings != null),
take(1)
)
.subscribe(settings => {
if (settings!.similarBookRecommendation ?? false) {
this.bookService
.getBookRecommendations(bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(recommendations => {
this.recommendedBooks = recommendations.sort(
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
);
});
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -0,0 +1,573 @@
@if (book$ | async; as book) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="flex flex-col h-full md:min-w-[90rem]">
@if (isLoading) {
<div class="absolute inset-0 bg-black opacity-25 z-10 "></div>
}
@if (isLoading) {
<p-progressSpinner [style]="{position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)'}"></p-progressSpinner>
}
<div class="flex-grow overflow-auto md:py-2 md:px-2 ">
<div class="flex flex-col md:flex-row w-full gap-4">
<div class="flex flex-col items-center gap-0 relative">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Image"
width="250"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
@if (isUploading) {
<p-progressSpinner
class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-10">
</p-progressSpinner>
}
<div class="flex items-center gap-2 pt-4">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['coverLocked']">
</p-button>
<p-button
[disabled]="book.metadata!['coverLocked']"
outlined
size="small"
icon="pi pi-search"
label="Search"
(onClick)="openCoverSearch()"
pTooltip="Search for cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined'"
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"
chooseLabel="Upload"
(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="flex flex-col flex-grow md:pl-2">
<div class="flex flex-col md:flex-row w-full gap-4 pb-1">
<div class="flex flex-col gap-1 md:w-2/3">
<label class="text-sm" for="title">Title</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="title" formControlName="title" class="w-full"/>
@if (!book.metadata!['titleLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('title')" severity="success"></p-button>
}
@if (book.metadata!['titleLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('title')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/3">
<label class="text-sm" for="subtitle">Subtitle</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="subtitle" formControlName="subtitle" class="w-full"/>
@if (!book.metadata!['subtitleLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('subtitle')" severity="success"></p-button>
}
@if (book.metadata!['subtitleLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('subtitle')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 md:basis-[71%]">
<label class="text-sm" for="authors">Authors</label>
<div class="flex justify-between items-center gap-2">
<p-autoComplete
class="w-full"
formControlName="authors"
[multiple]="true"
[dropdown]="false"
[suggestions]="filteredAuthors"
[forceSelection]="false"
[showClear]="true"
(completeMethod)="filterAuthors($event)"
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
(onSelect)="onAutoCompleteSelect('authors', $event)">
</p-autoComplete>
@if (!book.metadata!['authorsLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('authors')" severity="success"></p-button>
}
@if (book.metadata!['authorsLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('authors')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[20%]">
<label class="text-sm" for="publisher">Publisher</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="publisher" formControlName="publisher" class="w-full"/>
@if (!book.metadata!['publisherLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('publisher')" severity="success"></p-button>
}
@if (book.metadata!['publisherLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('publisher')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[14%]">
<label class="text-sm" for="language">Language</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="language" formControlName="language" class="w-full"/>
@if (!book.metadata!['languageLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('language')" severity="success"></p-button>
}
@if (book.metadata!['languageLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('language')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 w-full">
<label class="text-sm" for="categories">Genres</label>
<div class="flex justify-between items-center gap-2">
<div class="w-full">
<p-autoComplete
class="w-full"
formControlName="categories"
[multiple]="true"
[dropdown]="false"
[suggestions]="filteredCategories"
[forceSelection]="false"
[showClear]="true"
(completeMethod)="filterCategories($event)"
(onKeyUp)="onAutoCompleteKeyUp('categories', $event)"
(onSelect)="onAutoCompleteSelect('categories', $event)">
</p-autoComplete>
</div>
@if (!book.metadata!['categoriesLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('categories')" severity="success"></p-button>
}
@if (book.metadata!['categoriesLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('categories')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 w-full">
<label class="text-sm" for="moods">Moods</label>
<div class="flex justify-between items-center gap-2">
<div class="w-full">
<p-autoComplete
class="w-full"
formControlName="moods"
[multiple]="true"
[dropdown]="false"
[suggestions]="filteredMoods"
[forceSelection]="false"
[showClear]="true"
(completeMethod)="filterMoods($event)"
(onKeyUp)="onAutoCompleteKeyUp('moods', $event)"
(onSelect)="onAutoCompleteSelect('moods', $event)">
</p-autoComplete>
</div>
@if (!book.metadata!['moodsLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('moods')" severity="success"></p-button>
}
@if (book.metadata!['moodsLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('moods')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 w-full">
<label class="text-sm" for="tags">Tags</label>
<div class="flex justify-between items-center gap-2">
<div class="w-full">
<p-autoComplete
class="w-full"
formControlName="tags"
[multiple]="true"
[dropdown]="false"
[suggestions]="filteredTags"
[forceSelection]="false"
[showClear]="true"
(completeMethod)="filterTags($event)"
(onKeyUp)="onAutoCompleteKeyUp('tags', $event)"
(onSelect)="onAutoCompleteSelect('tags', $event)">
</p-autoComplete>
</div>
@if (!book.metadata!['tagsLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('tags')" severity="success"></p-button>
}
@if (book.metadata!['tagsLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('tags')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 md:basis-[75%]">
<label class="text-sm" for="seriesName">Series Name</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="seriesName" formControlName="seriesName" class="w-full"/>
@if (!book.metadata!['seriesNameLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesName')" severity="success"></p-button>
}
@if (book.metadata!['seriesNameLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesName')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[10%]">
<label class="text-sm" for="seriesNumber">Book #</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="seriesNumber" formControlName="seriesNumber" class="w-full min-w-12"/>
@if (!book.metadata!['seriesNumberLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesNumber')" severity="success"></p-button>
}
@if (book.metadata!['seriesNumberLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesNumber')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[10%]">
<label class="text-sm" for="seriesTotal">Total Books</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="seriesTotal" formControlName="seriesTotal" class="w-full min-w-12"/>
@if (!book.metadata!['seriesTotalLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesTotal')" severity="success"></p-button>
}
@if (book.metadata!['seriesTotalLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesTotal')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[10%]">
<label class="text-sm" for="pageCount">Pages</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="pageCount" formControlName="pageCount" class="w-full min-w-16"/>
@if (!book.metadata!['pageCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('pageCount')" severity="success"></p-button>
}
@if (book.metadata!['pageCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('pageCount')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:basis-[15%]">
<label class="text-sm" for="publishedDate">Publish Date</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="publishedDate" formControlName="publishedDate" class="w-full min-w-32"/>
@if (!book.metadata!['publishedDateLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('publishedDate')" severity="success"></p-button>
}
@if (book.metadata!['publishedDateLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('publishedDate')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="isbn10">ISBN 10</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="isbn10" formControlName="isbn10" class="w-full"/>
@if (!book.metadata!['isbn10Locked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('isbn10')" severity="success"></p-button>
}
@if (book.metadata!['isbn10Locked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('isbn10')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="isbn13">ISBN 13</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="isbn13" formControlName="isbn13" class="w-full"/>
@if (!book.metadata!['isbn13Locked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('isbn13')" severity="success"></p-button>
}
@if (book.metadata!['isbn13Locked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('isbn13')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="asin">ASIN (Amazon ID)</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="asin" formControlName="asin" class="w-full"/>
@if (!book.metadata!['asinLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
}
@if (book.metadata!['asinLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="amazonRating">Amazon ★</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="amazonRating" formControlName="amazonRating" class="w-full"/>
@if (!book.metadata!['amazonRatingLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="success"></p-button>
}
@if (book.metadata!['amazonRatingLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="amazonRatingCount">Amazon Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="amazonRatingCount" formControlName="amazonReviewCount" class="w-full"/>
@if (!book.metadata!['amazonReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="success"></p-button>
}
@if (book.metadata!['amazonReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="googleId">Google Books ID</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="googleId" formControlName="googleId" class="w-full"/>
@if (!book.metadata!['googleIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('googleId')" severity="success"></p-button>
}
@if (book.metadata!['googleIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('googleId')" severity="warn"></p-button>
}
</div>
</div>
</div>
<div class="flex flex-col md:flex-row w-full gap-4 mt-2 pb-1">
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="goodreadsId">Goodreads ID</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="goodreadsId" formControlName="goodreadsId" class="w-full"/>
@if (!book.metadata!['goodreadsIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="success"></p-button>
}
@if (book.metadata!['goodreadsIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="goodreadsRating">Goodreads ★</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="goodreadsRating" formControlName="goodreadsRating" class="w-full"/>
@if (!book.metadata!['goodreadsRatingLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="success"></p-button>
}
@if (book.metadata!['goodreadsRatingLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="goodreadsReviewCount">Goodreads Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="goodreadsReviewCount" formControlName="goodreadsReviewCount" class="w-full"/>
@if (!book.metadata!['goodreadsReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="success"></p-button>
}
@if (book.metadata!['goodreadsReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="hardcoverId">Hardcover ID</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="hardcoverId" formControlName="hardcoverId" class="w-full"/>
@if (!book.metadata!['hardcoverIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="success"></p-button>
}
@if (book.metadata!['hardcoverIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="hardcoverRating">Hardcover ★</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="hardcoverRating" formControlName="hardcoverRating" class="w-full"/>
@if (!book.metadata!['hardcoverRatingLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="success"></p-button>
}
@if (book.metadata!['hardcoverRatingLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 md:w-1/6">
<label class="text-sm" for="hardcoverReviewCount">Hardcover Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="hardcoverReviewCount" formControlName="hardcoverReviewCount" class="w-full"/>
@if (!book.metadata!['hardcoverReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="success"></p-button>
}
@if (book.metadata!['hardcoverReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="warn"></p-button>
}
</div>
</div>
<div class="flex flex-col gap-1 w-1/6">
<label class="text-sm" for="comicvineId">Comicvine ID</label>
<div class="flex justify-between items-center gap-2">
<input pSize="small" pInputText id="comicvineId" formControlName="comicvineId" class="w-full"/>
@if (!book.metadata!['comicvineIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="success"></p-button>
}
@if (book.metadata!['comicvineIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="warn"></p-button>
}
</div>
</div>
</div>
</div>
</div>
<div class="flex pt-8 w-full justify-between items-center gap-2">
<p-iftalabel class="flex w-full">
<textarea
id="description"
pTextarea
formControlName="description"
rows="12"
class="w-full">
</textarea>
<label for="description">Description</label>
</p-iftalabel>
@if (!book.metadata!['descriptionLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success"></p-button>
}
@if (book.metadata!['descriptionLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn"></p-button>
}
</div>
</div>
<div class="mt-auto">
<p-divider></p-divider>
<div class="flex flex-col gap-2 px-0 md:px-2 pt-4 md:pb-4 z-10">
<!-- Desktop Buttons -->
<div class="hidden sm:flex justify-between w-full gap-4">
@if (showNavigationButtons) {
<div class="flex gap-x-4">
<p-button label="Close" icon="pi pi-times" [outlined]="true" severity="danger" (onClick)="closeDialog()"></p-button>
<p-divider layout="vertical"/>
<p-button label="Previous Book" [disabled]="disablePrevious" icon="pi pi-arrow-left" [outlined]="true" severity="info" (onClick)="onPrevious()"></p-button>
<p-button label="Next Book" [disabled]="disableNext" icon="pi pi-arrow-right" iconPos="right" [outlined]="true" severity="info" (onClick)="onNext()"></p-button>
</div>
}
<div class="flex gap-x-4 items-center ml-auto">
<p-button
[label]="isAutoFetching ? 'Fetching…' : 'Auto Fetch'"
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
[outlined]="true"
severity="info"
(onClick)="autoFetch(book.id)"
[disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top">
</p-button>
<p-divider layout="vertical"/>
<p-button label="Unlock All" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()" pTooltip="Unlock all metadata fields for editing" tooltipPosition="top"></p-button>
<p-button label="Lock All" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()" pTooltip="Lock all metadata fields to prevent changes" tooltipPosition="top"></p-button>
<p-divider layout="vertical"/>
<p-button label="Save" icon="pi pi-check" [loading]="isSaving" [disabled]="isSaving" type="submit"></p-button>
</div>
</div>
<!-- Mobile Buttons -->
<div class="flex sm:hidden justify-between w-full flex-wrap">
@if (showNavigationButtons) {
<div class="flex gap-2 flex-wrap">
<p-button size="small" icon="pi pi-times" [outlined]="true" severity="danger" (onClick)="closeDialog()" pTooltip="Close" tooltipPosition="top"></p-button>
<p-button size="small" icon="pi pi-arrow-left" [disabled]="disablePrevious" [outlined]="true" severity="info" (onClick)="onPrevious()" pTooltip="Previous Book" tooltipPosition="top"></p-button>
<p-button size="small" icon="pi pi-arrow-right" [disabled]="disableNext" iconPos="right" [outlined]="true" severity="info" (onClick)="onNext()" pTooltip="Next Book" tooltipPosition="top"></p-button>
</div>
}
<div class="flex justify-between items-center w-full gap-4">
<div class="flex gap-4">
<p-button
icon="pi pi-bolt"
[outlined]="true"
severity="info"
(onClick)="autoFetch(book.id)"
[disabled]="isAutoFetching"
pTooltip="Auto Fetch"
tooltipPosition="top">
</p-button>
<p-button
icon="pi pi-lock-open"
[outlined]="true"
severity="success"
(onClick)="unlockAll()"
pTooltip="Unlock All"
tooltipPosition="top">
</p-button>
<p-button
icon="pi pi-lock"
[outlined]="true"
severity="warn"
(onClick)="lockAll()"
pTooltip="Lock All"
tooltipPosition="top">
</p-button>
</div>
<div>
<p-button
label="Save"
icon="pi pi-check"
[loading]="isSaving"
[disabled]="isSaving"
type="submit">
</p-button>
</div>
</div>
</div>
</div>
</div>
</form>
}
@@ -0,0 +1,11 @@
::ng-deep .p-tabpanels .custom-tab-padding {
padding: 1rem 0rem 0rem 0.5rem !important;
@media (min-width: 640px) {
padding: var(--p-tabs-tabpanel-padding) !important;
}
}
::ng-deep .p-autocomplete .p-chip .p-chip-label {
font-size: 12px;
}
@@ -0,0 +1,671 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output,} from "@angular/core";
import {InputText} from "primeng/inputtext";
import {Button} from "primeng/button";
import {Divider} from "primeng/divider";
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule,} from "@angular/forms";
import {Observable} from "rxjs";
import {AsyncPipe} from "@angular/common";
import {MessageService} from "primeng/api";
import {Book, BookMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
import {FileUpload, FileUploadErrorEvent, FileUploadEvent,} from "primeng/fileupload";
import {HttpResponse} from "@angular/common/http";
import {BookService} from "../../../../book/service/book.service";
import {ProgressSpinner} from "primeng/progressspinner";
import {Tooltip} from "primeng/tooltip";
import {filter, take} from "rxjs/operators";
import {DialogService} from "primeng/dynamicdialog";
import {takeUntilDestroyed} from "@angular/core/rxjs-interop";
import {MetadataRefreshRequest} from "../../../model/request/metadata-refresh-request.model";
import {MetadataRefreshType} from "../../../model/request/metadata-refresh-type.enum";
import {AutoComplete} from "primeng/autocomplete";
import {Textarea} from "primeng/textarea";
import {IftaLabel} from "primeng/iftalabel";
import {Image} from "primeng/image";
import {LazyLoadImageModule} from "ng-lazyload-image";
import {CoverSearchComponent} from '../../cover-search/cover-search.component';
@Component({
selector: "app-metadata-editor",
standalone: true,
templateUrl: "./metadata-editor.component.html",
styleUrls: ["./metadata-editor.component.scss"],
imports: [
InputText,
Button,
Divider,
FormsModule,
AsyncPipe,
ReactiveFormsModule,
FileUpload,
ProgressSpinner,
Tooltip,
AutoComplete,
Textarea,
IftaLabel,
Image,
LazyLoadImageModule,
],
})
export class MetadataEditorComponent implements OnInit {
@Input() book$!: Observable<Book | null>;
@Output() nextBookClicked = new EventEmitter<void>();
@Output() previousBookClicked = new EventEmitter<void>();
@Output() closeDialogButtonClicked = new EventEmitter<void>();
@Input() disableNext = false;
@Input() disablePrevious = false;
@Input() showNavigationButtons = false;
private messageService = inject(MessageService);
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
private dialogService = inject(DialogService);
private destroyRef = inject(DestroyRef);
metadataForm: FormGroup;
currentBookId!: number;
isUploading = false;
isLoading = false;
isSaving = false;
refreshingBookIds = new Set<number>();
isAutoFetching = false;
originalMetadata!: BookMetadata;
allAuthors!: string[];
allCategories!: string[];
allMoods!: string[];
allTags!: string[];
filteredCategories: string[] = [];
filteredAuthors: string[] = [];
filteredMoods: string[] = [];
filteredTags: string[] = [];
filterCategories(event: { query: string }) {
const query = event.query.toLowerCase();
this.filteredCategories = this.allCategories.filter((cat) =>
cat.toLowerCase().includes(query)
);
}
filterAuthors(event: { query: string }) {
const query = event.query.toLowerCase();
this.filteredAuthors = this.allAuthors.filter((cat) =>
cat.toLowerCase().includes(query)
);
}
filterMoods(event: { query: string }) {
const query = event.query.toLowerCase();
this.filteredMoods = this.allMoods.filter((mood) =>
mood.toLowerCase().includes(query)
);
}
filterTags(event: { query: string }) {
const query = event.query.toLowerCase();
this.filteredTags = this.allTags.filter((tag) =>
tag.toLowerCase().includes(query)
);
}
constructor() {
this.metadataForm = new FormGroup({
title: new FormControl(""),
subtitle: new FormControl(""),
authors: new FormControl(""),
categories: new FormControl(""),
moods: new FormControl(""),
tags: new FormControl(""),
publisher: new FormControl(""),
publishedDate: new FormControl(""),
isbn10: new FormControl(""),
isbn13: new FormControl(""),
description: new FormControl(""),
pageCount: new FormControl(""),
language: new FormControl(""),
asin: new FormControl(""),
personalRating: new FormControl(""),
amazonRating: new FormControl(""),
amazonReviewCount: new FormControl(""),
goodreadsId: new FormControl(""),
comicvineId: new FormControl(""),
goodreadsRating: new FormControl(""),
goodreadsReviewCount: new FormControl(""),
hardcoverId: new FormControl(""),
hardcoverRating: new FormControl(""),
hardcoverReviewCount: new FormControl(""),
googleId: new FormControl(""),
seriesName: new FormControl(""),
seriesNumber: new FormControl(""),
seriesTotal: new FormControl(""),
thumbnailUrl: new FormControl(""),
titleLocked: new FormControl(false),
subtitleLocked: new FormControl(false),
authorsLocked: new FormControl(false),
categoriesLocked: new FormControl(false),
moodsLocked: new FormControl(false),
tagsLocked: new FormControl(false),
publisherLocked: new FormControl(false),
publishedDateLocked: new FormControl(false),
isbn10Locked: new FormControl(false),
isbn13Locked: new FormControl(false),
descriptionLocked: new FormControl(false),
pageCountLocked: new FormControl(false),
languageLocked: new FormControl(false),
asinLocked: new FormControl(false),
personalRatingLocked: new FormControl(false),
amazonRatingLocked: new FormControl(false),
amazonReviewCountLocked: new FormControl(false),
goodreadsIdLocked: new FormControl(""),
comicvineIdLocked: new FormControl(false),
goodreadsRatingLocked: new FormControl(false),
goodreadsReviewCountLocked: new FormControl(false),
hardcoverIdLocked: new FormControl(false),
hardcoverRatingLocked: new FormControl(false),
hardcoverReviewCountLocked: new FormControl(false),
googleIdLocked: new FormControl(false),
seriesNameLocked: new FormControl(false),
seriesNumberLocked: new FormControl(false),
seriesTotalLocked: new FormControl(false),
coverLocked: new FormControl(false),
});
}
ngOnInit(): void {
this.book$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((book) => {
const metadata = book?.metadata;
if (!metadata) return;
this.currentBookId = metadata.bookId;
if (this.refreshingBookIds.has(book.id)) {
this.refreshingBookIds.delete(book.id);
this.isAutoFetching = false;
}
this.originalMetadata = structuredClone(metadata);
this.populateFormFromMetadata(metadata);
});
this.bookService.bookState$
.pipe(
filter((bookState) => bookState.loaded),
take(1)
)
.subscribe((bookState) => {
const authors = new Set<string>();
const categories = new Set<string>();
const moods = new Set<string>();
const tags = new Set<string>();
(bookState.books ?? []).forEach((book) => {
book.metadata?.authors?.forEach((author) => authors.add(author));
book.metadata?.categories?.forEach((category) =>
categories.add(category)
);
book.metadata?.moods?.forEach((mood) => moods.add(mood));
book.metadata?.tags?.forEach((tag) => tags.add(tag));
});
this.allAuthors = Array.from(authors);
this.allCategories = Array.from(categories);
this.allMoods = Array.from(moods);
this.allTags = Array.from(tags);
});
}
private populateFormFromMetadata(metadata: BookMetadata): void {
this.metadataForm.patchValue({
title: metadata.title ?? null,
subtitle: metadata.subtitle ?? null,
authors: [...(metadata.authors ?? [])].sort(),
categories: [...(metadata.categories ?? [])].sort(),
moods: [...(metadata.moods ?? [])].sort(),
tags: [...(metadata.tags ?? [])].sort(),
publisher: metadata.publisher ?? null,
publishedDate: metadata.publishedDate ?? null,
isbn10: metadata.isbn10 ?? null,
isbn13: metadata.isbn13 ?? null,
description: metadata.description ?? null,
pageCount: metadata.pageCount ?? null,
language: metadata.language ?? null,
rating: metadata.rating ?? null,
reviewCount: metadata.reviewCount ?? null,
asin: metadata.asin ?? null,
personalRating: metadata.personalRating ?? null,
amazonRating: metadata.amazonRating ?? null,
amazonReviewCount: metadata.amazonReviewCount ?? null,
goodreadsId: metadata.goodreadsId ?? null,
comicvineId: metadata.comicvineId ?? null,
goodreadsRating: metadata.goodreadsRating ?? null,
goodreadsReviewCount: metadata.goodreadsReviewCount ?? null,
hardcoverId: metadata.hardcoverId ?? null,
hardcoverRating: metadata.hardcoverRating ?? null,
hardcoverReviewCount: metadata.hardcoverReviewCount ?? null,
googleId: metadata.googleId ?? null,
seriesName: metadata.seriesName ?? null,
seriesNumber: metadata.seriesNumber ?? null,
seriesTotal: metadata.seriesTotal ?? null,
titleLocked: metadata.titleLocked ?? false,
subtitleLocked: metadata.subtitleLocked ?? false,
authorsLocked: metadata.authorsLocked ?? false,
categoriesLocked: metadata.categoriesLocked ?? false,
moodsLocked: metadata.moodsLocked ?? false,
tagsLocked: metadata.tagsLocked ?? false,
publisherLocked: metadata.publisherLocked ?? false,
publishedDateLocked: metadata.publishedDateLocked ?? false,
isbn10Locked: metadata.isbn10Locked ?? false,
isbn13Locked: metadata.isbn13Locked ?? false,
descriptionLocked: metadata.descriptionLocked ?? false,
pageCountLocked: metadata.pageCountLocked ?? false,
languageLocked: metadata.languageLocked ?? false,
asinLocked: metadata.asinLocked ?? false,
personalRatingLocked: metadata.personalRatingLocked ?? false,
amazonRatingLocked: metadata.amazonRatingLocked ?? false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked ?? false,
goodreadsIdLocked: metadata.goodreadsIdLocked ?? false,
comicvineIdLocked: metadata.comicvineIdLocked ?? false,
goodreadsRatingLocked: metadata.goodreadsRatingLocked ?? false,
goodreadsReviewCountLocked: metadata.goodreadsReviewCountLocked ?? false,
hardcoverIdLocked: metadata.hardcoverIdLocked ?? false,
hardcoverRatingLocked: metadata.hardcoverRatingLocked ?? false,
hardcoverReviewCountLocked: metadata.hardcoverReviewCountLocked ?? false,
googleIdLocked: metadata.googleIdLocked ?? false,
seriesNameLocked: metadata.seriesNameLocked ?? false,
seriesNumberLocked: metadata.seriesNumberLocked ?? false,
seriesTotalLocked: metadata.seriesTotalLocked ?? false,
coverLocked: metadata.coverLocked ?? false,
});
const lockableFields: { key: keyof BookMetadata; control: string }[] = [
{key: "titleLocked", control: "title"},
{key: "subtitleLocked", control: "subtitle"},
{key: "authorsLocked", control: "authors"},
{key: "categoriesLocked", control: "categories"},
{key: "moodsLocked", control: "moods"},
{key: "tagsLocked", control: "tags"},
{key: "publisherLocked", control: "publisher"},
{key: "publishedDateLocked", control: "publishedDate"},
{key: "languageLocked", control: "language"},
{key: "isbn10Locked", control: "isbn10"},
{key: "isbn13Locked", control: "isbn13"},
{key: "asinLocked", control: "asin"},
{key: "amazonReviewCountLocked", control: "amazonReviewCount"},
{key: "amazonRatingLocked", control: "amazonRating"},
{key: "personalRatingLocked", control: "personalRating"},
{key: "goodreadsIdLocked", control: "goodreadsId"},
{key: "comicvineIdLocked", control: "comicvineId"},
{key: "goodreadsReviewCountLocked", control: "goodreadsReviewCount"},
{key: "goodreadsRatingLocked", control: "goodreadsRating"},
{key: "hardcoverIdLocked", control: "hardcoverId"},
{key: "hardcoverReviewCountLocked", control: "hardcoverReviewCount"},
{key: "hardcoverRatingLocked", control: "hardcoverRating"},
{key: "googleIdLocked", control: "googleId"},
{key: "pageCountLocked", control: "pageCount"},
{key: "descriptionLocked", control: "description"},
{key: "seriesNameLocked", control: "seriesName"},
{key: "seriesNumberLocked", control: "seriesNumber"},
{key: "seriesTotalLocked", control: "seriesTotal"},
{key: "coverLocked", control: "thumbnailUrl"},
];
for (const {key, control} of lockableFields) {
const isLocked = metadata[key] === true;
const formControl = this.metadataForm.get(control);
if (formControl) {
isLocked ? formControl.disable() : formControl.enable();
}
}
}
onAutoCompleteSelect(fieldName: string, event: any) {
const values = this.metadataForm.get(fieldName)?.value || [];
if (!values.includes(event.value)) {
this.metadataForm.get(fieldName)?.setValue([...values, event.value]);
}
(event.originalEvent.target as HTMLInputElement).value = "";
}
onAutoCompleteKeyUp(fieldName: string, event: KeyboardEvent) {
if (event.key === "Enter") {
const input = event.target as HTMLInputElement;
const value = input.value?.trim();
if (value) {
const values = this.metadataForm.get(fieldName)?.value || [];
if (!values.includes(value)) {
this.metadataForm.get(fieldName)?.setValue([...values, value]);
}
input.value = "";
}
}
}
onSave(): void {
this.isSaving = true;
this.bookService
.updateBookMetadata(
this.currentBookId,
this.buildMetadataWrapper(undefined),
false
)
.subscribe({
next: (response) => {
this.isSaving = false;
this.messageService.add({
severity: "info",
summary: "Success",
detail: "Book metadata updated",
});
},
error: (err) => {
this.isSaving = false;
this.messageService.add({
severity: "error",
summary: "Error",
detail: err?.error?.message || "Failed to update book metadata",
});
},
});
}
toggleLock(field: string): void {
if (field === "thumbnailUrl") {
field = "cover";
}
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 {
this.metadataForm.get(field)?.enable();
}
this.updateMetadata(undefined);
}
lockAll(): void {
Object.keys(this.metadataForm.controls).forEach((key) => {
if (key.endsWith("Locked")) {
this.metadataForm.get(key)?.setValue(true);
const fieldName = key.replace("Locked", "");
this.metadataForm.get(fieldName)?.disable();
}
});
this.updateMetadata(true);
}
unlockAll(): void {
Object.keys(this.metadataForm.controls).forEach((key) => {
if (key.endsWith("Locked")) {
this.metadataForm.get(key)?.setValue(false);
const fieldName = key.replace("Locked", "");
this.metadataForm.get(fieldName)?.enable();
}
});
this.updateMetadata(false);
}
quillDisabled(): boolean {
return this.metadataForm.get("descriptionLocked")?.value === true;
}
private buildMetadataWrapper(
shouldLockAllFields?: boolean
): MetadataUpdateWrapper {
const form = this.metadataForm;
const metadata: BookMetadata = {
bookId: this.currentBookId,
title: form.get("title")?.value,
subtitle: form.get("subtitle")?.value,
authors: form.get("authors")?.value ?? [],
categories: form.get("categories")?.value ?? [],
moods: form.get("moods")?.value ?? [],
tags: form.get("tags")?.value ?? [],
publisher: form.get("publisher")?.value,
publishedDate: form.get("publishedDate")?.value,
isbn10: form.get("isbn10")?.value,
isbn13: form.get("isbn13")?.value,
description: form.get("description")?.value,
pageCount: form.get("pageCount")?.value,
rating: form.get("rating")?.value,
reviewCount: form.get("reviewCount")?.value,
asin: form.get("asin")?.value,
personalRating: form.get("personalRating")?.value,
amazonRating: form.get("amazonRating")?.value,
amazonReviewCount: form.get("amazonReviewCount")?.value,
goodreadsId: form.get("goodreadsId")?.value,
comicvineId: form.get("comicvineId")?.value,
goodreadsRating: form.get("goodreadsRating")?.value,
goodreadsReviewCount: form.get("goodreadsReviewCount")?.value,
hardcoverId: form.get("hardcoverId")?.value,
hardcoverRating: form.get("hardcoverRating")?.value,
hardcoverReviewCount: form.get("hardcoverReviewCount")?.value,
googleId: form.get("googleId")?.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,
// Locks
titleLocked: form.get("titleLocked")?.value,
subtitleLocked: form.get("subtitleLocked")?.value,
authorsLocked: form.get("authorsLocked")?.value,
categoriesLocked: form.get("categoriesLocked")?.value,
moodsLocked: form.get("moodsLocked")?.value,
tagsLocked: form.get("tagsLocked")?.value,
publisherLocked: form.get("publisherLocked")?.value,
publishedDateLocked: form.get("publishedDateLocked")?.value,
isbn10Locked: form.get("isbn10Locked")?.value,
isbn13Locked: form.get("isbn13Locked")?.value,
descriptionLocked: form.get("descriptionLocked")?.value,
pageCountLocked: form.get("pageCountLocked")?.value,
languageLocked: form.get("languageLocked")?.value,
asinLocked: form.get("asinLocked")?.value,
amazonRatingLocked: form.get("amazonRatingLocked")?.value,
personalRatingLocked: form.get("personalRatingLocked")?.value,
amazonReviewCountLocked: form.get("amazonReviewCountLocked")?.value,
goodreadsIdLocked: form.get("goodreadsIdLocked")?.value,
comicvineIdLocked: form.get("comicvineIdLocked")?.value,
goodreadsRatingLocked: form.get("goodreadsRatingLocked")?.value,
goodreadsReviewCountLocked: form.get("goodreadsReviewCountLocked")?.value,
hardcoverIdLocked: form.get("hardcoverIdLocked")?.value,
hardcoverRatingLocked: form.get("hardcoverRatingLocked")?.value,
hardcoverReviewCountLocked: form.get("hardcoverReviewCountLocked")?.value,
googleIdLocked: form.get("googleIdLocked")?.value,
seriesNameLocked: form.get("seriesNameLocked")?.value,
seriesNumberLocked: form.get("seriesNumberLocked")?.value,
seriesTotalLocked: form.get("seriesTotalLocked")?.value,
coverLocked: form.get("coverLocked")?.value,
...(shouldLockAllFields !== undefined && {
allFieldsLocked: shouldLockAllFields,
}),
};
const original = this.originalMetadata;
const wasCleared = (key: keyof BookMetadata): boolean => {
const current = (metadata[key] as any) ?? null;
const prev = (original[key] as any) ?? null;
const isEmpty = (val: any): boolean =>
val === null || val === "" || (Array.isArray(val) && val.length === 0);
return isEmpty(current) && !isEmpty(prev);
};
const clearFlags: MetadataClearFlags = {
title: wasCleared("title"),
subtitle: wasCleared("subtitle"),
authors: wasCleared("authors"),
categories: wasCleared("categories"),
moods: wasCleared("moods"),
tags: wasCleared("tags"),
publisher: wasCleared("publisher"),
publishedDate: wasCleared("publishedDate"),
isbn10: wasCleared("isbn10"),
isbn13: wasCleared("isbn13"),
description: wasCleared("description"),
pageCount: wasCleared("pageCount"),
language: wasCleared("language"),
asin: wasCleared("asin"),
personalRating: wasCleared("personalRating"),
amazonRating: wasCleared("personalRating"),
amazonReviewCount: wasCleared("amazonReviewCount"),
goodreadsId: wasCleared("goodreadsId"),
comicvineId: wasCleared("comicvineId"),
goodreadsRating: wasCleared("goodreadsRating"),
goodreadsReviewCount: wasCleared("goodreadsReviewCount"),
hardcoverId: wasCleared("hardcoverId"),
hardcoverRating: wasCleared("hardcoverRating"),
hardcoverReviewCount: wasCleared("hardcoverReviewCount"),
googleId: wasCleared("googleId"),
seriesName: wasCleared("seriesName"),
seriesNumber: wasCleared("seriesNumber"),
seriesTotal: wasCleared("seriesTotal"),
cover: false,
};
return {metadata, clearFlags};
}
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
let metadataUpdateWrapper = this.buildMetadataWrapper(shouldLockAllFields);
this.bookService
.updateBookMetadata(this.currentBookId, metadataUpdateWrapper, false)
.subscribe({
next: (response) => {
if (shouldLockAllFields !== undefined) {
this.messageService.add({
severity: "success",
summary: shouldLockAllFields
? "Metadata Locked"
: "Metadata Unlocked",
detail: shouldLockAllFields
? "All fields have been successfully locked."
: "All fields have been successfully unlocked.",
});
}
},
error: () => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: "Failed to update lock state",
});
},
});
}
getUploadCoverUrl(): string {
return this.bookService.getUploadCoverUrl(this.currentBookId);
}
onBeforeSend(): void {
this.isUploading = true;
}
onUpload(event: FileUploadEvent): void {
const response: HttpResponse<any> =
event.originalEvent as HttpResponse<any>;
if (response && response.status === 200) {
const bookMetadata: BookMetadata = response.body as BookMetadata;
this.bookService.handleBookMetadataUpdate(
this.currentBookId,
bookMetadata
);
this.isUploading = false;
} else {
this.isUploading = false;
this.messageService.add({
severity: "error",
summary: "Upload Failed",
detail: "An error occurred while uploading the cover",
life: 3000,
});
}
}
onUploadError($event: FileUploadErrorEvent) {
this.isUploading = false;
this.messageService.add({
severity: "error",
summary: "Upload Error",
detail: "An error occurred while uploading the cover",
life: 3000,
});
}
regenerateCover(bookId: number) {
this.bookService.regenerateCover(bookId).subscribe({
next: () => {
this.messageService.add({
severity: "success",
summary: "Success",
detail:
"Book cover regenerated successfully. Refresh page to see the new cover.",
});
},
error: () => {
this.messageService.add({
severity: "error",
summary: "Error",
detail: "Failed to start cover regeneration",
});
},
});
}
autoFetch(bookId: number) {
this.refreshingBookIds.add(bookId);
this.isAutoFetching = true;
const request: MetadataRefreshRequest = {
refreshType: MetadataRefreshType.BOOKS,
bookIds: [bookId],
};
this.bookService.autoRefreshMetadata(request).subscribe();
setTimeout(() => {
this.isAutoFetching = false;
this.refreshingBookIds.delete(bookId);
}, 15000);
}
onNext() {
this.nextBookClicked.emit();
}
onPrevious() {
this.previousBookClicked.emit();
}
closeDialog() {
this.closeDialogButtonClicked.emit();
}
openCoverSearch() {
const ref = this.dialogService.open(CoverSearchComponent, {
header: "Search Cover",
modal: true,
closable: true,
data: {
bookId: [this.currentBookId],
},
style: {
width: "90vw",
height: "90vh",
maxWidth: "1200px",
position: "absolute",
},
});
ref.onClose.subscribe((result) => {
if (result) {
this.metadataForm.get("thumbnailUrl")?.setValue(result);
this.onSave();
}
});
}
}
@@ -0,0 +1,242 @@
@if (book$ | async; as book) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="flex flex-col h-full w-full">
<div class="flex-grow overflow-auto p-0 md:p-4">
<div class="flex justify-center items-center" [ngStyle]="{'padding-bottom': '0.75rem', 'padding-left': '7.6rem'}">
<p class="ml-3 text-lg">Current Metadata</p>
<p-button
severity="success"
icon='pi pi-angle-left'
[ngStyle]="{'padding-left': '3rem', 'padding-right': '0.5rem'}"
[outlined]="true"
pTooltip="Move all missing fields" tooltipPosition="bottom"
(onClick)="copyMissing()"></p-button>
<p-button
severity="success"
icon='pi pi-angle-double-left'
[ngStyle]="{'padding-left': '0.5rem', 'padding-right': '2rem'}"
[outlined]="true"
pTooltip="Move all fields" tooltipPosition="bottom"
(onClick)="copyAll()"></p-button>
<p class="text-lg">Fetched Metadata</p>
</div>
<div class="form-row">
<label class="label"></label>
<div class="input-container">
@if (!metadataForm.get('coverLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (metadataForm.get('coverLocked')?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
<p-image
class="thumbnail"
[src]="metadataForm.get('thumbnailUrl')?.value"
alt="Image"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
<input type="hidden" id="thumbnailUrl" formControlName="thumbnailUrl" class="input"/>
<p-button
[icon]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"
[outlined]="true"
[ngClass]="
{
'green-outlined-button': isValueSaved('thumbnailUrl'),
'yellow-outlined-button': isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl'],
'red-outlined-button': isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']
}"
class="arrow-button"
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
(mouseenter)="onMouseEnter('thumbnailUrl')"
(mouseleave)="onMouseLeave('thumbnailUrl')"/>
<input type="hidden" [value]="fetchedMetadata.thumbnailUrl" class="input" readonly/>
<p-image
class="thumbnail"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Image"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
</div>
</div>
@for (field of metadataFieldsTop; track field) {
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<input pSize="small" fluid pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
[disabled]="metadataForm.get(field.lockedKey)?.value"/>
<p-button
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
[outlined]="true"
[ngClass]="
{
'green-outlined-button': isValueSaved(field.controlName),
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
}"
class="arrow-button"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"/>
<input pSize="small" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly/>
</div>
</div>
}
@for (field of metadataChips; track field) {
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<div class="w-full px-4">
<p-autoComplete
class="w-full"
formControlName="{{field.controlName}}"
[multiple]="true"
[dropdown]="false"
[forceSelection]="false"
[showClear]="true"
[suggestions]="getFiltered(field.controlName)"
(completeMethod)="filterItems($event, field.controlName)"
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
(onSelect)="onAutoCompleteSelect(field.controlName, $event)"
[disabled]="metadataForm.get(field.lockedKey)?.value">
</p-autoComplete>
</div>
<p-button
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
[outlined]="true"
[ngClass]="
{
'green-outlined-button': isValueSaved(field.controlName),
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
}"
class="arrow-button"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"/>
<div class="w-full px-4">
<p-autoComplete
[ngModel]="fetchedMetadata[field.fetchedKey] ?? []"
[ngModelOptions]="{ standalone: true }"
[disabled]="true"
[multiple]="true" [typeahead]="false" [dropdown]="false" [forceSelection]="false" styleClass="w-full">
</p-autoComplete>
</div>
</div>
</div>
}
@for (field of metadataDescription; track field) {
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<textarea rows="3" pTextarea id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
[disabled]="metadataForm.get(field.lockedKey)?.value"></textarea>
<p-button
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
[outlined]="true"
[ngClass]="
{
'green-outlined-button': isValueSaved(field.controlName),
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
}"
class="arrow-button"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"/>
<textarea rows="3" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly></textarea>
</div>
</div>
}
@for (field of metadataFieldsBottom; track field) {
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadataForm.get(field.lockedKey)?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<input pInputText pSize="small" id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
[disabled]="metadataForm.get(field.lockedKey)?.value"/>
<p-button
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
[outlined]="true"
[ngClass]="
{
'green-outlined-button': isValueSaved(field.controlName),
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
}"
class="arrow-button"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"/>
<input pInputText pSize="small" [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly/>
</div>
</div>
}
<div class="flex justify-center items-center" [ngStyle]="{'padding-bottom': '0.75rem', 'padding-left': '7.6rem'}">
<p class="ml-3 text-lg">Current Metadata</p>
<p-button
severity="success"
icon='pi pi-angle-left'
[ngStyle]="{'padding-left': '3rem', 'padding-right': '0.5rem'}"
[outlined]="true"
pTooltip="Move all missing fields" tooltipPosition="bottom"
(onClick)="copyMissing()"></p-button>
<p-button
severity="success"
icon='pi pi-angle-double-left'
[ngStyle]="{'padding-left': '0.5rem', 'padding-right': '2rem'}"
[outlined]="true"
pTooltip="Move all fields" tooltipPosition="bottom"
(onClick)="copyAll()"></p-button>
<p class="text-lg">Fetched Metadata</p>
</div>
</div>
@if (!reviewMode) {
<div class="mt-auto">
<p-divider></p-divider>
<div class="flex justify-between px-2 pt-4">
<p-button label="To Metadata List" icon="pi pi-arrow-left" severity="info" (onClick)="goBackClick()"></p-button>
<div class="flex gap-x-4 justify-end">
<p-button label="Unlock All" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()"></p-button>
<p-button label="Lock All" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button>
<p-divider layout="vertical"/>
<p-button
label="Save"
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[loading]="isSaving"
[disabled]="isSaving"
type="submit"></p-button>
</div>
</div>
</div>
}
</form>
}
@@ -0,0 +1,59 @@
.form-row {
display: flex;
align-items: center;
margin-bottom: 0.5rem;
width: 100%;
justify-content: flex-start;
}
.label {
width: 7rem;
text-align: left;
}
.input-container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
}
.input {
width: 50%;
padding: 0.5rem;
border-radius: 0.25rem;
margin: 0 1rem;
}
.thumbnail {
width: 15.625rem;
height: 21.875rem;
border-radius: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
margin-left: 2.5rem;
margin-right: 2.5rem;
}
.arrow-button {
padding-left: 1rem;
padding-right: 1rem;
}
.yellow-outlined-button {
--p-button-outlined-primary-border-color: yellow;
--p-button-outlined-primary-color: yellow;
}
.green-outlined-button {
--p-button-outlined-primary-border-color: limegreen;
--p-button-outlined-primary-color: limegreen;
}
.red-outlined-button {
--p-button-outlined-primary-border-color: #E32636;
--p-button-outlined-primary-color: #E32636;
}
::ng-deep .p-inputchips {
width: 100% !important;
}
@@ -0,0 +1,675 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {Book, BookMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model';
import {MessageService} from 'primeng/api';
import {Button} from 'primeng/button';
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {Divider} from 'primeng/divider';
import {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 {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {AutoComplete} from 'primeng/autocomplete';
import {Image} from 'primeng/image';
import {LazyLoadImageModule} from 'ng-lazyload-image';
@Component({
selector: 'app-metadata-picker',
standalone: true,
templateUrl: './metadata-picker.component.html',
styleUrls: ['./metadata-picker.component.scss'],
imports: [
Button,
FormsModule,
InputText,
Divider,
ReactiveFormsModule,
NgClass,
NgStyle,
Tooltip,
AsyncPipe,
Textarea,
AutoComplete,
Image,
LazyLoadImageModule
]
})
export class MetadataPickerComponent implements OnInit {
metadataFieldsTop = [
{label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title'},
{label: 'Subtitle', controlName: 'subtitle', lockedKey: 'subtitleLocked', fetchedKey: 'subtitle'},
{label: 'Publisher', controlName: 'publisher', lockedKey: 'publisherLocked', fetchedKey: 'publisher'},
{label: 'Published', controlName: 'publishedDate', lockedKey: 'publishedDateLocked', fetchedKey: 'publishedDate'}
];
metadataChips = [
{label: 'Authors', controlName: 'authors', lockedKey: 'authorsLocked', fetchedKey: 'authors'},
{label: 'Genres', controlName: 'categories', lockedKey: 'categoriesLocked', fetchedKey: 'categories'},
{label: 'Moods', controlName: 'moods', lockedKey: 'moodsLocked', fetchedKey: 'moods'},
{label: 'Tags', controlName: 'tags', lockedKey: 'tagsLocked', fetchedKey: 'tags'},
];
metadataDescription = [
{label: 'Description', controlName: 'description', lockedKey: 'descriptionLocked', fetchedKey: 'description'},
];
metadataFieldsBottom = [
{label: 'Series', controlName: 'seriesName', lockedKey: 'seriesNameLocked', fetchedKey: 'seriesName'},
{label: 'Book #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber'},
{label: 'Total Books', controlName: 'seriesTotal', lockedKey: 'seriesTotalLocked', fetchedKey: 'seriesTotal'},
{label: 'Language', controlName: 'language', lockedKey: 'languageLocked', fetchedKey: 'language'},
{label: 'ISBN-10', controlName: 'isbn10', lockedKey: 'isbn10Locked', fetchedKey: 'isbn10'},
{label: 'ISBN-13', controlName: 'isbn13', lockedKey: 'isbn13Locked', fetchedKey: 'isbn13'},
{label: 'ASIN', controlName: 'asin', lockedKey: 'asinLocked', fetchedKey: 'asin'},
{label: 'Amz Reviews', controlName: 'amazonReviewCount', lockedKey: 'amazonReviewCountLocked', fetchedKey: 'amazonReviewCount'},
{label: 'Amz Rating', controlName: 'amazonRating', lockedKey: 'amazonRatingLocked', fetchedKey: 'amazonRating'},
{label: 'Comicvine ID', controlName: 'comicvineId', lockedKey: 'comicvineIdLocked', fetchedKey: 'comicvineId'},
{label: 'Goodreads ID', controlName: 'goodreadsId', lockedKey: 'goodreadsIdLocked', fetchedKey: 'goodreadsId'},
{label: 'GR Reviews', controlName: 'goodreadsReviewCount', lockedKey: 'goodreadsReviewCountLocked', fetchedKey: 'goodreadsReviewCount'},
{label: 'GR Rating', controlName: 'goodreadsRating', lockedKey: 'goodreadsRatingLocked', fetchedKey: 'goodreadsRating'},
{label: 'Hardcover ID', controlName: 'hardcoverId', lockedKey: 'hardcoverIdLocked', fetchedKey: 'hardcoverId'},
{label: 'HC Reviews', controlName: 'hardcoverReviewCount', lockedKey: 'hardcoverReviewCountLocked', fetchedKey: 'hardcoverReviewCount'},
{label: 'HC Rating', controlName: 'hardcoverRating', lockedKey: 'hardcoverRatingLocked', fetchedKey: 'hardcoverRating'},
{label: 'Google ID', controlName: 'googleId', lockedKey: 'googleIdLocked', fetchedKey: 'googleIdRating'},
{label: 'Pages', controlName: 'pageCount', lockedKey: 'pageCountLocked', fetchedKey: 'pageCount'}
];
@Input() reviewMode!: boolean;
@Input() fetchedMetadata!: BookMetadata;
@Input() book$!: Observable<Book | null>;
@Output() goBack = new EventEmitter<boolean>();
allAuthors!: string[];
allCategories!: string[];
allMoods!: string[];
allTags!: string[];
filteredCategories: string[] = [];
filteredAuthors: string[] = [];
filteredMoods: string[] = [];
filteredTags: string[] = [];
getFiltered(controlName: string): string[] {
if (controlName === 'authors') return this.filteredAuthors;
if (controlName === 'categories') return this.filteredCategories;
if (controlName === 'moods') return this.filteredMoods;
if (controlName === 'tags') return this.filteredTags;
return [];
}
filterItems(event: { query: string }, controlName: string) {
const query = event.query.toLowerCase();
if (controlName === 'authors') {
this.filteredAuthors = this.allAuthors.filter(a => a.toLowerCase().includes(query));
} else if (controlName === 'categories') {
this.filteredCategories = this.allCategories.filter(c => c.toLowerCase().includes(query));
} else if (controlName === 'moods') {
this.filteredMoods = this.allMoods.filter(m => m.toLowerCase().includes(query));
} else if (controlName === 'tags') {
this.filteredTags = this.allTags.filter(t => t.toLowerCase().includes(query));
}
}
metadataForm: FormGroup;
currentBookId!: number;
copiedFields: Record<string, boolean> = {};
savedFields: Record<string, boolean> = {};
originalMetadata!: BookMetadata;
isSaving = false;
private messageService = inject(MessageService);
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
private destroyRef = inject(DestroyRef);
constructor() {
this.metadataForm = new FormGroup({
title: new FormControl(''),
subtitle: new FormControl(''),
authors: new FormControl(''),
categories: new FormControl(''),
moods: new FormControl(''),
tags: new FormControl(''),
publisher: new FormControl(''),
publishedDate: new FormControl(''),
isbn10: new FormControl(''),
isbn13: new FormControl(''),
description: new FormControl(''),
pageCount: new FormControl(''),
language: new FormControl(''),
asin: new FormControl(''),
amazonRating: new FormControl(''),
amazonReviewCount: new FormControl(''),
goodreadsId: new FormControl(''),
comicvineId: new FormControl(''),
goodreadsRating: new FormControl(''),
goodreadsReviewCount: new FormControl(''),
hardcoverId: new FormControl(''),
hardcoverRating: new FormControl(''),
hardcoverReviewCount: new FormControl(''),
googleId: new FormControl(''),
seriesName: new FormControl(''),
seriesNumber: new FormControl(''),
seriesTotal: new FormControl(''),
thumbnailUrl: new FormControl(''),
titleLocked: new FormControl(false),
subtitleLocked: new FormControl(false),
authorsLocked: new FormControl(false),
categoriesLocked: new FormControl(false),
moodsLocked: new FormControl(false),
tagsLocked: new FormControl(false),
publisherLocked: new FormControl(false),
publishedDateLocked: new FormControl(false),
isbn10Locked: new FormControl(false),
isbn13Locked: new FormControl(false),
descriptionLocked: new FormControl(false),
pageCountLocked: new FormControl(false),
languageLocked: new FormControl(false),
asinLocked: new FormControl(false),
personalRatingLocked: new FormControl(false),
amazonRatingLocked: new FormControl(false),
amazonReviewCountLocked: new FormControl(false),
goodreadsIdLocked: new FormControl(false),
comicvineIdLocked: new FormControl(false),
goodreadsRatingLocked: new FormControl(false),
goodreadsReviewCountLocked: new FormControl(false),
hardcoverIdLocked: new FormControl(false),
hardcoverRatingLocked: new FormControl(false),
hardcoverReviewCountLocked: new FormControl(false),
googleIdLocked: new FormControl(false),
seriesNameLocked: new FormControl(false),
seriesNumberLocked: new FormControl(false),
seriesTotalLocked: new FormControl(false),
coverLocked: new FormControl(false),
});
}
ngOnInit(): void {
this.bookService.bookState$
.pipe(
filter(bookState => bookState.loaded),
take(1)
)
.subscribe(bookState => {
const authors = new Set<string>();
const categories = new Set<string>();
const moods = new Set<string>();
const tags = new Set<string>();
(bookState.books ?? []).forEach(book => {
book.metadata?.authors?.forEach(author => authors.add(author));
book.metadata?.categories?.forEach(category => categories.add(category));
book.metadata?.moods?.forEach(mood => moods.add(mood));
book.metadata?.tags?.forEach(tag => tags.add(tag));
});
this.allAuthors = Array.from(authors);
this.allCategories = Array.from(categories);
this.allMoods = Array.from(moods);
this.allTags = Array.from(tags);
});
this.book$
.pipe(
filter((book): book is Book => !!book && !!book.metadata),
map(book => book.metadata),
takeUntilDestroyed(this.destroyRef)
).subscribe((metadata) => {
if (this.reviewMode) {
this.metadataForm.reset();
this.copiedFields = {};
this.savedFields = {};
this.hoveredFields = {};
}
if (metadata) {
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn);
this.currentBookId = metadata.bookId;
this.metadataForm.patchValue({
title: metadata.title || null,
subtitle: metadata.subtitle || null,
authors: [...(metadata.authors ?? [])].sort(),
categories: [...(metadata.categories ?? [])].sort(),
moods: [...(metadata.moods ?? [])].sort(),
tags: [...(metadata.tags ?? [])].sort(),
publisher: metadata.publisher || null,
publishedDate: metadata.publishedDate || null,
isbn10: metadata.isbn10 || null,
isbn13: metadata.isbn13 || null,
description: metadata.description || null,
pageCount: metadata.pageCount || null,
language: metadata.language || null,
asin: metadata.asin || null,
amazonRating: metadata.amazonRating || null,
amazonReviewCount: metadata.amazonReviewCount || null,
goodreadsId: metadata.goodreadsId || null,
comicvineId: metadata.comicvineId || null,
goodreadsRating: metadata.goodreadsRating || null,
goodreadsReviewCount: metadata.goodreadsReviewCount || null,
hardcoverId: metadata.hardcoverId || null,
hardcoverRating: metadata.hardcoverRating || null,
hardcoverReviewCount: metadata.hardcoverReviewCount || null,
googleId: metadata.googleId || null,
seriesName: metadata.seriesName || null,
seriesNumber: metadata.seriesNumber || null,
seriesTotal: metadata.seriesTotal || null,
thumbnailUrl: this.urlHelper.getCoverUrl(metadata.bookId, metadata.coverUpdatedOn),
titleLocked: metadata.titleLocked || false,
subtitleLocked: metadata.subtitleLocked || false,
authorsLocked: metadata.authorsLocked || false,
categoriesLocked: metadata.categoriesLocked || false,
moodsLocked: metadata.moodsLocked || false,
tagsLocked: metadata.tagsLocked || false,
publisherLocked: metadata.publisherLocked || false,
publishedDateLocked: metadata.publishedDateLocked || false,
isbn10Locked: metadata.isbn10Locked || false,
isbn13Locked: metadata.isbn13Locked || false,
descriptionLocked: metadata.descriptionLocked || false,
pageCountLocked: metadata.pageCountLocked || false,
languageLocked: metadata.languageLocked || false,
asinLocked: metadata.asinLocked || false,
personalRatingLocked: metadata.personalRatingLocked || false,
amazonRatingLocked: metadata.amazonRatingLocked || false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked || false,
goodreadsIdLocked: metadata.goodreadsIdLocked || false,
comicvineIdLocked: metadata.comicvineIdLocked || false,
goodreadsRatingLocked: metadata.goodreadsRatingLocked || false,
goodreadsReviewCountLocked: metadata.goodreadsReviewCountLocked || false,
hardcoverIdLocked: metadata.hardcoverIdLocked || false,
hardcoverRatingLocked: metadata.hardcoverRatingLocked || false,
hardcoverReviewCountLocked: metadata.hardcoverReviewCountLocked || false,
googleIdLocked: metadata.googleIdLocked || false,
seriesNameLocked: metadata.seriesNameLocked || false,
seriesNumberLocked: metadata.seriesNumberLocked || false,
seriesTotalLocked: metadata.seriesTotalLocked || false,
coverLocked: metadata.coverLocked || false,
});
// Always enable all fields before applying locked state
Object.keys(this.metadataForm.controls).forEach((key) => {
if (!key.endsWith('Locked')) {
this.metadataForm.get(key)?.enable({emitEvent: false});
}
});
if (metadata.titleLocked) this.metadataForm.get('title')?.disable({emitEvent: false});
if (metadata.subtitleLocked) this.metadataForm.get('subtitle')?.disable({emitEvent: false});
if (metadata.authorsLocked) this.metadataForm.get('authors')?.disable({emitEvent: false});
if (metadata.categoriesLocked) this.metadataForm.get('categories')?.disable({emitEvent: false});
if (metadata.moodsLocked) this.metadataForm.get('moods')?.disable({emitEvent: false});
if (metadata.tagsLocked) this.metadataForm.get('tags')?.disable({emitEvent: false});
if (metadata.publisherLocked) this.metadataForm.get('publisher')?.disable({emitEvent: false});
if (metadata.publishedDateLocked) this.metadataForm.get('publishedDate')?.disable({emitEvent: false});
if (metadata.languageLocked) this.metadataForm.get('language')?.disable({emitEvent: false});
if (metadata.isbn10Locked) this.metadataForm.get('isbn10')?.disable({emitEvent: false});
if (metadata.isbn13Locked) this.metadataForm.get('isbn13')?.disable({emitEvent: false});
if (metadata.asinLocked) this.metadataForm.get('asin')?.disable({emitEvent: false});
if (metadata.personalRatingLocked) this.metadataForm.get('personalRating')?.disable({emitEvent: false});
if (metadata.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable({emitEvent: false});
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable({emitEvent: false});
if (metadata.googleIdLocked) this.metadataForm.get('googleIdCount')?.disable({emitEvent: false});
if (metadata.comicvineIdLocked) this.metadataForm.get('comicvineId')?.disable({emitEvent: false});
if (metadata.goodreadsIdLocked) this.metadataForm.get('goodreadsId')?.disable({emitEvent: false});
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable({emitEvent: false});
if (metadata.goodreadsRatingLocked) this.metadataForm.get('goodreadsRating')?.disable({emitEvent: false});
if (metadata.hardcoverIdLocked) this.metadataForm.get('hardcoverId')?.disable({emitEvent: false});
if (metadata.hardcoverReviewCountLocked) this.metadataForm.get('hardcoverReviewCount')?.disable({emitEvent: false});
if (metadata.hardcoverRatingLocked) this.metadataForm.get('hardcoverRating')?.disable({emitEvent: false});
if (metadata.googleIdLocked) this.metadataForm.get('googleId')?.disable({emitEvent: false});
if (metadata.pageCountLocked) this.metadataForm.get('pageCount')?.disable({emitEvent: false});
if (metadata.descriptionLocked) this.metadataForm.get('description')?.disable({emitEvent: false});
if (metadata.seriesNameLocked) this.metadataForm.get('seriesName')?.disable({emitEvent: false});
if (metadata.seriesNumberLocked) this.metadataForm.get('seriesNumber')?.disable({emitEvent: false});
if (metadata.seriesTotalLocked) this.metadataForm.get('seriesTotal')?.disable({emitEvent: false});
}
});
}
onAutoCompleteSelect(fieldName: string, event: any) {
const values = this.metadataForm.get(fieldName)?.value || [];
if (!values.includes(event.value)) {
this.metadataForm.get(fieldName)?.setValue([...values, event.value]);
}
(event.originalEvent.target as HTMLInputElement).value = '';
}
onAutoCompleteKeyUp(fieldName: string, event: KeyboardEvent) {
if (event.key === 'Enter') {
const input = event.target as HTMLInputElement;
const value = input.value?.trim();
if (value) {
const values = this.metadataForm.get(fieldName)?.value || [];
if (!values.includes(value)) {
this.metadataForm.get(fieldName)?.setValue([...values, value]);
}
input.value = '';
}
}
}
onSave(): void {
this.isSaving = true;
const updatedBookMetadata = this.buildMetadataWrapper(undefined);
this.bookService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false).subscribe({
next: (bookMetadata) => {
this.isSaving = false;
Object.keys(this.copiedFields).forEach((field) => {
if (this.copiedFields[field]) {
this.savedFields[field] = true;
}
});
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book metadata updated'});
},
error: () => {
this.isSaving = false;
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update book metadata'});
}
});
}
private buildMetadataWrapper(shouldLockAllFields: boolean | undefined): MetadataUpdateWrapper {
const updatedBookMetadata: BookMetadata = {
bookId: this.currentBookId,
title: this.metadataForm.get('title')?.value || this.copiedFields['title'] ? this.getValueOrCopied('title') : '',
subtitle: this.metadataForm.get('subtitle')?.value || this.copiedFields['subtitle'] ? this.getValueOrCopied('subtitle') : '',
authors: this.metadataForm.get('authors')?.value || this.copiedFields['authors'] ? this.getArrayFromFormField('authors', this.fetchedMetadata.authors) : [],
categories: this.metadataForm.get('categories')?.value || this.copiedFields['categories'] ? this.getArrayFromFormField('categories', this.fetchedMetadata.categories) : [],
moods: this.metadataForm.get('moods')?.value || this.copiedFields['moods'] ? this.getArrayFromFormField('moods', this.fetchedMetadata.moods) : [],
tags: this.metadataForm.get('tags')?.value || this.copiedFields['tags'] ? this.getArrayFromFormField('tags', this.fetchedMetadata.tags) : [],
publisher: this.metadataForm.get('publisher')?.value || this.copiedFields['publisher'] ? this.getValueOrCopied('publisher') : '',
publishedDate: this.metadataForm.get('publishedDate')?.value || this.copiedFields['publishedDate'] ? this.getValueOrCopied('publishedDate') : '',
isbn10: this.metadataForm.get('isbn10')?.value || this.copiedFields['isbn10'] ? this.getValueOrCopied('isbn10') : '',
isbn13: this.metadataForm.get('isbn13')?.value || this.copiedFields['isbn13'] ? this.getValueOrCopied('isbn13') : '',
description: this.metadataForm.get('description')?.value || this.copiedFields['description'] ? this.getValueOrCopied('description') : '',
pageCount: this.metadataForm.get('pageCount')?.value || this.copiedFields['pageCount'] ? this.getPageCountOrCopied() : null,
language: this.metadataForm.get('language')?.value || this.copiedFields['language'] ? this.getValueOrCopied('language') : '',
asin: this.metadataForm.get('asin')?.value || this.copiedFields['asin'] ? this.getValueOrCopied('asin') : '',
personalRating: this.metadataForm.get('personalRating')?.value || this.copiedFields['personalRating'] ? this.getNumberOrCopied('personalRating') : null,
amazonRating: this.metadataForm.get('amazonRating')?.value || this.copiedFields['amazonRating'] ? this.getNumberOrCopied('amazonRating') : null,
amazonReviewCount: this.metadataForm.get('amazonReviewCount')?.value || this.copiedFields['amazonReviewCount'] ? this.getNumberOrCopied('amazonReviewCount') : null,
goodreadsId: this.metadataForm.get('goodreadsId')?.value || this.copiedFields['goodreadsId'] ? this.getValueOrCopied('goodreadsId') : '',
comicvineId: this.metadataForm.get('comicvineId')?.value || this.copiedFields['comicvineId'] ? this.getValueOrCopied('comicvineId') : '',
goodreadsRating: this.metadataForm.get('goodreadsRating')?.value || this.copiedFields['goodreadsRating'] ? this.getNumberOrCopied('goodreadsRating') : null,
goodreadsReviewCount: this.metadataForm.get('goodreadsReviewCount')?.value || this.copiedFields['goodreadsReviewCount'] ? this.getNumberOrCopied('goodreadsReviewCount') : null,
hardcoverId: this.metadataForm.get('hardcoverId')?.value || this.copiedFields['hardcoverId'] ? this.getValueOrCopied('hardcoverId') : '',
hardcoverRating: this.metadataForm.get('hardcoverRating')?.value || this.copiedFields['hardcoverRating'] ? this.getNumberOrCopied('hardcoverRating') : null,
hardcoverReviewCount: this.metadataForm.get('hardcoverReviewCount')?.value || this.copiedFields['hardcoverReviewCount'] ? this.getNumberOrCopied('hardcoverReviewCount') : null,
googleId: this.metadataForm.get('googleId')?.value || this.copiedFields['googleId'] ? this.getValueOrCopied('googleId') : '',
seriesName: this.metadataForm.get('seriesName')?.value || this.copiedFields['seriesName'] ? this.getValueOrCopied('seriesName') : '',
seriesNumber: this.metadataForm.get('seriesNumber')?.value || this.copiedFields['seriesNumber'] ? this.getNumberOrCopied('seriesNumber') : null,
seriesTotal: this.metadataForm.get('seriesTotal')?.value || this.copiedFields['seriesTotal'] ? this.getNumberOrCopied('seriesTotal') : null,
thumbnailUrl: this.getThumbnail(),
titleLocked: this.metadataForm.get('titleLocked')?.value,
subtitleLocked: this.metadataForm.get('subtitleLocked')?.value,
authorsLocked: this.metadataForm.get('authorsLocked')?.value,
categoriesLocked: this.metadataForm.get('categoriesLocked')?.value,
moodsLocked: this.metadataForm.get('moodsLocked')?.value,
tagsLocked: this.metadataForm.get('tagsLocked')?.value,
publisherLocked: this.metadataForm.get('publisherLocked')?.value,
publishedDateLocked: this.metadataForm.get('publishedDateLocked')?.value,
isbn10Locked: this.metadataForm.get('isbn10Locked')?.value,
isbn13Locked: this.metadataForm.get('isbn13Locked')?.value,
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
languageLocked: this.metadataForm.get('languageLocked')?.value,
asinLocked: this.metadataForm.get('asinLocked')?.value,
personalRatingLocked: this.metadataForm.get('personalRatingLocked')?.value,
amazonRatingLocked: this.metadataForm.get('amazonRatingLocked')?.value,
amazonReviewCountLocked: this.metadataForm.get('amazonReviewCountLocked')?.value,
goodreadsIdLocked: this.metadataForm.get('goodreadsIdLocked')?.value,
comicvineIdLocked: this.metadataForm.get('comicvineIdLocked')?.value,
goodreadsRatingLocked: this.metadataForm.get('goodreadsRatingLocked')?.value,
goodreadsReviewCountLocked: this.metadataForm.get('goodreadsReviewCountLocked')?.value,
hardcoverIdLocked: this.metadataForm.get('hardcoverIdLocked')?.value,
hardcoverRatingLocked: this.metadataForm.get('hardcoverRatingLocked')?.value,
hardcoverReviewCountLocked: this.metadataForm.get('hardcoverReviewCountLocked')?.value,
googleIdLocked: this.metadataForm.get('googleIdLocked')?.value,
seriesNameLocked: this.metadataForm.get('seriesNameLocked')?.value,
seriesNumberLocked: this.metadataForm.get('seriesNumberLocked')?.value,
seriesTotalLocked: this.metadataForm.get('seriesTotalLocked')?.value,
coverLocked: this.metadataForm.get('coverLocked')?.value,
...(shouldLockAllFields !== undefined && {allFieldsLocked: shouldLockAllFields}),
};
const clearFlags: MetadataClearFlags = this.inferClearFlags(updatedBookMetadata, this.originalMetadata);
return {
metadata: updatedBookMetadata,
clearFlags: clearFlags
};
}
private inferClearFlags(current: BookMetadata, original: BookMetadata): MetadataClearFlags {
return {
title: !current.title && !!original.title,
subtitle: !current.subtitle && !!original.subtitle,
authors: current.authors?.length === 0 && original.authors?.length! > 0,
categories: current.categories?.length === 0 && original.categories?.length! > 0,
moods: current.moods?.length === 0 && original.moods?.length! > 0,
tags: current.tags?.length === 0 && original.tags?.length! > 0,
publisher: !current.publisher && !!original.publisher,
publishedDate: !current.publishedDate && !!original.publishedDate,
isbn10: !current.isbn10 && !!original.isbn10,
isbn13: !current.isbn13 && !!original.isbn13,
description: !current.description && !!original.description,
pageCount: current.pageCount === null && original.pageCount !== null,
language: !current.language && !!original.language,
asin: !current.asin && !!original.asin,
amazonRating: current.amazonRating === null && original.amazonRating !== null,
amazonReviewCount: current.amazonReviewCount === null && original.amazonReviewCount !== null,
goodreadsId: !current.goodreadsId && !!original.goodreadsId,
comicvineId: !current.comicvineId && !!original.comicvineId,
goodreadsRating: current.goodreadsRating === null && original.goodreadsRating !== null,
goodreadsReviewCount: current.goodreadsReviewCount === null && original.goodreadsReviewCount !== null,
hardcoverId: !current.hardcoverId && !!original.hardcoverId,
hardcoverRating: current.hardcoverRating === null && original.hardcoverRating !== null,
hardcoverReviewCount: current.hardcoverReviewCount === null && original.hardcoverReviewCount !== null,
googleId: !current.googleId && !!original.googleId,
seriesName: !current.seriesName && !!original.seriesName,
seriesNumber: current.seriesNumber === null && original.seriesNumber !== null,
seriesTotal: current.seriesTotal === null && original.seriesTotal !== null,
cover: !current.thumbnailUrl && !!original.thumbnailUrl,
personalRating: current.personalRating === null && original.personalRating !== null,
};
}
getThumbnail() {
const thumbnailUrl = this.metadataForm.get('thumbnailUrl')?.value;
if (thumbnailUrl?.includes('api/v1')) {
return null;
}
return this.copiedFields['thumbnailUrl'] ? this.getValueOrCopied('thumbnailUrl') : null;
}
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
this.bookService.updateBookMetadata(this.currentBookId, this.buildMetadataWrapper(shouldLockAllFields), false).subscribe({
next: (response) => {
if (shouldLockAllFields !== undefined) {
this.messageService.add({
severity: 'success',
summary: shouldLockAllFields ? 'Metadata Locked' : 'Metadata Unlocked',
detail: shouldLockAllFields
? 'All fields have been successfully locked.'
: 'All fields have been successfully unlocked.',
});
}
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to update lock state',
});
}
});
}
toggleLock(field: string): void {
if (field === 'thumbnailUrl') {
field = 'cover'
}
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 {
this.metadataForm.get(field)?.enable();
}
this.updateMetadata(undefined);
}
copyMissing(): void {
Object.keys(this.fetchedMetadata).forEach((field) => {
const isLocked = this.metadataForm.get(`${field}Locked`)?.value;
const currentValue = this.metadataForm.get(field)?.value;
const fetchedValue = this.fetchedMetadata[field];
const isEmpty = Array.isArray(currentValue)
? currentValue.length === 0
: !currentValue;
if (!isLocked && isEmpty && fetchedValue) {
this.copyFetchedToCurrent(field);
}
});
}
copyAll() {
Object.keys(this.fetchedMetadata).forEach((field) => {
const isLocked = this.metadataForm.get(`${field}Locked`)?.value;
if (!isLocked && this.fetchedMetadata[field] && field !== 'thumbnailUrl') {
this.copyFetchedToCurrent(field);
}
});
}
copyFetchedToCurrent(field: string): void {
if (field === 'thumbnailUrl') {
field = 'cover';
}
const isLocked = this.metadataForm.get(`${field}Locked`)?.value;
if (isLocked) {
this.messageService.add({
severity: 'warn',
summary: 'Action Blocked',
detail: `${field} is locked and cannot be updated.`
});
return;
}
if (field === 'cover') {
field = 'thumbnailUrl';
}
const value = this.fetchedMetadata[field];
if (value) {
this.metadataForm.get(field)?.setValue(value);
this.copiedFields[field] = true;
this.highlightCopiedInput(field);
}
}
private getNumberOrCopied(field: string): number | null {
const formValue = this.metadataForm.get(field)?.value;
if (formValue === '' || formValue === null || isNaN(formValue)) {
this.copiedFields[field] = true;
return this.fetchedMetadata[field] || null;
}
return Number(formValue);
}
private getPageCountOrCopied(): number | null {
const formValue = this.metadataForm.get('pageCount')?.value;
if (formValue === '' || formValue === null || isNaN(formValue)) {
this.copiedFields['pageCount'] = true;
return this.fetchedMetadata.pageCount || null;
}
return Number(formValue);
}
private getValueOrCopied(field: string): string {
const formValue = this.metadataForm.get(field)?.value;
if (!formValue || formValue === '') {
this.copiedFields[field] = true;
return this.fetchedMetadata[field] || '';
}
return formValue;
}
getArrayFromFormField(field: string, fallbackValue: any): any[] {
const fieldValue = this.metadataForm.get(field)?.value;
if (!fieldValue) {
return fallbackValue ? (Array.isArray(fallbackValue) ? fallbackValue : [fallbackValue]) : [];
}
if (typeof fieldValue === 'string') {
return fieldValue.split(',').map(item => item.trim());
}
return Array.isArray(fieldValue) ? fieldValue : [];
}
lockAll(): void {
Object.keys(this.metadataForm.controls).forEach((key) => {
if (key.endsWith('Locked')) {
this.metadataForm.get(key)?.setValue(true);
const fieldName = key.replace('Locked', '');
this.metadataForm.get(fieldName)?.disable();
}
});
this.updateMetadata(true);
}
unlockAll(): void {
Object.keys(this.metadataForm.controls).forEach((key) => {
if (key.endsWith('Locked')) {
this.metadataForm.get(key)?.setValue(false);
const fieldName = key.replace('Locked', '');
this.metadataForm.get(fieldName)?.enable();
}
});
this.updateMetadata(false);
}
highlightCopiedInput(field: string): void {
this.copiedFields = {...this.copiedFields, [field]: true};
}
isValueCopied(field: string): boolean {
return this.copiedFields[field];
}
isValueSaved(field: string): boolean {
return this.savedFields[field];
}
goBackClick() {
this.goBack.emit(true);
}
hoveredFields: { [key: string]: boolean } = {};
onMouseEnter(controlName: string): void {
if (this.isValueCopied(controlName) && !this.isValueSaved(controlName)) {
this.hoveredFields[controlName] = true;
}
}
onMouseLeave(controlName: string): void {
this.hoveredFields[controlName] = false;
}
resetField(field: string) {
this.metadataForm.get(field)?.setValue(this.originalMetadata[field]);
this.copiedFields[field] = false;
this.hoveredFields[field] = false;
}
}
@@ -0,0 +1,124 @@
@if (selectedFetchedMetadata$ | async; as selectedFetchedMetadata) {
<div class="h-full w-full flex-auto min-w-[80rem]">
<app-metadata-picker
[fetchedMetadata]="selectedFetchedMetadata"
[book$]="book$"
(goBack)="onGoBack()">
</app-metadata-picker>
</div>
} @else {
<form class="flex flex-col w-full h-full pt-2 min-w-full md:min-w-[60rem] pr-0 md:pr-2 pl-0 md:pl-2" [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="flex flex-col space-y-3">
<div class="grid grid-cols-1 md:flex md:flex-row w-full gap-2 md:gap-4 md:items-end">
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="provider">Providers</label>
<p-multiselect
id="provider"
class="w-full"
[filter]="false"
showToggleAll="false"
[options]="providers"
formControlName="provider"
placeholder="Select Providers">
</p-multiselect>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-56">
<label for="isbn">ISBN</label>
<input pInputText formControlName="isbn" id="isbn" class="w-full" placeholder="ISBN-10 or ISBN-13"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="title">Title</label>
<input pInputText formControlName="title" id="title" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="author">Author</label>
<input pInputText formControlName="author" id="author" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full sm:w-fit md:w-auto">
<label class="invisible md:visible h-0 md:h-auto">Search</label>
<div class="flex justify-center md:justify-start">
<p-button
label="Search"
type="submit"
outlined="true"
[disabled]="!isSearchEnabled || loading"
class="w-full sm:w-fit md:w-auto">
</p-button>
</div>
</div>
</div>
<div class="text-sm text-gray-400 flex items-start gap-2">
<i class="pi pi-info-circle text-sky-600 mt-0.5"></i>
<span>
When an ISBN is provided, the search will use only the ISBN. If no ISBN is given, the search will fall back to Title and Author.
</span>
</div>
</div>
@if (loading) {
<div class="flex justify-center items-center flex-col gap-4 h-[40dvh] md:h-[70dvh] text-center">
<p-progress-spinner ariaLabel="Loading metadata..."/>
<p class="text-gray-300">
Fetching metadata from your selected sources.<br/>
This may take a few moments...
</p>
</div>
}
@if (!loading) {
@if (searchTriggered && allFetchedMetadata.length === 0) {
<div class="flex flex-col items-center justify-center h-[50dvh] md:h-[70dvh] text-center">
<p class="text-gray-300">No metadata results found.<br/>Try adjusting your search criteria.</p>
</div>
}
@if (!searchTriggered && allFetchedMetadata.length === 0) {
<div class="flex flex-col items-center justify-center h-[50dvh] md:h-[70dvh] text-center">
<p class="text-gray-300">Start by searching for metadata using the search bar above.</p>
</div>
}
@if (allFetchedMetadata.length > 0) {
<div class="mt-4 md:mt-8 flex-1 overflow-y-auto">
@for (metadata of allFetchedMetadata; track metadata) {
<div class="book-item flex flex-col w-full">
<div class="flex flex-row w-full book-item-content cursor-pointer" (click)="onBookClick(metadata)">
<img [src]="metadata.thumbnailUrl || 'assets/images/missing-cover.jpg'" alt="Image" class="img-fixed-dimensions pr-0 md:pr-2 md:py-3 self-center md:self-start"/>
<div class="flex flex-col w-full m-2">
<div class="flex flex-col md:flex-row gap-2 md:gap-4 justify-between">
<p class="font-bold">{{ truncateText(metadata['title']!, 90) }}</p>
<div class="flex flex-wrap gap-2 text-sm">
@if (metadata['isbn10']) {
<p>ISBN10: {{ metadata['isbn10']}}</p>
<span class="hidden md:inline">|</span>
}
@if (metadata['isbn13']) {
<p>ISBN13: {{ metadata['isbn13']}}</p>
<span class="hidden md:inline">|</span>
}
<p>Published: {{ metadata['publishedDate'] }}</p>
</div>
</div>
<div class="flex flex-wrap gap-2 text-sm">
@if (metadata['authors'] && metadata['authors'].length > 0) {
<p>by {{ truncateText(metadata['authors'].join(', '), 70) }}</p>
<span class="hidden md:inline">|</span>
}
<p>Source: <span [innerHTML]="buildProviderLink(metadata)"></span></p>
</div>
<p class="mt-4 truncate-text p-secondary">
{{ sanitizeHtml(metadata['description']) }}
</p>
</div>
</div>
<p-divider></p-divider>
</div>
}
</div>
}
}
</form>
}
@@ -0,0 +1,36 @@
.truncate-text {
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
.img-fixed-dimensions {
height: 150px;
width: 100px;
object-fit: fill;
}
.book-item {
position: relative;
cursor: pointer;
}
.book-item-content {
position: relative;
}
.book-item:hover .book-item-content::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(255, 255, 255, 0.075);
}
.book-item:hover .book-item-content {
box-shadow: 0 0 0 rgba(255, 255, 255, 0.9);
}
@@ -0,0 +1,202 @@
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {Divider} from 'primeng/divider';
import {MultiSelect} from 'primeng/multiselect';
import {ProgressSpinner} from 'primeng/progressspinner';
import {FetchMetadataRequest} from '../../../model/request/fetch-metadata-request.model';
import {Book, BookMetadata} from '../../../../book/model/book.model';
import {BookService} from '../../../../book/service/book.service';
import {AppSettings} from '../../../../../shared/model/app-settings.model';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {BehaviorSubject, combineLatest, Observable, Subject, Subscription, takeUntil} from 'rxjs';
import {distinctUntilChanged, filter, switchMap} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import {AsyncPipe} from '@angular/common';
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
@Component({
selector: 'app-metadata-searcher',
templateUrl: './metadata-searcher.component.html',
styleUrls: ['./metadata-searcher.component.scss'],
imports: [
ReactiveFormsModule,
Button,
InputText,
Divider,
ProgressSpinner,
MetadataPickerComponent,
MultiSelect,
AsyncPipe
],
standalone: true
})
export class MetadataSearcherComponent implements OnInit, OnDestroy {
form: FormGroup;
providers: string[] = [];
allFetchedMetadata: BookMetadata[] = [];
bookId!: number;
loading: boolean = false;
searchTriggered = false;
@Input() book$!: Observable<Book | null>;
selectedFetchedMetadata$ = new BehaviorSubject<BookMetadata | null>(null);
private formBuilder = inject(FormBuilder);
private bookService = inject(BookService);
private appSettingsService = inject(AppSettingsService);
private route = inject(ActivatedRoute);
private subscription: Subscription = new Subscription();
private cancelRequest$ = new Subject<void>();
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
constructor() {
this.form = this.formBuilder.group({
provider: null,
title: [''],
author: [''],
isbn: ['']
});
}
ngOnInit() {
this.subscription.add(
this.route.paramMap
.pipe(
switchMap(params => {
const bookId = +params.get('id')!;
if (this.bookId !== bookId) {
this.bookId = bookId;
this.cancelRequest$.next();
this.loading = false;
this.allFetchedMetadata = [];
this.selectedFetchedMetadata$.next(null);
}
return combineLatest([this.book$, this.appSettings$]);
}),
filter(([book, settings]) => !!book && !!settings),
distinctUntilChanged(([prevBook], [currBook]) => prevBook?.id === currBook?.id)
)
.subscribe(([book, settings]) => {
const providerSettings = settings?.metadataProviderSettings ?? {};
this.providers = Object.entries(providerSettings)
.filter(([_, value]) => !!value && typeof value === 'object' && 'enabled' in value && (value as any).enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
this.resetFormFromBook(book!);
if (settings!.autoBookSearch) {
this.onSubmit();
}
})
);
}
private resetFormFromBook(book: Book): void {
this.selectedFetchedMetadata$.next(null);
this.allFetchedMetadata = [];
this.bookId = book.id;
this.form.patchValue({
provider: this.providers,
title: book.metadata?.title ?? '',
author: book.metadata?.authors?.[0] ?? '',
isbn: book.metadata?.isbn13 ?? book.metadata?.isbn10 ?? ''
});
}
ngOnDestroy(): void {
this.cancelRequest$.next();
this.subscription.unsubscribe();
this.selectedFetchedMetadata$.complete();
}
get isSearchEnabled(): boolean {
const providerSelected = !!this.form.get('provider')?.value;
const title = this.form.get('title')?.value;
const isbn = this.form.get('isbn')?.value;
return providerSelected && (title || isbn);
}
onSubmit(): void {
this.searchTriggered = true;
if (this.form.valid) {
const providerKeys = this.form.get('provider')?.value;
if (!providerKeys) return;
const fetchRequest: FetchMetadataRequest = {
bookId: this.bookId,
providers: providerKeys,
title: this.form.get('title')?.value,
author: this.form.get('author')?.value,
isbn: this.form.get('isbn')?.value
};
this.loading = true;
this.cancelRequest$.next();
this.bookService.fetchBookMetadata(fetchRequest.bookId, fetchRequest)
.pipe(takeUntil(this.cancelRequest$))
.subscribe({
next: (fetchedMetadata) => {
this.loading = false;
this.allFetchedMetadata = fetchedMetadata.map(m => ({
...m,
thumbnailUrl: m.thumbnailUrl
}));
},
error: () => {
this.loading = false;
}
});
} else {
console.warn('Form is invalid. Please fill in all required fields.');
}
}
onBookClick(fetchedMetadata: BookMetadata) {
this.selectedFetchedMetadata$.next(fetchedMetadata);
}
onGoBack() {
this.selectedFetchedMetadata$.next(null);
}
sanitizeHtml(htmlString: string | null | undefined): string {
if (!htmlString) return '';
return htmlString.replace(/<\/?[^>]+(>|$)/g, '').trim();
}
truncateText(text: string | null, length: number): string {
const safeText = text ?? '';
return safeText.length > length ? safeText.substring(0, length) + '...' : safeText;
}
buildProviderLink(metadata: BookMetadata): string {
if (metadata.asin) {
return `<a href="https://www.amazon.com/dp/${metadata.asin}" target="_blank">Amazon</a>`;
} else if (metadata.goodreadsId) {
return `<a href="https://www.goodreads.com/book/show/${metadata.goodreadsId}" target="_blank">Goodreads</a>`;
} else if (metadata.googleId) {
return `<a href="https://books.google.com/books?id=${metadata.googleId}" target="_blank">Google</a>`;
} else if (metadata.hardcoverId) {
return `<a href="https://hardcover.app/books/${metadata.hardcoverId}" target="_blank">Hardcover</a>`;
} else if (metadata['doubanId']) {
return `<a href="https://book.douban.com/subject/${metadata['doubanId']}" target="_blank">Douban</a>`;
} else if (metadata.comicvineId) {
if (metadata.comicvineId.startsWith('4000')) {
const name = metadata.seriesName ? metadata.seriesName.replace(/ /g, '-').toLowerCase() + "-" + metadata.seriesNumber : '';
return `<a href="https://comicvine.gamespot.com/${name}/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
}
const name = metadata.seriesName;
return `<a href="https://comicvine.gamespot.com/volume/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
}
throw new Error("No provider ID found in metadata.");
}
}
@@ -0,0 +1,614 @@
@if (book$ | async; as book) {
<div class="p-0 md:p-2 flex flex-col h-full w-full rounded-xl">
<div class="flex flex-col md:flex-row gap-4 md:gap-6 pb-8">
<div class="flex justify-center md:justify-start">
<div class="relative w-[175px] md:w-[250px]">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Image"
width="250"
appendTo="body"
[preview]="true">
</p-image>
@if (book?.metadata!.seriesNumber != null) {
<div class="absolute top-2 left-2 bg-black/60 text-white px-2 py-0.5 rounded-lg text-xs font-semibold">
#{{ book?.metadata!.seriesNumber }}
</div>
}
@let progress = getProgressPercent(book);
@if (progress !== null) {
<p-progressBar
[value]="progress"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="{
'rounded-b-xl': false,
'progress-complete': progress === 100,
'progress-incomplete': progress < 100
}"
[style]="{ height: '6px' }"
></p-progressBar>
}
@if (getKoProgressPercent(book) !== null) {
<p-progressBar
[value]="getKoProgressPercent(book)"
[showValue]="false"
[ngClass]="[
getProgressPercent(book) == null ? 'cover-progress-bar-ko-only' : 'cover-progress-bar-ko-both',
getKoProgressPercent(book) === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'
]"
[style]="{ height: '6px' }"
>
</p-progressBar>
}
</div>
</div>
<div class="flex flex-col justify-between flex-grow">
<div class="space-y-4">
<div class="flex items-start justify-between">
<div class="flex flex-col text-center md:text-left w-full">
@if (book?.metadata?.seriesName) {
<p
class="text-blue-600 cursor-pointer hover:underline"
(click)="goToSeries(book?.metadata?.seriesName!)"
>
{{ book?.metadata?.seriesName }}
@if (book?.metadata?.seriesNumber) {
#{{ book?.metadata?.seriesNumber }}
}
</p>
}
<div class="flex flex-col items-center md:items-start gap-1">
<div class="flex items-center gap-2 justify-center md:justify-start flex-wrap text-center md:text-left">
<h2 class="text-2xl md:text-3xl font-extrabold leading-tight">
{{ book?.metadata?.title }}@if (book?.metadata?.subtitle) {
: {{ book.metadata?.subtitle }}
}
</h2>
<i
class="pi align-middle"
[ngClass]="isMetadataFullyLocked(book?.metadata!) ? 'pi-lock text-red-500' : 'pi-lock-open text-green-500'"
[title]="isMetadataFullyLocked(book?.metadata!) ? 'Metadata is locked' : 'Metadata is unlocked'"
pTooltip="{{ isMetadataFullyLocked(book?.metadata!) ? 'This book metadata is locked.' : 'This book metadata is unlocked.' }}"
tooltipPosition="top"
></i>
</div>
<p class="text-lg">
@for (author of book?.metadata!.authors; track $index; let isLast = $last) {
<a class="hover:underline dark:text-blue-400 cursor-pointer" (click)="goToAuthorBooks(author)">
{{ author }}
</a>
@if (!isLast) {
<span>, </span>
}
}
</p>
</div>
</div>
</div>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-start text-sm w-full">
<div class="flex justify-center sm:justify-start">
<div class="flex items-center gap-2">
<i class="pi pi-thumbs-up-fill text-yellow-500" pTooltip="Personal Rating" tooltipPosition="top"></i>
<p-rating
[ngModel]="book?.metadata!.personalRating"
(onRate)="onPersonalRatingChange(book, $event)"
stars="10"
[style.--p-rating-icon-active-color]="getStarColorScaled(book?.metadata!.personalRating, 10)">
</p-rating>
</div>
<p-button
text
size="small"
icon="pi pi-undo"
severity="warn"
(onClick)="resetPersonalRating(book)"
pTooltip="Reset Rating"
tooltipPosition="top">
</p-button>
</div>
@if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.googleId) {
<span class="hidden sm:inline text-gray-400 text-xl px-1 leading-none">|</span>
}
<div class="flex flex-wrap justify-center sm:justify-start gap-4 pt-1">
@if (book?.metadata?.amazonRating) {
<a
class="flex items-center gap-1"
[href]="'https://www.amazon.com/dp/' + (book.metadata?.asin ?? '')"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="getRatingTooltip(book, 'amazon')"
tooltipPosition="top"
>
<img
src="https://www.amazon.com/favicon.ico"
alt="Amazon"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
<span class="font-semibold">
{{ getRatingPercent(book.metadata!.amazonRating) }}%
</span>
</a>
}
@if (book?.metadata?.goodreadsRating) {
<a
class="flex items-center gap-1"
[href]="'https://www.goodreads.com/book/show/' + (book.metadata?.goodreadsId ?? '')"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="getRatingTooltip(book, 'goodreads')"
tooltipPosition="top"
>
<img
src="https://www.goodreads.com/favicon.ico"
alt="Goodreads"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
<span class="font-semibold">
{{ getRatingPercent(book.metadata!.goodreadsRating) }}%
</span>
</a>
}
@if (book?.metadata?.hardcoverRating) {
<a
class="flex items-center gap-1"
[href]="'https://hardcover.app/books/' + (book.metadata?.hardcoverId ?? '')"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="getRatingTooltip(book, 'hardcover')"
tooltipPosition="top"
>
<img
src="https://assets.hardcover.app/static/favicon.ico"
alt="Hardcover"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
<span class="font-semibold">
{{ getRatingPercent(book.metadata!.hardcoverRating) }}%
</span>
</a>
}
@if (book?.metadata?.googleId) {
<a
class="flex items-center gap-1"
[href]="'https://books.google.com/books?id=' + book.metadata!.googleId"
target="_blank"
rel="noopener noreferrer"
>
<img
src="https://books.google.com/favicon.ico"
alt="Google Books"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
</a>
}
@if (book?.metadata?.comicvineId) {
<a
class="flex items-center gap-1"
[href]="'https://comicvine.gamespot.com/' + book.metadata!.comicvineId"
target="_blank"
rel="noopener noreferrer"
>
<img
src="https://www.comicvine.com/favicon.ico"
alt="Comic Vine"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
</a>
}
</div>
</div>
<div class="flex flex-col space-y-2">
@if (book?.metadata?.categories?.length) {
<div class="flex items-center gap-1">
<p class="font-bold text-sm w-[50px]">Genres:</p>
<div class="overflow-x-auto scrollbar-hide max-w-7xl">
<div class="flex gap-2 w-max max-w-[1150px]">
@for (category of book.metadata!.categories; track category) {
<a (click)="goToCategory(category)" class="shrink-0 no-underline cursor-pointer">
<app-tag color="rose" size="xs">{{ category }}</app-tag>
</a>
}
</div>
</div>
</div>
}
@if (book?.metadata?.moods?.length) {
<div class="flex items-center gap-1">
<p class="font-bold text-sm w-[50px]">Moods:</p>
<div class="overflow-x-auto scrollbar-hide max-w-7xl">
<div class="flex gap-2 w-max max-w-[1150px]">
@for (mood of book.metadata!.moods; track mood) {
<a (click)="goToMood(mood)" class="shrink-0 no-underline cursor-pointer">
<app-tag color="indigo" size="xs">{{ mood }}</app-tag>
</a>
}
</div>
</div>
</div>
}
@if (book?.metadata?.tags?.length) {
<div class="flex items-center gap-1">
<p class="font-bold text-sm w-[50px]">Tags:</p>
<div class="overflow-x-auto scrollbar-hide max-w-7xl">
<div class="flex gap-2 w-max max-w-[1150px]">
@for (tag of book.metadata!.tags; track tag) {
<a (click)="goToTag(tag)" class="shrink-0 no-underline cursor-pointer">
<app-tag color="cyan" size="xs">{{ tag }}</app-tag>
</a>
}
</div>
</div>
</div>
}
</div>
<div class="px-1 md:px-0">
<div class="grid md:grid-cols-4 gap-y-2.5 text-sm pt-2 md:pt-4 pb-2 text-gray-300 md:min-w-[60rem] md:max-w-[100rem]">
<p class="whitespace-nowrap max-w-[250px] overflow-hidden text-ellipsis">
<span class="font-bold">Library: </span>
@if (book?.libraryName) {
<span>{{ book.libraryName }}</span>
}
</p>
<p class="whitespace-nowrap max-w-[250px] overflow-hidden text-ellipsis">
<span class="font-bold">Publisher: </span>
@if (book?.metadata?.publisher) {
<span class="underline hover:opacity-80 cursor-pointer" (click)="goToPublisher(book?.metadata?.publisher!)">
{{ book?.metadata?.publisher }}
</span>
} @else {
<span>-</span>
}
</p>
<p><strong>Published:</strong> {{ book?.metadata!.publishedDate || '-' }}</p>
<p><strong>Language:</strong> {{ book?.metadata!.language || '-' }}</p>
<p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">File Type:</span>
<app-tag size="3xs" variant="pill" [color]="getFileTypeColor(getFileExtension(book?.filePath))">
{{ (getFileExtension(book?.filePath) | uppercase) || '-' }}
</app-tag>
</p>
<p class="whitespace-nowrap flex items-center">
<span class="font-bold mr-2">BookLore Progress:</span>
<span class="inline-flex items-center">
<app-tag size="3xs" variant="pill" [color]="getProgressColor(getProgressPercent(book))">
{{ getProgressPercent(book) !== null ? getProgressPercent(book) + '%' : 'N/A' }}
</app-tag>
@if (getProgressPercent(book) !== null) {
<p-button
pTooltip="Reset progress"
tooltipPosition="bottom"
icon="pi pi-refresh"
size="small"
severity="danger"
text
class="ml-1 custom-button-padding"
(onClick)="resetProgress(book, ResetProgressTypes.BOOKLORE)">
</p-button>
}
</span>
</p>
<p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">Metadata Match:</span>
@if (book?.metadataMatchScore != null) {
<app-tag size="3xs" variant="pill" [color]="getMatchScoreColor(book?.metadataMatchScore!)">
{{ (book?.metadataMatchScore!) | number:'1.0-0' }}%
</app-tag>
} @else {
<span>-</span>
}
</p>
<p>
<strong>ISBN:</strong>
@if (book?.metadata?.isbn13 || book?.metadata?.isbn10) {
{{ book.metadata!.isbn13 }}
@if (book?.metadata?.isbn13 && book?.metadata?.isbn10) {
/
}
{{ book.metadata!.isbn10 }}
} @else {
<span>-</span>
}
</p>
<p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">Read Status:</span>
<app-tag size="3xs" variant="pill" [color]="getStatusColor(selectedReadStatus)">
{{ getStatusLabel(selectedReadStatus) }}
</app-tag>
<i
class="pi pi-pencil cursor-pointer text-[cornflowerblue] hover:text-[darkturquoise] transition-colors"
(click)="menu.toggle($event)">
</i>
<p-menu #menu [popup]="true" [model]="readStatusMenuItems"></p-menu>
</p>
@if (book?.koreaderProgress && book.koreaderProgress?.percentage != null) {
<p class="whitespace-nowrap flex items-center">
<span class="font-bold mr-2">KOReader Progress:</span>
<span class="inline-flex items-center">
<app-tag size="3xs" variant="pill" [color]="getKoProgressColor(getKOReaderPercentage(book))">
{{ getKOReaderPercentage(book) + '%' }}
</app-tag>
@if (getKOReaderPercentage(book) !== null) {
<p-button
pTooltip="Reset progress"
tooltipPosition="bottom"
icon="pi pi-refresh"
size="small"
severity="danger"
text
class="ml-1 custom-button-padding"
(onClick)="resetProgress(book, ResetProgressTypes.KOREADER)">
</p-button>
}
</span>
</p>
}
@if (selectedReadStatus === ReadStatus.READ) {
<div>
@if (book?.dateFinished) {
<div class="flex items-center gap-2">
<p><strong>Finished On: </strong></p>
@if (!isEditingDateFinished) {
<div class="flex items-center gap-2">
<p>{{ formatDate(book.dateFinished) }}</p>
<i class="pi pi-pencil text-[cornflowerblue] hover:text-[darkturquoise] cursor-pointer"
(click)="toggleDateFinishedEdit(book)">
</i>
</div>
} @else {
<div class="flex items-center">
<p-datepicker
[(ngModel)]="editDateFinished"
dateFormat="dd-M-yy"
size="small"
[showIcon]="true"
iconDisplay="input"
[style]="{ 'width': '125px', 'font-size': '12px' }"
class="text-xs">
</p-datepicker>
<p-button
rounded
icon="pi pi-check"
size="small"
severity="success"
text
(onClick)="saveDateFinished(book)"
pTooltip="Save date">
</p-button>
<p-button
rounded
icon="pi pi-times"
size="small"
severity="danger"
text
(onClick)="cancelDateFinishedEdit()"
pTooltip="Cancel">
</p-button>
</div>
}
</div>
}
</div>
}
<p><strong>Page Count:</strong> {{ book?.metadata!.pageCount || '-' }}</p>
<p><strong>File Size:</strong> {{ getFileSizeInMB(book) }}</p>
</div>
<div class="flex items-center gap-2">
<span class="font-semibold text-sm">File Path:</span>
<i
class="pi cursor-pointer text-sm"
[ngClass]="showFilePath ? 'pi-eye-slash' : 'pi-eye'"
(click)="showFilePath = !showFilePath"
></i>
@if (showFilePath) {
<code class="text-xs font-mono truncate text-gray-300">{{ book?.filePath }}</code>
}
</div>
</div>
</div>
@if (userService.userState$ | async; as userState) {
<div class="flex flex-wrap gap-3 pt-6">
@if (book!.bookType === 'PDF') {
@if (readMenuItems$ | async; as readItems) {
<p-splitbutton
label="Read"
icon="pi pi-book"
[model]="readItems"
(onClick)="read(book.id, 'ngx')"
severity="primary"/>
}
}
@if (book!.bookType !== 'PDF') {
<p-button
label="Read"
icon="pi pi-book"
(onClick)="read(book?.metadata!.bookId, undefined)"
severity="primary"/>
}
<p-button
label="Shelf"
icon="pi pi-folder"
severity="secondary"
outlined
(onClick)="assignShelf(book.id)">
</p-button>
@if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
@if (downloadMenuItems$ | async; as downloadItems) {
<p-splitbutton
label="Download"
icon="pi pi-download"
[model]="downloadItems"
(onClick)="download(book!.id)"
severity="success"
outlined/>
}
} @else {
<p-button
label="Download"
icon="pi pi-download"
severity="success"
outlined
(onClick)="download(book!.id)">
</p-button>
}
}
@if (userState.user!.permissions.canEmailBook || userState.user!.permissions.admin) {
@if (emailMenuItems$ | async; as emailItems) {
<p-splitbutton
label="Quick Send"
icon="pi pi-send"
[model]="emailItems"
(onClick)="quickSend(book!.id)"
outlined
severity="info">
</p-splitbutton>
}
}
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
@if (refreshMenuItems$ | async; as refreshItems) {
<p-splitbutton
[label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'"
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
[outlined]="true"
[model]="refreshItems"
severity="warn"
(onClick)="quickRefresh(book!.id)"
[disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top">
</p-splitbutton>
}
}
@if (userState.user!.permissions.canDeleteBook || userState.user!.permissions.admin) {
@if (otherItems$ | async; as otherItems) {
<p-button icon="pi pi-ellipsis-v" outlined severity="primary" (click)="entitymenu.toggle($event)"></p-button>
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
}
}
</div>
}
</div>
</div>
<div class="px-4 pb-2 pt-4 mb-4 md:mb-6 md:mx-2 border border-[var(--border-color)] rounded-xl">
<div [ngClass]="{ 'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded }" class="transition-all duration-300 overflow-hidden description-container">
<div class="readonly-editor px-2">
<p-editor #quillEditor [readonly]="true" [style]="{height: '200px'}" [(ngModel)]="book.metadata!.description">
<ng-template #header>
</ng-template>
</p-editor>
</div>
</div>
@if (book.metadata!.description && book.metadata!.description.length > 500) {
<p-button
[label]="isExpanded ? 'Show less' : 'Show more'"
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
iconPos="right"
size="small"
text
(click)="toggleExpand()">
</p-button>
}
</div>
<p-tabs lazy="true" class="custom-p-tabs" [value]="defaultTabValue" scrollable>
<p-tablist>
@if (bookInSeries.length > 0) {
<p-tab [value]="1">
<i class="pi pi-ethereum"></i> More in Series
</p-tab>
}
<p-tab [value]="2">
<i class="pi pi-bookmark"></i> Similar Books
</p-tab>
<p-tab [value]="3">
<i class="pi pi-pen-to-square"></i> Notes
</p-tab>
<p-tab [value]="4">
<i class="pi pi-comments"></i> Reviews
</p-tab>
</p-tablist>
<p-tabpanels>
<p-tabpanel [value]="1">
<div class="pt-2">
@if (bookInSeries.length > 0) {
<div>
<div class="dashboard-scroller-infinite"
infiniteScroll
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50"
[horizontal]="true">
@for (bookInSeriesItem of bookInSeries; track bookInSeriesItem) {
<div class="dashboard-scroller-card">
<app-book-card-lite-component [book]="bookInSeriesItem" [isActive]="bookInSeriesItem.id === book.id"></app-book-card-lite-component>
</div>
}
</div>
</div>
}
</div>
</p-tabpanel>
<p-tabpanel [value]="2">
<div class="pt-2">
@if (recommendedBooks.length > 0) {
<div>
<div class="dashboard-scroller-infinite"
infiniteScroll
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50"
[horizontal]="true">
@for (book of recommendedBooks; track book.book.id) {
<div class="dashboard-scroller-card">
<app-book-card-lite-component [book]="book.book"></app-book-card-lite-component>
</div>
}
</div>
</div>
}
</div>
</p-tabpanel>
<p-tabpanel [value]="3">
<app-book-notes-component [bookId]="book.id"></app-book-notes-component>
</p-tabpanel>
<p-tabpanel [value]="4">
<app-book-reviews [bookId]="book.id"></app-book-reviews>
</p-tabpanel>
</p-tabpanels>
</p-tabs>
</div>
} @else {
<div class="flex flex-col justify-center items-center h-full gap-4">
<p-progressSpinner
strokeWidth="4"
fill="transparent"
animationDuration=".8s">
</p-progressSpinner>
<p style="color: var(--primary-color);">
Loading book details...
</p>
</div>
}
@@ -0,0 +1,171 @@
::ng-deep .readonly-editor .p-editor {
.p-editor-toolbar.ql-snow {
padding: 0 !important;
border: none !important;
box-shadow: none !important;
}
.p-editor-content.ql-snow {
border: none !important;
border-end-end-radius: 0 !important;
border-end-start-radius: 0 !important;
}
.ql-editor {
padding: 0 !important;
}
}
::ng-deep .readonly-editor .ql-container {
font-size: 14px !important;
}
::ng-deep p-togglebutton.my-visibility-toggle span[data-pc-section="label"] {
display: none;
padding: 0px !important;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
.scrollbar-hide {
scrollbar-width: none;
-ms-overflow-style: none; /* for IE 10+ */
}
.dashboard-scroller-infinite {
display: flex;
overflow-x: auto;
overflow-y: hidden;
scroll-snap-type: x mandatory;
padding: 0.25rem;
gap: 1.25rem;
width: 100%;
height: 100%;
}
.dashboard-scroller-card {
width: 115px;
flex-basis: 115px;
flex-shrink: 0;
flex-grow: 0;
scroll-snap-align: start;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
border-radius: 8px;
&:hover {
transform: translateY(-4px);
&::after {
opacity: 1;
}
}
&::after {
content: '';
position: absolute;
bottom: 0;
left: 7%;
right: 7%;
height: 4px;
background: linear-gradient(
90deg,
transparent,
var(--p-primary-500),
transparent
);
border-radius: 50%;
opacity: 0;
transition: all 0.4s ease;
filter: blur(4px);
}
}
.description-container {
max-height: 60px;
overflow: hidden;
transition: max-height 0.3s ease-in-out;
}
.description-container .description-content {
max-height: 250px;
overflow-y: auto;
}
.line-clamp-none {
max-height: none;
overflow: visible;
}
.series-number-overlay {
position: absolute;
top: 6px;
right: 6px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
font-size: 0.8rem;
padding: 1px 3px;
border-radius: 3px;
z-index: 3;
}
.cover-progress-bar,
.cover-progress-bar-ko-both,
.cover-progress-bar-ko-only {
position: absolute;
left: 0;
right: 0;
z-index: 2;
pointer-events: none;
}
.cover-progress-bar {
bottom: 0;
}
.cover-progress-bar-ko-both {
bottom: 0;
height: 12px;
z-index: 3;
}
.cover-progress-bar-ko-only {
bottom: 0;
}
.custom-p-tabs > .p-tabpanels {
padding-top: 10px !important;
padding-bottom: 0 !important;
padding-left: 0 !important;
padding-right: 0 !important;
}
::ng-deep .p-inputchips {
width: 100%;
}
::ng-deep .progress-incomplete .p-progressbar-value {
background-color: #3b82f6;
}
::ng-deep .progress-complete .p-progressbar-value {
background-color: #22c55e;
}
::ng-deep .progress-incomplete-ko .p-progressbar-value {
background-color: #fbbf24;
}
::ng-deep .progress-complete-ko .p-progressbar-value {
background-color: #8b5cf6;
}
::ng-deep .custom-button-padding .p-button {
padding-block: 0rem !important;
}
::ng-deep .custom-tag-padding {
padding: 0.1rem !important;
}
@@ -0,0 +1,830 @@
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {Button} from 'primeng/button';
import {AsyncPipe, DecimalPipe, NgClass, UpperCasePipe} from '@angular/common';
import {Observable} from 'rxjs';
import {BookService} from '../../../../book/service/book.service';
import {Rating, RatingRateEvent} from 'primeng/rating';
import {FormsModule} from '@angular/forms';
import {Book, BookMetadata, BookRecommendation, FileInfo, ReadStatus} from '../../../../book/model/book.model';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {UserService} from '../../../../settings/user-management/user.service';
import {SplitButton} from 'primeng/splitbutton';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
import {BookSenderComponent} from '../../../../book/components/book-sender/book-sender.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {EmailService} from '../../../../settings/email/email.service';
import {ShelfAssignerComponent} from '../../../../book/components/shelf-assigner/shelf-assigner.component';
import {Tooltip} from 'primeng/tooltip';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Editor} from 'primeng/editor';
import {ProgressBar} from 'primeng/progressbar';
import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum';
import {MetadataRefreshRequest} from '../../../model/request/metadata-refresh-request.model';
import {Router} from '@angular/router';
import {filter, map, switchMap, take, tap} from 'rxjs/operators';
import {Menu} from 'primeng/menu';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {BookCardLiteComponent} from '../../../../book/components/book-card-lite/book-card-lite-component';
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
import {DatePicker} from 'primeng/datepicker';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {BookReviewsComponent} from '../../../../book/components/book-reviews/book-reviews.component';
import {ProgressSpinner} from 'primeng/progressspinner';
import {TieredMenu} from 'primeng/tieredmenu';
import {AdditionalFileUploaderComponent} from '../../../../book/components/additional-file-uploader/additional-file-uploader.component';
import {Image} from 'primeng/image';
import {BookDialogHelperService} from '../../../../book/components/book-browser/BookDialogHelperService';
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
import {MetadataFetchOptionsComponent} from '../../metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
import {BookNotesComponent} from '../../../../book/components/book-notes/book-notes-component';
@Component({
selector: 'app-metadata-viewer',
standalone: true,
templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss',
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker, Tab, TabList, TabPanel, TabPanels, Tabs, BookReviewsComponent, BookNotesComponent, ProgressSpinner, TieredMenu, Image, TagComponent, UpperCasePipe]
})
export class MetadataViewerComponent implements OnInit, OnChanges {
@Input() book$!: Observable<Book | null>;
@Input() recommendedBooks: BookRecommendation[] = [];
@ViewChild(Editor) quillEditor!: Editor;
private originalRecommendedBooks: BookRecommendation[] = [];
private dialogService = inject(DialogService);
private emailService = inject(EmailService);
private messageService = inject(MessageService);
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
protected userService = inject(UserService);
private confirmationService = inject(ConfirmationService);
private bookDialogHelperService = inject(BookDialogHelperService);
private router = inject(Router);
private destroyRef = inject(DestroyRef);
private dialogRef?: DynamicDialogRef;
emailMenuItems$!: Observable<MenuItem[]>;
readMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
otherItems$!: Observable<MenuItem[]>;
downloadMenuItems$!: Observable<MenuItem[]>;
bookInSeries: Book[] = [];
isExpanded = false;
showFilePath = false;
isAutoFetching = false;
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
selectedReadStatus: ReadStatus = ReadStatus.UNREAD;
isEditingDateFinished = false;
editDateFinished: Date | null = null;
readStatusOptions: { value: ReadStatus, label: string }[] = [
{value: ReadStatus.UNREAD, label: 'Unread'},
{value: ReadStatus.PAUSED, label: 'Paused'},
{value: ReadStatus.READING, label: 'Reading'},
{value: ReadStatus.RE_READING, label: 'Re-reading'},
{value: ReadStatus.READ, label: 'Read'},
{value: ReadStatus.PARTIALLY_READ, label: 'Partially Read'},
{value: ReadStatus.ABANDONED, label: 'Abandoned'},
{value: ReadStatus.WONT_READ, label: 'Won\'t Read'},
{value: ReadStatus.UNSET, label: 'Unset'},
];
ngOnInit(): void {
this.emailMenuItems$ = this.book$.pipe(
map(book => book?.metadata ?? null),
filter((metadata): metadata is BookMetadata => metadata != null),
map((metadata): MenuItem[] => [
{
label: 'Custom Send',
command: () => {
this.dialogService.open(BookSenderComponent, {
header: 'Send Book to Email',
modal: true,
closable: true,
style: {position: 'absolute', top: '20%'},
data: {bookId: metadata.bookId}
});
}
}
])
);
this.refreshMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Custom Fetch',
icon: 'pi pi-sync',
command: () => {
this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
bookIds: [book.id],
metadataRefreshType: MetadataRefreshType.BOOKS,
},
});
}
}
])
);
this.readMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Streaming Reader',
command: () => this.read(book.id, 'streaming')
}
])
);
this.downloadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null &&
((book.alternativeFormats !== undefined && book.alternativeFormats.length > 0) ||
(book.supplementaryFiles !== undefined && book.supplementaryFiles.length > 0))),
map((book): MenuItem[] => {
const items: MenuItem[] = [];
// Add alternative formats
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
items.push({
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(book.id, format.id)
});
});
}
// Add separator if both types exist
if (book.alternativeFormats && book.alternativeFormats.length > 0 &&
book.supplementaryFiles && book.supplementaryFiles.length > 0) {
items.push({separator: true});
}
// Add supplementary files
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(book.id, file.id)
});
});
}
return items;
})
);
this.otherItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => {
const items: MenuItem[] = [
{
label: 'Upload File',
icon: 'pi pi-upload',
command: () => {
this.dialogService.open(AdditionalFileUploaderComponent, {
header: 'Upload Additional File',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '10%',
},
data: {book}
});
},
},
{
label: 'Organize Files',
icon: 'pi pi-arrows-h',
command: () => {
this.openFileMoverDialog(book.id);
},
},
{
label: 'Delete Book',
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to delete "${book.metadata?.title}"?`,
header: 'Confirm Deletion',
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookService.deleteBooks(new Set([book.id])).subscribe({
next: () => {
if (this.metadataCenterViewMode === 'route') {
this.router.navigate(['/dashboard']);
} else {
this.dialogRef?.close();
}
},
error: () => {
}
});
}
});
},
},
];
// Add delete additional files menu if there are any additional files
if ((book.alternativeFormats && book.alternativeFormats.length > 0) ||
(book.supplementaryFiles && book.supplementaryFiles.length > 0)) {
const deleteFileItems: MenuItem[] = [];
// Add alternative formats
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
deleteFileItems.push({
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
icon: this.getFileIcon(extension),
command: () => this.deleteAdditionalFile(book.id, format.id, format.fileName || 'file')
});
});
}
// Add separator if both types exist
if (book.alternativeFormats && book.alternativeFormats.length > 0 &&
book.supplementaryFiles && book.supplementaryFiles.length > 0) {
deleteFileItems.push({separator: true});
}
// Add supplementary files
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
deleteFileItems.push({
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
icon: this.getFileIcon(extension),
command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file')
});
});
}
items.push({
label: 'Delete Additional Files',
icon: 'pi pi-trash',
items: deleteFileItems
});
}
return items;
})
);
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
take(1)
)
.subscribe(userState => {
this.metadataCenterViewMode = userState.user?.userSettings.metadataCenterViewMode ?? 'route';
});
this.book$
.pipe(
takeUntilDestroyed(this.destroyRef),
filter((book): book is Book => book != null && book.metadata != null)
)
.subscribe(book => {
const metadata = book.metadata;
this.isAutoFetching = false;
this.loadBooksInSeriesAndFilterRecommended(metadata!.bookId);
if (this.quillEditor?.quill) {
this.quillEditor.quill.root.innerHTML = metadata!.description;
}
this.selectedReadStatus = book.readStatus ?? ReadStatus.UNREAD;
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['recommendedBooks']) {
this.originalRecommendedBooks = [...this.recommendedBooks];
this.withCurrentBook(book => this.filterRecommendations(book));
}
}
private withCurrentBook(callback: (book: Book | null) => void): void {
this.book$.pipe(take(1)).subscribe(callback);
}
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
this.bookService.getBooksInSeries(bookId).pipe(
tap(series => {
series.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
this.bookInSeries = series;
this.originalRecommendedBooks = [...this.recommendedBooks];
}),
switchMap(() => this.book$.pipe(take(1))),
takeUntilDestroyed(this.destroyRef)
).subscribe(book => this.filterRecommendations(book));
}
private filterRecommendations(book: Book | null): void {
if (!this.originalRecommendedBooks) return;
const bookInSeriesIds = new Set(this.bookInSeries.map(book => book.id));
this.recommendedBooks = this.originalRecommendedBooks.filter(
rec => !bookInSeriesIds.has(rec.book.id)
);
}
get defaultTabValue(): number {
return this.bookInSeries && this.bookInSeries.length > 0 ? 1 : 2;
}
toggleExpand(): void {
this.isExpanded = !this.isExpanded;
}
read(bookId: number | undefined, reader: "ngx" | "streaming" | undefined): void {
if (bookId) this.bookService.readBook(bookId, reader);
}
download(bookId: number) {
this.bookService.downloadFile(bookId);
}
downloadAdditionalFile(bookId: number, fileId: number) {
this.bookService.downloadAdditionalFile(bookId, fileId);
}
deleteAdditionalFile(bookId: number, fileId: number, fileName: string) {
this.confirmationService.confirm({
message: `Are you sure you want to delete the additional file "${fileName}"?`,
header: 'Confirm File Deletion',
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookService.deleteAdditionalFile(bookId, fileId).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Success',
detail: `Additional file "${fileName}" deleted successfully`
});
},
error: (error) => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: `Failed to delete additional file: ${error.message || 'Unknown error'}`
});
}
});
}
});
}
quickRefresh(bookId: number) {
this.isAutoFetching = true;
const request: MetadataRefreshRequest = {
refreshType: MetadataRefreshType.BOOKS,
bookIds: [bookId],
};
this.bookService.autoRefreshMetadata(request).subscribe();
setTimeout(() => {
this.isAutoFetching = false;
}, 15000);
}
quickSend(bookId: number) {
this.emailService.emailBookQuick(bookId).subscribe({
next: () => this.messageService.add({
severity: 'info',
summary: 'Success',
detail: 'The book sending has been scheduled.',
}),
error: (err) => this.messageService.add({
severity: 'error',
summary: 'Error',
detail: err?.error?.message || 'An error occurred while sending the book.',
})
});
}
assignShelf(bookId: number) {
this.dialogService.open(ShelfAssignerComponent, {
header: `Update Book's Shelves`,
modal: true,
closable: true,
contentStyle: {overflow: 'auto'},
baseZIndex: 10,
style: {position: 'absolute', top: '15%'},
data: {book: this.bookService.getBookByIdFromState(bookId)}
});
}
updateReadStatus(status: ReadStatus): void {
if (!status) {
return;
}
this.book$.pipe(take(1)).subscribe(book => {
if (!book || !book.id) {
return;
}
this.bookService.updateBookReadStatus(book.id, status).subscribe({
next: (updatedBooks) => {
this.selectedReadStatus = status;
this.messageService.add({
severity: 'success',
summary: 'Read Status Updated',
detail: `Marked as "${this.getStatusLabel(status)}"`,
life: 2000
});
},
error: (err) => {
console.error('Failed to update read status:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update read status.',
life: 3000
});
}
});
});
}
resetProgress(book: Book, type: ResetProgressType): void {
this.confirmationService.confirm({
message: `Reset reading progress for "${book.metadata?.title}"?`,
header: 'Confirm Reset',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'Cancel',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookService.resetProgress(book.id, type).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Progress Reset',
detail: 'Reading progress has been reset.',
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not reset progress.',
life: 1500
});
}
});
}
});
}
onPersonalRatingChange(book: Book, {value: personalRating}: RatingRateEvent): void {
if (!book?.metadata) return;
const updatedMetadata = {...book.metadata, personalRating};
this.bookService.updateBookMetadata(book.id, {
metadata: updatedMetadata,
clearFlags: {personalRating: false}
}, false).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Rating Saved',
detail: 'Personal rating updated successfully'
});
},
error: err => {
console.error('Failed to update personal rating:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update personal rating'
});
}
});
}
resetPersonalRating(book: Book): void {
if (!book?.metadata) return;
const updatedMetadata = {...book.metadata, personalRating: null};
this.bookService.updateBookMetadata(book.id, {
metadata: updatedMetadata,
clearFlags: {personalRating: true}
}, false).subscribe({
next: () => {
this.messageService.add({
severity: 'info',
summary: 'Rating Reset',
detail: 'Personal rating has been cleared.'
});
},
error: err => {
console.error('Failed to reset personal rating:', err);
this.messageService.add({
severity: 'error',
summary: 'Reset Failed',
detail: 'Could not reset personal rating'
});
}
});
}
goToAuthorBooks(author: string): void {
this.handleMetadataClick('author', author);
}
goToCategory(category: string): void {
this.handleMetadataClick('category', category);
}
goToMood(mood: string): void {
this.handleMetadataClick('mood', mood);
}
goToTag(tag: string): void {
this.handleMetadataClick('tag', tag);
}
goToSeries(seriesName: string): void {
const encodedSeriesName = encodeURIComponent(seriesName);
this.router.navigate(['/series', encodedSeriesName]);
}
goToPublisher(publisher: string): void {
this.handleMetadataClick('publisher', publisher);
}
private navigateToFilteredBooks(filterKey: string, filterValue: string): void {
this.router.navigate(['/all-books'], {
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: `${filterKey}:${filterValue}`
}
});
}
private handleMetadataClick(filterKey: string, filterValue: string): void {
if (this.metadataCenterViewMode === 'dialog') {
this.dialogRef?.close();
setTimeout(() => this.navigateToFilteredBooks(filterKey, filterValue), 200);
} else {
this.navigateToFilteredBooks(filterKey, filterValue);
}
}
isMetadataFullyLocked(metadata: BookMetadata): boolean {
const lockedKeys = Object.keys(metadata).filter(k => k.endsWith('Locked'));
return lockedKeys.length > 0 && lockedKeys.every(k => metadata[k] === true);
}
getFileSizeInMB(fileInfo: FileInfo | null | undefined): string {
const sizeKb = fileInfo?.fileSizeKb;
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
}
getProgressPercent(book: Book): number | null {
if (book.epubProgress?.percentage != null) {
return book.epubProgress.percentage;
}
if (book.pdfProgress?.percentage != null) {
return book.pdfProgress.percentage;
}
if (book.cbxProgress?.percentage != null) {
return book.cbxProgress.percentage;
}
return null;
}
getKoProgressPercent(book: Book): number | null {
if (book.koreaderProgress?.percentage != null) {
return book.koreaderProgress.percentage;
}
return null;
}
getFileExtension(filePath?: string): string | null {
if (!filePath) return null;
const parts = filePath.split('.');
if (parts.length < 2) return null;
return parts.pop()?.toUpperCase() || null;
}
getFileIcon(fileType: string | null): string {
if (!fileType) return 'pi pi-file';
switch (fileType.toLowerCase()) {
case 'pdf':
return 'pi pi-file-pdf';
case 'epub':
case 'mobi':
case 'azw3':
return 'pi pi-book';
case 'cbz':
case 'cbr':
case 'cbx':
return 'pi pi-image';
default:
return 'pi pi-file';
}
}
getFileTypeColor(fileType: string | null | undefined): TagColor {
if (!fileType) return 'gray';
switch (fileType.toLowerCase()) {
case 'pdf':
return 'pink';
case 'epub':
return 'indigo';
case 'cbz':
return 'teal';
case 'cbr':
return 'purple';
case 'cb7':
return 'blue';
default:
return 'gray';
}
}
getStarColorScaled(rating?: number | null, maxScale: number = 5): string {
if (rating == null) {
return 'rgb(203, 213, 225)';
}
const normalized = rating / maxScale;
if (normalized >= 0.9) {
return 'rgb(34, 197, 94)';
} else if (normalized >= 0.75) {
return 'rgb(52, 211, 153)';
} else if (normalized >= 0.6) {
return 'rgb(234, 179, 8)';
} else if (normalized >= 0.4) {
return 'rgb(249, 115, 22)';
} else {
return 'rgb(239, 68, 68)';
}
}
getMatchScoreColor(score: number): TagColor {
if (score >= 0.95) return 'emerald';
if (score >= 0.90) return 'green';
if (score >= 0.80) return 'lime';
if (score >= 0.70) return 'yellow';
if (score >= 0.60) return 'amber';
if (score >= 0.50) return 'orange';
if (score >= 0.40) return 'red';
if (score >= 0.30) return 'rose';
return 'pink';
}
getStatusColor(status: string | null | undefined): TagColor {
const normalized = status?.toUpperCase() ?? '';
switch (normalized) {
case 'UNREAD':
return 'gray';
case 'PAUSED':
return 'zinc';
case 'READING':
return 'blue';
case 'RE_READING':
return 'indigo';
case 'READ':
return 'green';
case 'PARTIALLY_READ':
return 'yellow';
case 'ABANDONED':
return 'red';
case 'WONT_READ':
return 'pink';
default:
return 'gray';
}
}
getProgressColor(progress: number | null | undefined): TagColor {
if (progress == null) return 'gray';
return 'blue';
}
getKoProgressColor(progress: number | null | undefined): TagColor {
if (progress == null) return 'gray';
return 'amber';
}
getKOReaderPercentage(book: Book): number | null {
const p = book?.koreaderProgress?.percentage;
return p != null ? Math.round(p * 10) / 10 : null;
}
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover'): string {
const meta = book?.metadata;
if (!meta) return '';
switch (source) {
case 'amazon':
return meta.amazonRating != null
? `★ ${meta.amazonRating} | ${meta.amazonReviewCount?.toLocaleString() ?? '0'} reviews`
: '';
case 'goodreads':
return meta.goodreadsRating != null
? `★ ${meta.goodreadsRating} | ${meta.goodreadsReviewCount?.toLocaleString() ?? '0'} reviews`
: '';
case 'hardcover':
return meta.hardcoverRating != null
? `★ ${meta.hardcoverRating} | ${meta.hardcoverReviewCount?.toLocaleString() ?? '0'} reviews`
: '';
default:
return '';
}
}
getRatingPercent(rating: number | null | undefined): number {
if (rating == null) return 0;
return Math.round((rating / 5) * 100);
}
readStatusMenuItems = this.readStatusOptions.map(option => ({
label: option.label,
command: () => this.updateReadStatus(option.value)
}));
getStatusLabel(value: string): string {
return this.readStatusOptions.find(o => o.value === value)?.label.toUpperCase() ?? 'UNSET';
}
formatDate(dateString: string | undefined): string {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
toggleDateFinishedEdit(book: Book): void {
if (this.isEditingDateFinished) {
this.isEditingDateFinished = false;
this.editDateFinished = null;
} else {
this.isEditingDateFinished = true;
this.editDateFinished = book.dateFinished ? new Date(book.dateFinished) : new Date();
}
}
saveDateFinished(book: Book): void {
if (!book) return;
const dateToSave = this.editDateFinished ? this.editDateFinished.toISOString() : null;
this.bookService.updateDateFinished(book.id, dateToSave).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Date Updated',
detail: 'Book finish date has been updated.',
life: 1500
});
this.isEditingDateFinished = false;
this.editDateFinished = null;
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update book finish date.',
life: 3000
});
}
});
}
cancelDateFinishedEdit(): void {
this.isEditingDateFinished = false;
this.editDateFinished = null;
}
openFileMoverDialog(bookId: number): void {
this.bookDialogHelperService.openFileMoverDialog(new Set([bookId]));
}
protected readonly ResetProgressTypes = ResetProgressTypes;
protected readonly ReadStatus = ReadStatus;
}