"""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 (images for scheduled receipts are kept in the database). The same process runs the scheduler (receipt_scheduler) over the schedules in the database (receipt_store). Webhooks (/hook/{id}) are the one route for other services: nginx forwards them without the admin login, still adding the token, and each schedule's own secret authorizes the call. """ from __future__ import annotations import argparse import base64 import datetime as dt import hashlib import hmac import io import json import logging import os import queue import re import secrets import sys import threading from collections import OrderedDict from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from urllib.parse import parse_qsl from zoneinfo import available_timezones from fastapi import ( Depends, FastAPI, File, Form, Header, HTTPException, Query, Request, UploadFile, ) from fastapi.responses import FileResponse, JSONResponse from pydantic import BaseModel, Field, ValidationError from starlette.concurrency import run_in_threadpool import receipt import receipt_models as models from receipt_content import VARIABLES from receipt_scheduler import QueueFull, RateLimited, Scheduler from receipt_sources import SourceError, fetch, json_value, parse_events, parse_items from receipt_store import Store, default_path, iso, utcnow from receipt_triggers import TriggerError, describe, ruleset TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret MIN_TOKEN_CHARS = 16 MAX_NOTE_CHARS = models.MAX_NOTE_CHARS MAX_CAPTION_CHARS = models.MAX_CAPTION_CHARS 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 MAX_HOOK_BODY = 64 * 1024 # 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") WEB_DIR = Path(__file__).resolve().parent / "web" STATIC_NAME = re.compile(r"^[a-z_]+\.(js|css|svg)$") STATIC_TYPES = {".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml"} 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)) class Qr(BaseModel): content: str = Field(min_length=1, max_length=2000) caption: str = Field(default="", max_length=MAX_CAPTION_CHARS) class PreviewIn(models.Model): blocks: list[models.Block] = Field(min_length=1, max_length=models.MAX_BLOCKS) trigger: models.Trigger | None = None schedule_id: str | None = None class TriggerPreviewIn(models.Model): trigger: models.Trigger class Toggle(models.Model): enabled: bool class SourceTest(models.SourceIn): name: str = "test" @dataclass class Job: id: str kind: str user: str | None state: str = "queued" # queued -> printing -> done | failed message: str = "" error: str | None = None # "unavailable", "dropped" or "failed" when state is failed source: str = "manual" schedule_id: str | None = None name: str | None = None 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. With a store, every job is also written to the print history. """ def __init__(self, config: receipt.PrinterConfig, store: Store | None = None): self.config = config self.store = store self.printer_lock = threading.Lock() self.listeners: list[Callable[[Job], None]] = [] # called with each finished job 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, *, source: str = "manual", schedule_id: str | None = None, name: str | None = None, ) -> Job: job = Job(secrets.token_hex(8), kind, user, source=source, schedule_id=schedule_id, name=name) # Under the lock, so the worker can't record a state before the run exists. with self._changed: try: self._pending.put_nowait((job, payload)) except queue.Full: raise QueueFull from None self._jobs[job.id] = job while len(self._jobs) > MAX_JOB_HISTORY: self._jobs.popitem(last=False) if self.store is not None: self.store.add_run(kind, source, "queued", run_id=job.id, schedule_id=schedule_id, name=name, user=user, payload=payload) 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 if self.store is not None: self.store.finish_run(job.id, 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.PrinterDropped as e: self._update(job, "failed", f"Printer unavailable: {e}", "dropped") 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) for listener in self.listeners: try: listener(job) except Exception: log.exception("job listener failed") def hash_secret(secret: str) -> str: return hashlib.sha256(secret.encode()).hexdigest() def png_data_url(image) -> str: buf = io.BytesIO() image.save(buf, "PNG", optimize=True) return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() def preview_json(blocks: list[receipt.Block], warnings: list[str]) -> dict: parts = [] for block in blocks: for part in block.parts: if "image" in part: parts.append({"image": png_data_url(part["image"])}) else: parts.append({k: part.get(k) for k in ("text", "size", "bold", "center")}) height = receipt.receipt_height(blocks) return { "ok": True, "parts": parts, "height_mm": round(height / receipt.DOTS_PER_MM), "max_mm": receipt.MAX_PRINT_HEIGHT_DOTS // receipt.DOTS_PER_MM, "too_long": height > receipt.MAX_PRINT_HEIGHT_DOTS, "warnings": warnings, } def run_name(text: str, limit: int = 60) -> str: """A one-line label for the history list.""" line = next((ln.strip() for ln in text.splitlines() if ln.strip()), "") return line if len(line) <= limit else line[: limit - 1] + "…" def create_app( config: receipt.PrinterConfig, token: str, store: Store | None = None, clock: Callable[[], dt.datetime] | None = None, start_scheduler: bool = True, ) -> FastAPI: store = store or Store() store.fail_interrupted_runs() jobs = PrintQueue(config, store) scheduler = Scheduler(store, jobs, clock or utcnow) jobs.listeners.append(scheduler.job_finished) if start_scheduler: scheduler.start() app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app.state.jobs = jobs app.state.store = store app.state.scheduler = scheduler 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 queue_job(kind: str, payload: bytes, user: str | None, name: str) -> JSONResponse: try: job = jobs.submit(kind, payload, user, name=name) except QueueFull: raise HTTPException(503, "The print queue is full; try again shortly.") from None return accepted(job) def accepted(job: Job) -> JSONResponse: return JSONResponse({"ok": True, "job": job.public()}, status_code=202) def settings() -> models.Settings: return scheduler.settings() def source_name(source_id: str) -> str: source = store.source(source_id) return source["name"] if source else "a deleted calendar" def schedule_out(row: dict, secret: str | None = None) -> dict: out = {k: row[k] for k in ("id", "name", "enabled", "spec", "next_run_at", "last_run_at", "last_status", "last_message", "created_at", "updated_at")} try: spec = models.ScheduleSpec.model_validate(row["spec"]) out["summary"] = describe(spec.trigger, settings(), source_name) except ValidationError: out["summary"] = "Invalid schedule" return out if spec.trigger.type == "webhook": out["hook_path"] = f"hook/{row['id']}" out["has_secret"] = store.state(row["id"], "hook_secret") is not None if secret: out["secret"] = secret return out def get_schedule(schedule_id: str) -> dict: row = store.schedule(schedule_id) if row is None: raise HTTPException(404, "No such schedule.") return row def check_spec(spec: models.ScheduleSpec) -> None: """References and rules the models can't check alone; raises a 400.""" trigger = spec.trigger if trigger.type == "recurring": if trigger.start is None: trigger.start = utcnow().astimezone(settings().tz).date() try: ruleset(trigger) except TriggerError as e: raise HTTPException(400, str(e)) from None if trigger.type == "sun" and settings().location is None: raise HTTPException(400, "Sun times need a location: set one in Settings first.") if trigger.type == "calendar": source = store.source(trigger.source_id) if source is None or source["kind"] != "ics": raise HTTPException(400, "Pick a saved calendar for the reminders.") for block in spec.blocks: if block.type in ("agenda", "headlines"): kind = "ics" if block.type == "agenda" else "rss" for source_id in block.source_ids: source = store.source(source_id) if source is None or source["kind"] != kind: raise HTTPException(400, f"A {block.type} block reads a missing source.") if block.type == "image" and store.asset(block.asset_id) is None: raise HTTPException(400, "An image block's picture has been deleted.") def spec_dict(body: models.ScheduleSpec) -> dict: return body.model_dump(mode="json", include={"trigger", "blocks", "options"}) def new_secret(schedule_id: str) -> str: secret = secrets.token_urlsafe(24) store.set_state(schedule_id, "hook_secret", hash_secret(secret)) return secret def uses(predicate: Callable[[dict], bool]) -> list[str]: """Names of schedules whose spec matches (to refuse deleting what they use).""" return [row["name"] for row in store.schedules() if predicate(row["spec"])] authed = [Depends(require_token)] posting = [Depends(require_token), Depends(require_page_request)] # --- page --- @app.get("/healthz") def healthz() -> dict: return {"ok": True} @app.get("/", dependencies=authed) def page() -> FileResponse: return FileResponse(WEB_DIR / "index.html", headers={"Cache-Control": "no-cache"}) @app.get("/static/{name}", dependencies=authed) def static(name: str) -> FileResponse: path = WEB_DIR / name if not STATIC_NAME.match(name) or not path.is_file(): raise HTTPException(404, "Not found.") return FileResponse(path, media_type=STATIC_TYPES[path.suffix], headers={"Cache-Control": "no-cache"}) # --- printing now --- @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 queue_job("note", payload, x_remote_user or None, run_name(body.text)) @app.post("/api/qr", dependencies=posting) def qr(body: Qr, x_remote_user: str | None = Header(default=None)) -> JSONResponse: payload = render(receipt.render_qr, body.content, body.caption.strip() or None) return queue_job("qr", payload, x_remote_user or None, run_name(body.content)) def read_upload(file: UploadFile) -> bytes: 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." ) return data @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 = read_upload(file) payload = render(receipt.render_image, io.BytesIO(data), message.strip() or None) return queue_job("image", payload, x_remote_user or None, run_name(message) or file.filename or "image") @app.post("/api/preview/image", dependencies=posting) def preview_image( file: UploadFile = File(...), # noqa: B008 message: str = Form(default="", max_length=MAX_CAPTION_CHARS), ) -> dict: data = read_upload(file) block = render(receipt.image_block, io.BytesIO(data), message.strip() or None) return preview_json([block], []) @app.post("/api/preview", dependencies=posting) def preview(body: PreviewIn) -> dict: now = scheduler.clock() current = settings() row = {"id": body.schedule_id, "name": ""} if body.schedule_id and (saved := store.schedule(body.schedule_id)): row["name"] = saved["name"] values = scheduler.sample_values(body.trigger, now, current) if body.trigger else {} spec = models.ScheduleSpec.model_construct(blocks=body.blocks, options=models.Options()) try: built = scheduler.build(row, spec, now, current, [values], preview=True) except receipt.InvalidJob as e: raise HTTPException(400, str(e)) from None if not built.blocks: raise HTTPException(400, "Nothing to print.") return preview_json(built.blocks, built.warnings) # --- history --- @app.get("/api/runs", dependencies=authed) def runs( limit: int = Query(default=50, ge=1, le=200), before: str | None = Query(default=None, max_length=40), schedule_id: str | None = Query(default=None, max_length=40), state: str | None = Query(default=None, max_length=20), ) -> dict: return {"ok": True, "runs": store.runs(limit, before, schedule_id, state)} @app.post("/api/runs/{run_id}/reprint", dependencies=posting) def reprint(run_id: str, x_remote_user: str | None = Header(default=None)) -> JSONResponse: found = store.run_payload(run_id) if found is None: raise HTTPException(404, "That print is too old to print again.") row, payload = found return queue_job(row["kind"], payload, x_remote_user or None, row["name"] or row["kind"]) # --- schedules --- @app.get("/api/schedules", dependencies=authed) def list_schedules() -> dict: return {"ok": True, "schedules": [schedule_out(r) for r in store.schedules()]} @app.get("/api/schedules/{schedule_id}", dependencies=authed) def read_schedule(schedule_id: str) -> dict: return {"ok": True, "schedule": schedule_out(get_schedule(schedule_id))} @app.post("/api/schedules", dependencies=posting) def add_schedule(body: models.ScheduleIn) -> JSONResponse: check_spec(body) row = store.add_schedule(body.name, spec_dict(body), body.enabled) secret = new_secret(row["id"]) if body.trigger.type == "webhook" else None row = scheduler.reschedule(row) log.info("schedule %s (%s) added", row["id"], row["name"]) return JSONResponse({"ok": True, "schedule": schedule_out(row, secret)}, status_code=201) @app.put("/api/schedules/{schedule_id}", dependencies=posting) def edit_schedule(schedule_id: str, body: models.ScheduleIn) -> dict: old = get_schedule(schedule_id) check_spec(body) spec = spec_dict(body) fields = {"name": body.name, "enabled": body.enabled, "spec": spec, "updated_at": iso(utcnow())} if spec["trigger"] != old["spec"].get("trigger"): store.clear_state(schedule_id, keep=("hook_secret",)) fields.update(last_status=None, last_message=None) row = store.update_schedule(schedule_id, **fields) secret = None if body.trigger.type == "webhook" and store.state(schedule_id, "hook_secret") is None: secret = new_secret(schedule_id) row = scheduler.reschedule(row) return {"ok": True, "schedule": schedule_out(row, secret)} @app.delete("/api/schedules/{schedule_id}", dependencies=posting) def delete_schedule(schedule_id: str) -> dict: if not store.delete_schedule(schedule_id): raise HTTPException(404, "No such schedule.") return {"ok": True} @app.post("/api/schedules/{schedule_id}/toggle", dependencies=posting) def toggle_schedule(schedule_id: str, body: Toggle) -> dict: get_schedule(schedule_id) row = store.update_schedule(schedule_id, enabled=body.enabled) if body.enabled: row = scheduler.reschedule(row) return {"ok": True, "schedule": schedule_out(row)} @app.post("/api/schedules/{schedule_id}/duplicate", dependencies=posting) def duplicate_schedule(schedule_id: str) -> JSONResponse: old = get_schedule(schedule_id) row = store.add_schedule(f"{old['name']} (copy)"[:100], old["spec"], enabled=False) return JSONResponse({"ok": True, "schedule": schedule_out(row)}, status_code=201) @app.post("/api/schedules/{schedule_id}/run", dependencies=posting) def test_schedule(schedule_id: str) -> JSONResponse: row = get_schedule(schedule_id) try: job = scheduler.test_print(row) except receipt.InvalidJob as e: raise HTTPException(400, str(e)) from None except ValidationError: raise HTTPException(400, "This schedule is invalid; edit and save it.") from None except QueueFull: raise HTTPException(503, "The print queue is full; try again shortly.") from None return accepted(job) @app.post("/api/schedules/{schedule_id}/secret", dependencies=posting) def regenerate_secret(schedule_id: str) -> dict: row = get_schedule(schedule_id) if row["spec"].get("trigger", {}).get("type") != "webhook": raise HTTPException(400, "Only webhook schedules have a secret.") return {"ok": True, "schedule": schedule_out(row, new_secret(schedule_id))} @app.post("/api/triggers/preview", dependencies=posting) def preview_trigger(body: TriggerPreviewIn) -> dict: trigger = body.trigger current = settings() if trigger.type == "recurring" and trigger.start is None: trigger.start = scheduler.clock().astimezone(current.tz).date() out = {"ok": True, "summary": describe(trigger, current, source_name), "next": [], "error": None} try: out["next"] = [iso(t) for t in scheduler.trigger_runs(trigger, scheduler.clock(), current, 5)] except (TriggerError, SourceError) as e: out["error"] = str(e) return out @app.get("/api/upcoming", dependencies=authed) def upcoming(hours: int = Query(default=24, ge=1, le=24 * 7)) -> dict: now = scheduler.clock() horizon = now + dt.timedelta(hours=hours) items = [] for row in store.schedules(): if not row["enabled"]: continue try: times = scheduler.next_runs(row, 20) except (TriggerError, SourceError, ValidationError): continue items.extend({"schedule_id": row["id"], "name": row["name"], "at": iso(t)} for t in times if t <= horizon) items.sort(key=lambda i: i["at"]) return {"ok": True, "upcoming": items[:50]} @app.get("/api/variables", dependencies=authed) def variables() -> dict: return {"ok": True, "variables": VARIABLES} # --- images for scheduled receipts --- @app.get("/api/assets", dependencies=authed) def list_assets() -> dict: return {"ok": True, "assets": store.assets()} @app.post("/api/assets", dependencies=posting) def add_asset(file: UploadFile = File(...)) -> JSONResponse: # noqa: B008 data = read_upload(file) render(receipt.image_block, io.BytesIO(data)) # refuse what wouldn't print asset = store.add_asset((file.filename or "image")[:100], data) return JSONResponse({"ok": True, "asset": asset}, status_code=201) @app.delete("/api/assets/{asset_id}", dependencies=posting) def delete_asset(asset_id: str) -> dict: users = uses(lambda spec: any(b.get("asset_id") == asset_id for b in spec.get("blocks", []))) if users: raise HTTPException(409, f"Used by: {', '.join(users)}.") if not store.delete_asset(asset_id): raise HTTPException(404, "No such image.") return {"ok": True} # --- saved calendars and feeds --- @app.get("/api/sources", dependencies=authed) def list_sources() -> dict: return {"ok": True, "sources": store.sources()} @app.post("/api/sources", dependencies=posting) def add_source(body: models.SourceIn) -> JSONResponse: source = store.add_source(body.name, body.kind, body.url) return JSONResponse({"ok": True, "source": source}, status_code=201) @app.put("/api/sources/{source_id}", dependencies=posting) def edit_source(source_id: str, body: models.SourceIn) -> dict: old = store.source(source_id) if old is None: raise HTTPException(404, "No such source.") scheduler.cache.forget(old["url"]) return {"ok": True, "source": store.update_source(source_id, body.name, body.kind, body.url)} @app.delete("/api/sources/{source_id}", dependencies=posting) def delete_source(source_id: str) -> dict: def reads(spec: dict) -> bool: if spec.get("trigger", {}).get("source_id") == source_id: return True return any(source_id in b.get("source_ids", []) for b in spec.get("blocks", [])) users = uses(reads) if users: raise HTTPException(409, f"Used by: {', '.join(users)}.") if not store.delete_source(source_id): raise HTTPException(404, "No such source.") return {"ok": True} @app.post("/api/sources/test", dependencies=posting) def test_source(body: SourceTest) -> dict: try: data = fetch(body.url) if body.kind == "ics": now = scheduler.clock() events = parse_events(data, now, now + dt.timedelta(days=7), settings().tz) first = f" Next: {events[0].title}." if events else "" return {"ok": True, "output": f"{len(events)} events in the next 7 days.{first}"} items = parse_items(data) first = f" Latest: {items[0].title}" if items else "" return {"ok": True, "output": f"{len(items)} items.{first}"} except SourceError as e: return {"ok": False, "output": f"Couldn't read it: {e}"} @app.post("/api/watch/test", dependencies=posting) def test_watch(trigger: models.WatchTrigger) -> dict: try: data = fetch(trigger.url) if trigger.kind == "rss": items = parse_items(data) latest = f" Latest: {items[0].title}" if items else "" return {"ok": True, "output": f"{len(items)} items.{latest}"} value = json_value(data, trigger.path) return {"ok": True, "output": f"{trigger.path or 'Value'} is {value!r}."} except SourceError as e: return {"ok": False, "output": f"Couldn't read it: {e}"} # --- settings --- @app.get("/api/settings", dependencies=authed) def read_settings() -> dict: return {"ok": True, "settings": settings().model_dump(mode="json"), "timezones": sorted(available_timezones())} @app.put("/api/settings", dependencies=posting) def save_settings(body: models.Settings) -> dict: store.save_settings(body.model_dump(mode="json")) scheduler.reschedule_all() return {"ok": True, "settings": body.model_dump(mode="json")} # --- webhooks (no page header: called by other services) --- @app.post("/hook/{schedule_id}", dependencies=authed) async def hook( schedule_id: str, request: Request, key: str | None = Query(default=None, max_length=200), x_hook_secret: str | None = Header(default=None), ) -> JSONResponse: body = bytearray() async for chunk in request.stream(): body.extend(chunk) if len(body) > MAX_HOOK_BODY: raise HTTPException(413, f"Body over {MAX_HOOK_BODY // 1024} KB.") return await run_in_threadpool( call_hook, schedule_id, x_hook_secret or key, bytes(body), request.headers.get("content-type", ""), ) def call_hook(schedule_id: str, secret: str | None, body: bytes, content_type: str) -> JSONResponse: row = store.schedule(schedule_id) stored = store.state(schedule_id, "hook_secret") if row else None if (row is None or stored is None or not secret or row["spec"].get("trigger", {}).get("type") != "webhook" or not hmac.compare_digest(hash_secret(secret), stored)): raise HTTPException(404, "No such webhook, or the wrong secret.") if not row["enabled"]: raise HTTPException(409, "This webhook's schedule is turned off.") try: job, message = scheduler.fire_webhook(row, hook_payload(body, content_type)) except RateLimited as e: raise HTTPException(429, str(e)) from None except receipt.InvalidJob as e: raise HTTPException(400, str(e)) from None except QueueFull: raise HTTPException(503, "The print queue is full; try again shortly.") from None if job is None: return JSONResponse({"ok": True, "skipped": message}) return accepted(job) return app def hook_payload(body: bytes, content_type: str) -> dict: """A webhook body as template values: JSON objects as they are, forms as fields, else text.""" text = body.decode("utf-8", errors="replace") if not text.strip(): return {} if "json" in content_type or text.lstrip().startswith(("{", "[")): try: data = json.loads(text) except ValueError: data = None if isinstance(data, dict): return data if data is not None: return {"value": data} if "x-www-form-urlencoded" in content_type: return dict(parse_qsl(text)) return {"text": text} 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 store = Store(default_path()) log.info("data in %s", store.path) uvicorn.run(create_app(config, token, store), host=host.strip("[]"), port=int(port)) return 0