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
This commit is contained in:
agent 2026-11-03 09:43:32 +00:00
parent 2608d10dd2
commit 46aa1236ed
32 changed files with 1761 additions and 160 deletions

287
server/main.mjs Normal file
View file

@ -0,0 +1,287 @@
// Theater reader server: serves the app from public/ and a small JSON API for
// plays stored on a volume. Uploading and editing need UPLOAD_PASSWORD;
// transcription additionally needs ANTHROPIC_API_KEY.
import http from "node:http";
import { readFile, writeFile, stat } from "node:fs/promises";
import { createHash, timingSafeEqual } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createStore, NotFound } from "./store.mjs";
import { DEFAULT_MODEL, makeClient, transcribePage, describeError, splitPage, assemble } from "./transcribe.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const env = process.env;
export const config = {
port: Number(env.PORT || 8080),
dataDir: env.DATA_DIR || "/data",
publicDir: path.resolve(here, "../public"),
seedDir: path.resolve(here, "../seed"),
apiKey: env.ANTHROPIC_API_KEY || "",
model: env.CLAUDE_MODEL || DEFAULT_MODEL,
password: env.UPLOAD_PASSWORD || "",
dailyPageLimit: Number(env.DAILY_PAGE_LIMIT || 300),
maxPages: Number(env.MAX_PAGES || 80),
maxImageBytes: 8 * 1024 * 1024,
maxTextBytes: 2 * 1024 * 1024,
concurrency: 3,
};
const MIME = {
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".woff2": "font/woff2",
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
};
const SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; frame-ancestors 'none'",
};
class HttpError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
function send(res, status, body, type = "application/json; charset=utf-8", extra = {}) {
const data = typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body);
res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-cache", ...SECURITY_HEADERS, ...extra });
res.end(data);
}
async function readBody(req, limit) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw new HttpError(413, "Soubor je příliš velký.");
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function readJson(req) {
try { return JSON.parse((await readBody(req, 64 * 1024)).toString("utf8") || "{}"); }
catch (err) { if (err instanceof HttpError) throw err; throw new HttpError(400, "Neplatný JSON."); }
}
const digest = (s) => createHash("sha256").update(String(s)).digest();
function isAuthed(req) {
const given = req.headers["x-upload-password"];
return Boolean(config.password && given && timingSafeEqual(digest(given), digest(config.password)));
}
async function requireAuth(req) {
if (!config.password) throw new HttpError(403, "Nahrávání je vypnuté: na serveru není nastavené UPLOAD_PASSWORD.");
if (!isAuthed(req)) {
await new Promise((r) => setTimeout(r, 1000)); // slow down password guessing
throw new HttpError(401, "Špatné heslo.");
}
}
// ---- usage cap: pages transcribed per UTC day, so a leaked password can't run up a big bill
async function takePages(n) {
const file = path.join(config.dataDir, "usage.json");
const day = new Date().toISOString().slice(0, 10);
let usage = {};
try { usage = JSON.parse(await readFile(file, "utf8")); } catch { /* first use */ }
const used = usage.day === day ? usage.pages : 0;
if (used + n > config.dailyPageLimit)
throw new HttpError(429, `Denní limit ${config.dailyPageLimit} stran je vyčerpán (dnes už ${used}). Zkuste to zítra.`);
await writeFile(file, JSON.stringify({ day, pages: used + n }));
}
// ---- transcription job (runs in the background; progress lives in meta.json)
const running = new Set();
export async function runJob(store, id, client) {
if (running.has(id)) return;
running.add(id);
try {
const meta = await store.getMeta(id);
const results = meta.pages.slice(0, meta.images);
const todo = [];
for (let i = 0; i < meta.images; i++) if (!results[i] || results[i].error) todo.push(i);
let done = meta.images - todo.length;
await store.updateMeta(id, () => ({ status: "processing", progress: { done, total: meta.images } }));
const worker = async () => {
while (todo.length) {
const i = todo.shift();
let result;
try {
const { text } = await transcribePage(client, config.model, await store.getImage(id, i + 1));
result = splitPage(text);
} catch (err) {
console.error(`[${id}] page ${i + 1}: ${describeError(err)}`);
result = { num: "?", error: describeError(err) };
}
results[i] = result;
done++;
await store.updateMeta(id, (m) => {
const pages = m.pages.slice();
pages[i] = result;
return { pages, progress: { done, total: meta.images } };
});
}
};
await Promise.all(Array.from({ length: config.concurrency }, worker));
const failed = results.filter((r) => r.error).length;
await store.setText(id, assemble(results));
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: config.model }));
} catch (err) {
console.error(`[${id}] job failed:`, err);
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: describeError(err) })).catch(() => {});
} finally {
running.delete(id);
}
}
// ---- API
const publicMeta = ({ pages, ...m }) => ({ ...m, failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])) });
async function api(req, res, store, client, parts) {
const method = req.method;
const [, , id, sub, n] = parts; // ["", "plays", id, sub, n]
if (parts[1] === "config" && method === "GET")
return send(res, 200, { uploads: Boolean(config.password), transcription: Boolean(config.apiKey), model: config.model, maxPages: config.maxPages });
if (parts[1] === "login" && method === "POST") { await requireAuth(req); return send(res, 200, { ok: true }); }
if (parts[1] !== "plays") throw new HttpError(404, "Nenalezeno.");
if (!id) {
if (method === "GET") {
const authed = isAuthed(req);
const plays = (await store.list()).filter((p) => p.published || authed).map(publicMeta);
return send(res, 200, plays);
}
if (method === "POST") {
await requireAuth(req);
const { title, note } = await readJson(req);
if (typeof title !== "string" || !title.trim()) throw new HttpError(400, "Chybí název hry.");
const meta = await store.create({ title: title.trim().slice(0, 200), note: String(note || "").trim().slice(0, 500) });
return send(res, 201, publicMeta(meta));
}
throw new HttpError(405, "Metoda není povolena.");
}
const meta = await store.getMeta(id);
// Unpublished plays are visible only with the password.
if (!meta.published && !isAuthed(req)) throw new NotFound(id);
if (!sub) {
if (method === "GET") return send(res, 200, publicMeta(meta));
if (method === "PATCH") {
await requireAuth(req);
const body = await readJson(req);
const patch = {};
if (typeof body.title === "string" && body.title.trim()) patch.title = body.title.trim().slice(0, 200);
if (typeof body.note === "string") patch.note = body.note.trim().slice(0, 500);
if (typeof body.published === "boolean") patch.published = body.published;
return send(res, 200, publicMeta(await store.updateMeta(id, () => patch)));
}
if (method === "DELETE") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
await store.remove(id);
return send(res, 200, { ok: true });
}
}
if (sub === "text") {
if (method === "GET") return send(res, 200, await store.getText(id), MIME[".txt"]);
if (method === "PUT") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
const text = (await readBody(req, config.maxTextBytes)).toString("utf8");
await store.setText(id, text);
return send(res, 200, publicMeta(await store.updateMeta(id, () => ({ edited: true }))));
}
}
if (sub === "images" && n) {
const num = Number(n);
if (method === "GET") return send(res, 200, await store.getImage(id, num), "image/jpeg", { "Cache-Control": "private, max-age=3600" });
if (method === "PUT") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje.");
if (!Number.isInteger(num) || num < 1 || num > config.maxPages) throw new HttpError(400, `Nejvýše ${config.maxPages} stran.`);
if (!/^image\/jpeg\b/.test(req.headers["content-type"] || "")) throw new HttpError(415, "Očekávám JPEG.");
const buf = await readBody(req, config.maxImageBytes);
if (buf[0] !== 0xff || buf[1] !== 0xd8) throw new HttpError(415, "Soubor není JPEG.");
await store.putImage(id, num, buf);
return send(res, 200, publicMeta(await store.updateMeta(id, (m) => {
const pages = m.pages.slice();
pages[num - 1] = null; // a replaced photo gets transcribed again
return { images: Math.max(m.images, num), pages };
})));
}
}
if (sub === "transcribe" && method === "POST") {
await requireAuth(req);
if (!config.apiKey) throw new HttpError(503, "Přepis není nastavený: na serveru chybí ANTHROPIC_API_KEY.");
if (running.has(id)) throw new HttpError(409, "Přepis už běží.");
if (!meta.images) throw new HttpError(400, "Nejdřív nahrajte fotky stran.");
if (meta.edited) throw new HttpError(409, "Text už byl ručně upraven; nový přepis by úpravy přepsal.");
const pending = Array.from({ length: meta.images }, (_, i) => meta.pages[i]).filter((p) => !p || p.error).length;
if (!pending) throw new HttpError(400, "Všechny strany už jsou přepsané.");
await takePages(pending);
const next = await store.updateMeta(id, () => ({ status: "processing", progress: { done: meta.images - pending, total: meta.images }, jobError: null }));
runJob(store, id, client);
return send(res, 202, publicMeta(next));
}
throw new HttpError(405, "Metoda není povolena.");
}
// ---- static files
async function serveStatic(req, res, pathname) {
if (req.method !== "GET" && req.method !== "HEAD") throw new HttpError(405, "Metoda není povolena.");
const rel = pathname === "/" ? "index.html" : decodeURIComponent(pathname).replace(/^\/+/, "");
const file = path.resolve(config.publicDir, rel);
if (!file.startsWith(config.publicDir + path.sep)) throw new HttpError(404, "Nenalezeno.");
let info;
try { info = await stat(file); } catch { throw new HttpError(404, "Nenalezeno."); }
if (!info.isFile()) throw new HttpError(404, "Nenalezeno.");
const ext = path.extname(file);
const cache = rel.startsWith("fonts/") ? "public, max-age=2592000" : "no-cache";
res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream", "Content-Length": info.size, "Cache-Control": cache, ...SECURITY_HEADERS });
if (req.method === "HEAD") return res.end();
res.end(await readFile(file));
}
export function createServer(store, client) {
return http.createServer(async (req, res) => {
const { pathname } = new URL(req.url, "http://localhost");
try {
if (pathname === "/healthz") return send(res, 200, "ok", MIME[".txt"]);
if (pathname.startsWith("/api/")) return await api(req, res, store, client, pathname.slice(4).split("/"));
return await serveStatic(req, res, pathname);
} catch (err) {
if (err instanceof NotFound) return send(res, 404, { error: "Nenalezeno." });
if (err instanceof HttpError) return send(res, err.status, { error: err.message });
console.error(`${req.method} ${pathname}:`, err);
if (!res.headersSent) send(res, 500, { error: "Chyba serveru." });
}
});
}
async function main() {
const store = createStore(config.dataDir);
await store.init();
const seeded = await store.seed(config.seedDir);
if (seeded) console.log(`seeded ${seeded} play(s) into ${store.root}`);
const client = config.apiKey ? makeClient(config.apiKey) : null;
// Resume transcriptions interrupted by a restart.
for (const meta of await store.list())
if (meta.status === "processing") {
if (client) runJob(store, meta.id, client);
else await store.updateMeta(meta.id, () => ({ status: "draft", progress: null, jobError: "přepis přerušen" }));
}
createServer(store, client).listen(config.port, () => {
console.log(`theater-reader on :${config.port} (data ${config.dataDir}; uploads ${config.password ? "on" : "off"}; transcription ${client ? config.model : "off"})`);
});
}
if (process.argv[1] === fileURLToPath(import.meta.url)) main();