refactor(metadata): metadata source query service (#2718)
This commit is contained in:
@@ -0,0 +1,262 @@
|
||||
import type {AppSettings} from '../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {HttpTestingController} from '@angular/common/http/testing';
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, sseResponse, sseStream} from '../../../core/testing/query-testing';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {
|
||||
metadataSourceKeys,
|
||||
type CoverSearchParams,
|
||||
type MetadataSearchParams,
|
||||
MetadataSourceQueryService,
|
||||
} from './metadata-source-query.service';
|
||||
|
||||
const BOOKS_URL = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
const PROVIDERS_URL = `${API_CONFIG.BASE_URL}/api/v1/metadata/providers`;
|
||||
|
||||
const SEARCH: MetadataSearchParams = {
|
||||
bookId: 7,
|
||||
providers: ['GoodReads', 'Amazon', 'GoodReads'],
|
||||
title: ' Dune ',
|
||||
author: '',
|
||||
isbn: ' ',
|
||||
};
|
||||
|
||||
interface Deferred {
|
||||
readonly promise: Promise<void>;
|
||||
readonly resolve: () => void;
|
||||
}
|
||||
|
||||
function deferred(): Deferred {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(settle => { resolve = () => { settle(); }; });
|
||||
return {promise, resolve};
|
||||
}
|
||||
|
||||
function event(title: string): string {
|
||||
return `data:{"bookId":7,"title":"${title}"}\n\n`;
|
||||
}
|
||||
|
||||
function coverEvent(index: number): string {
|
||||
return `data:${JSON.stringify({url: `https://example.test/${index}.jpg`, width: index * 100, height: index * 150, index})}\n\n`;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
class ProspectiveHost {
|
||||
private readonly metadata = inject(MetadataSourceQueryService);
|
||||
readonly query = injectQuery(() => this.metadata.prospective(SEARCH));
|
||||
}
|
||||
|
||||
const COVERS: CoverSearchParams = {
|
||||
bookId: 7,
|
||||
title: ' Dune ',
|
||||
author: ' Frank Herbert ',
|
||||
coverType: 'ebook',
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
class CoversHost {
|
||||
private readonly metadata = inject(MetadataSourceQueryService);
|
||||
readonly query = injectQuery(() => this.metadata.coverSearch(COVERS));
|
||||
}
|
||||
|
||||
describe('MetadataSourceQueryService', () => {
|
||||
const appSettings = signal<{
|
||||
metadataProviderSettings: Partial<Record<keyof AppSettings['metadataProviderSettings'], {enabled: boolean; apiKey?: string} | null>>;
|
||||
} | null>(null);
|
||||
let service: MetadataSourceQueryService;
|
||||
let queryClient: QueryClient;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
appSettings.set(null);
|
||||
const harness = createQueryClientHarness();
|
||||
queryClient = harness.queryClient;
|
||||
queryClient.setDefaultOptions({queries: {retry: false}});
|
||||
authService = createAuthServiceStub();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...harness.providers,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: {appSettings}},
|
||||
MetadataSourceQueryService,
|
||||
ProspectiveHost,
|
||||
CoversHost,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(MetadataSourceQueryService);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
http.match(PROVIDERS_URL)
|
||||
.filter(request => !request.cancelled)
|
||||
.forEach(request => request.flush([]));
|
||||
http.verify();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function answerProviders(entries: readonly {name: string; enabled: boolean}[]): Promise<void> {
|
||||
await flushQueryAsync();
|
||||
http.match(PROVIDERS_URL).forEach(request => request.flush(entries));
|
||||
await flushQueryAsync();
|
||||
}
|
||||
|
||||
it('takes the enabled flag from the backend, in catalog order', async () => {
|
||||
expect(service.enabledProviders()).toEqual([]);
|
||||
|
||||
await answerProviders([
|
||||
{name: 'Amazon', enabled: true},
|
||||
{name: 'GoodReads', enabled: false},
|
||||
{name: 'OpenLibrary', enabled: true},
|
||||
]);
|
||||
|
||||
expect(service.enabledProviders().map(provider => provider.id)).toEqual(['OpenLibrary', 'Amazon']);
|
||||
});
|
||||
|
||||
it('ignores a provider the catalog lacks and treats an omitted one as disabled', async () => {
|
||||
await answerProviders([
|
||||
{name: 'Amazon', enabled: true},
|
||||
{name: 'Bookwyrm', enabled: true},
|
||||
]);
|
||||
|
||||
expect(service.providers()).toHaveLength(11);
|
||||
expect(service.enabledProviders().map(provider => provider.id)).toEqual(['Amazon']);
|
||||
});
|
||||
|
||||
it('removes its cached metadata queries when the authenticated session ends', () => {
|
||||
queryClient.setQueryData(metadataSourceKeys.fileMetadata(7), {bookId: 7});
|
||||
|
||||
authService.token.set(null);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(queryClient.getQueryData(metadataSourceKeys.fileMetadata(7))).toBeUndefined();
|
||||
});
|
||||
|
||||
it('looks an isbn up with a POST carrying the trimmed isbn', async () => {
|
||||
const result = queryClient.fetchQuery(service.isbnLookup(' 9780441013593 '));
|
||||
|
||||
const request = http.expectOne(`${BOOKS_URL}/metadata/isbn-lookup`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({isbn: '9780441013593'});
|
||||
request.flush({bookId: 7, title: 'Dune'});
|
||||
|
||||
await expect(result).resolves.toEqual({bookId: 7, title: 'Dune'});
|
||||
});
|
||||
|
||||
it('treats an ISBN lookup 404 as no match', async () => {
|
||||
const result = queryClient.fetchQuery(service.isbnLookup('9780441013593'));
|
||||
http.expectOne(`${BOOKS_URL}/metadata/isbn-lookup`).flush(null, {status: 404, statusText: 'Not Found'});
|
||||
|
||||
await expect(result).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('keeps other ISBN lookup failures as errors', async () => {
|
||||
const result = queryClient.fetchQuery({...service.isbnLookup('9780441013593'), retry: false});
|
||||
http.expectOne(`${BOOKS_URL}/metadata/isbn-lookup`).flush(null, {status: 503, statusText: 'Unavailable'});
|
||||
|
||||
await expect(result).rejects.toMatchObject({status: 503});
|
||||
});
|
||||
|
||||
describe('prospective', () => {
|
||||
it('posts the normalised search', async () => {
|
||||
const fetchStub = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
sseResponse(sseStream([event('One')])),
|
||||
);
|
||||
|
||||
TestBed.inject(ProspectiveHost);
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(fetchStub).toHaveBeenCalledOnce();
|
||||
expect(service.prospective(SEARCH).queryKey).toEqual(
|
||||
service.prospective({bookId: 7, providers: ['Amazon', 'GoodReads'], title: 'Dune'}).queryKey,
|
||||
);
|
||||
const [url, init] = fetchStub.mock.calls[0];
|
||||
expect(url).toBe(`${BOOKS_URL}/7/metadata/prospective`);
|
||||
expect(init?.method).toBe('POST');
|
||||
expect(init?.body).toBe(JSON.stringify({
|
||||
bookId: 7,
|
||||
providers: ['Amazon', 'GoodReads'],
|
||||
title: 'Dune',
|
||||
author: '',
|
||||
isbn: '',
|
||||
}));
|
||||
});
|
||||
|
||||
it('grows the result list as the stream delivers events', async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const secondEvent = deferred();
|
||||
const endOfStream = deferred();
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
controller.enqueue(encoder.encode(event('One')));
|
||||
await secondEvent.promise;
|
||||
controller.enqueue(encoder.encode(event('Two')));
|
||||
await endOfStream.promise;
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(sseResponse(stream));
|
||||
|
||||
const host = TestBed.inject(ProspectiveHost);
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(host.query.data()).toEqual([{bookId: 7, title: 'One'}]);
|
||||
expect(host.query.isFetching()).toBe(true);
|
||||
|
||||
secondEvent.resolve();
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(host.query.data()).toEqual([{bookId: 7, title: 'One'}, {bookId: 7, title: 'Two'}]);
|
||||
expect(host.query.isFetching()).toBe(true);
|
||||
|
||||
endOfStream.resolve();
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(host.query.isFetching()).toBe(false);
|
||||
});
|
||||
|
||||
it('fails the query with the http status when the stream request is rejected', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 503}));
|
||||
|
||||
const host = TestBed.inject(ProspectiveHost);
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(host.query.isError()).toBe(true);
|
||||
expect(host.query.error()).toMatchObject({status: 503});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('covers', () => {
|
||||
it('posts the normalised cover search', async () => {
|
||||
const fetchStub = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
sseResponse(sseStream([coverEvent(1)])),
|
||||
);
|
||||
|
||||
TestBed.inject(CoversHost);
|
||||
await flushQueryAsync();
|
||||
|
||||
expect(fetchStub).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchStub.mock.calls[0];
|
||||
expect(url).toBe(`${BOOKS_URL}/7/metadata/covers`);
|
||||
expect(init?.method).toBe('POST');
|
||||
expect(init?.body).toBe(JSON.stringify({
|
||||
title: 'Dune',
|
||||
author: 'Frank Herbert',
|
||||
coverType: 'ebook',
|
||||
}));
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {
|
||||
experimental_streamedQuery,
|
||||
injectQuery,
|
||||
queryOptions,
|
||||
QueryClient,
|
||||
} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {httpGet, postSseJson, QUERY_DEFAULTS, toAbortablePromise} from '../../../core/data/query-transport';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import type {BookMetadata} from '../../book/model/book.model';
|
||||
import {MetadataCatalogService} from '../../../shared/metadata/metadata-catalog.service';
|
||||
import type {MetadataProviderDescriptor, MetadataProviderId} from '../../../shared/metadata/metadata-providers';
|
||||
import type {SidecarMetadata, SidecarSyncStatus} from './sidecar.models';
|
||||
|
||||
interface MetadataProviderState {
|
||||
readonly name: MetadataProviderId;
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
export interface MetadataSourceProvider extends MetadataProviderDescriptor {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
export interface MetadataSearchParams {
|
||||
readonly bookId: number;
|
||||
readonly providers: readonly MetadataProviderId[];
|
||||
readonly title?: string;
|
||||
readonly author?: string;
|
||||
readonly isbn?: string;
|
||||
}
|
||||
|
||||
export type MetadataSearchResult = BookMetadata & {readonly provider: MetadataProviderId};
|
||||
|
||||
export interface CoverImage {
|
||||
url: string;
|
||||
width: number;
|
||||
height: number;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export interface CoverSearchParams {
|
||||
readonly bookId: number;
|
||||
readonly title?: string;
|
||||
readonly author?: string;
|
||||
readonly coverType: 'ebook' | 'audiobook';
|
||||
}
|
||||
|
||||
export const metadataSourceKeys = {
|
||||
all: () => ['metadata-sources'] as const,
|
||||
providerList: () => [...metadataSourceKeys.all(), 'providers'] as const,
|
||||
prospective: (params: MetadataSearchParams) =>
|
||||
[...metadataSourceKeys.all(), 'prospective', params] as const,
|
||||
covers: (params: CoverSearchParams) =>
|
||||
[...metadataSourceKeys.all(), 'covers', params] as const,
|
||||
isbnLookup: (isbn: string) => [...metadataSourceKeys.all(), 'isbn', isbn] as const,
|
||||
fileMetadata: (bookId: number) => [...metadataSourceKeys.all(), 'file', bookId] as const,
|
||||
sidecar: (bookId: number) => [...metadataSourceKeys.all(), 'sidecar', bookId] as const,
|
||||
sidecarStatus: (bookId: number) => [...metadataSourceKeys.sidecar(bookId), 'status'] as const,
|
||||
};
|
||||
|
||||
const STREAM_DEFAULTS = {
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
} as const;
|
||||
|
||||
function normalizeSearchParams(params: MetadataSearchParams) {
|
||||
return {
|
||||
bookId: params.bookId,
|
||||
providers: [...new Set(params.providers)].sort((a, b) => a.localeCompare(b)),
|
||||
title: params.title?.trim() ?? '',
|
||||
author: params.author?.trim() ?? '',
|
||||
isbn: params.isbn?.trim() ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCoverSearchParams(params: CoverSearchParams): CoverSearchParams {
|
||||
return {
|
||||
bookId: params.bookId,
|
||||
title: params.title?.trim() || undefined,
|
||||
author: params.author?.trim() || undefined,
|
||||
coverType: params.coverType,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class MetadataSourceQueryService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly catalog = inject(MetadataCatalogService);
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private readonly providerList = injectQuery(() => queryOptions({
|
||||
queryKey: metadataSourceKeys.providerList(),
|
||||
queryFn: ({signal}) => httpGet<readonly MetadataProviderState[]>(
|
||||
this.http,
|
||||
`${API_CONFIG.BASE_URL}/api/v1/metadata/providers`,
|
||||
signal,
|
||||
),
|
||||
...QUERY_DEFAULTS,
|
||||
staleTime: Infinity,
|
||||
}));
|
||||
|
||||
readonly providersLoading = computed(() => this.providerList.isPending());
|
||||
|
||||
readonly providers = computed<readonly MetadataSourceProvider[]>(() => {
|
||||
const enabled = new Map((this.providerList.data() ?? []).map(entry => [entry.name, entry.enabled]));
|
||||
return this.catalog.providers().map(provider => ({
|
||||
...provider,
|
||||
enabled: enabled.get(provider.id) ?? false,
|
||||
}));
|
||||
});
|
||||
readonly enabledProviders = computed(() => this.providers().filter(provider => provider.enabled));
|
||||
|
||||
refreshProviders(): Promise<void> {
|
||||
return this.queryClient.invalidateQueries({queryKey: metadataSourceKeys.providerList()});
|
||||
}
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (this.authService.token() === null) {
|
||||
this.queryClient.removeQueries({queryKey: metadataSourceKeys.all()});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
prospective(params: MetadataSearchParams) {
|
||||
const normalized = normalizeSearchParams(params);
|
||||
const body = JSON.stringify(normalized);
|
||||
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.prospective(normalized),
|
||||
queryFn: experimental_streamedQuery({
|
||||
streamFn: ({signal}) => postSseJson<MetadataSearchResult>(this.authService, `${this.baseUrl}/${params.bookId}/metadata/prospective`, body, signal),
|
||||
refetchMode: 'reset',
|
||||
}),
|
||||
...STREAM_DEFAULTS,
|
||||
});
|
||||
}
|
||||
|
||||
coverSearch(params: CoverSearchParams) {
|
||||
const normalized = normalizeCoverSearchParams(params);
|
||||
const {title, author, coverType} = normalized;
|
||||
const body = JSON.stringify({title, author, coverType});
|
||||
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.covers(normalized),
|
||||
queryFn: experimental_streamedQuery({
|
||||
streamFn: ({signal}) => postSseJson<CoverImage>(this.authService, `${this.baseUrl}/${params.bookId}/metadata/covers`, body, signal),
|
||||
refetchMode: 'reset',
|
||||
}),
|
||||
...STREAM_DEFAULTS,
|
||||
});
|
||||
}
|
||||
|
||||
isbnLookup(isbn: string) {
|
||||
const trimmed = isbn.trim();
|
||||
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.isbnLookup(trimmed),
|
||||
queryFn: async ({signal}): Promise<BookMetadata | null> => {
|
||||
try {
|
||||
return await toAbortablePromise(
|
||||
this.http.post<BookMetadata>(`${this.baseUrl}/metadata/isbn-lookup`, {isbn: trimmed}),
|
||||
signal,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpErrorResponse && error.status === 404) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
...QUERY_DEFAULTS,
|
||||
});
|
||||
}
|
||||
|
||||
fileMetadata(bookId: number) {
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.fileMetadata(bookId),
|
||||
queryFn: ({signal}): Promise<BookMetadata> => httpGet<BookMetadata>(
|
||||
this.http,
|
||||
`${this.baseUrl}/${bookId}/file-metadata`,
|
||||
signal,
|
||||
),
|
||||
...QUERY_DEFAULTS,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
|
||||
sidecar(bookId: number) {
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.sidecar(bookId),
|
||||
queryFn: ({signal}): Promise<SidecarMetadata> => httpGet<SidecarMetadata>(
|
||||
this.http,
|
||||
`${this.baseUrl}/${bookId}/sidecar`,
|
||||
signal,
|
||||
),
|
||||
...QUERY_DEFAULTS,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
|
||||
sidecarStatus(bookId: number) {
|
||||
return queryOptions({
|
||||
queryKey: metadataSourceKeys.sidecarStatus(bookId),
|
||||
queryFn: ({signal}): Promise<{status: SidecarSyncStatus}> => httpGet<{status: SidecarSyncStatus}>(
|
||||
this.http,
|
||||
`${this.baseUrl}/${bookId}/sidecar/status`,
|
||||
signal,
|
||||
),
|
||||
...QUERY_DEFAULTS,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type {MetadataProviderIdFieldName} from '../../../shared/metadata/metadata-providers';
|
||||
|
||||
interface SidecarCoverInfo {
|
||||
source: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface SidecarSeries {
|
||||
name?: string;
|
||||
number?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
type SidecarIdentifiers = Partial<Record<MetadataProviderIdFieldName, string>>;
|
||||
|
||||
interface SidecarRating {
|
||||
average?: number;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
interface SidecarRatings {
|
||||
amazon?: SidecarRating;
|
||||
goodreads?: SidecarRating;
|
||||
hardcover?: SidecarRating;
|
||||
lubimyczytac?: SidecarRating;
|
||||
ranobedb?: SidecarRating;
|
||||
audible?: SidecarRating;
|
||||
applebooks?: SidecarRating;
|
||||
}
|
||||
|
||||
interface SidecarBookMetadata {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
authors?: string[];
|
||||
publisher?: string;
|
||||
publishedDate?: string;
|
||||
description?: string;
|
||||
isbn10?: string;
|
||||
isbn13?: string;
|
||||
language?: string;
|
||||
pageCount?: number;
|
||||
categories?: string[];
|
||||
moods?: string[];
|
||||
tags?: string[];
|
||||
series?: SidecarSeries;
|
||||
identifiers?: SidecarIdentifiers;
|
||||
ratings?: SidecarRatings;
|
||||
ageRating?: number;
|
||||
contentRating?: string;
|
||||
narrator?: string;
|
||||
abridged?: boolean;
|
||||
}
|
||||
|
||||
export interface SidecarMetadata {
|
||||
version: string;
|
||||
generatedAt: string;
|
||||
generatedBy: string;
|
||||
metadata: SidecarBookMetadata;
|
||||
cover?: SidecarCoverInfo;
|
||||
}
|
||||
|
||||
export type SidecarSyncStatus = 'IN_SYNC' | 'OUTDATED' | 'MISSING' | 'CONFLICT' | 'NOT_APPLICABLE';
|
||||
Reference in New Issue
Block a user