Add scheduled and event-driven printing with a new web UI
CI / test (3.10) (push) Successful in 1m20s
CI / test (3.12) (push) Successful in 1m49s
CI / test (3.13) (push) Successful in 1m5s

The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:

- Triggers: once, recurring (rrule-based, DST-safe), sun times,
  reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
  with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
  {days_until:..}, rotating {choice}, trigger vars), QR, saved images,
  random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
  window for missed runs (never replayed), retries on connect failure
  only; a mid-job drop (new PrinterDropped) is never resent.

receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 23:58:26 +01:00
co-authored by Claude Opus 5.5
parent fa99c3076c
commit ba92f1fbda
29 changed files with 5433 additions and 294 deletions
+579 -243
View File
@@ -9,40 +9,76 @@ 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.
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, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
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 = 4000
MAX_CAPTION_CHARS = 500
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")
@@ -53,6 +89,29 @@ class Note(BaseModel):
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
@@ -60,7 +119,10 @@ class Job:
user: str | None
state: str = "queued" # queued -> printing -> done | failed
message: str = ""
error: str | None = None # "unavailable" or "failed" when state is failed
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")}
@@ -71,12 +133,15 @@ class PrintQueue:
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.
behind a long print. With a store, every job is also written to the
print history.
"""
def __init__(self, config: receipt.PrinterConfig):
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)
@@ -86,16 +151,31 @@ class PrintQueue:
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
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
@@ -110,6 +190,8 @@ class PrintQueue:
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:
@@ -119,6 +201,8 @@ class PrintQueue:
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:
@@ -127,12 +211,66 @@ class PrintQueue:
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 create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
jobs = PrintQueue(config)
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(
@@ -150,19 +288,105 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
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("/", response_class=HTMLResponse, dependencies=authed)
def page() -> str:
return PAGE
@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:
@@ -191,7 +415,20 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
@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))
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(
@@ -199,17 +436,329 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
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."
)
data = read_upload(file)
payload = render(receipt.render_image, io.BytesIO(data), message.strip() or None)
return accepted(jobs.submit("image", payload, x_remote_user 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
@@ -234,220 +783,7 @@ def serve(args: argparse.Namespace) -> int:
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False
uvicorn.run(create_app(config, token), host=host.strip("[]"), port=int(port))
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
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>
"""