Make Metadata Fetching and Updates Fully Reactive and Real-Time

This commit is contained in:
aditya.chandel
2025-06-19 10:41:11 -06:00
committed by Aditya Chandel
parent 551234f02a
commit ddc0244234
13 changed files with 660 additions and 642 deletions
@@ -11,16 +11,16 @@
</p-tablist>
<p-tabpanels class="overflow-auto" style="height: calc(100vh - 10rem);">
<p-tabpanel value="view">
<app-metadata-viewer [book]="book" [recommendedBooks]="recommendedBooks"></app-metadata-viewer>
<app-metadata-viewer [book$]="book$" [recommendedBooks]="recommendedBooks"></app-metadata-viewer>
</p-tabpanel>
@if (admin || canEditMetadata) {
<p-tabpanel value="edit">
<app-metadata-editor></app-metadata-editor>
<app-metadata-editor [book$]="book$"></app-metadata-editor>
</p-tabpanel>
}
@if (admin || canEditMetadata) {
<p-tabpanel value="match">
<app-metadata-searcher></app-metadata-searcher>
<app-metadata-searcher [book$]="book$"></app-metadata-searcher>
</p-tabpanel>
}
</p-tabpanels>
@@ -1,14 +1,12 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {BookMetadataCenterService} from './book-metadata-center.service';
import {UserService} from '../../../settings/user-management/user.service';
import {Book, BookRecommendation} from '../../model/book.model';
import {Subscription} from 'rxjs';
import {distinctUntilChanged, filter, map, switchMap, take} from 'rxjs/operators';
import {Observable, Subscription} from 'rxjs';
import {distinctUntilChanged, filter, map, shareReplay, switchMap, take, tap} from 'rxjs/operators';
import {BookService} from '../../service/book.service';
import {AppSettingsService} from '../../../core/service/app-settings.service';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component';
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
@@ -17,27 +15,25 @@ import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.c
selector: 'app-book-metadata-center',
standalone: true,
templateUrl: './book-metadata-center.component.html',
styleUrl: './book-metadata-center.component.scss',
imports: [
TabList,
Tabs,
TabList,
Tab,
TabPanels,
MetadataViewerComponent,
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 metadataCenterService = inject(BookMetadataCenterService);
private userService = inject(UserService);
private appSettingsService = inject(AppSettingsService);
book: Book | undefined;
book$!: Observable<Book>;
recommendedBooks: BookRecommendation[] = [];
tab: string = 'view';
canEditMetadata: boolean = false;
@@ -45,35 +41,39 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
private userSubscription: Subscription = Subscription.EMPTY;
private routeSubscription: Subscription = Subscription.EMPTY;
private tabSubscription: Subscription = Subscription.EMPTY;
private appSettings$ = this.appSettingsService.appSettings$;
ngOnInit(): void {
this.bookService.loadBooks();
this.routeSubscription = this.route.paramMap.pipe(
switchMap(params => {
const bookId = Number(params.get('bookId'));
if (isNaN(bookId)) throw new Error('Invalid book ID');
return this.route.queryParamMap.pipe(
map(queryParams => ({
bookId,
tab: queryParams.get('tab') ?? 'view'
}))
);
}),
switchMap(({bookId, tab}) => {
const validTabs = ['view', 'edit', 'match'];
this.tab = validTabs.includes(tab) ? tab : 'view';
return this.bookService.getBookByIdFromAPI(bookId, true);
}),
filter(book => !!book && !!book.metadata),
distinctUntilChanged((prev, curr) => prev.id === curr.id)
).subscribe(book => {
this.book = book;
this.metadataCenterService.emitBookChanged(book);
this.metadataCenterService.emitMetadata(book.metadata!);
this.fetchBookRecommendationsIfNeeded(book.metadata!.bookId);
this.book$ = this.route.paramMap.pipe(
map(params => Number(params.get('bookId'))),
filter(bookId => !isNaN(bookId)),
distinctUntilChanged(),
switchMap(bookId =>
this.bookService.bookState$.pipe(
map(state => state.books?.find(b => b.id === bookId)),
filter((book): book is Book => !!book && !!book.metadata),
distinctUntilChanged((a, b) => a.id === b.id && a.metadata === b.metadata),
switchMap(book =>
this.bookService.getBookByIdFromAPI(book.id, true).pipe(
tap(bookWithDescription => {
this.fetchBookRecommendationsIfNeeded(bookWithDescription.metadata!.bookId);
})
)
)
)
),
shareReplay(1)
);
this.tabSubscription = this.route.queryParamMap.pipe(
map(queryParams => queryParams.get('tab') ?? 'view'),
distinctUntilChanged()
).subscribe(tab => {
const validTabs = ['view', 'edit', 'match'];
this.tab = validTabs.includes(tab) ? tab : 'view';
});
this.userSubscription = this.userService.userState$.subscribe(userData => {
@@ -86,7 +86,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
ngOnDestroy(): void {
this.userSubscription.unsubscribe();
this.routeSubscription.unsubscribe();
this.metadataCenterService.emitBookChanged(null);
this.tabSubscription.unsubscribe();
}
private fetchBookRecommendationsIfNeeded(bookId: number): void {
@@ -96,8 +96,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
take(1)
)
.subscribe(settings => {
const similarBookRecommendation = settings!.similarBookRecommendation ?? false;
if (similarBookRecommendation) {
if (settings!.similarBookRecommendation ?? false) {
this.bookService.getBookRecommendations(bookId).subscribe(recommendations => {
this.recommendedBooks = recommendations;
});
@@ -1,23 +0,0 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {Book, BookMetadata} from '../../model/book.model';
@Injectable({
providedIn: 'root'
})
export class BookMetadataCenterService {
private bookMetadataSubject = new BehaviorSubject<BookMetadata | null>(null);
currentMetadata$ = this.bookMetadataSubject.asObservable();
emitMetadata(bookMetadata: BookMetadata) {
this.bookMetadataSubject.next(bookMetadata);
}
bookChangedSubject = new BehaviorSubject<Book | null>(null);
bookChanged$ = this.bookChangedSubject.asObservable();
emitBookChanged(book: Book | null) {
this.bookChangedSubject.next(book);
}
}
@@ -1,4 +1,4 @@
@if (bookMetadata$ | async; as metadata) {
@if (book$ | async; as book) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="flex flex-col h-full">
@if (isLoading) {
<div class="absolute inset-0 bg-black opacity-25 z-10 "></div>
@@ -6,12 +6,11 @@
@if (isLoading) {
<p-progressSpinner [style]="{position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)'}"></p-progressSpinner>
}
<div class="flex-grow overflow-auto p-4">
<div class="flex flex-row w-full gap-4">
<div class="flex flex-col items-center gap-2 relative">
<img
[attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)"
[attr.src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Image"
width="250"
[ngClass]="{ 'brightness-50': isUploading }"
@@ -24,17 +23,17 @@
<div class="flex items-center gap-6">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(metadata.bookId)"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover"
tooltipPosition="top"
[outlined]="true"
severity="warn"
[disabled]="metadata['coverLocked']">
[disabled]="book.metadata!['coverLocked']">
</p-button>
<p-fileupload
pTooltip="Upload cover"
tooltipPosition="top"
[disabled]="metadata['coverLocked']"
[disabled]="book.metadata!['coverLocked']"
name="file"
[url]="getUploadCoverUrl()"
mode="basic"
@@ -47,10 +46,10 @@
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!metadata['coverLocked']) {
@if (!book.metadata!['coverLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (metadata['coverLocked']) {
@if (book.metadata!['coverLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
</div>
@@ -62,10 +61,10 @@
<label for="title">Title</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="title" formControlName="title" class="w-full"/>
@if (!metadata['titleLocked']) {
@if (!book.metadata!['titleLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('title')" severity="success"></p-button>
}
@if (metadata['titleLocked']) {
@if (book.metadata!['titleLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('title')" severity="warn"></p-button>
}
</div>
@@ -74,10 +73,10 @@
<label for="subtitle">Subtitle</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="subtitle" formControlName="subtitle" class="w-full"/>
@if (!metadata['subtitleLocked']) {
@if (!book.metadata!['subtitleLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('subtitle')" severity="success"></p-button>
}
@if (metadata['subtitleLocked']) {
@if (book.metadata!['subtitleLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('subtitle')" severity="warn"></p-button>
}
</div>
@@ -89,10 +88,10 @@
<label for="authors">Authors</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="authors" formControlName="authors" class="w-full"/>
@if (!metadata['authorsLocked']) {
@if (!book.metadata!['authorsLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('authors')" severity="success"></p-button>
}
@if (metadata['authorsLocked']) {
@if (book.metadata!['authorsLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('authors')" severity="warn"></p-button>
}
</div>
@@ -101,10 +100,10 @@
<label for="publisher">Publisher</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="publisher" formControlName="publisher" class="w-full"/>
@if (!metadata['publisherLocked']) {
@if (!book.metadata!['publisherLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('publisher')" severity="success"></p-button>
}
@if (metadata['publisherLocked']) {
@if (book.metadata!['publisherLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('publisher')" severity="warn"></p-button>
}
</div>
@@ -116,10 +115,10 @@
<label for="categories">Categories</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="categories" formControlName="categories" class="w-full"/>
@if (!metadata['categoriesLocked']) {
@if (!book.metadata!['categoriesLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('categories')" severity="success"></p-button>
}
@if (metadata['categoriesLocked']) {
@if (book.metadata!['categoriesLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('categories')" severity="warn"></p-button>
}
</div>
@@ -128,10 +127,10 @@
<label for="publishedDate">Publish Date</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="publishedDate" formControlName="publishedDate" class="w-full"/>
@if (!metadata['publishedDateLocked']) {
@if (!book.metadata!['publishedDateLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('publishedDate')" severity="success"></p-button>
}
@if (metadata['publishedDateLocked']) {
@if (book.metadata!['publishedDateLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('publishedDate')" severity="warn"></p-button>
}
</div>
@@ -140,10 +139,10 @@
<label for="language">Language</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="language" formControlName="language" class="w-full"/>
@if (!metadata['languageLocked']) {
@if (!book.metadata!['languageLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('language')" severity="success"></p-button>
}
@if (metadata['languageLocked']) {
@if (book.metadata!['languageLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('language')" severity="warn"></p-button>
}
</div>
@@ -154,10 +153,10 @@
<label for="seriesName">Series Name</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="seriesName" formControlName="seriesName" class="w-full"/>
@if (!metadata['seriesNameLocked']) {
@if (!book.metadata!['seriesNameLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesName')" severity="success"></p-button>
}
@if (metadata['seriesNameLocked']) {
@if (book.metadata!['seriesNameLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesName')" severity="warn"></p-button>
}
</div>
@@ -166,10 +165,10 @@
<label for="seriesNumber">Book Number</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="seriesNumber" formControlName="seriesNumber" class="w-full"/>
@if (!metadata['seriesNumberLocked']) {
@if (!book.metadata!['seriesNumberLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesNumber')" severity="success"></p-button>
}
@if (metadata['seriesNumberLocked']) {
@if (book.metadata!['seriesNumberLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesNumber')" severity="warn"></p-button>
}
</div>
@@ -178,10 +177,10 @@
<label for="seriesTotal">Books in Series</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="seriesTotal" formControlName="seriesTotal" class="w-full"/>
@if (!metadata['seriesTotalLocked']) {
@if (!book.metadata!['seriesTotalLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('seriesTotal')" severity="success"></p-button>
}
@if (metadata['seriesTotalLocked']) {
@if (book.metadata!['seriesTotalLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('seriesTotal')" severity="warn"></p-button>
}
</div>
@@ -193,10 +192,10 @@
<label for="isbn10">ISBN 10</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="isbn10" formControlName="isbn10" class="w-full"/>
@if (!metadata['isbn10Locked']) {
@if (!book.metadata!['isbn10Locked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('isbn10')" severity="success"></p-button>
}
@if (metadata['isbn10Locked']) {
@if (book.metadata!['isbn10Locked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('isbn10')" severity="warn"></p-button>
}
</div>
@@ -205,10 +204,10 @@
<label for="isbn13">ISBN 13</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="isbn13" formControlName="isbn13" class="w-full"/>
@if (!metadata['isbn13Locked']) {
@if (!book.metadata!['isbn13Locked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('isbn13')" severity="success"></p-button>
}
@if (metadata['isbn13Locked']) {
@if (book.metadata!['isbn13Locked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('isbn13')" severity="warn"></p-button>
}
</div>
@@ -217,10 +216,10 @@
<label for="asin">ASIN (Amazon ID)</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="asin" formControlName="asin" class="w-full"/>
@if (!metadata['asinLocked']) {
@if (!book.metadata!['asinLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
}
@if (metadata['asinLocked']) {
@if (book.metadata!['asinLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
}
</div>
@@ -229,10 +228,10 @@
<label for="amazonRating">Amazon ★</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="amazonRating" formControlName="amazonRating" class="w-full"/>
@if (!metadata['amazonRatingLocked']) {
@if (!book.metadata!['amazonRatingLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="success"></p-button>
}
@if (metadata['amazonRatingLocked']) {
@if (book.metadata!['amazonRatingLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="warn"></p-button>
}
</div>
@@ -241,10 +240,10 @@
<label for="amazonRatingCount">Amazon Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="amazonRatingCount" formControlName="amazonReviewCount" class="w-full"/>
@if (!metadata['amazonReviewCountLocked']) {
@if (!book.metadata!['amazonReviewCountLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="success"></p-button>
}
@if (metadata['amazonReviewCountLocked']) {
@if (book.metadata!['amazonReviewCountLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="warn"></p-button>
}
</div>
@@ -253,10 +252,10 @@
<label for="googleId">Google Books ID</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="googleId" formControlName="googleId" class="w-full"/>
@if (!metadata['googleIdLocked']) {
@if (!book.metadata!['googleIdLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('googleId')" severity="success"></p-button>
}
@if (metadata['googleIdLocked']) {
@if (book.metadata!['googleIdLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('googleId')" severity="warn"></p-button>
}
</div>
@@ -268,10 +267,10 @@
<label for="goodreadsId">Goodreads ID</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="goodreadsId" formControlName="goodreadsId" class="w-full"/>
@if (!metadata['goodreadsIdLocked']) {
@if (!book.metadata!['goodreadsIdLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="success"></p-button>
}
@if (metadata['goodreadsIdLocked']) {
@if (book.metadata!['goodreadsIdLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="warn"></p-button>
}
</div>
@@ -280,10 +279,10 @@
<label for="goodreadsRating">Goodreads ★</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="goodreadsRating" formControlName="goodreadsRating" class="w-full"/>
@if (!metadata['goodreadsRatingLocked']) {
@if (!book.metadata!['goodreadsRatingLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="success"></p-button>
}
@if (metadata['goodreadsRatingLocked']) {
@if (book.metadata!['goodreadsRatingLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="warn"></p-button>
}
</div>
@@ -292,10 +291,10 @@
<label for="goodreadsReviewCount">Goodreads Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="goodreadsReviewCount" formControlName="goodreadsReviewCount" class="w-full"/>
@if (!metadata['goodreadsReviewCountLocked']) {
@if (!book.metadata!['goodreadsReviewCountLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="success"></p-button>
}
@if (metadata['goodreadsReviewCountLocked']) {
@if (book.metadata!['goodreadsReviewCountLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="warn"></p-button>
}
</div>
@@ -304,10 +303,10 @@
<label for="hardcoverId">Hardcover ID</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="hardcoverId" formControlName="hardcoverId" class="w-full"/>
@if (!metadata['hardcoverIdLocked']) {
@if (!book.metadata!['hardcoverIdLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="success"></p-button>
}
@if (metadata['hardcoverIdLocked']) {
@if (book.metadata!['hardcoverIdLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="warn"></p-button>
}
</div>
@@ -316,10 +315,10 @@
<label for="hardcoverRating">Hardcover ★</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="hardcoverRating" formControlName="hardcoverRating" class="w-full"/>
@if (!metadata['hardcoverRatingLocked']) {
@if (!book.metadata!['hardcoverRatingLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="success"></p-button>
}
@if (metadata['hardcoverRatingLocked']) {
@if (book.metadata!['hardcoverRatingLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="warn"></p-button>
}
</div>
@@ -328,10 +327,10 @@
<label for="hardcoverReviewCount">Hardcover Reviews</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="hardcoverReviewCount" formControlName="hardcoverReviewCount" class="w-full"/>
@if (!metadata['hardcoverReviewCountLocked']) {
@if (!book.metadata!['hardcoverReviewCountLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="success"></p-button>
}
@if (metadata['hardcoverReviewCountLocked']) {
@if (book.metadata!['hardcoverReviewCountLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="warn"></p-button>
}
</div>
@@ -394,18 +393,16 @@
</p-tabpanel>
</p-tabpanels>
</p-tabs>
@if (!metadata['descriptionLocked']) {
@if (!book.metadata!['descriptionLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success"></p-button>
}
@if (metadata['descriptionLocked']) {
@if (book.metadata!['descriptionLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn"></p-button>
}
</div>
</div>
</div>
</div>
<div class="mt-auto">
<p-divider></p-divider>
<div class="flex justify-between px-2 pt-1 pb-4 bg-gray-900 z-10">
@@ -418,10 +415,20 @@
</div>
}
<div class="flex gap-x-4 items-center ml-auto">
<p-button label="Restore Metadata" icon="pi pi-refresh" [outlined]="true" severity="danger" (onClick)="restoreMetadata()"></p-button>
<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-button label="Restore" icon="pi pi-refresh" [outlined]="true" severity="danger" (onClick)="restoreMetadata()" pTooltip="Revert all changes to original metadata" tooltipPosition="top"></p-button>
<p-divider layout="vertical"/>
<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-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>
@@ -1,13 +1,12 @@
import {Component, EventEmitter, inject, Input, OnInit, Output, ViewChild} from '@angular/core';
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output, ViewChild} 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 {BookMetadataCenterService} from '../book-metadata-center.service';
import { AsyncPipe, NgClass } from '@angular/common';
import {AsyncPipe, NgClass} from '@angular/common';
import {MessageService} from 'primeng/api';
import {BookMetadata} from '../../../model/book.model';
import {Book, BookMetadata} from '../../../model/book.model';
import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
import {FileUpload, FileUploadErrorEvent, FileUploadEvent} from 'primeng/fileupload';
import {HttpResponse} from '@angular/common/http';
@@ -19,6 +18,9 @@ import {debounceTime} from 'rxjs/operators';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {MetadataRestoreDialogComponent} from '../../../components/book-browser/metadata-restore-dialog-component/metadata-restore-dialog-component';
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';
@Component({
selector: 'app-metadata-editor',
@@ -42,12 +44,13 @@ import {DialogService} from 'primeng/dynamicdialog';
Tab,
TabPanels,
TabPanel
]
]
})
export class MetadataEditorComponent implements OnInit {
@ViewChild(Editor) quillEditor!: Editor;
@Input() book$!: Observable<Book | null>;
@Output() nextBookClicked = new EventEmitter<void>();
@Output() previousBookClicked = new EventEmitter<void>();
@Output() closeDialogButtonClicked = new EventEmitter<void>();
@@ -56,13 +59,12 @@ export class MetadataEditorComponent implements OnInit {
@Input() disablePrevious = false;
@Input() showNavigationButtons = false;
private metadataCenterService = inject(BookMetadataCenterService);
private messageService = inject(MessageService);
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
private dialogService = inject(DialogService);
private destroyRef = inject(DestroyRef);
bookMetadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
metadataForm: FormGroup;
currentBookId!: number;
isUploading = false;
@@ -70,6 +72,9 @@ export class MetadataEditorComponent implements OnInit {
htmlTextarea = '';
isSaving = false;
refreshingBookIds = new Set<number>();
isAutoFetching = false;
constructor() {
this.metadataForm = new FormGroup({
title: new FormControl(''),
@@ -128,117 +133,128 @@ export class MetadataEditorComponent implements OnInit {
}
ngOnInit(): void {
this.bookMetadata$.subscribe((metadata) => {
if (metadata) {
this.book$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(book => {
const metadata = book?.metadata;
if (!metadata) return;
this.currentBookId = metadata.bookId;
if (this.quillEditor && this.quillEditor.quill) {
if (this.refreshingBookIds.has(book.id)) {
this.refreshingBookIds.delete(book.id);
this.isAutoFetching = false;
}
if (this.quillEditor?.quill) {
this.quillEditor.quill.root.innerHTML = metadata.description;
this.quillDisabled();
}
this.metadataForm.patchValue({
title: metadata.title || null,
subtitle: metadata.subtitle || null,
authors: (metadata.authors || []).sort().join(', '),
categories: (metadata.categories || []).sort().join(', '),
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,
amazonRating: metadata.amazonRating || null,
amazonReviewCount: metadata.amazonReviewCount || null,
goodreadsId: metadata.goodreadsId || 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,
this.populateFormFromMetadata(metadata);
});
titleLocked: metadata.titleLocked || false,
subtitleLocked: metadata.subtitleLocked || false,
authorsLocked: metadata.authorsLocked || false,
categoriesLocked: metadata.categoriesLocked || 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,
amazonRatingLocked: metadata.amazonRatingLocked || false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked || false,
goodreadsIdLocked: metadata.goodreadsIdLocked || 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,
thumbnailUrlLocked: metadata.coverLocked || false,
});
this.metadataForm.get('description')?.valueChanges
.pipe(debounceTime(100), takeUntilDestroyed(this.destroyRef))
.subscribe(value => {
if (this.htmlTextarea !== value) {
this.htmlTextarea = value;
}
});
}
const lockableFields: { key: keyof BookMetadata, control: string }[] = [
{key: 'titleLocked', control: 'title'},
{key: 'subtitleLocked', control: 'subtitle'},
{key: 'authorsLocked', control: 'authors'},
{key: 'categoriesLocked', control: 'categories'},
{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: 'goodreadsIdLocked', control: 'goodreadsId'},
{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'}
];
lockableFields.forEach(({key, control}) => {
const isLocked = metadata[key] === true;
const formControl = this.metadataForm.get(control);
if (formControl) {
isLocked ? formControl.disable() : formControl.enable();
}
});
this.metadataForm.get('reviewCount')?.disable();
this.metadataForm.get('rating')?.disable();
}
this.metadataForm.get('description')?.valueChanges
.pipe(debounceTime(100))
.subscribe(value => {
if (this.htmlTextarea !== value) {
this.htmlTextarea = value;
}
});
private populateFormFromMetadata(metadata: BookMetadata): void {
this.metadataForm.patchValue({
title: metadata.title ?? null,
subtitle: metadata.subtitle ?? null,
authors: (metadata.authors ?? []).sort().join(', '),
categories: (metadata.categories ?? []).sort().join(', '),
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,
amazonRating: metadata.amazonRating ?? null,
amazonReviewCount: metadata.amazonReviewCount ?? null,
goodreadsId: metadata.goodreadsId ?? 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,
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,
amazonRatingLocked: metadata.amazonRatingLocked ?? false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked ?? false,
goodreadsIdLocked: metadata.goodreadsIdLocked ?? 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,
thumbnailUrlLocked: 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: '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: 'goodreadsIdLocked', control: 'goodreadsId'},
{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'}
];
for (const {key, control} of lockableFields) {
const isLocked = metadata[key] === true;
const formControl = this.metadataForm.get(control);
if (formControl) {
isLocked ? formControl.disable() : formControl.enable();
}
}
this.metadataForm.get('reviewCount')?.disable();
this.metadataForm.get('rating')?.disable();
}
onSave(): void {
@@ -247,7 +263,6 @@ export class MetadataEditorComponent implements OnInit {
next: (response) => {
this.isSaving = false;
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book metadata updated'});
this.metadataCenterService.emitMetadata(response);
},
error: (err) => {
this.isSaving = false;
@@ -374,7 +389,6 @@ export class MetadataEditorComponent implements OnInit {
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
this.bookService.updateBookMetadata(this.currentBookId, this.buildMetadata(shouldLockAllFields), false).subscribe({
next: (response) => {
this.metadataCenterService.emitMetadata(response);
if (shouldLockAllFields !== undefined) {
this.messageService.add({
severity: 'success',
@@ -408,7 +422,6 @@ export class MetadataEditorComponent implements OnInit {
if (response && response.status === 200) {
const bookMetadata: BookMetadata = response.body as BookMetadata;
this.bookService.handleBookMetadataUpdate(this.currentBookId, bookMetadata);
this.metadataCenterService.emitMetadata(bookMetadata);
this.isUploading = false;
} else {
this.isUploading = false;
@@ -455,6 +468,17 @@ export class MetadataEditorComponent implements OnInit {
});
}
autoFetch(bookId: number) {
this.refreshingBookIds.add(bookId);
this.isAutoFetching = true;
const request: MetadataRefreshRequest = {
quick: true,
refreshType: MetadataRefreshType.BOOKS,
bookIds: [bookId],
};
this.bookService.autoRefreshMetadata(request).subscribe();
}
onNext() {
this.nextBookClicked.emit();
}
@@ -1,6 +1,6 @@
@if (bookMetadata$ | async; as metadata) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="h-full flex pt-1 flex-col">
<div class="overflow-y-scroll flex-1">
@if (book$ | async; as book) {
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="flex flex-col h-full">
<div class="flex-grow overflow-auto 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
@@ -22,10 +22,10 @@
<div class="form-row">
<label class="label"></label>
<div class="input-container">
@if (!metadata['coverLocked']) {
@if (!book.metadata!['coverLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (metadata['coverLocked']) {
@if (book.metadata!['coverLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
<img [src]="metadataForm.get('thumbnailUrl')?.value" alt="Book Thumbnail" class="thumbnail"/>
@@ -51,10 +51,10 @@
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadata[field.lockedKey]) {
@if (!book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadata[field.lockedKey]) {
@if (book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<input pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
@@ -79,10 +79,10 @@
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadata[field.lockedKey]) {
@if (!book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadata[field.lockedKey]) {
@if (book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<textarea rows="6" pTextarea id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"></textarea>
@@ -107,10 +107,10 @@
<div class="form-row">
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
<div class="input-container">
@if (!metadata[field.lockedKey]) {
@if (!book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
}
@if (metadata[field.lockedKey]) {
@if (book.metadata![field.lockedKey]) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
}
<input pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
@@ -150,15 +150,20 @@
<p class="text-lg">Fetched Metadata</p>
</div>
</div>
<div class="flex flex-col gap-x-4 mt-auto">
<div class="mt-auto">
<p-divider></p-divider>
<div class="flex justify-between">
<div class="flex justify-between px-2 pt-1 pb-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="pi pi-check" type="submit"></p-button>
<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>
@@ -1,17 +1,18 @@
import {Component, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {BookMetadata} from '../../../model/book.model';
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {Book, BookMetadata} from '../../../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 {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {Divider} from 'primeng/divider';
import {BookMetadataCenterService} from '../book-metadata-center.service';
import {Observable} from 'rxjs';
import {Tooltip} from 'primeng/tooltip';
import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
import {BookService} from '../../../service/book.service';
import {Textarea} from 'primeng/textarea';
import {filter, map} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
@Component({
selector: 'app-metadata-picker',
@@ -29,7 +30,7 @@ import {Textarea} from 'primeng/textarea';
Tooltip,
AsyncPipe,
Textarea
]
]
})
export class MetadataPickerComponent implements OnInit {
@@ -66,6 +67,7 @@ export class MetadataPickerComponent implements OnInit {
];
@Input() fetchedMetadata!: BookMetadata;
@Input() book$!: Observable<Book | null>;
@Output() goBack = new EventEmitter<boolean>();
metadataForm: FormGroup;
@@ -73,13 +75,12 @@ export class MetadataPickerComponent implements OnInit {
copiedFields: Record<string, boolean> = {};
savedFields: Record<string, boolean> = {};
originalMetadata!: BookMetadata;
isSaving = false;
private metadataCenterService = inject(BookMetadataCenterService);
private messageService = inject(MessageService);
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
bookMetadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
private destroyRef = inject(DestroyRef);
constructor() {
this.metadataForm = new FormGroup({
@@ -138,7 +139,13 @@ export class MetadataPickerComponent implements OnInit {
}
ngOnInit(): void {
this.bookMetadata$.subscribe((metadata) => {
this.book$
.pipe(
filter((book): book is Book => !!book && !!book.metadata),
map(book => book.metadata),
takeUntilDestroyed(this.destroyRef)
).
subscribe((metadata) => {
if (metadata) {
this.originalMetadata = metadata;
this.originalMetadata.thumbnailUrl = this.urlHelper.getCoverUrl(metadata.bookId, metadata.coverUpdatedOn);
@@ -226,18 +233,20 @@ export class MetadataPickerComponent implements OnInit {
}
onSave(): void {
this.isSaving = true;
const updatedBookMetadata = this.buildMetadata(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'});
this.metadataCenterService.emitMetadata(bookMetadata);
},
error: () => {
this.isSaving = false;
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update book metadata'});
}
});
@@ -314,8 +323,6 @@ export class MetadataPickerComponent implements OnInit {
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
this.bookService.updateBookMetadata(this.currentBookId, this.buildMetadata(shouldLockAllFields), false).subscribe({
next: (response) => {
this.metadataCenterService.emitMetadata(response);
if (shouldLockAllFields !== undefined) {
this.messageService.add({
severity: 'success',
@@ -1,9 +1,18 @@
@if (!selectedFetchedMetadata) {
@if (selectedFetchedMetadata$ | async; as selectedFetchedMetadata) {
<div class="h-full flex-auto">
<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" [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="flex w-full gap-x-4 items-end">
<div class="flex flex-col gap-1 w-3/12">
<label>Providers</label>
<p-multiselect id="provider" class="w-full" [filter]="false" showToggleAll="false" [options]="providers" formControlName="provider" placeholder="Select Providers"></p-multiselect>
<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-5/12">
<label for="title">Title</label>
@@ -54,9 +63,3 @@
}
</form>
}
@if (selectedFetchedMetadata) {
<div class="h-full flex-auto">
<app-metadata-picker [fetchedMetadata]="selectedFetchedMetadata" (goBack)="onGoBack()"></app-metadata-picker>
</div>
}
@@ -1,39 +1,72 @@
import {Component, inject, 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 {
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 {ProgressSpinner} from 'primeng/progressspinner';
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
import {BookMetadataCenterService} from '../book-metadata-center.service';
import {MultiSelect} from 'primeng/multiselect';
import {Book, BookMetadata} from '../../../model/book.model';
import {BookService} from '../../../service/book.service';
import {combineLatest, Observable, Subject, Subscription, takeUntil} from 'rxjs';
import {AppSettings} from '../../../../core/model/app-settings.model';
import {AppSettingsService} from '../../../../core/service/app-settings.service';
import {distinctUntilChanged, filter, switchMap} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import { FetchMetadataRequest } from '../../model/request/fetch-metadata-request.model';
import { MetadataPickerComponent } from '../metadata-picker/metadata-picker.component';
import { Book, BookMetadata } from '../../../model/book.model';
import { BookService } from '../../../service/book.service';
import { AppSettings } from '../../../../core/model/app-settings.model';
import { AppSettingsService } from '../../../../core/service/app-settings.service';
import {
combineLatest,
Observable,
Subject,
Subscription,
takeUntil,
BehaviorSubject
} from 'rxjs';
import {
distinctUntilChanged,
filter,
switchMap
} from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import {AsyncPipe} from '@angular/common';
@Component({
selector: 'app-metadata-searcher',
templateUrl: './metadata-searcher.component.html',
styleUrls: ['./metadata-searcher.component.scss'],
imports: [ReactiveFormsModule, Button, InputText, Divider, ProgressSpinner, MetadataPickerComponent, MultiSelect],
imports: [
ReactiveFormsModule,
Button,
InputText,
Divider,
ProgressSpinner,
MetadataPickerComponent,
MultiSelect,
AsyncPipe
],
standalone: true
})
export class MetadataSearcherComponent implements OnInit, OnDestroy {
form: FormGroup;
providers: string[] = [];
allFetchedMetadata: BookMetadata[] = [];
selectedFetchedMetadata!: BookMetadata | null;
bookId!: number;
loading: boolean = false;
@Input() book$!: Observable<Book | null>;
selectedFetchedMetadata$ = new BehaviorSubject<BookMetadata | null>(null);
private formBuilder = inject(FormBuilder);
private metadataCenterService = inject(BookMetadataCenterService);
private bookService = inject(BookService);
private appSettingsService = inject(AppSettingsService);
private route = inject(ActivatedRoute);
@@ -42,69 +75,64 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
private cancelRequest$ = new Subject<void>();
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
bookChanged$: Observable<Book | null> = this.metadataCenterService.bookChanged$;
constructor() {
this.form = this.formBuilder.group({
provider: null,
title: [''],
author: [''],
author: ['']
});
}
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.selectedFetchedMetadata = null;
this.allFetchedMetadata = [];
this.form.patchValue({
provider: this.providers,
title: '',
author: '',
});
}
return combineLatest([this.bookChanged$, this.appSettings$]);
}),
filter(([book, settings]) => !!book && !!settings),
distinctUntilChanged(([prevBook], [currBook]) => prevBook?.id === currBook?.id)
).subscribe(([book, settings]) => {
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]) => {
this.providers = Object.entries(settings!.metadataProviderSettings)
.filter(([_, value]) => value.enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
this.providers = Object.entries(settings!.metadataProviderSettings)
.filter(([key, value]) => value.enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
console.log('aditya')
this.resetFormFromBook(book!);
const autoBookSearchEnabled = settings!.autoBookSearch ?? false;
if (book) {
this.selectedFetchedMetadata = null;
this.allFetchedMetadata = [];
this.bookId = book.id;
this.form.patchValue({
provider: this.providers,
title: book.metadata?.title || null,
author: book.metadata?.authors?.length ? book.metadata.authors[0] : ''
});
if (autoBookSearchEnabled) {
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] ?? ''
});
}
ngOnDestroy(): void {
this.cancelRequest$.next();
this.subscription.unsubscribe();
this.allFetchedMetadata = [];
this.selectedFetchedMetadata = null;
this.selectedFetchedMetadata$.complete();
}
get isSearchEnabled(): boolean {
@@ -116,25 +144,26 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
onSubmit(): void {
if (this.form.valid) {
const providerKeys = this.form.get('provider')?.value;
if (!providerKeys) {
return;
}
if (!providerKeys) return;
const fetchRequest: FetchMetadataRequest = {
bookId: this.bookId,
providers: providerKeys,
title: this.form.get('title')?.value,
author: this.form.get('author')?.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((fetchedMetadata) => ({
...fetchedMetadata,
thumbnailUrl: fetchedMetadata.thumbnailUrl
this.allFetchedMetadata = fetchedMetadata.map(m => ({
...m,
thumbnailUrl: m.thumbnailUrl
}));
},
error: () => {
@@ -146,6 +175,24 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
}
}
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>`;
@@ -159,24 +206,4 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
throw new Error("No provider ID found in metadata.");
}
truncateText(text: string | null, length: number): string {
const safeText = text ?? '';
return safeText.length > length ? safeText.substring(0, length) + '...' : safeText;
}
onBookClick(fetchedMetadata: BookMetadata) {
this.selectedFetchedMetadata = fetchedMetadata;
}
onGoBack() {
this.selectedFetchedMetadata = null;
}
sanitizeHtml(htmlString: string | null | undefined): string {
if (!htmlString) {
return '';
}
return htmlString.replace(/<\/?[^>]+(>|$)/g, '').trim();
}
}
@@ -1,26 +1,26 @@
<div class="pt-2 flex flex-col h-full">
@if (metadata$ | async; as metadata) {
@if (book$ | async; as book) {
<div>
<div class="flex flex-row">
<div class="cover-wrapper relative">
<img
[attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)"
[attr.src]="urlHelper.getCoverUrl(book?.metadata!.bookId, book?.metadata!.coverUpdatedOn)"
class="book-cover placeholder"
alt="Cover of {{ metadata.title }}"
alt="Cover of {{ book?.metadata!.title }}"
loading="lazy"
width="225"
style="min-width: 225px;"
/>
@if (metadata?.seriesNumber != null) {
@if (book?.metadata!.seriesNumber != null) {
<div class="series-number-overlay">
#{{ metadata?.seriesNumber }}
#{{ book?.metadata!.seriesNumber }}
</div>
}
@if (getProgressPercent() !== null) {
@if (getProgressPercent(book) !== null) {
<p-progressBar
[value]="getProgressPercent()"
[value]="getProgressPercent(book)"
[showValue]="true"
[ngClass]="{ 'progress-complete': getProgressPercent() === 100, 'progress-incomplete': getProgressPercent()! < 100 }"
[ngClass]="{ 'progress-complete': getProgressPercent(book) === 100, 'progress-incomplete': getProgressPercent(book)! < 100 }"
[style]="{ height: '10px' }">
</p-progressBar>
}
@@ -29,22 +29,22 @@
<div class="pl-6 flex flex-col w-full">
<div class="flex flex-row items-center justify-between">
<div>
@if (metadata.seriesName) {
<p class="italic">{{ metadata.seriesName }} #{{ metadata.seriesNumber }}</p>
@if (book?.metadata!.seriesName) {
<p class="italic">{{ book?.metadata!.seriesName }} #{{ book?.metadata!.seriesNumber }}</p>
}
<div class="flex items-center gap-2">
<p class="text-2xl font-bold m-0">{{ metadata.title }}</p>
<p class="text-2xl font-bold m-0">{{ book?.metadata!.title }}</p>
<i
class="pi"
[ngClass]="isMetadataFullyLocked(metadata) ? 'pi-lock text-red-500' : 'pi-lock-open text-green-500'"
[title]="isMetadataFullyLocked(metadata) ? 'Metadata is locked' : 'Metadata is unlocked'"
[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'"
style="font-size: 1.25rem;"
pTooltip="{{ isMetadataFullyLocked(metadata) ? 'This book metadata is locked.' : 'This book 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 metadata?.authors; track author; let isLast = $last) {
@for (author of book?.metadata!.authors; track author; let isLast = $last) {
<a
class="underline hover:opacity-80"
[routerLink]="['/all-books']"
@@ -64,72 +64,72 @@
</div>
</div>
<div class="flex items-center gap-2 pt-2">
@if (metadata.amazonRating || metadata.goodreadsRating || metadata.hardcoverRating) {
@if (metadata.amazonRating) {
@if (metadata.asin) {
<a class="flex items-center gap-1" [href]="'https://www.amazon.com/dp/' + metadata.asin" target="_blank" rel="noopener noreferrer">
@if (book?.metadata!.amazonRating || book?.metadata!.goodreadsRating || book?.metadata!.hardcoverRating) {
@if (book?.metadata!.amazonRating) {
@if (book?.metadata!.asin) {
<a class="flex items-center gap-1" [href]="'https://www.amazon.com/dp/' + book?.metadata!.asin" target="_blank" rel="noopener noreferrer">
<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"/>
<p class="font-semibold">{{ metadata.amazonRating }}</p>
<p class="font-semibold">{{ book?.metadata!.amazonRating }}</p>
</a>
} @else {
<span class="flex items-center gap-1">
<img src="https://www.amazon.com/favicon.ico" alt="Amazon" class="w-5 h-5 object-contain"/>
<p class="font-semibold">{{ metadata.amazonRating }}</p>
<p class="font-semibold">{{ book?.metadata!.amazonRating }}</p>
</span>
}
<p-rating [ngModel]="metadata.amazonRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata.amazonRating)">
<p-rating [ngModel]="book?.metadata!.amazonRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(book?.metadata!.amazonRating)">
</p-rating>
<p class="font-semibold">({{ metadata.amazonReviewCount | number:'1.0-0' }})</p>
@if (metadata.goodreadsRating || metadata.hardcoverRating) {
<p class="font-semibold">({{ book?.metadata!.amazonReviewCount | number:'1.0-0' }})</p>
@if (book?.metadata!.goodreadsRating || book?.metadata!.hardcoverRating) {
<span>|</span>
}
}
@if (metadata.goodreadsRating) {
@if (metadata.goodreadsId) {
<a class="flex items-center gap-1" [href]="'https://www.goodreads.com/book/show/' + metadata.goodreadsId" target="_blank" rel="noopener noreferrer">
@if (book?.metadata!.goodreadsRating) {
@if (book?.metadata!.goodreadsId) {
<a class="flex items-center gap-1" [href]="'https://www.goodreads.com/book/show/' + book?.metadata!.goodreadsId" target="_blank" rel="noopener noreferrer">
<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"/>
<p class="font-semibold">{{ metadata.goodreadsRating }}</p>
<p class="font-semibold">{{ book?.metadata!.goodreadsRating }}</p>
</a>
} @else {
<span class="flex items-center gap-1">
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads" class="w-5 h-5 object-contain"/>
<p class="font-semibold">{{ metadata.goodreadsRating }}</p>
<p class="font-semibold">{{ book?.metadata!.goodreadsRating }}</p>
</span>
}
<p-rating [ngModel]="metadata.goodreadsRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata.goodreadsRating)">
<p-rating [ngModel]="book?.metadata!.goodreadsRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(book?.metadata!.goodreadsRating)">
</p-rating>
<p class="font-semibold">({{ metadata.goodreadsReviewCount | number:'1.0-0' }})</p>
@if (metadata.hardcoverRating) {
<p class="font-semibold">({{ book?.metadata!.goodreadsReviewCount | number:'1.0-0' }})</p>
@if (book?.metadata!.hardcoverRating) {
<span>|</span>
}
}
@if (metadata.hardcoverRating) {
@if (metadata.hardcoverId) {
<a class="flex items-center gap-1" [href]="'https://hardcover.app/books/' + metadata.hardcoverId" target="_blank" rel="noopener noreferrer">
@if (book?.metadata!.hardcoverRating) {
@if (book?.metadata!.hardcoverId) {
<a class="flex items-center gap-1" [href]="'https://hardcover.app/books/' + book?.metadata!.hardcoverId" target="_blank" rel="noopener noreferrer">
<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"/>
<p class="font-semibold">{{ metadata.hardcoverRating }}</p>
<p class="font-semibold">{{ book?.metadata!.hardcoverRating }}</p>
</a>
} @else {
<span class="flex items-center gap-1">
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover" class="w-5 h-5 object-contain"/>
<p class="font-semibold">{{ metadata.hardcoverRating }}</p>
<p class="font-semibold">{{ book?.metadata!.hardcoverRating }}</p>
</span>
}
<p-rating [ngModel]="metadata.hardcoverRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata.hardcoverRating)">
<p-rating [ngModel]="book?.metadata!.hardcoverRating" readonly stars="5"
[style.--p-rating-icon-active-color]="getStarColor(book?.metadata!.hardcoverRating)">
</p-rating>
<p class="font-semibold">({{ metadata.hardcoverReviewCount | number:'1.0-0' }})</p>
@if ((metadata.amazonRating || metadata.goodreadsRating || metadata.hardcoverRating) && metadata.googleId) {
<p class="font-semibold">({{ book?.metadata!.hardcoverReviewCount | number:'1.0-0' }})</p>
@if ((book?.metadata!.amazonRating || book?.metadata!.goodreadsRating || book?.metadata!.hardcoverRating) && book?.metadata!.googleId) {
<span>|</span>
}
}
@if (metadata.googleId) {
<a class="flex items-center gap-1" [href]="'https://books.google.com/books?id=' + metadata.googleId" target="_blank" rel="noopener noreferrer">
@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>
@@ -137,18 +137,18 @@
} @else {
<p-rating
[(ngModel)]="metadata.rating"
[(ngModel)]="book?.metadata!.rating"
readonly
stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata.rating)">
[style.--p-rating-icon-active-color]="getStarColor(book?.metadata!.rating)">
</p-rating>
<p class="font-semibold">
{{ metadata?.reviewCount ? '(' + (metadata?.reviewCount | number:'1.0-0') + ' Ratings)' : 'No Ratings' }}
{{ book.metadata?.reviewCount ? '(' + (book.metadata?.reviewCount | number:'1.0-0') + ' Ratings)' : 'No Ratings' }}
</p>
}
</div>
<div class="flex gap-2 pt-4 overflow-x-auto scrollbar-hide">
@for (category of metadata.categories; track category) {
@for (category of book?.metadata!.categories; track category) {
<a
[routerLink]="['/all-books']"
[queryParams]="{
@@ -173,10 +173,10 @@
{{ getFileExtension(book?.filePath) || '-' }}
</span>
</p>
<p class="whitespace-nowrap"><span class="font-bold">Publisher:</span> {{ metadata.publisher || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ metadata.publishedDate || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Publisher:</span> {{ book?.metadata!.publisher || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ book?.metadata!.publishedDate || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ book?.metadata!.language || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ book?.metadata!.isbn10 || '-' }}</p>
<p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">Metadata Score:</span>
@if (book?.metadataMatchScore != null) {
@@ -189,17 +189,17 @@
<span>-</span>
}
</p>
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ metadata.pageCount || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB() }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ book?.metadata!.pageCount || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB(book) }}</p>
<p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">Progress:</span>
<span
class="inline-block px-2 py-0.5 rounded-full text-xs font-bold text-white"
[ngClass]="getProgressColorClass(getProgressPercent())">
{{ getProgressPercent() !== null ? getProgressPercent() + '%' : 'N/A' }}
[ngClass]="getProgressColorClass(getProgressPercent(book))">
{{ getProgressPercent(book) !== null ? getProgressPercent(book) + '%' : 'N/A' }}
</span>
</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ metadata.isbn13 || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ book?.metadata!.isbn13 || '-' }}</p>
</div>
<div class="pt-2 flex items-center gap-2 w-full">
<span class="font-semibold flex-shrink-0">File Path:</span>
@@ -227,18 +227,20 @@
@if (userService.userState$ | async; as userData) {
<div class="pl-6 pt-4 flex flex-row w-full gap-4">
@if (book!.bookType === 'PDF') {
<p-splitbutton
label="Read"
icon="pi pi-book"
[model]="readMenuItems"
(onClick)="read(metadata.bookId, 'ngx')"
severity="info"/>
@if (readMenuItems$ | async; as readItems) {
<p-splitbutton
label="Read"
icon="pi pi-book"
[model]="readItems"
(onClick)="read(book.id, 'ngx')"
severity="info"/>
}
}
@if (book!.bookType !== 'PDF') {
<p-button
label="Read"
icon="pi pi-book"
(onClick)="read(metadata.bookId, undefined)"
(onClick)="read(book?.metadata!.bookId, undefined)"
severity="info"/>
}
<p-button
@@ -246,7 +248,7 @@
icon="pi pi-folder"
severity="info"
outlined
(onClick)="assignShelf(metadata.bookId)">
(onClick)="assignShelf(book.id)">
</p-button>
@if (userData.permissions.canDownload || userData.permissions.admin) {
<p-button
@@ -254,49 +256,55 @@
icon="pi pi-download"
severity="info"
outlined
(onClick)="download(metadata.bookId)">
(onClick)="download(book.id)">
</p-button>
}
@if (userData.permissions.canEmailBook || userData.permissions.admin) {
<p-splitbutton
label="Quick Send"
icon="pi pi-send"
[model]="emailMenuItems"
(onClick)="quickSend(metadata.bookId)"
outlined
severity="info">
</p-splitbutton>
@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 (userData.permissions.canEditMetadata || userData.permissions.admin) {
<p-splitbutton
label="Quick Refresh"
icon="pi pi-bolt"
[model]="refreshMenuItems"
(onClick)="quickRefresh(metadata.bookId)"
outlined
severity="info">
</p-splitbutton>
@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="info"
(onClick)="quickRefresh(book.id)"
[disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top">
</p-splitbutton>
}
}
</div>
}
</div>
</div>
</div>
}
<p-divider></p-divider>
<p-divider></p-divider>
@if (metadata$ | async; as metadata) {
<div class="flex-1 space-y-2 px-2">
<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: '250px'}" [(ngModel)]="metadata.description">
<p-editor #quillEditor [readonly]="true" [style]="{height: '250px'}" [(ngModel)]="book.metadata!.description">
<ng-template #header>
</ng-template>
</p-editor>
</div>
</div>
@if (metadata.description && metadata.description.length > 100) {
@if (book.metadata!.description && book.metadata!.description.length > 100) {
<div class="text-left">
<button pButton
type="button"
@@ -1,9 +1,8 @@
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {Button, ButtonDirective} from 'primeng/button';
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
import {first, Observable} from 'rxjs';
import {Observable} from 'rxjs';
import {BookService} from '../../../service/book.service';
import {BookMetadataCenterService} from '../book-metadata-center.service';
import {Rating} from 'primeng/rating';
import {FormsModule} from '@angular/forms';
import {Tag} from 'primeng/tag';
@@ -28,6 +27,7 @@ import {MetadataFetchOptionsComponent} from '../../metadata-options-dialog/metad
import {MetadataRefreshType} from '../../model/request/metadata-refresh-type.enum';
import {MetadataRefreshRequest} from '../../model/request/metadata-refresh-request.model';
import {RouterLink} from '@angular/router';
import {filter, map, take} from 'rxjs/operators';
@Component({
selector: 'app-metadata-viewer',
@@ -38,113 +38,112 @@ import {RouterLink} from '@angular/router';
})
export class MetadataViewerComponent implements OnInit, OnChanges {
@Input() book: Book | undefined;
@Input() book$!: Observable<Book | null>;
@Input() recommendedBooks: BookRecommendation[] = [];
private originalRecommendedBooks: BookRecommendation[] = [];
@ViewChild(Editor) quillEditor!: Editor;
private originalRecommendedBooks: BookRecommendation[] = [];
private dialogService = inject(DialogService);
private emailService = inject(EmailService);
private messageService = inject(MessageService);
private bookService = inject(BookService);
private metadataCenterService = inject(BookMetadataCenterService);
protected urlHelper = inject(UrlHelperService);
protected userService = inject(UserService);
private destroyRef = inject(DestroyRef);
metadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
emailMenuItems: MenuItem[] | undefined;
readMenuItems: MenuItem[] | undefined;
refreshMenuItems: MenuItem[] | undefined;
emailMenuItems$!: Observable<MenuItem[]>;
readMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
bookInSeries: Book[] = [];
isExpanded = false;
showFilePath = false;
isAutoFetching = false;
ngOnInit(): void {
this.emailMenuItems = [
{
label: 'Custom Send',
command: () => {
this.metadata$.pipe(first()).subscribe((metadata) => {
if (metadata) {
this.dialogService.open(BookSenderComponent, {
header: 'Send Book to Email',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '15%',
},
data: {
bookId: metadata.bookId,
}
});
}
});
}
}
];
this.refreshMenuItems = [
{
label: 'Granular Refresh',
icon: 'pi pi-database',
command: () => {
this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
bookIds: [this.book!.id],
metadataRefreshType: MetadataRefreshType.BOOKS,
},
});
},
}
];
this.readMenuItems = [
{
label: 'Streaming Reader',
command: () => {
this.read(this.book?.id, "streaming")
},
}
];
this.metadata$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((metadata) => {
if (metadata) {
this.loadBooksInSeriesAndFilterRecommended(metadata.bookId);
if (this.quillEditor && this.quillEditor.quill) {
this.quillEditor.quill.root.innerHTML = metadata.description;
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: '15%' },
data: { bookId: metadata.bookId }
});
}
}
});
}
])
);
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
this.bookService.getBooksInSeries(bookId).subscribe((bookInSeries) => {
bookInSeries.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
this.bookInSeries = bookInSeries;
this.originalRecommendedBooks = [...this.recommendedBooks];
this.filterRecommendations();
});
this.refreshMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Granular Refresh',
icon: 'pi pi-database',
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.book$
.pipe(
takeUntilDestroyed(this.destroyRef),
map(book => book?.metadata),
filter((metadata): metadata is BookMetadata => metadata != null)
)
.subscribe(metadata => {
this.isAutoFetching = false;
this.loadBooksInSeriesAndFilterRecommended(metadata.bookId);
if (this.quillEditor?.quill) {
this.quillEditor.quill.root.innerHTML = metadata.description;
}
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['recommendedBooks']) {
this.originalRecommendedBooks = [...this.recommendedBooks];
this.filterRecommendations();
this.book$.pipe(take(1)).subscribe(book => this.filterRecommendations(book));
}
}
private filterRecommendations(): void {
if (!this.originalRecommendedBooks) {
return;
}
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
this.bookService.getBooksInSeries(bookId).subscribe(bookInSeries => {
bookInSeries.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
this.bookInSeries = bookInSeries;
this.originalRecommendedBooks = [...this.recommendedBooks];
this.book$.pipe(take(1)).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)
@@ -156,7 +155,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
}
read(bookId: number | undefined, reader: "ngx" | "streaming" | undefined): void {
this.bookService.readBook(bookId!, reader);
if (bookId) this.bookService.readBook(bookId, reader);
}
download(bookId: number) {
@@ -164,31 +163,27 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
}
quickRefresh(bookId: number) {
const metadataRefreshRequest: MetadataRefreshRequest = {
this.isAutoFetching = true;
const request: MetadataRefreshRequest = {
quick: true,
refreshType: MetadataRefreshType.BOOKS,
bookIds: [bookId],
};
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
this.bookService.autoRefreshMetadata(request).subscribe();
}
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) => {
const errorMessage = err?.error?.message || 'An error occurred while sending the book.';
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: errorMessage,
});
},
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.',
})
});
}
@@ -197,53 +192,28 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
header: `Update Book's Shelves`,
modal: true,
closable: true,
contentStyle: {overflow: 'auto'},
contentStyle: { overflow: 'auto' },
baseZIndex: 10,
style: {
position: 'absolute',
top: '15%',
},
data: {
book: this.bookService.getBookByIdFromState(bookId),
},
style: { position: 'absolute', top: '15%' },
data: { book: this.bookService.getBookByIdFromState(bookId) }
});
}
isMetadataFullyLocked(metadata: BookMetadata): boolean {
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
if (lockedKeys.length === 0) {
return false;
}
return lockedKeys.every(key => metadata[key] === true);
const lockedKeys = Object.keys(metadata).filter(k => k.endsWith('Locked'));
return lockedKeys.length > 0 && lockedKeys.every(k => metadata[k] === true);
}
getFileSizeInMB(): string {
const sizeKb = this.book?.fileSizeKb;
if (sizeKb != null) {
const sizeMb = sizeKb / 1024;
return `${sizeMb.toFixed(2)} MB`;
}
return '-';
getFileSizeInMB(book: Book | null): string {
const sizeKb = book?.fileSizeKb;
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
}
getProgressPercent(): number | undefined {
if (this.book?.bookType === 'PDF') {
return this.book.pdfProgress?.percentage;
} else if (this.book?.bookType === 'CBX') {
return this.book?.cbxProgress?.percentage;
} else {
return this.book?.epubProgress?.percentage;
}
}
copyFilePath() {
if (this.book?.filePath) {
navigator.clipboard.writeText(this.book.filePath).then(() => {
this.messageService.add({severity: 'success', summary: 'Copied', detail: 'File path copied to clipboard.'});
}, () => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to copy file path.'});
});
}
getProgressPercent(book: Book | null): number | undefined {
if (!book) return;
return book.bookType === 'PDF' ? book.pdfProgress?.percentage
: book.bookType === 'CBX' ? book.cbxProgress?.percentage
: book.epubProgress?.percentage;
}
getFileExtension(filePath?: string): string | null {
@@ -12,8 +12,9 @@
@if (admin || canEditMetadata) {
<p-tabpanel value="edit">
<app-metadata-editor
[disableNext]="currentIndex >= books.length - 1"
[disablePrevious]="currentIndex <= 0"
[book$]="book$"
[disableNext]="disableNext"
[disablePrevious]="disablePrevious"
(nextBookClicked)="handleNextBook()"
(previousBookClicked)="handlePreviousBook()"
(closeDialogButtonClicked)="handleCloseDialogButton()"
@@ -23,7 +24,7 @@
}
@if (admin || canEditMetadata) {
<p-tabpanel value="match">
<app-metadata-searcher></app-metadata-searcher>
<app-metadata-searcher [book$]="book$"></app-metadata-searcher>
</p-tabpanel>
}
</p-tabpanels>
@@ -5,10 +5,9 @@ import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {Book} from '../../model/book.model';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {BookService} from '../../service/book.service';
import {MessageService} from 'primeng/api';
import {Subscription} from 'rxjs';
import {BehaviorSubject, combineLatest, Observable, Subscription} from 'rxjs';
import {UserService} from '../../../settings/user-management/user.service';
import {BookMetadataCenterService} from '../book-metadata-center/book-metadata-center.service';
import {distinctUntilChanged, filter, map, shareReplay, switchMap} from 'rxjs/operators';
@Component({
selector: 'app-multi-book-metadata-editor-component',
@@ -28,21 +27,21 @@ import {BookMetadataCenterService} from '../book-metadata-center/book-metadata-c
export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
bookIds: number[] = [];
books: Book[] = [];
filteredBooks: Book[] = [];
loading = false;
private userSubscription: Subscription = Subscription.EMPTY;
private metadataSubscription: Subscription = Subscription.EMPTY;
canEditMetadata: boolean = false;
admin: boolean = false;
currentIndex = 0;
currentIndex$ = new BehaviorSubject<number>(0);
book$!: Observable<Book>;
canEditMetadata = false;
admin = false;
private readonly config = inject(DynamicDialogConfig);
private readonly ref = inject(DynamicDialogRef);
private readonly bookService = inject(BookService);
private readonly messageService = inject(MessageService);
private userService = inject(UserService);
private metadataCenterService = inject(BookMetadataCenterService);
private readonly userService = inject(UserService);
private userSubscription: Subscription = Subscription.EMPTY;
ngOnInit(): void {
this.bookIds = this.config.data?.bookIds ?? [];
@@ -53,65 +52,56 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
this.admin = userPermissions?.admin ?? false;
});
this.metadataSubscription = this.metadataCenterService.currentMetadata$.subscribe(updatedMetadata => {
if (updatedMetadata) {
const index = this.books.findIndex(book => book.metadata?.bookId === updatedMetadata.bookId);
if (index !== -1) {
this.books[index] = {
...this.books[index],
metadata: updatedMetadata
};
}
}
});
const filteredBooks$ = this.bookService.bookState$.pipe(
map(state => state.books?.filter(book =>
!!book?.metadata && this.bookIds.includes(book.id)
) ?? []),
filter(books => books.length > 0),
map(books => {
this.filteredBooks = books;
return books;
})
);
this.loading = true;
this.bookService.getBooksByIdsFromAPI(this.bookIds, true).subscribe({
next: (fetchedBooks) => {
this.books = fetchedBooks;
this.loading = false;
if (this.books.length > 0) {
this.metadataCenterService.emitBookChanged(this.books[this.currentIndex]);
this.metadataCenterService.emitMetadata(this.books[this.currentIndex].metadata!);
}
},
error: (err) => {
this.loading = false;
this.messageService.add({
severity: 'error',
summary: 'Failed to load books',
detail: err.message || 'An error occurred while fetching books.'
});
}
});
this.book$ = combineLatest([filteredBooks$, this.currentIndex$]).pipe(
map(([books, index]) => books[index]),
filter((book): book is Book => !!book),
distinctUntilChanged((a, b) => a.id === b.id && a.metadata === b.metadata),
switchMap(book =>
this.bookService.getBookByIdFromAPI(book.id, true)
),
shareReplay(1)
);
}
ngOnDestroy(): void {
this.userSubscription.unsubscribe();
this.metadataSubscription.unsubscribe();
this.metadataCenterService.emitBookChanged(null);
this.currentIndex$.complete();
}
handleNextBook() {
if (this.currentIndex < this.books.length - 1) {
this.currentIndex++;
const book = this.books[this.currentIndex];
this.metadataCenterService.emitBookChanged(book);
this.metadataCenterService.emitMetadata(book.metadata!);
const next = this.currentIndex$.value + 1;
if (next < this.filteredBooks.length) {
this.currentIndex$.next(next);
}
}
handlePreviousBook() {
if (this.currentIndex > 0) {
this.currentIndex--;
const book = this.books[this.currentIndex];
this.metadataCenterService.emitBookChanged(book);
this.metadataCenterService.emitMetadata(book.metadata!);
const prev = this.currentIndex$.value - 1;
if (prev >= 0) {
this.currentIndex$.next(prev);
}
}
handleCloseDialogButton() {
this.ref.close();
}
get disableNext(): boolean {
return this.currentIndex$.value >= this.filteredBooks.length - 1;
}
get disablePrevious(): boolean {
return this.currentIndex$.value <= 0;
}
}