Files
receipt_maker/receipt_web.py
T
adamfandClaude Opus 5.5 597bace442
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s
Send each print as one job, queue web prints, and harden deploys
Render every print to a complete ESC/POS payload (reset, content, cut)
and send it once over a fresh connection. Only the connect is retried,
so a link that drops mid-job can no longer print a partial image followed
by a full one, and no text size leaks into the next job. Prints are
capped at about 1 m of paper: tall images shrink, over-long notes are
refused.

Replace the argparse/stdout plumbing with PrinterConfig, InvalidJob and
PrinterUnavailable, and one run_command() dispatcher shared by the CLI
and TUI. Status now really connects; before, escpos's lazy open meant
the web server always reported the printer ready. Rendering with the
TM-T20II profile makes QR centering take effect.

The web server validates and renders jobs in the request (400 on bad
input), queues them for a single worker and answers 202; the page
long-polls /api/jobs/{id}, so no request outlives nginx's proxy timeout
while its job still prints. Status reports busy instead of waiting, and
jobs are logged with the nginx user.

update.sh tests new commits in a scratch worktree before touching the
live clone, and rolls back if /healthz doesn't answer after the restart.
The unit runs from the venv, and the web server defaults to localhost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:07:58 +01:00

454 lines
17 KiB
Python

