* docs: define ebook architecture matching audiobooks * docs: plan ebook audiobook-parity implementation * feat: add ebook scanner parser foundation * fix: harden ebook scanner foundation * fix: handle ebook isbn labels * fix: guard ebook subtree scans * feat: scan ebook libraries in core * fix: preserve ebook scan people credits * fix: refresh ebook scan metadata safely * feat: persist ebook series membership * test: cover ebook series persistence decisions * fix: address ebook scanner PR review * docs: clarify ebook foundation PR scope * feat: add ebook metadata enricher * fix: harden ebook poster cache * feat: wire ebook metadata sync task * feat: expose ebook library metadata setup * feat: add ebook catalog scope support * feat: add ebook detail view * feat: label ebook file versions by format * feat: use file-size copy for downloads * feat: use file language in download dialog * test: cover ebook detail authors and downloads * fix: drop narrator credits from ebook scanner merges * fix: align ebook collection filters with book media * fix: drop asin provider ids from ebook enrichment * fix: force ebook people refresh for stale narrators * chore: omit ebook planning docs from branch * feat: add ebook detail related content * feat: add ebook reader file entrypoint * feat: render ebooks with foliate reader * feat: persist ebook reader progress * feat: add ebook reader controls * feat: extract ebook pdf metadata * feat: favor scanner isbn during ebook enrichment * feat: extract fbz ebook metadata * feat: count cbz ebook pages * feat: show ebook file page counts * feat: show ebook download summaries * feat: switch ebook reader files * feat: prefer epub for ebook read action * feat: surface ebook reader progress * feat: sync ebook reader progress cache * feat: hide ebook read action for unsupported files * feat: filter ebook reader file selector * fix: serve fbz ebook archives with reader mime type * fix: detect fbz ebooks from compound filename * fix: authorize fbz ebooks from compound filename * fix: scope ebook catalog facets * fix: reject narrator queries for ebooks * fix: build ebook recommendation text from authors * fix: include ebooks in embedding eligibility * fix: include ebooks in recommendation media mix * fix: include ebooks in recently added recommendations * feat: include ebook progress in recommendation signals * feat: include ebooks in continue watching sections * feat: include ebooks in catalog progress metrics * fix: read ebook isbn from epub metadata * fix: filter ebook asin provider aliases * fix: fall back from unsupported ebook reader files * fix: sort ebook catalogs by reader progress * fix: filter ebook catalogs by reader progress * fix: include ebooks in last watched catalog filters * feat: reflect ebook reader progress in item user state * feat: share ebook progress state across item surfaces * feat: report ebook scan progress * fix: include ebook activity in recommendations * fix: expose ebook reader progress on item detail * fix: support ebook subtree scans * fix: honor profile header for ebook item progress * fix: add ebook library default sections * fix: route ebook continue cards to reader * fix: hide watched toggle for ebooks * fix: route ebook watch tonight cards to reader * fix: route ebook hero actions to reader * fix: detect archive ebook reader formats by filename * feat: cache embedded ebook covers during scan * fix: encode ebook hero reader links * fix: persist non-epub ebook reader progress * fix: scope narrator catalog badges to audiobooks * fix: merge ebook reader progress during item repair * fix: label ebook progress filters as read * fix: show ebook related rails as book covers * fix: remove txt ebook reader support * fix: reject txt ebook reader files * fix: label ebook advanced filters as read * fix: label ebook personalized sorts as read * fix: remove plain text reader loader path * test: cover ebook unread catalog rules * fix: preserve ebook reader library context * fix: link ebook genres with library scope * fix: encode related rail item links * fix: encode catalog card item links * fix: encode hero and continue item links * fix: encode watch tonight item links * fix: encode recommendation and search item links * test: cover ebook scan format set * fix: label ebook search results clearly * fix: make global search prompt media neutral * fix: encode catalog read API ids * fix: encode item API ids * fix: include ebook reader vendor in docker build * fix: make ebook reader build clean * fix: clean ebook embedded descriptions * docs: plan ebook reader shell parity * feat: add ebook reader shell controls * fix: widen ebook scrolled reader flow * fix: remove scrolled reader content width cap * docs: plan ebook reader full parity * feat: persist ebook reader config * feat: add ebook annotations and bookmarks * feat: add ebook reader tools and aids * feat: add ebook advanced reader settings * fix: keep ebook reader panel in viewport * fix: use foliate sizing units for ebook scroll flow * fix: keep ebook settings controls readable * fix: simplify ebook reader settings controls * feat(ebooks): extract local covers during scan (#98) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): add reader profiles and ruler (#99) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * Merge branch 'main' into work/ebooks-reader-base Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(docker): copy foliate-js vendor into Dockerfile.dev frontend stage foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): render Continue Reading sections as upright poster cards All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): stop related-rail highlight ring clipping on detail pages Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): harden ebook scanning against data loss and bad metadata - Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): make enrichment failures non-terminal with dedicated backoff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): gate ebook progress on hidden history and centralize threshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(recommendations): correct watcher counting and wire ebook taste signals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): harden ebook reader endpoints and serve a Content-Security-Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(api): native read-state endpoints for ebooks - POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts progress 1.0 preserving the reader's file/location (or picks the preferred reader file for never-opened books); mark unread mirrors video unwatch semantics and deletes the progress row. - /history/remove accepts ebooks: hides via user_history_hidden_items without touching the reading position (hidden != unread; next reading activity resurfaces the book, mirroring video re-watch). - Access-filter checks match the video branch; shared logic lives in ebook_read_state.go. Sort metrics/user-state thresholds use the shared constant; profile-header fallback deduplicated. Clients: response is {type: "ebook", affected_count: 1, played: bool}; the existing watched SSE event fires. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): harden the ebook reader UI - Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): mark read/unread affordances for ebooks - Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: record the PR #124 review and hardening pass Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
548 lines
15 KiB
TypeScript
548 lines
15 KiB
TypeScript
import type { ApiError, RefreshResponse } from "./types";
|
|
import { storage } from "../utils/storage";
|
|
|
|
type ProfileUnverifiedListener = () => void;
|
|
let profileUnverifiedListener: ProfileUnverifiedListener | null = null;
|
|
|
|
export function onProfileUnverified(listener: ProfileUnverifiedListener | null) {
|
|
profileUnverifiedListener = listener;
|
|
}
|
|
|
|
let accessToken: string | null = null;
|
|
let refreshPromise: Promise<boolean> | null = null;
|
|
|
|
export function setAccessToken(token: string | null) {
|
|
accessToken = token;
|
|
}
|
|
|
|
export function getAccessToken(): string | null {
|
|
return accessToken;
|
|
}
|
|
|
|
function getRefreshToken(): string | null {
|
|
return storage.get(storage.KEYS.REFRESH_TOKEN);
|
|
}
|
|
|
|
export function setRefreshToken(token: string | null) {
|
|
if (token) {
|
|
storage.set(storage.KEYS.REFRESH_TOKEN, token);
|
|
} else {
|
|
storage.remove(storage.KEYS.REFRESH_TOKEN);
|
|
}
|
|
}
|
|
|
|
function getProfileId(): string | null {
|
|
return storage.get(storage.KEYS.PROFILE_ID);
|
|
}
|
|
|
|
export function setProfileId(id: string | null) {
|
|
if (id) {
|
|
storage.set(storage.KEYS.PROFILE_ID, id);
|
|
} else {
|
|
storage.remove(storage.KEYS.PROFILE_ID);
|
|
}
|
|
}
|
|
|
|
let profileToken: string | null = null;
|
|
|
|
export function setProfileToken(token: string | null) {
|
|
profileToken = token;
|
|
if (token) {
|
|
storage.set(storage.KEYS.PROFILE_TOKEN, token);
|
|
try {
|
|
sessionStorage.removeItem(storage.KEYS.PROFILE_TOKEN);
|
|
} catch {
|
|
// Storage unavailable
|
|
}
|
|
} else {
|
|
storage.remove(storage.KEYS.PROFILE_TOKEN);
|
|
try {
|
|
sessionStorage.removeItem(storage.KEYS.PROFILE_TOKEN);
|
|
} catch {
|
|
// Storage unavailable
|
|
}
|
|
}
|
|
}
|
|
|
|
export function getProfileToken(): string | null {
|
|
if (!profileToken) {
|
|
profileToken = storage.get(storage.KEYS.PROFILE_TOKEN);
|
|
}
|
|
if (!profileToken) {
|
|
try {
|
|
profileToken = sessionStorage.getItem(storage.KEYS.PROFILE_TOKEN);
|
|
if (profileToken) {
|
|
storage.set(storage.KEYS.PROFILE_TOKEN, profileToken);
|
|
sessionStorage.removeItem(storage.KEYS.PROFILE_TOKEN);
|
|
}
|
|
} catch {
|
|
// Storage unavailable
|
|
}
|
|
}
|
|
return profileToken;
|
|
}
|
|
|
|
function getOrCreateDeviceId(): string | null {
|
|
const existing = storage.get(storage.KEYS.DEVICE_ID);
|
|
if (existing) {
|
|
return existing;
|
|
}
|
|
|
|
let nextId: string | null = null;
|
|
try {
|
|
nextId =
|
|
typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
|
|
? crypto.randomUUID()
|
|
: `web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
} catch {
|
|
nextId = `web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
if (nextId) {
|
|
storage.set(storage.KEYS.DEVICE_ID, nextId);
|
|
}
|
|
return nextId;
|
|
}
|
|
|
|
function detectDevicePlatform(): string {
|
|
if (typeof navigator === "undefined") {
|
|
return "Web";
|
|
}
|
|
|
|
const userAgent = navigator.userAgent.toLowerCase();
|
|
if (/iphone|ipad|ipod/.test(userAgent)) return "iOS Web";
|
|
if (/android/.test(userAgent)) return "Android Web";
|
|
if (/mac os x|macintosh/.test(userAgent)) return "macOS Web";
|
|
if (/windows/.test(userAgent)) return "Windows Web";
|
|
if (/linux/.test(userAgent)) return "Linux Web";
|
|
return "Web";
|
|
}
|
|
|
|
function detectDeviceName(): string {
|
|
if (typeof navigator === "undefined") {
|
|
return "Web Browser";
|
|
}
|
|
|
|
const platform = detectDevicePlatform().replace(/\s+Web$/, "");
|
|
let browser = "Browser";
|
|
const userAgent = navigator.userAgent;
|
|
|
|
if (/Edg\//.test(userAgent)) browser = "Edge";
|
|
else if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) browser = "Chrome";
|
|
else if (/Firefox\//.test(userAgent)) browser = "Firefox";
|
|
else if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) browser = "Safari";
|
|
|
|
return `${browser} on ${platform}`;
|
|
}
|
|
|
|
function getDeviceHeaders(): Record<string, string> {
|
|
const deviceId = getOrCreateDeviceId();
|
|
if (!deviceId) {
|
|
return {};
|
|
}
|
|
|
|
return {
|
|
"X-Silo-Device-Id": deviceId,
|
|
"X-Silo-Device-Name": detectDeviceName(),
|
|
"X-Silo-Device-Platform": detectDevicePlatform(),
|
|
};
|
|
}
|
|
|
|
async function attemptRefresh(): Promise<boolean> {
|
|
const rt = getRefreshToken();
|
|
if (!rt) return false;
|
|
|
|
try {
|
|
const data = await refreshAccessToken(rt, fetch);
|
|
if (!data) return false;
|
|
setAccessToken(data.access_token);
|
|
setRefreshToken(data.refresh_token);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function bootstrapAccessToken(fetchImpl: typeof fetch = fetch): Promise<boolean> {
|
|
if (accessToken) {
|
|
return true;
|
|
}
|
|
|
|
const rt = getRefreshToken();
|
|
if (!rt) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const data = await refreshAccessToken(rt, fetchImpl);
|
|
if (!data) {
|
|
return false;
|
|
}
|
|
setAccessToken(data.access_token);
|
|
setRefreshToken(data.refresh_token);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function refreshAccessToken(
|
|
refreshToken: string,
|
|
fetchImpl: typeof fetch,
|
|
): Promise<RefreshResponse | null> {
|
|
const res = await fetchImpl("/api/v1/auth/refresh", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ refresh_token: refreshToken }),
|
|
});
|
|
if (!res.ok) {
|
|
return null;
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export class ApiClientError extends Error {
|
|
/**
|
|
* Raw parsed JSON body of the error response, when the body parsed as JSON.
|
|
* Carries fields the normalized `details: ApiError` does not surface (e.g.
|
|
* plugin validation `field_errors` / `form_error` on a 400). Undefined for
|
|
* non-JSON or empty bodies.
|
|
*/
|
|
public body?: unknown;
|
|
|
|
constructor(
|
|
public status: number,
|
|
public code: string,
|
|
message: string,
|
|
public details?: ApiError,
|
|
) {
|
|
super(message);
|
|
this.name = "ApiClientError";
|
|
}
|
|
}
|
|
|
|
function fallbackApiErrorMessage(res: Response): string {
|
|
const statusText = res.statusText.trim();
|
|
if (statusText) {
|
|
return statusText;
|
|
}
|
|
if (res.status === 401) {
|
|
return "Authentication required.";
|
|
}
|
|
if (res.status === 403) {
|
|
return "You do not have permission to perform this action.";
|
|
}
|
|
if (res.status === 404) {
|
|
return "Requested resource was not found.";
|
|
}
|
|
if (res.status >= 500) {
|
|
return "Request failed. Please try again.";
|
|
}
|
|
if (res.status > 0) {
|
|
return `Request failed (${res.status}).`;
|
|
}
|
|
return "Request failed.";
|
|
}
|
|
|
|
function normalizeApiError(apiErr: Partial<ApiError> | null, res: Response): ApiError {
|
|
const payload = apiErr && typeof apiErr === "object" ? apiErr : {};
|
|
const code =
|
|
typeof payload.error === "string" && payload.error.trim() ? payload.error : "unknown";
|
|
const message =
|
|
typeof payload.message === "string" && payload.message.trim()
|
|
? payload.message.trim()
|
|
: fallbackApiErrorMessage(res);
|
|
|
|
return {
|
|
...payload,
|
|
error: code,
|
|
message,
|
|
};
|
|
}
|
|
|
|
function hasHeader(headers: Record<string, string>, name: string): boolean {
|
|
const target = name.toLowerCase();
|
|
return Object.keys(headers).some((key) => key.toLowerCase() === target);
|
|
}
|
|
|
|
interface ParsedApiError {
|
|
/** Normalized error with guaranteed `error`/`message` fields. */
|
|
apiErr: ApiError;
|
|
/** Raw parsed JSON body, or undefined when the body wasn't JSON/empty. */
|
|
raw?: unknown;
|
|
}
|
|
|
|
async function parseApiError(res: Response): Promise<ParsedApiError> {
|
|
let apiErr: Partial<ApiError> = {};
|
|
let raw: unknown;
|
|
try {
|
|
raw = await res.json();
|
|
if (raw && typeof raw === "object") {
|
|
apiErr = raw as Partial<ApiError>;
|
|
}
|
|
} catch {
|
|
// response wasn't JSON
|
|
}
|
|
return { apiErr: normalizeApiError(apiErr, res), raw };
|
|
}
|
|
|
|
/** Builds an ApiClientError from a parsed error response, attaching the raw body. */
|
|
function apiClientErrorFrom(status: number, parsed: ParsedApiError): ApiClientError {
|
|
const err = new ApiClientError(status, parsed.apiErr.error, parsed.apiErr.message, parsed.apiErr);
|
|
err.body = parsed.raw;
|
|
return err;
|
|
}
|
|
|
|
export interface RestoredUserSession<TUser> {
|
|
user: TUser;
|
|
accessToken: string;
|
|
refreshToken: string;
|
|
}
|
|
|
|
export async function restoreUserSession<TUser>({
|
|
accessToken,
|
|
refreshToken,
|
|
fetchImpl = fetch,
|
|
}: {
|
|
accessToken: string;
|
|
refreshToken: string;
|
|
fetchImpl?: typeof fetch;
|
|
}): Promise<RestoredUserSession<TUser>> {
|
|
let restoredAccessToken = accessToken;
|
|
let restoredRefreshToken = refreshToken;
|
|
|
|
const requestUser = (token: string) =>
|
|
fetchImpl("/api/v1/auth/me", {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
let res = await requestUser(restoredAccessToken);
|
|
|
|
if (res.status === 401) {
|
|
const refreshed = await refreshAccessToken(restoredRefreshToken, fetchImpl);
|
|
if (refreshed) {
|
|
restoredAccessToken = refreshed.access_token;
|
|
restoredRefreshToken = refreshed.refresh_token;
|
|
res = await requestUser(restoredAccessToken);
|
|
}
|
|
}
|
|
|
|
if (!res.ok) {
|
|
throw apiClientErrorFrom(res.status, await parseApiError(res));
|
|
}
|
|
|
|
return {
|
|
user: (await res.json()) as TUser,
|
|
accessToken: restoredAccessToken,
|
|
refreshToken: restoredRefreshToken,
|
|
};
|
|
}
|
|
|
|
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
const headers = buildApiHeaders(options);
|
|
|
|
let res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
|
|
// Auto-refresh on 401
|
|
if (res.status === 401 && getRefreshToken()) {
|
|
if (!refreshPromise) {
|
|
refreshPromise = attemptRefresh().finally(() => {
|
|
refreshPromise = null;
|
|
});
|
|
}
|
|
const refreshed = await refreshPromise;
|
|
if (refreshed) {
|
|
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
}
|
|
}
|
|
|
|
if (!res.ok) {
|
|
const parsed = await parseApiError(res);
|
|
if (res.status === 403 && parsed.apiErr.error === "profile_unverified") {
|
|
setProfileToken(null);
|
|
profileUnverifiedListener?.();
|
|
}
|
|
throw apiClientErrorFrom(res.status, parsed);
|
|
}
|
|
|
|
// Handle empty successful responses.
|
|
if (res.status === 204 || res.status === 205) {
|
|
return undefined as T;
|
|
}
|
|
const text = await res.text();
|
|
if (text.trim() === "") {
|
|
return undefined as T;
|
|
}
|
|
return JSON.parse(text) as T;
|
|
}
|
|
|
|
function buildApiHeaders(options: RequestInit = {}): Record<string, string> {
|
|
const headers: Record<string, string> = {
|
|
...(options.headers as Record<string, string>),
|
|
};
|
|
if (!(options.body instanceof FormData) && !hasHeader(headers, "Content-Type")) {
|
|
headers["Content-Type"] = "application/json";
|
|
}
|
|
if (accessToken) {
|
|
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
}
|
|
const profileId = getProfileId();
|
|
if (profileId) {
|
|
headers["X-Profile-Id"] = profileId;
|
|
}
|
|
const profToken = getProfileToken();
|
|
if (profToken) {
|
|
headers["X-Profile-Token"] = profToken;
|
|
}
|
|
Object.assign(headers, getDeviceHeaders());
|
|
return headers;
|
|
}
|
|
|
|
/**
|
|
* Fire-and-forget API request that survives page unload (pagehide / tab close).
|
|
* Sends the same auth, profile, and device headers as `api`, plus `keepalive`
|
|
* so the browser finishes the request after the document is gone. The response
|
|
* is intentionally ignored: no token refresh or error handling is possible
|
|
* while the page is unloading.
|
|
*/
|
|
export function apiKeepalive(path: string, options: RequestInit = {}): void {
|
|
const headers = buildApiHeaders(options);
|
|
void fetch(`/api/v1${path}`, { ...options, headers, keepalive: true }).catch(() => {
|
|
// Best-effort write during unload; nothing left to recover into.
|
|
});
|
|
}
|
|
|
|
/** Downloads a binary API response and triggers a browser file save. */
|
|
export async function apiDownload(
|
|
path: string,
|
|
filename: string,
|
|
options: RequestInit = {},
|
|
): Promise<void> {
|
|
let headers = buildApiHeaders(options);
|
|
let res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
|
|
if (res.status === 401 && getRefreshToken()) {
|
|
if (!refreshPromise) {
|
|
refreshPromise = attemptRefresh().finally(() => {
|
|
refreshPromise = null;
|
|
});
|
|
}
|
|
const refreshed = await refreshPromise;
|
|
if (refreshed) {
|
|
headers = buildApiHeaders(options);
|
|
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
}
|
|
}
|
|
|
|
if (!res.ok) {
|
|
throw apiClientErrorFrom(res.status, await parseApiError(res));
|
|
}
|
|
|
|
const blob = await res.blob();
|
|
const url = URL.createObjectURL(blob);
|
|
const anchor = document.createElement("a");
|
|
anchor.href = url;
|
|
anchor.download = filename;
|
|
anchor.click();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
/**
|
|
* apiBlob buffers the entire response body in memory, so cap what it will
|
|
* accept; beyond this a download is the right tool, not an in-tab blob.
|
|
*/
|
|
export const API_BLOB_MAX_BYTES = 512 * 1024 * 1024;
|
|
|
|
export async function apiBlob(path: string, options: RequestInit = {}): Promise<Blob> {
|
|
let headers = buildApiHeaders(options);
|
|
let res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
|
|
if (res.status === 401 && getRefreshToken()) {
|
|
if (!refreshPromise) {
|
|
refreshPromise = attemptRefresh().finally(() => {
|
|
refreshPromise = null;
|
|
});
|
|
}
|
|
const refreshed = await refreshPromise;
|
|
if (refreshed) {
|
|
headers = buildApiHeaders(options);
|
|
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
res = await fetch(`/api/v1${path}`, { ...options, headers });
|
|
}
|
|
}
|
|
|
|
if (!res.ok) {
|
|
throw apiClientErrorFrom(res.status, await parseApiError(res));
|
|
}
|
|
|
|
// Reject oversized bodies up front instead of crashing the tab while
|
|
// buffering them. When the header is absent, proceed; streaming byte counts
|
|
// are not worth the complexity here.
|
|
const contentLength = Number(res.headers.get("Content-Length"));
|
|
if (Number.isFinite(contentLength) && contentLength > API_BLOB_MAX_BYTES) {
|
|
const sizeMiB = Math.round(contentLength / (1024 * 1024));
|
|
const limitMiB = Math.round(API_BLOB_MAX_BYTES / (1024 * 1024));
|
|
throw new ApiClientError(
|
|
res.status,
|
|
"response_too_large",
|
|
`This file is too large to open in the browser (${sizeMiB} MiB, limit ${limitMiB} MiB). Download it instead.`,
|
|
);
|
|
}
|
|
|
|
return res.blob();
|
|
}
|
|
|
|
// People API
|
|
export async function searchPeople(query: string, limit = 20): Promise<import("./types").Person[]> {
|
|
const params = new URLSearchParams({ q: query, limit: String(limit) });
|
|
return api<import("./types").Person[]>(`/people?${params}`);
|
|
}
|
|
|
|
export async function getPerson(id: string): Promise<import("./types").Person> {
|
|
return api<import("./types").Person>(`/people/${id}`);
|
|
}
|
|
|
|
export async function refreshPerson(
|
|
id: string,
|
|
): Promise<import("./types").PersonRefreshQueuedResponse> {
|
|
return api<import("./types").PersonRefreshQueuedResponse>(`/people/${id}/refresh`, {
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
export async function adminRefreshPerson(id: string): Promise<import("./types").Person> {
|
|
return api<import("./types").Person>(`/admin/people/${id}/refresh`, {
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
export async function adminUpdatePerson(
|
|
id: string,
|
|
data: import("./types").UpdatePersonRequest,
|
|
): Promise<import("./types").Person> {
|
|
return api<import("./types").Person>(`/admin/people/${id}`, {
|
|
method: "PATCH",
|
|
body: JSON.stringify(data),
|
|
});
|
|
}
|
|
|
|
export async function getPersonCatalogItems(
|
|
id: string,
|
|
type?: string,
|
|
limit = 24,
|
|
offset = 0,
|
|
): Promise<import("./types").BrowseResponse> {
|
|
const params = new URLSearchParams({
|
|
source: "person",
|
|
person_id: id,
|
|
limit: String(limit),
|
|
offset: String(offset),
|
|
});
|
|
if (type) params.set("type", type);
|
|
return api<import("./types").BrowseResponse>(`/catalog?${params}`);
|
|
}
|