Print events with a QR code to events.photoreport.pt/e/<slug>; 300 dpi prints with the event's band and border; approval and limits; live queue in the app; apps/print-agent pairs with a one-time code, reports CUPS printers, claims jobs for loaded paper and prints with lp. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
120 lines
4.6 KiB
TypeScript
120 lines
4.6 KiB
TypeScript
import type { ClaimedJob } from "@photoreport/contracts";
|
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import type { PrintProvider } from "./providers.js";
|
|
|
|
export interface AgentOptions {
|
|
api: string;
|
|
token: string;
|
|
provider: PrintProvider;
|
|
version: string;
|
|
fetchImpl?: typeof fetch;
|
|
log?: (msg: string) => void;
|
|
heartbeatMs?: number;
|
|
idleMs?: number;
|
|
}
|
|
|
|
export class AgentError extends Error {
|
|
constructor(
|
|
message: string,
|
|
readonly status: number,
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The loop next to the printers: tell the server which printers are here (every 15 s), take the next job for one
|
|
* of them, print it, report back. One job at a time per station keeps dye-sub printers from fighting over paper.
|
|
*/
|
|
export class PrintAgent {
|
|
private stopped = false;
|
|
private readonly fetch: typeof fetch;
|
|
private readonly log: (msg: string) => void;
|
|
|
|
constructor(private readonly opts: AgentOptions) {
|
|
this.fetch = opts.fetchImpl ?? fetch;
|
|
this.log = opts.log ?? (() => {});
|
|
}
|
|
|
|
private async call<T>(method: string, url: string, body?: unknown): Promise<T> {
|
|
const res = await this.fetch(`${this.opts.api}${url}`, {
|
|
method,
|
|
headers: { authorization: `Bearer ${this.opts.token}`, ...(body !== undefined && { "content-type": "application/json" }) },
|
|
...(body !== undefined && { body: JSON.stringify(body) }),
|
|
signal: AbortSignal.timeout(30_000),
|
|
});
|
|
if (!res.ok) throw new AgentError(`${method} ${url}: ${res.status}`, res.status);
|
|
return (await res.json()) as T;
|
|
}
|
|
|
|
async heartbeat(): Promise<void> {
|
|
const printers = await this.opts.provider.list();
|
|
await this.call("POST", "/v1/print/agent/heartbeat", { agentVersion: this.opts.version, printers });
|
|
}
|
|
|
|
/** Claims and prints one job. Returns false when there was nothing to do. */
|
|
async once(): Promise<boolean> {
|
|
const { job } = await this.call<{ job: ClaimedJob | null }>("POST", "/v1/print/agent/claim");
|
|
if (!job) return false;
|
|
const dir = await mkdtemp(path.join(tmpdir(), "pr-print-"));
|
|
try {
|
|
const res = await this.fetch(`${this.opts.api}${job.file}`, { headers: { authorization: `Bearer ${this.opts.token}` }, signal: AbortSignal.timeout(60_000) });
|
|
if (!res.ok) throw new Error(`download ${res.status}`);
|
|
const file = path.join(dir, `${job.id}.jpg`);
|
|
await writeFile(file, Buffer.from(await res.arrayBuffer()));
|
|
await this.opts.provider.print(job.printer, file, { size: job.size, copies: job.copies });
|
|
await this.call("POST", `/v1/print/agent/jobs/${job.id}/result`, { ok: true });
|
|
this.log(`printed ${job.id} on ${job.printer} (${job.size} x${job.copies})`);
|
|
} catch (err) {
|
|
const error = err instanceof Error ? err.message : String(err);
|
|
this.log(`job ${job.id} failed: ${error}`);
|
|
await this.call("POST", `/v1/print/agent/jobs/${job.id}/result`, { ok: false, error }).catch(() => {});
|
|
} finally {
|
|
await rm(dir, { recursive: true, force: true });
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async run(): Promise<void> {
|
|
const heartbeatMs = this.opts.heartbeatMs ?? 15_000;
|
|
const idleMs = this.opts.idleMs ?? 2_000;
|
|
let lastBeat = 0;
|
|
let backoff = idleMs;
|
|
while (!this.stopped) {
|
|
try {
|
|
if (Date.now() - lastBeat > heartbeatMs) {
|
|
await this.heartbeat();
|
|
lastBeat = Date.now();
|
|
}
|
|
const worked = await this.once();
|
|
backoff = idleMs;
|
|
if (!worked) await sleep(idleMs);
|
|
} catch (err) {
|
|
if (err instanceof AgentError && err.status === 401) {
|
|
this.log("the server no longer knows this station: pair it again");
|
|
throw err;
|
|
}
|
|
this.log(`server unreachable (${err instanceof Error ? err.message : err}); retrying`);
|
|
await sleep(backoff);
|
|
backoff = Math.min(backoff * 2, 60_000);
|
|
}
|
|
}
|
|
}
|
|
|
|
stop(): void {
|
|
this.stopped = true;
|
|
}
|
|
}
|
|
|
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
/** Exchanges a one-time pairing code (shown in the app) for this station's token. */
|
|
export async function pair(api: string, code: string, info: { platform: string; agentVersion: string }, fetchImpl: typeof fetch = fetch): Promise<string> {
|
|
const res = await fetchImpl(`${api}/v1/print/agent/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, ...info }) });
|
|
if (res.status === 401) throw new Error("code inválido ou expirado: gera outro na app (Impressão > Estações)");
|
|
if (!res.ok) throw new Error(`pairing failed (${res.status})`);
|
|
return ((await res.json()) as { token: string }).token;
|
|
}
|