refactor(metadata): metadata source query service (#2718)
This commit is contained in:
@@ -0,0 +1,104 @@
|
|||||||
|
import {HttpErrorResponse} from '@angular/common/http';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
|
import type {AuthService} from '../../shared/service/auth.service';
|
||||||
|
import {sseResponse, sseStream} from '../testing/query-testing';
|
||||||
|
import {postSseJson} from './query-transport';
|
||||||
|
|
||||||
|
interface Chunk {
|
||||||
|
readonly id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collect(events: AsyncIterable<Chunk>): Promise<Chunk[]> {
|
||||||
|
const collected: Chunk[] = [];
|
||||||
|
for await (const event of events) {
|
||||||
|
collected.push(event);
|
||||||
|
}
|
||||||
|
return collected;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('postSseJson', () => {
|
||||||
|
const ensureAccessToken = vi.fn((options: {forceRefresh?: boolean} = {}) =>
|
||||||
|
of(options.forceRefresh ? 'refreshed-token' : 'token-123'));
|
||||||
|
const auth = {ensureAccessToken} as unknown as AuthService;
|
||||||
|
let fetchStub: ReturnType<typeof vi.spyOn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
ensureAccessToken.mockClear();
|
||||||
|
fetchStub = vi.spyOn(globalThis, 'fetch');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('posts the body with a bearer token and reads the streamed events', async () => {
|
||||||
|
fetchStub.mockResolvedValue(sseResponse(sseStream(['data:{"id":1}\n\n'])));
|
||||||
|
|
||||||
|
const events = await postSseJson<Chunk>(auth, '/stream', '{"q":1}', new AbortController().signal);
|
||||||
|
|
||||||
|
expect(await collect(events)).toEqual([{id: 1}]);
|
||||||
|
const [url, init] = fetchStub.mock.calls[0];
|
||||||
|
expect(url).toBe('/stream');
|
||||||
|
expect(init?.method).toBe('POST');
|
||||||
|
expect(init?.body).toBe('{"q":1}');
|
||||||
|
expect(init?.headers).toEqual({
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': 'Bearer token-123',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refreshes the token once and retries when the request is rejected as unauthenticated', async () => {
|
||||||
|
fetchStub
|
||||||
|
.mockResolvedValueOnce(new Response(null, {status: 401}))
|
||||||
|
.mockResolvedValueOnce(sseResponse(sseStream(['data:{"id":2}\n\n'])));
|
||||||
|
|
||||||
|
const events = await postSseJson<Chunk>(auth, '/stream', '{}', new AbortController().signal);
|
||||||
|
|
||||||
|
expect(await collect(events)).toEqual([{id: 2}]);
|
||||||
|
expect(ensureAccessToken).toHaveBeenNthCalledWith(2, {forceRefresh: true});
|
||||||
|
expect(fetchStub.mock.calls[1][1]?.headers).toEqual({
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': 'Bearer refreshed-token',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails with the http status when the retried request is still rejected', async () => {
|
||||||
|
fetchStub.mockResolvedValue(new Response(null, {status: 401, statusText: 'Unauthorized'}));
|
||||||
|
|
||||||
|
await expect(postSseJson(auth, '/stream', '{}', new AbortController().signal))
|
||||||
|
.rejects.toMatchObject({status: 401, statusText: 'Unauthorized'});
|
||||||
|
expect(fetchStub).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails with the http status rather than a bare message', async () => {
|
||||||
|
fetchStub.mockResolvedValue(new Response(null, {status: 503, statusText: 'Unavailable'}));
|
||||||
|
|
||||||
|
const failure = await postSseJson(auth, '/stream', '{}', new AbortController().signal).catch((error: unknown) => error);
|
||||||
|
|
||||||
|
expect(failure).toBeInstanceOf(HttpErrorResponse);
|
||||||
|
expect(failure).toMatchObject({status: 503, url: '/stream'});
|
||||||
|
expect(fetchStub).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes the abort signal to the request', async () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
fetchStub.mockImplementation((_url: unknown, init?: RequestInit) => {
|
||||||
|
controller.abort();
|
||||||
|
return init?.signal?.aborted
|
||||||
|
? Promise.reject(new DOMException('Aborted', 'AbortError'))
|
||||||
|
: Promise.resolve(sseResponse(sseStream(['data:{"id":3}\n\n'])));
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(postSseJson(auth, '/stream', '{}', controller.signal)).rejects.toThrow('Aborted');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails when the token cannot be obtained', async () => {
|
||||||
|
ensureAccessToken.mockReturnValueOnce(throwError(() => new Error('No refresh token available')));
|
||||||
|
|
||||||
|
await expect(postSseJson(auth, '/stream', '{}', new AbortController().signal))
|
||||||
|
.rejects.toThrow('No refresh token available');
|
||||||
|
expect(fetchStub).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
import {HttpErrorResponse} from '@angular/common/http';
|
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
|
||||||
import {Observable} from 'rxjs';
|
import {firstValueFrom, lastValueFrom, Observable, takeUntil} from 'rxjs';
|
||||||
|
|
||||||
|
import type {AuthService} from '../../shared/service/auth.service';
|
||||||
|
import {readSseJson} from './sse';
|
||||||
|
|
||||||
export function retryTransientQueryError(failureCount: number, error: unknown): boolean {
|
export function retryTransientQueryError(failureCount: number, error: unknown): boolean {
|
||||||
if (failureCount >= 2) {
|
if (failureCount >= 2) {
|
||||||
@@ -28,3 +31,44 @@ export function abortSignal(signal: AbortSignal): Observable<void> {
|
|||||||
return () => signal.removeEventListener('abort', onAbort);
|
return () => signal.removeEventListener('abort', onAbort);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function toAbortablePromise<T>(source: Observable<T>, signal: AbortSignal): Promise<T> {
|
||||||
|
return lastValueFrom(source.pipe(takeUntil(abortSignal(signal))));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function httpGet<T>(http: HttpClient, url: string, signal: AbortSignal): Promise<T> {
|
||||||
|
return toAbortablePromise(http.get<T>(url), signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function postSseJson<T>(
|
||||||
|
auth: AuthService,
|
||||||
|
url: string,
|
||||||
|
body: string,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<AsyncIterable<T>> {
|
||||||
|
const send = async (options: {forceRefresh?: boolean} = {}) => {
|
||||||
|
const token = await firstValueFrom(auth.ensureAccessToken(options));
|
||||||
|
return fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = await send();
|
||||||
|
if (response.status === 401) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
response = await send({forceRefresh: true});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
throw new HttpErrorResponse({status: response.status, statusText: response.statusText, url});
|
||||||
|
}
|
||||||
|
|
||||||
|
return readSseJson<T>(response);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {sseResponse, sseStream} from '../testing/query-testing';
|
||||||
|
import {readSseJson} from './sse';
|
||||||
|
|
||||||
|
interface Chunk {
|
||||||
|
readonly id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collect(chunks: readonly string[]): Promise<Chunk[]> {
|
||||||
|
const events: Chunk[] = [];
|
||||||
|
for await (const event of readSseJson<Chunk>(sseResponse(sseStream(chunks)))) {
|
||||||
|
events.push(event);
|
||||||
|
}
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('readSseJson', () => {
|
||||||
|
it('reads one event per chunk', async () => {
|
||||||
|
expect(await collect(['data:{"id":1}\n\n', 'data:{"id":2}\n\n'])).toEqual([{id: 1}, {id: 2}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads two events arriving in one chunk', async () => {
|
||||||
|
expect(await collect(['data:{"id":1}\n\ndata:{"id":2}\n\n'])).toEqual([{id: 1}, {id: 2}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads one event split across chunks', async () => {
|
||||||
|
expect(await collect(['data:{"id', '":1}\n\n'])).toEqual([{id: 1}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads a trailing event that has no final newline', async () => {
|
||||||
|
expect(await collect(['data:{"id":1}\n\n', 'data:{"id":2}'])).toEqual([{id: 1}, {id: 2}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips an empty data line', async () => {
|
||||||
|
expect(await collect(['data:\n\n', 'data:{"id":1}\n\n'])).toEqual([{id: 1}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when a payload is not JSON', async () => {
|
||||||
|
await expect(collect(['data:not-json\n\n'])).rejects.toThrow(SyntaxError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when the response has no body', async () => {
|
||||||
|
const events = readSseJson<Chunk>(new Response(null, {status: 204}));
|
||||||
|
await expect(events[Symbol.asyncIterator]().next()).rejects.toThrow('Response body is null');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
async function* readLines(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncIterable<string> {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const {done, value} = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer += decoder.decode(value, {stream: true});
|
||||||
|
const lines = buffer.split('\n');
|
||||||
|
buffer = lines.pop() ?? '';
|
||||||
|
yield* lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield buffer;
|
||||||
|
} finally {
|
||||||
|
await reader.cancel().catch(() => undefined);
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function* readSseJson<T>(response: Response): AsyncIterable<T> {
|
||||||
|
const reader = response.body?.getReader();
|
||||||
|
if (!reader) {
|
||||||
|
throw new Error('Response body is null');
|
||||||
|
}
|
||||||
|
|
||||||
|
for await (const line of readLines(reader)) {
|
||||||
|
if (!line.startsWith('data:')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = line.slice(5).trim();
|
||||||
|
if (payload !== '') {
|
||||||
|
const parsed: T = JSON.parse(payload);
|
||||||
|
yield parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,10 +3,12 @@ import {provideHttpClient} from '@angular/common/http';
|
|||||||
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {provideTanStackQuery, QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
import {provideTanStackQuery, QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
||||||
|
import {of, type Observable} from 'rxjs';
|
||||||
|
|
||||||
interface AuthServiceStub {
|
interface AuthServiceStub {
|
||||||
token: WritableSignal<string | null>;
|
token: WritableSignal<string | null>;
|
||||||
getInternalAccessToken: () => string | null;
|
getInternalAccessToken: () => string | null;
|
||||||
|
ensureAccessToken: (options?: {forceRefresh?: boolean}) => Observable<string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QueryClientHarness {
|
export interface QueryClientHarness {
|
||||||
@@ -19,6 +21,7 @@ export function createAuthServiceStub(initialToken: string | null = 'token-123')
|
|||||||
return {
|
return {
|
||||||
token,
|
token,
|
||||||
getInternalAccessToken: () => token(),
|
getInternalAccessToken: () => token(),
|
||||||
|
ensureAccessToken: () => of(token() ?? ''),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,3 +90,19 @@ export async function flushQueryAsync(rounds = 5): Promise<void> {
|
|||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
appRef.tick();
|
appRef.tick();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function sseStream(chunks: readonly string[]): ReadableStream<Uint8Array> {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
return new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
controller.enqueue(encoder.encode(chunk));
|
||||||
|
}
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sseResponse(body: ReadableStream<Uint8Array>, status = 200): Response {
|
||||||
|
return new Response(body, {status, headers: {'Content-Type': 'text/event-stream'}});
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,19 +18,6 @@ export const BOOK_READ_STATUSES = [
|
|||||||
export type KnownBookReadStatus = typeof BOOK_READ_STATUSES[number];
|
export type KnownBookReadStatus = typeof BOOK_READ_STATUSES[number];
|
||||||
export type BookReadStatus = KnownBookReadStatus | (string & {});
|
export type BookReadStatus = KnownBookReadStatus | (string & {});
|
||||||
|
|
||||||
export const BOOK_METADATA_PROVIDERS = [
|
|
||||||
'Amazon',
|
|
||||||
'GoodReads',
|
|
||||||
'Google',
|
|
||||||
'Hardcover',
|
|
||||||
'Comicvine',
|
|
||||||
'Douban',
|
|
||||||
'Lubimyczytac',
|
|
||||||
'Ranobedb',
|
|
||||||
'Audible',
|
|
||||||
] as const;
|
|
||||||
export type BookMetadataProvider = typeof BOOK_METADATA_PROVIDERS[number] | (string & {});
|
|
||||||
|
|
||||||
export interface BookFileResponse {
|
export interface BookFileResponse {
|
||||||
id: number;
|
id: number;
|
||||||
bookId: number;
|
bookId: number;
|
||||||
@@ -267,7 +254,7 @@ export interface BookDetailMetadata extends BookMetadataFields {
|
|||||||
abridged?: boolean;
|
abridged?: boolean;
|
||||||
audiobookMetadata?: BookDetailAudiobookMetadata;
|
audiobookMetadata?: BookDetailAudiobookMetadata;
|
||||||
comicMetadata?: BookDetailComicMetadata;
|
comicMetadata?: BookDetailComicMetadata;
|
||||||
provider?: BookMetadataProvider;
|
provider?: string;
|
||||||
externalUrl?: string;
|
externalUrl?: string;
|
||||||
thumbnailUrl?: string;
|
thumbnailUrl?: string;
|
||||||
titleLocked?: boolean;
|
titleLocked?: boolean;
|
||||||
|
|||||||
@@ -172,7 +172,8 @@ export interface BookMetadata {
|
|||||||
goodreadsId?: string;
|
goodreadsId?: string;
|
||||||
comicvineId?: string;
|
comicvineId?: string;
|
||||||
hardcoverId?: string;
|
hardcoverId?: string;
|
||||||
hardcoverBookId?: number | null;
|
hardcoverBookId?: string | null;
|
||||||
|
doubanId?: string;
|
||||||
googleId?: string;
|
googleId?: string;
|
||||||
pageCount?: number | null;
|
pageCount?: number | null;
|
||||||
language?: string;
|
language?: string;
|
||||||
@@ -183,6 +184,8 @@ export interface BookMetadata {
|
|||||||
goodreadsRating?: number | null;
|
goodreadsRating?: number | null;
|
||||||
goodreadsReviewCount?: number | null;
|
goodreadsReviewCount?: number | null;
|
||||||
hardcoverReviewCount?: number | null;
|
hardcoverReviewCount?: number | null;
|
||||||
|
doubanRating?: number | null;
|
||||||
|
doubanReviewCount?: number | null;
|
||||||
lubimyczytacId?: string;
|
lubimyczytacId?: string;
|
||||||
lubimyczytacRating?: number | null;
|
lubimyczytacRating?: number | null;
|
||||||
ranobedbId?: string;
|
ranobedbId?: string;
|
||||||
@@ -227,6 +230,7 @@ export interface BookMetadata {
|
|||||||
goodreadsIdLocked?: boolean;
|
goodreadsIdLocked?: boolean;
|
||||||
hardcoverIdLocked?: boolean;
|
hardcoverIdLocked?: boolean;
|
||||||
hardcoverBookIdLocked?: boolean;
|
hardcoverBookIdLocked?: boolean;
|
||||||
|
doubanIdLocked?: boolean;
|
||||||
googleIdLocked?: boolean;
|
googleIdLocked?: boolean;
|
||||||
pageCountLocked?: boolean;
|
pageCountLocked?: boolean;
|
||||||
languageLocked?: boolean;
|
languageLocked?: boolean;
|
||||||
@@ -236,6 +240,8 @@ export interface BookMetadata {
|
|||||||
goodreadsReviewCountLocked?: boolean;
|
goodreadsReviewCountLocked?: boolean;
|
||||||
hardcoverRatingLocked?: boolean;
|
hardcoverRatingLocked?: boolean;
|
||||||
hardcoverReviewCountLocked?: boolean;
|
hardcoverReviewCountLocked?: boolean;
|
||||||
|
doubanRatingLocked?: boolean;
|
||||||
|
doubanReviewCountLocked?: boolean;
|
||||||
lubimyczytacIdLocked?: boolean;
|
lubimyczytacIdLocked?: boolean;
|
||||||
lubimyczytacRatingLocked?: boolean;
|
lubimyczytacRatingLocked?: boolean;
|
||||||
ranobedbIdLocked?: boolean;
|
ranobedbIdLocked?: boolean;
|
||||||
|
|||||||
@@ -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';
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {computed, Injectable, signal} from '@angular/core';
|
||||||
|
|
||||||
|
import {METADATA_PROVIDER_LIST, type MetadataProviderDescriptor} from './metadata-providers';
|
||||||
|
|
||||||
|
@Injectable({providedIn: 'root'})
|
||||||
|
export class MetadataCatalogService {
|
||||||
|
readonly providers = signal<readonly MetadataProviderDescriptor[]>(METADATA_PROVIDER_LIST).asReadonly();
|
||||||
|
readonly reviewProviders = computed(() => this.providers().filter(provider => provider.supportsReviews));
|
||||||
|
|
||||||
|
private readonly byId = computed(
|
||||||
|
() => new Map<string, MetadataProviderDescriptor>(this.providers().map(provider => [provider.id, provider])),
|
||||||
|
);
|
||||||
|
|
||||||
|
provider(id: string): MetadataProviderDescriptor | undefined {
|
||||||
|
return this.byId().get(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
const providers = [
|
||||||
|
{
|
||||||
|
id: 'OpenLibrary',
|
||||||
|
settingsKey: 'openLibrary',
|
||||||
|
labelKey: 'metadata.providers.openLibrary',
|
||||||
|
book: {ids: ['openlibraryId']},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Amazon',
|
||||||
|
settingsKey: 'amazon',
|
||||||
|
labelKey: 'metadata.providers.amazon',
|
||||||
|
hasOptions: true,
|
||||||
|
supportsReviews: true,
|
||||||
|
book: {ids: ['asin'], rating: 'amazonRating', reviewCount: 'amazonReviewCount', labelKeys: {asin: 'metadata.providerFields.asin'}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'GoodReads',
|
||||||
|
settingsKey: 'goodReads',
|
||||||
|
labelKey: 'metadata.providers.goodReads',
|
||||||
|
supportsReviews: true,
|
||||||
|
book: {ids: ['goodreadsId'], rating: 'goodreadsRating', reviewCount: 'goodreadsReviewCount'},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Google',
|
||||||
|
settingsKey: 'google',
|
||||||
|
labelKey: 'metadata.providers.google',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['googleId']},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Hardcover',
|
||||||
|
settingsKey: 'hardcover',
|
||||||
|
labelKey: 'metadata.providers.hardcover',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['hardcoverId', 'hardcoverBookId'], rating: 'hardcoverRating', reviewCount: 'hardcoverReviewCount', labelKeys: {hardcoverBookId: 'metadata.providerFields.hardcoverBookId'}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Comicvine',
|
||||||
|
settingsKey: 'comicvine',
|
||||||
|
labelKey: 'metadata.providers.comicvine',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['comicvineId']},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Douban',
|
||||||
|
settingsKey: 'douban',
|
||||||
|
labelKey: 'metadata.providers.douban',
|
||||||
|
supportsReviews: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Lubimyczytac',
|
||||||
|
settingsKey: 'lubimyczytac',
|
||||||
|
labelKey: 'metadata.providers.lubimyczytac',
|
||||||
|
book: {ids: ['lubimyczytacId'], rating: 'lubimyczytacRating'},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Ranobedb',
|
||||||
|
settingsKey: 'ranobedb',
|
||||||
|
labelKey: 'metadata.providers.ranobedb',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['ranobedbId'], rating: 'ranobedbRating'},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'Audible',
|
||||||
|
settingsKey: 'audible',
|
||||||
|
labelKey: 'metadata.providers.audible',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['audibleId'], rating: 'audibleRating', reviewCount: 'audibleReviewCount'},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'AppleBooks',
|
||||||
|
settingsKey: 'appleBooks',
|
||||||
|
labelKey: 'metadata.providers.appleBooks',
|
||||||
|
hasOptions: true,
|
||||||
|
book: {ids: ['applebooksId'], rating: 'applebooksRating', reviewCount: 'applebooksReviewCount'},
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type MetadataProviderId = typeof providers[number]['id'];
|
||||||
|
|
||||||
|
type BookAspect = Extract<typeof providers[number], {book: unknown}>['book'];
|
||||||
|
type FieldForRole<Aspect, Role extends string> = Aspect extends Record<Role, infer Name extends string> ? Name : never;
|
||||||
|
|
||||||
|
export type MetadataProviderIdFieldName = BookAspect['ids'][number];
|
||||||
|
export type MetadataProviderRatingFieldName = FieldForRole<BookAspect, 'rating'>;
|
||||||
|
export type MetadataProviderReviewCountFieldName = FieldForRole<BookAspect, 'reviewCount'>;
|
||||||
|
|
||||||
|
export type MetadataProviderScoreFieldName = MetadataProviderRatingFieldName | MetadataProviderReviewCountFieldName;
|
||||||
|
export type MetadataProviderFieldName = MetadataProviderIdFieldName | MetadataProviderScoreFieldName;
|
||||||
|
|
||||||
|
export interface MetadataProviderBookFields {
|
||||||
|
readonly ids: readonly MetadataProviderIdFieldName[];
|
||||||
|
readonly rating?: MetadataProviderRatingFieldName;
|
||||||
|
readonly reviewCount?: MetadataProviderReviewCountFieldName;
|
||||||
|
readonly labelKeys?: Partial<Record<MetadataProviderFieldName, string>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MetadataProviderDescriptor {
|
||||||
|
readonly id: MetadataProviderId;
|
||||||
|
readonly settingsKey: Uncapitalize<MetadataProviderId>;
|
||||||
|
readonly labelKey: string;
|
||||||
|
readonly hasOptions?: boolean;
|
||||||
|
readonly supportsReviews?: boolean;
|
||||||
|
readonly book?: MetadataProviderBookFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const METADATA_PROVIDER_LIST: readonly MetadataProviderDescriptor[] = providers;
|
||||||
@@ -2805,6 +2805,23 @@
|
|||||||
},
|
},
|
||||||
"fetchOptions": {
|
"fetchOptions": {
|
||||||
"startRefresh": "Start Refresh"
|
"startRefresh": "Start Refresh"
|
||||||
|
},
|
||||||
|
"providers": {
|
||||||
|
"openLibrary": "Open Library",
|
||||||
|
"amazon": "Amazon",
|
||||||
|
"google": "Google Books",
|
||||||
|
"goodReads": "Goodreads",
|
||||||
|
"hardcover": "Hardcover",
|
||||||
|
"comicvine": "Comic Vine",
|
||||||
|
"douban": "Douban",
|
||||||
|
"lubimyczytac": "Lubimyczytać",
|
||||||
|
"ranobedb": "RanobeDB",
|
||||||
|
"audible": "Audible",
|
||||||
|
"appleBooks": "Apple Books"
|
||||||
|
},
|
||||||
|
"providerFields": {
|
||||||
|
"asin": "Amazon ASIN",
|
||||||
|
"hardcoverBookId": "Hardcover Book ID"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"notebook": {
|
"notebook": {
|
||||||
|
|||||||
Reference in New Issue
Block a user