import { mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { compareShelf } from '../shared/shelf.ts'; import { join } from 'node:path'; import { Hono } from 'hono'; import type { Context } from 'hono'; import type { Book, CardData, Hierarchy, SearchResult, Settings } from '../shared/types.ts'; import { normalizeIsbn } from '../shared/isbn.ts'; import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts'; import type { Db, Filter, NewBook } from './db.ts'; import type { Jobs, ResolverLike } from './jobs.ts'; import type { renderCalibrationPdf, renderCardsPdf } from './pdf/render.ts'; import type { classNames } from '../shared/lcc-outline.ts'; export type RenderCardsPdf = typeof renderCardsPdf; export type RenderCalibrationPdf = typeof renderCalibrationPdf; export type ClassNames = typeof classNames; /** The plain-word hierarchy of a call number and the book's stored tail (see hierarchy.ts). */ export type HierarchyOf = (callNumber: string | null, tail: string[] | null) => Hierarchy; export interface EventBus { on(listener: (event: string, data: unknown) => void): () => void; emitBook(book: Book): void; emitDeleted(id: number): void; listenerCount(): number; } export function createEventBus(): EventBus { const listeners = new Set<(event: string, data: unknown) => void>(); const emit = (event: string, data: unknown) => { for (const l of [...listeners]) l(event, data); }; return { on(l) { listeners.add(l); return () => { listeners.delete(l); }; }, emitBook: (book) => emit('book', book), emitDeleted: (id) => emit('deleted', { id }), listenerCount: () => listeners.size, }; } export interface AppDeps { /** The port the page is served from; the only Origin (on localhost / 127.0.0.1) allowed to change state. */ port?: number; db: Db; jobs: Jobs; resolver: ResolverLike; renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf; classNames: ClassNames; /** Defaults to the main class and subclass names alone (no outline ranges, no tail). */ hierarchy?: HierarchyOf; events?: EventBus; /** Where pictures the scanner failed to read are kept for tuning (the newest 30). */ capturesDir?: string; } class HttpError extends Error { status: 400 | 404; constructor(status: 400 | 404, message: string) { super(message); this.status = status; } } const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null); const strList = (v: unknown): string[] | null => Array.isArray(v) && v.every((x) => typeof x === 'string') ? v.map((x) => x.trim()).filter(Boolean) : null; const yearOf = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : null); // A typed call number is kept as typed when it does not parse; it sorts last and is flagged. function callNumberFields(raw: string): Partial { const cn = parseCallNumber(raw); if (cn) { return { callNumber: formatCallNumber(cn), sortKey: sortKeyOfRaw(raw), status: 'resolved', attentionReason: null, manualOverride: true, confidence: 'manual', source: 'manual' }; } return { callNumber: raw, sortKey: sortKeyOfRaw(raw), status: 'needs_attention', attentionReason: 'Call number not recognised', manualOverride: true, confidence: 'manual', source: 'manual' }; } function cacheKeys(book: Book): string[] { const keys: string[] = []; if (book.isbn13) keys.push(`ol-data:${book.isbn13}`, `ol-search:${book.isbn13}`, `loc-isbn:${book.isbn13}`); if (book.lccn) keys.push(`loc-lccn:${book.lccn}`); return keys; } export function createApp(deps: AppDeps): Hono { const { db, jobs, resolver, classNames } = deps; const hierarchyOf: HierarchyOf = deps.hierarchy ?? ((callNumber) => { const cn = callNumber ? parseCallNumber(callNumber) : null; const names = classNames(cn?.letters ?? ''); return { outline: [names.className, names.subclassName].filter((x): x is string => !!x), tail: [] }; }); const events = deps.events ?? createEventBus(); const app = new Hono(); app.onError((err, c) => { if (err instanceof HttpError) return c.json({ error: err.message }, err.status); console.error(err); return c.json({ error: 'Internal error' }, 500); }); // A web page on another origin must not be able to drive this local app. Requests without an // Origin header (curl, tests, same-origin GET-like navigations) are not browser cross-site requests. app.use('*', async (c, next) => { const method = c.req.method; const origin = c.req.header('origin'); if (origin !== undefined && (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE')) { const port = deps.port ?? (new URL(c.req.url).port || '80'); if (origin !== `http://localhost:${port}` && origin !== `http://127.0.0.1:${port}`) { return c.json({ error: 'Cross-origin request refused' }, 403); } } await next(); }); async function body(c: Context): Promise> { try { const v = await c.req.json(); if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record; } catch { /* fall through */ } throw new HttpError(400, 'Invalid JSON body'); } function bookParam(c: Context): Book { const id = Number(c.req.param('id')); const book = Number.isInteger(id) ? db.getBook(id) : null; if (!book) throw new HttpError(404, 'Book not found'); return book; } function addPending(fields: NewBook): { book: Book; created: boolean } { const r = db.insertPending({ inQueue: true, ...fields }); if (r.created) { events.emitBook(r.book); if (r.book.status === 'pending') jobs.enqueue(r.book.id); } return r; } let captureSeq = 0; const MAX_CAPTURE_BYTES = 8 * 1024 * 1024, KEEP_CAPTURES = 30; app.post('/api/debug/capture', async (c) => { const dir = deps.capturesDir; if (!dir) throw new HttpError(404, 'Saving captures is not set up'); const declared = Number(c.req.header('content-length') ?? 0); if (declared > MAX_CAPTURE_BYTES) return c.json({ error: 'Picture too large' }, 413); const bytes = new Uint8Array(await c.req.arrayBuffer()); if (bytes.length > MAX_CAPTURE_BYTES) return c.json({ error: 'Picture too large' }, 413); const isPng = bytes.length > 8 && [0x89, 0x50, 0x4e, 0x47].every((v, i) => bytes[i] === v); if (!isPng) throw new HttpError(400, 'Expected a PNG picture'); mkdirSync(dir, { recursive: true }); const saved = `capture-${new Date().toISOString().replace(/[:.]/g, '-')}-${String(captureSeq++ % 10000).padStart(4, '0')}.png`; writeFileSync(join(dir, saved), bytes); const old = readdirSync(dir).filter((f) => /^capture-.*\.png$/.test(f)).sort().reverse().slice(KEEP_CAPTURES); for (const f of old) { try { unlinkSync(join(dir, f)); } catch { /* already gone */ } } return c.json({ saved }); }); app.post('/api/scan', async (c) => { const b = await body(c); const isbn = typeof b.isbn === 'string' ? normalizeIsbn(b.isbn) : null; if (!isbn) throw new HttpError(400, 'Not a valid ISBN'); const { book, created } = addPending({ isbn13: isbn, title: isbn }); return c.json({ book, duplicate: !created }); }); app.post('/api/books/lccn', async (c) => { const lccn = str((await body(c)).lccn)?.replace(/\s+/g, ''); if (!lccn) throw new HttpError(400, 'LCCN is required'); return c.json({ book: addPending({ lccn, title: lccn }).book }); }); app.get('/api/search', async (c) => { const title = c.req.query('title')?.trim() ?? ''; const author = c.req.query('author')?.trim() ?? ''; if (!title && !author) throw new HttpError(400, 'Enter a title or an author'); const results: SearchResult[] = await resolver.search(title, author); return c.json(results); }); app.post('/api/books/from-search', async (c) => { const r = (await body(c)).result as Record | undefined; const title = r && str(r.title); if (!r || !title) throw new HttpError(400, 'A search result is required'); const { book } = addPending({ title, authors: strList(r.authors) ?? [], year: yearOf(r.year), publisher: str(r.publisher), // (The result's LCCN is a work-level one: it may belong to another edition, so it is not saved.) }); return c.json({ book }); }); app.post('/api/books/manual', async (c) => { const b = await body(c); const title = str(b.title); if (!title) throw new HttpError(400, 'Title is required'); const fields: NewBook = { title, authors: strList(b.authors) ?? [], year: yearOf(b.year), publisher: str(b.publisher), }; const callNumber = str(b.callNumber); if (callNumber) Object.assign(fields, callNumberFields(callNumber)); return c.json({ book: addPending(fields).book }); }); app.get('/api/books/:id/hierarchy', (c) => { const book = db.getBook(Number(c.req.param('id'))); if (!book) throw new HttpError(404, 'No such book'); return c.json(hierarchyOf(book.callNumber, book.hierarchyTail)); }); app.get('/api/books', (c) => { const f = c.req.query('filter'); const filter: Filter = f === 'queue' || f === 'attention' ? f : 'all'; return c.json(db.listBooks({ filter, q: c.req.query('q') })); }); app.patch('/api/books/:id', async (c) => { const cur = bookParam(c); const b = await body(c); const patch: Partial = {}; if ('title' in b) { const t = str(b.title); if (!t) throw new HttpError(400, 'Title cannot be empty'); patch.title = t; } if ('authors' in b) { const a = strList(b.authors); if (!a) throw new HttpError(400, 'Authors must be a list of names'); patch.authors = a; } if ('publisher' in b) patch.publisher = b.publisher === null ? null : str(b.publisher); if ('year' in b) { if (b.year !== null && yearOf(b.year) === null) throw new HttpError(400, 'Year must be a number'); patch.year = b.year === null ? null : yearOf(b.year); } if ('callNumber' in b) { const cn = str(b.callNumber); if (!cn) throw new HttpError(400, 'Call number cannot be empty'); Object.assign(patch, callNumberFields(cn)); } const updated = db.updateBook(cur.id, patch)!; events.emitBook(updated); return c.json({ book: updated }); }); app.delete('/api/books/:id', (c) => { const book = bookParam(c); db.deleteBook(book.id); events.emitDeleted(book.id); return c.json({ ok: true }); }); app.post('/api/books/:id/queue', (c) => { const book = bookParam(c); const updated = db.updateBook(book.id, { inQueue: true })!; events.emitBook(updated); return c.json({ book: updated }); }); app.post('/api/books/:id/retry', (c) => { const book = bookParam(c); if (book.manualOverride) throw new HttpError(400, 'This call number was entered by hand, so there is nothing to look up'); // "Look up again" must really ask again, so forget what the sources told us for this book. for (const key of cacheKeys(book)) db.cache.delete(key); if (book.title) db.cache.deletePrefix(`loc-title:${book.title}|`); // The title search and the similar-books searches are keyed by words as the lookup saw them (not necessarily // as stored now), so the lookup itself is told to ignore its cache and write fresh answers. const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!; events.emitBook(updated); jobs.enqueue(book.id, { fresh: true }); return c.json({ book: updated }); }); app.get('/api/print.pdf', async (c) => { const s = Number(c.req.query('start') ?? '1'); const startPosition = (s === 2 || s === 3 ? s : 1) as 1 | 2 | 3; const books = db.listBooks({ filter: 'queue' }) .filter((b) => b.status === 'resolved' && b.callNumber) .sort(compareShelf); if (!books.length) throw new HttpError(400, 'Nothing to print'); const cards: CardData[] = books.map((b) => { return { callNumber: b.callNumber!, hierarchy: hierarchyOf(b.callNumber, b.hierarchyTail), title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: b.authors, publisher: b.publisher, year: b.year, subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate', }; }); const pdf = await deps.renderCardsPdf(cards, { ...db.getSettings(), startPosition }); return new Response(pdf as BodyInit, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="booksorter-cards.pdf"', 'X-Book-Ids': books.map((b) => b.id).join(','), }, }); }); app.post('/api/print/confirm', async (c) => { const ids = (await body(c)).ids; if (!Array.isArray(ids) || !ids.every((i) => Number.isInteger(i))) throw new HttpError(400, 'ids must be a list of book ids'); const now = new Date().toISOString(); for (const id of ids as number[]) { const b = db.updateBook(id, { printedAt: now, inQueue: false }); if (b) events.emitBook(b); } return c.json({ ok: true }); }); app.get('/api/calibration.pdf', async (c) => { const pdf = await deps.renderCalibrationPdf(db.getSettings()); return new Response(pdf as BodyInit, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="booksorter-calibration.pdf"' }, }); }); app.get('/api/settings', (c) => c.json(db.getSettings())); app.put('/api/settings', async (c) => { const b = await body(c); const clamp = (v: unknown): number => { if (typeof v !== 'number' || !Number.isFinite(v)) throw new HttpError(400, 'Offsets must be numbers'); return Math.max(-10, Math.min(10, v)); }; const s: Settings = { offsetXmm: clamp(b.offsetXmm), offsetYmm: clamp(b.offsetYmm) }; db.putSettings(s); return c.json(s); }); app.get('/api/events', (c) => { const enc = new TextEncoder(); let off: (() => void) | null = null; let heartbeat: ReturnType | null = null; const cleanup = () => { off?.(); off = null; if (heartbeat) clearInterval(heartbeat); heartbeat = null; }; const stream = new ReadableStream({ start(controller) { const send = (text: string) => { try { controller.enqueue(enc.encode(text)); } catch { cleanup(); } }; send(': connected\n\n'); off = events.on((event, data) => send(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); heartbeat = setInterval(() => send(': ping\n\n'), 25000); heartbeat.unref(); c.req.raw.signal.addEventListener('abort', () => { cleanup(); try { controller.close(); } catch { /* already closed */ } }, { once: true }); }, cancel: cleanup, }); return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, }); }); return app; }