"""Web server for printing from the website; launched via `./receipt.py serve`.
Runs on the machine the printer is cabled to. nginx on the web host gates
/receipt/ on the site's admin session (auth_request), strips the prefix and
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
without that token, so reaching this port directly is not enough.
Jobs are rendered and validated in the request (bad input is a 400 at once),
then queued: POST answers 202 with a job id and the page long-polls
/api/jobs/{id}, so no request waits behind another print long enough for
nginx's proxy timeout to report a failure while the job still prints.
Uploads are printed from memory and never written to disk.
"""
from __future__ import annotations
import argparse
import hmac
import io
import logging
import os
import queue
import secrets
import sys
import threading
from collections import OrderedDict
from dataclasses import dataclass
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Query, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
import receipt
TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret
MIN_TOKEN_CHARS = 16
MAX_NOTE_CHARS = 4000
MAX_CAPTION_CHARS = 500
MAX_QUEUED = 10 # jobs waiting for the printer; more is a 503
MAX_JOB_HISTORY = 50 # finished jobs kept for polling
MAX_WAIT_SECONDS = 25 # long-poll cap, well under nginx's 90 s proxy_read_timeout
# Sent by the page's fetch(). A cross-site form can't set it, and a cross-site
# fetch that sets it needs a CORS preflight, which nginx's auth gate refuses.
CSRF_HEADER_VALUE = "receipt"
FINISHED = ("done", "failed")
log = logging.getLogger("receipt_web")
class Note(BaseModel):
text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS)
timestamp: bool = False
size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES))
@dataclass
class Job:
id: str
kind: str
user: str | None
state: str = "queued" # queued -> printing -> done | failed
message: str = ""
error: str | None = None # "unavailable" or "failed" when state is failed
def public(self) -> dict:
return {k: getattr(self, k) for k in ("id", "kind", "state", "message", "error")}
class PrintQueue:
"""Rendered jobs waiting for the printer, sent one at a time by a worker thread.
The printer takes a single connection, so the worker holds printer_lock
for each send; the status check only tries the lock, so it never waits
behind a long print.
"""
def __init__(self, config: receipt.PrinterConfig):
self.config = config
self.printer_lock = threading.Lock()
self._changed = threading.Condition()
self._jobs: OrderedDict[str, Job] = OrderedDict()
self._pending: queue.Queue[tuple[Job, bytes]] = queue.Queue(MAX_QUEUED)
threading.Thread(target=self._work, name="print-worker", daemon=True).start()
@property
def queued(self) -> int:
return self._pending.qsize()
def submit(self, kind: str, payload: bytes, user: str | None) -> Job:
job = Job(secrets.token_hex(8), kind, user)
try:
self._pending.put_nowait((job, payload))
except queue.Full:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
with self._changed:
self._jobs[job.id] = job
while len(self._jobs) > MAX_JOB_HISTORY:
self._jobs.popitem(last=False)
log.info("job %s: %s queued by %s", job.id, kind, user or "unknown")
return job
def wait(self, job_id: str, timeout: float) -> Job | None:
"""The job, once finished or after timeout seconds; None if unknown."""
with self._changed:
job = self._jobs.get(job_id)
if job is not None:
self._changed.wait_for(lambda: job.state in FINISHED, timeout)
return job
def _update(self, job: Job, state: str, message: str = "", error: str | None = None) -> None:
with self._changed:
job.state, job.message, job.error = state, message, error
self._changed.notify_all()
def _work(self) -> None:
while True:
job, payload = self._pending.get()
self._update(job, "printing")
with self.printer_lock:
try:
receipt.send(self.config, payload)
except receipt.PrinterUnavailable as e:
self._update(job, "failed", f"Printer unavailable: {e}", "unavailable")
except Exception as e:
log.exception("job %s failed", job.id)
self._update(job, "failed", f"Error: {e}", "failed")
else:
self._update(job, "done", "Printed.")
log.info("job %s: %s %s", job.id, job.state, job.message)
def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
jobs = PrintQueue(config)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.state.jobs = jobs
def require_token(x_receipt_token: str | None = Header(default=None)) -> None:
if x_receipt_token is None or not hmac.compare_digest(
x_receipt_token.encode(), token.encode()
):
raise HTTPException(401, "Missing or invalid token.")
def require_page_request(x_requested_with: str | None = Header(default=None)) -> None:
if x_requested_with != CSRF_HEADER_VALUE:
raise HTTPException(403, "Requests must come from the receipt page.")
def render(build, *args) -> bytes:
try:
return build(*args)
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
def accepted(job: Job) -> JSONResponse:
return JSONResponse({"ok": True, "job": job.public()}, status_code=202)
authed = [Depends(require_token)]
posting = [Depends(require_token), Depends(require_page_request)]
@app.get("/healthz")
def healthz() -> dict:
return {"ok": True}
@app.get("/", response_class=HTMLResponse, dependencies=authed)
def page() -> str:
return PAGE
@app.get("/api/status", dependencies=authed)
def status() -> JSONResponse:
if jobs.queued or not jobs.printer_lock.acquire(blocking=False):
busy = f"Printing ({jobs.queued} more queued)."
return JSONResponse({"ok": True, "busy": True, "output": busy})
try:
receipt.close_quietly(receipt.connect(config))
except receipt.PrinterUnavailable as e:
body = {"ok": False, "output": f"Printer unavailable: {e}"}
return JSONResponse(body, status_code=503)
finally:
jobs.printer_lock.release()
reachable = f"Printer reachable ({config.target})."
return JSONResponse({"ok": True, "busy": False, "output": reachable})
@app.get("/api/jobs/{job_id}", dependencies=authed)
def job_status(
job_id: str, wait: float = Query(default=0, ge=0, le=MAX_WAIT_SECONDS)
) -> dict:
job = jobs.wait(job_id, wait)
if job is None:
raise HTTPException(404, "No such job (the server may have restarted).")
return {"ok": True, "job": job.public()}
@app.post("/api/note", dependencies=posting)
def note(body: Note, x_remote_user: str | None = Header(default=None)) -> JSONResponse:
payload = render(receipt.render_note, body.text, body.timestamp, body.size)
return accepted(jobs.submit("note", payload, x_remote_user or None))
@app.post("/api/image", dependencies=posting)
def image(
file: UploadFile = File(...), # noqa: B008 - FastAPI's declaration idiom
message: str = Form(default="", max_length=MAX_CAPTION_CHARS),
x_remote_user: str | None = Header(default=None),
) -> JSONResponse:
data = file.file.read(receipt.MAX_IMAGE_BYTES + 1)
if len(data) > receipt.MAX_IMAGE_BYTES:
raise HTTPException(
413, f"Image exceeds the {receipt.MAX_IMAGE_BYTES // 1024 // 1024} MB cap."
)
payload = render(receipt.render_image, io.BytesIO(data), message.strip() or None)
return accepted(jobs.submit("image", payload, x_remote_user or None))
return app
def serve(args: argparse.Namespace) -> int:
import uvicorn
token = os.environ.get(TOKEN_ENV, "")
if len(token) < MIN_TOKEN_CHARS:
print(
f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters "
"(e.g. `openssl rand -hex 32`); nginx on the web host sends the same value.",
file=sys.stderr,
)
return 1
host, sep, port = args.listen.rpartition(":")
if not sep or not port.isdigit():
print(f"--listen must be host:port, got {args.listen!r}.", file=sys.stderr)
return 1
# Never run the sudo connect script from a request: the service expects the
# printer link to be configured persistently (see README).
config = receipt.PrinterConfig(ip=args.ip, port=args.port, usb=args.usb, no_setup=True)
# Our own handler, not basicConfig: escpos logs chatty INFO lines through the root logger.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(name)s: %(message)s"))
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False
uvicorn.run(create_app(config, token), host=host.strip("[]"), port=int(port))
return 0
PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Receipt Printer</title>
<style>
:root {
--bg: #f6f5f2; --card: #fff; --text: #1d1d1b; --muted: #6b6a66;
--border: #dcdad4; --accent: #2f5bd3; --ok: #1f7a3a; --err: #b42318;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161615; --card: #20201e; --text: #ecebe7; --muted: #9c9a94;
--border: #3a3936; --accent: #7a9cff; --ok: #5cc27c; --err: #ff7a6b;
}
}
* { box-sizing: border-box; }
body {
margin: 0; padding: 24px 16px; background: var(--bg); color: var(--text);
font: 15px/1.5 system-ui, sans-serif;
}
main { max-width: 560px; margin: 0 auto; display: grid; gap: 16px; }
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
h1 { font-size: 1.3rem; margin: 0; }
h2 { font-size: 1rem; margin: 0 0 10px; }
section {
background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px;
}
textarea, input[type=text], select {
width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px;
background: var(--bg); color: var(--text); font: inherit;
}
select { width: auto; padding: 4px 6px; margin-left: 4px; }
textarea { min-height: 140px; font-family: ui-monospace, monospace; resize: vertical; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px;
margin-top: 10px; flex-wrap: wrap; }
button {
padding: 8px 16px; border: 0; border-radius: 6px; background: var(--accent); color: #fff;
font: inherit; font-weight: 600; cursor: pointer;
}
button:disabled { opacity: .5; cursor: progress; }
.pill {
font-size: .85rem; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--border);
color: var(--muted); background: none; cursor: pointer; font-weight: 400;
}
.pill.ok { color: var(--ok); border-color: var(--ok); }
.pill.err { color: var(--err); border-color: var(--err); }
#drop {
display: block; border: 2px dashed var(--border); border-radius: 8px; padding: 16px;
text-align: center; color: var(--muted); cursor: pointer;
}
#drop.over { border-color: var(--accent); }
#preview { max-width: 100%; max-height: 260px; display: none; margin: 10px auto 0;
filter: grayscale(1); }
#file { display: none; }
#log { white-space: pre-wrap; font-family: ui-monospace, monospace; font-size: .85rem;
margin: 0; color: var(--muted); }
#log.ok { color: var(--ok); }
#log.err { color: var(--err); }
.muted { color: var(--muted); font-size: .85rem; }
</style>
</head>
<body>
<main>
<header>
<h1>Receipt printer</h1>
<button id="status" class="pill" title="Check again">checking…</button>
</header>
<section>
<h2>Note</h2>
<form id="note-form">
<textarea id="note" maxlength="4000" placeholder="Your note" required></textarea>
<div class="row">
<label class="muted"><input type="checkbox" id="timestamp"> Date/time header</label>
<label class="muted">Size
<select id="size">
<option value="1">Normal (48 per line)</option>
<option value="2" selected>Large (24 per line)</option>
<option value="3">Huge (16 per line)</option>
</select>
</label>
<button type="submit">Print note</button>
</div>
</form>
</section>
<section>
<h2>Image</h2>
<form id="image-form">
<label id="drop" for="file">Choose, drop or paste an image</label>
<input type="file" id="file" accept="image/*">
<img id="preview" alt="">
<div class="row">
<input type="text" id="caption" maxlength="500" placeholder="Caption (optional)">
</div>
<div class="row">
<span class="muted">Max 16 MB. Printed full width, dithered.</span>
<button type="submit">Print image</button>
</div>
</form>
</section>
<section><pre id="log">Ready.</pre></section>
</main>
<script>
const $ = (id) => document.getElementById(id);
const log = $("log");
let picked = null;
function show(text, cls) { log.textContent = text; log.className = cls || ""; }
async function call(path, init) {
init = init || {};
init.headers = Object.assign({"X-Requested-With": "receipt"}, init.headers || {});
const res = await fetch(path, init);
let body = {};
try { body = await res.json(); } catch (e) { /* nginx pages aren't JSON */ }
if (!("ok" in body) && !("detail" in body)) {
// Not from this server: nginx's offline page, or its login redirect.
const offline = [502, 503, 504].includes(res.status);
return {ok: false, text: offline ? "The printer machine is offline."
: "Signed out? Reload the page and sign in."};
}
let detail = body.detail;
if (Array.isArray(detail)) detail = detail.map((d) => d.msg).join("; ");
return {ok: res.ok && body.ok !== false, text: body.output || detail || res.statusText,
job: body.job, busy: body.busy};
}
async function checkStatus() {
const pill = $("status");
pill.textContent = "checking…"; pill.className = "pill";
const r = await call("api/status");
pill.textContent = r.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline";
pill.className = "pill " + (r.ok ? "ok" : "err");
pill.title = r.text;
}
// POST answers 202 with a queued job; long-poll it until it finishes.
async function submit(path, init) {
const buttons = document.querySelectorAll("button");
buttons.forEach((b) => b.disabled = true);
show("Sending…");
let job = null;
try {
let r = await call(path, init);
while (r.ok && r.job && !["done", "failed"].includes(r.job.state)) {
job = r.job;
show(job.state === "queued" ? "Queued…" : "Printing…");
r = await call("api/jobs/" + job.id + "?wait=20");
}
if (!r.ok || !r.job) { show(r.text, "err"); return false; }
const ok = r.job.state === "done";
show(r.job.message, ok ? "ok" : "err");
return ok;
} catch (e) {
show("Request failed: " + e + (job ? " (the job may still print)" : ""), "err");
return false;
} finally {
buttons.forEach((b) => b.disabled = false);
}
}
$("note-form").addEventListener("submit", async (e) => {
e.preventDefault();
const ok = await submit("api/note", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked,
size: Number($("size").value)}),
});
if (ok) $("note").value = "";
});
function pick(file) {
if (!file || !file.type.startsWith("image/")) return;
picked = file;
const preview = $("preview");
if (preview.src) URL.revokeObjectURL(preview.src);
preview.src = URL.createObjectURL(file);
preview.style.display = "block";
$("drop").textContent = file.name || "Pasted image";
}
$("file").addEventListener("change", (e) => pick(e.target.files[0]));
const drop = $("drop");
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => {
e.preventDefault(); drop.classList.remove("over"); pick(e.dataTransfer.files[0]);
});
document.addEventListener("paste", (e) => {
const item = [...e.clipboardData.items].find((i) => i.type.startsWith("image/"));
if (item) pick(item.getAsFile());
});
$("image-form").addEventListener("submit", async (e) => {
e.preventDefault();
if (!picked) { show("Choose an image first.", "err"); return; }
const data = new FormData();
data.append("file", picked, picked.name || "pasted.png");
data.append("message", $("caption").value);
await submit("api/image", {method: "POST", body: data});
});
$("status").addEventListener("click", checkStatus);
checkStatus();
</script>
</body>
</html>
"""