theater-reader/server/store.mjs
agent 46aa1236ed Let people add plays from photos; library, editor, compose; full-page PDF
- Replace the static nginx site with a small Node server: serves public/,
  stores plays on a /data volume and exposes a JSON API. Writes need a
  shared UPLOAD_PASSWORD; unpublished plays are hidden without it.
- Page photos (shrunk to <=1.15 MP JPEG in the browser) are transcribed
  one request per page by a Claude vision model (claude-haiku-5-5 by
  default, CLAUDE_MODEL to change) into the play markup, then stitched
  together: speaker spellings unified, gaps in page numbers marked as
  missing pages, failed pages flagged. DAILY_PAGE_LIMIT caps spend.
- New pages: library (play menu), add (upload + progress), editor (text
  next to the photos, checks for [?] readings and one-off names, publish,
  delete). The reader loads plays from the API and remembers the chosen
  role per play; old /?postava= links still work.
- PDF export: text now flows across original pages and prints at the
  on-screen size, so A4 sheets are full instead of half empty; page
  numbers in the footer.
- docker-compose.yml + .env.example for one-click deploys; the 1931 play
  moves to seed/ and is copied into an empty volume on first start.
- Tests: parser leniency, transcription assembly, API end to end with a
  stubbed Claude client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-03 09:43:32 +00:00

120 lines
4.4 KiB
JavaScript

// Plays on disk, one directory each under DATA_DIR/plays/<id>/:
// meta.json { id, title, note, published, status, created, updated, images, pages, progress, model }
// play.txt the markup
// img/NNN.jpg the uploaded page photos, in upload order
// Writes go to a temp file and are renamed into place so a crash never leaves half a file.
import { mkdir, readFile, writeFile, rename, readdir, rm, cp, stat } from "node:fs/promises";
import { randomBytes } from "node:crypto";
import path from "node:path";
const ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
export class NotFound extends Error {}
export function slugify(title) {
const base = title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase()
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50) || "hra";
return `${base}-${randomBytes(3).toString("hex")}`;
}
export function createStore(dataDir) {
const root = path.join(dataDir, "plays");
const dir = (id) => {
if (!ID_RE.test(id)) throw new NotFound(id);
return path.join(root, id);
};
async function atomicWrite(file, data) {
const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`;
await writeFile(tmp, data);
await rename(tmp, file);
}
async function getMeta(id) {
try {
return JSON.parse(await readFile(path.join(dir(id), "meta.json"), "utf8"));
} catch (err) {
if (err.code === "ENOENT") throw new NotFound(id);
throw err;
}
}
// Serialise read-modify-write of one play's meta (the transcription job and
// HTTP requests both update it).
const locks = new Map();
function updateMeta(id, fn) {
const run = (locks.get(id) || Promise.resolve()).then(async () => {
const meta = await getMeta(id);
const next = { ...meta, ...(await fn(meta)), updated: new Date().toISOString() };
await atomicWrite(path.join(dir(id), "meta.json"), JSON.stringify(next, null, 2));
return next;
});
locks.set(id, run.catch(() => {}));
return run;
}
return {
root,
async init() { await mkdir(root, { recursive: true }); },
async list() {
const ids = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory() && ID_RE.test(d.name));
const metas = await Promise.all(ids.map((d) => getMeta(d.name).catch(() => null)));
return metas.filter(Boolean).sort((a, b) => a.title.localeCompare(b.title, "cs"));
},
getMeta,
updateMeta,
async create({ title, note = "", id = slugify(title), text = "", published = false, status = "draft" }) {
const d = dir(id);
await mkdir(path.join(d, "img"), { recursive: true });
const now = new Date().toISOString();
const meta = { id, title, note, published, status, created: now, updated: now, images: 0, pages: [], progress: null };
await atomicWrite(path.join(d, "play.txt"), text);
await atomicWrite(path.join(d, "meta.json"), JSON.stringify(meta, null, 2));
return meta;
},
async getText(id) {
try { return await readFile(path.join(dir(id), "play.txt"), "utf8"); }
catch (err) { if (err.code === "ENOENT") throw new NotFound(id); throw err; }
},
async setText(id, text) {
await getMeta(id);
await atomicWrite(path.join(dir(id), "play.txt"), text);
},
imagePath(id, n) {
if (!Number.isInteger(n) || n < 1 || n > 999) throw new NotFound(`${id}/${n}`);
return path.join(dir(id), "img", `${String(n).padStart(3, "0")}.jpg`);
},
async putImage(id, n, buf) { await atomicWrite(this.imagePath(id, n), buf); },
async getImage(id, n) {
try { return await readFile(this.imagePath(id, n)); }
catch (err) { if (err.code === "ENOENT") throw new NotFound(`${id}/${n}`); throw err; }
},
async clearImages(id) {
const d = path.join(dir(id), "img");
await rm(d, { recursive: true, force: true });
await mkdir(d);
},
async remove(id) {
await getMeta(id);
await rm(dir(id), { recursive: true, force: true });
},
// First start with an empty volume: copy in the plays bundled with the image.
async seed(seedDir) {
if ((await readdir(root)).length) return 0;
let n = 0;
for (const d of await readdir(seedDir).catch(() => [])) {
if (!ID_RE.test(d) || !(await stat(path.join(seedDir, d))).isDirectory()) continue;
await cp(path.join(seedDir, d), path.join(root, d), { recursive: true });
n++;
}
return n;
},
};
}