From ba92f1fbda47b8ab18aac1e9d508dd0316d84e3d Mon Sep 17 00:00:00 2001 From: Adam French Date: Fri, 23 Oct 2026 23:58:26 +0100 Subject: [PATCH] Add scheduled and event-driven printing with a new web UI 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 --- CLAUDE.md | 5 +- README.md | 20 + pyproject.toml | 17 +- receipt.py | 218 +++++++--- receipt_content.py | 372 ++++++++++++++++ receipt_models.py | 282 +++++++++++++ receipt_scheduler.py | 609 ++++++++++++++++++++++++++ receipt_sources.py | 186 ++++++++ receipt_store.py | 409 ++++++++++++++++++ receipt_triggers.py | 295 +++++++++++++ receipt_web.py | 822 +++++++++++++++++++++++++----------- tests/conftest.py | 32 ++ tests/fixtures/calendar.ics | 33 ++ tests/fixtures/feed.xml | 10 + tests/test_scheduler.py | 237 +++++++++++ tests/test_triggers.py | 180 ++++++++ tests/test_web.py | 102 +++++ web/api.js | 90 ++++ web/app.css | 270 ++++++++++++ web/app.js | 54 +++ web/dom.js | 154 +++++++ web/editor.js | 591 ++++++++++++++++++++++++++ web/history.js | 69 +++ web/index.html | 24 ++ web/paper.js | 35 ++ web/presets.js | 163 +++++++ web/print.js | 149 +++++++ web/schedules.js | 126 ++++++ web/settings.js | 173 ++++++++ 29 files changed, 5433 insertions(+), 294 deletions(-) create mode 100644 receipt_content.py create mode 100644 receipt_models.py create mode 100644 receipt_scheduler.py create mode 100644 receipt_sources.py create mode 100644 receipt_store.py create mode 100644 receipt_triggers.py create mode 100644 tests/fixtures/calendar.ics create mode 100644 tests/fixtures/feed.xml create mode 100644 tests/test_scheduler.py create mode 100644 tests/test_triggers.py create mode 100644 web/api.js create mode 100644 web/app.css create mode 100644 web/app.js create mode 100644 web/dom.js create mode 100644 web/editor.js create mode 100644 web/history.js create mode 100644 web/index.html create mode 100644 web/paper.js create mode 100644 web/presets.js create mode 100644 web/print.js create mode 100644 web/schedules.js create mode 100644 web/settings.js diff --git a/CLAUDE.md b/CLAUDE.md index 002b106..a622e8e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,6 +7,8 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt - `receipt.py` — the CLI; subcommand per `cmd_*` function - `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which captures stdout/stderr for the log panel and returns an `ActionResult` (rc, output, error kind). `textual` is an optional dependency (`[tui]` extra); the CLI works without it - `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. POSTs render the job in the request (`InvalidJob` → 400), queue the bytes in a `PrintQueue` and answer 202; one worker thread sends them, and the page long-polls `/api/jobs/{id}`. `/api/status` only tries the printer lock, so it never waits behind a print. Uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile) +- Scheduling (all run inside `serve`; `[web]` extra): `receipt_store.py` (SQLite at `$RECEIPT_DATA_DIR/receipt.db`, default `~/.local/share/receipt-maker`; additive-only migrations so `update.sh` rollbacks still read it), `receipt_models.py` (pydantic specs: a schedule is trigger + blocks + options), `receipt_triggers.py` (next fire times, DST-safe, plain-English `describe()`), `receipt_sources.py` (ICS/RSS/JSON fetch + parse), `receipt_content.py` (blocks → `receipt.Block`s, `{var}` template fill — never `str.format`), `receipt_scheduler.py` (`tick(now)` is deterministic; tests drive it with a fake clock). Webhooks are `POST /hook/{id}` with a per-schedule secret +- `web/` — the page (vanilla ES modules, no build step), served by token-gated routes with relative URLs - `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) tests the new Gitea commit in a scratch worktree, then fast-forwards the server's clone, restarts `receipt-web` and rolls back if `/healthz` doesn't answer. Pushing to Gitea `master` is the deploy - `connect_receipt.sh` — brings up the printer's network interface (needs sudo); run automatically before any print over Ethernet. The TUI runs it with output captured (`PrinterConfig.quiet_setup`, set by `run_action()`) so it can't corrupt the screen - `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network @@ -14,7 +16,8 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt ## Conventions - Printer/network constants live at the top of `receipt.py`; IP/port overridable via `--ip`/`--port` or `RECEIPT_PRINTER_IP`/`RECEIPT_PRINTER_PORT` -- Every print is `render_*()` → bytes → `send(config, payload)`: `render()` builds the job on an escpos `Dummy` (ESC @ first, cut last), and `send()` connects fresh, writes it once and closes. Only the connect is retried; a mid-job drop raises `PrinterUnavailable` and is never replayed. `cmd_*` handlers take a `PrinterConfig`, not a printer handle +- Receipts are lists of `receipt.Block` (height, ESC/POS build, preview parts); `render_blocks()` makes one job of them and refuses one over `MAX_PRINT_HEIGHT_DOTS` +- Every print is `render_*()` → bytes → `send(config, payload)`: `render()` builds the job on an escpos `Dummy` (ESC @ first, cut last), and `send()` connects fresh, writes it once and closes. Only the connect is retried; a mid-job drop raises `PrinterDropped` (a `PrinterUnavailable`) and is never replayed, by `send()` or by the scheduler's retries. `cmd_*` handlers take a `PrinterConfig`, not a printer handle - User errors raise `InvalidJob`, printer trouble raises `PrinterUnavailable`; `main()`, `run_action()` and the web server turn them into messages / status codes - Images are prepared in memory (`prepare_for_print`: white-composite alpha → resize to 576px → autocontrast → 1-bit dither); nothing is written except the `img/` download cache. `MAX_PRINT_HEIGHT_DOTS` caps paper per job (tall images shrink, long notes are refused) - `run_command()` dispatches every subcommand except `tui`/`serve`, for both `main()` and `run_action()` (via the `PRINT_COMMANDS` registry) diff --git a/README.md b/README.md index 3bc5f1e..dc0f525 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,24 @@ sudo nmcli con add type ethernet ifname eth0 con-name receipt-printer connection Jobs are checked and rendered when submitted (a bad note or image is rejected straight away), then queued and printed one at a time. The page shows each job as queued, printing, then done or failed, and the status pill shows "printer busy" during a print rather than waiting for it. Each job is logged to the service's journal with the signed-in user nginx forwards. If the server machine is off, the site shows "printer machine offline". +### Schedules + +The page has four tabs: **Print** (note, image or QR code, with a preview of the paper), **Schedules**, **History** and **Settings**. A schedule is *when* + *what* + *options*: + +- **When**: once; repeating (every N days/weeks/months/years, chosen weekdays, "first weekday of the month", several times a day, or a custom RRULE); at sunrise/sunset/dawn/dusk ± minutes; N minutes before each event in a calendar; when an RSS feed gets new items or a JSON value changes/crosses a threshold; or when its webhook is called. +- **What**: a receipt built from blocks: notes (with `{date}`, `{time}`, `{days_until:12-25}`, `{choice}` from a rotating list, and `{event.title}`, `{item.title}`, `{payload.text}`… from the trigger), QR codes, saved images, a random /bant/ image, a calendar agenda, feed headlines and dividers. It is rendered fresh each time it fires, as one job. +- **Options**: what to do in quiet hours (wait, skip, print anyway), skip when the agenda/headlines are empty, how late a missed run may still print (after a restart; later ones are logged as missed, never replayed), and retries if the printer is off (a job that dropped mid-print is never retried). + +Settings hold the time zone, location (for sun times), quiet hours, a daily cap on automatic prints, a pause switch (holiday mode), and saved calendars (ICS, e.g. Google Calendar's secret iCal address) and feeds. Everything lives in SQLite at `~/.local/share/receipt-maker/receipt.db` (`RECEIPT_DATA_DIR` to move it), outside the clone, so deploys and rollbacks leave it alone. + +**Webhooks**: a webhook schedule gets a URL (`…/receipt/hook/`) and a secret, shown once. Call it with the secret in `X-Hook-Secret` or `?key=`; JSON fields become `{payload.…}` and a plain-text body is `{payload.text}`: + +```bash +curl -X POST https://www.adam-french.co.uk/receipt/hook/ -H 'X-Hook-Secret: ' -d 'Buy milk' +``` + +The site's admin login would block other services, so nginx on stpvm needs a `location /receipt/hook/` without the `auth_request` (still adding `X-Receipt-Token`, ideally with `limit_req` and `client_max_body_size 64k`). Until then webhooks work over Tailscale only. + ### Automatic updates `receipt-update.timer` runs `deploy/update.sh` every 5 minutes. When `master` on Gitea has moved, the script: @@ -139,6 +157,8 @@ Both checks also run in CI on every push, on Python 3.10, 3.12 and 3.13. Gitea A - `receipt.py` — main script - `receipt_tui.py` — Textual terminal UI (`./receipt.py tui`) - `receipt_web.py` — web server for printing from the site (`./receipt.py serve`) +- `receipt_store.py`, `receipt_models.py`, `receipt_triggers.py`, `receipt_sources.py`, `receipt_content.py`, `receipt_scheduler.py` — schedules (run by `serve`) +- `web/` — the web page - `deploy/receipt-web.service` — systemd user unit for the web server - `deploy/update.sh`, `deploy/receipt-update.{service,timer}` — automatic updates from Gitea - `connect_receipt.sh` — network setup for the USB Ethernet adapter diff --git a/pyproject.toml b/pyproject.toml index 1eaada7..a4f8e82 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,12 @@ web = [ "fastapi>=0.110", "uvicorn>=0.29", "python-multipart>=0.0.9", # FastAPI's form/upload parsing + "python-dateutil>=2.8", # recurrence rules + "icalendar>=5.0", + "recurring-ical-events>=2.1", # expands recurring calendar events + "feedparser>=6.0", + "astral>=3.2", # sunrise/sunset + "tzdata", # zoneinfo data where the OS has none (slim images) ] dev = [ "pytest>=8.0", @@ -29,6 +35,12 @@ dev = [ "uvicorn>=0.29", # imported by receipt_web.serve(), which the tests call "python-multipart>=0.0.9", "httpx>=0.27", # FastAPI's TestClient + "python-dateutil>=2.8", # recurrence rules + "icalendar>=5.0", + "recurring-ical-events>=2.1", # expands recurring calendar events + "feedparser>=6.0", + "astral>=3.2", # sunrise/sunset + "tzdata", # zoneinfo data where the OS has none (slim images) ] [project.scripts] @@ -39,7 +51,10 @@ requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [tool.setuptools] -py-modules = ["receipt", "receipt_tui", "receipt_web"] +py-modules = [ + "receipt", "receipt_tui", "receipt_web", "receipt_store", "receipt_models", + "receipt_sources", "receipt_triggers", "receipt_content", "receipt_scheduler", +] [tool.ruff] line-length = 100 diff --git a/receipt.py b/receipt.py index 64ffd8d..4929827 100755 --- a/receipt.py +++ b/receipt.py @@ -12,8 +12,8 @@ import random import subprocess import sys import textwrap -from collections.abc import Callable -from dataclasses import dataclass +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import BinaryIO @@ -54,6 +54,8 @@ PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi TEXT_COLUMNS = 48 # font A columns on 80mm paper TEXT_SIZES = (1, 2, 3) # note character magnifications; columns shrink to match LINE_HEIGHT_DOTS = 30 # default line spacing (3.75 mm) at size 1 +DOTS_PER_MM = 8 # 203 dpi +QR_MODULE_DOTS = 8 # the largest module size that reliably fits 576px with quiet zones MAX_PRINT_HEIGHT_DOTS = 8000 # about 1 m of paper; longer jobs are shrunk or refused HTTP_TIMEOUT = 15 # seconds MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image @@ -80,6 +82,10 @@ class PrinterUnavailable(Exception): """The printer couldn't be reached, or the link dropped during a job.""" +class PrinterDropped(PrinterUnavailable): + """The link dropped after a job's bytes started going out; never retry it.""" + + @dataclass(frozen=True) class PrinterConfig: """How to reach the printer; built from the CLI's global options.""" @@ -181,7 +187,7 @@ def send(config: PrinterConfig, payload: bytes) -> None: try: p._raw(payload) # escpos's raw-write hook; the payload is already complete ESC/POS except (OSError, escpos_exceptions.Error) as e: - raise PrinterUnavailable( + raise PrinterDropped( f"the link to {config.target} dropped mid-job, so it may have printed partially ({e})" ) from e finally: @@ -200,13 +206,15 @@ def render(build: Callable[[printer.Escpos], None]) -> bytes: return job.output -def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image: +def prepare_for_print( + img_path: Path | BinaryIO, max_height: int = MAX_PRINT_HEIGHT_DOTS +) -> Image.Image: """Load an image resized to full printer width and dithered for thermal output. Transparency is composited onto white (thermal paper), then the image is autocontrast-stretched and Floyd-Steinberg dithered to 1-bit. An image that - would print taller than MAX_PRINT_HEIGHT_DOTS is shrunk to that height and - centered instead. + would print taller than max_height is shrunk to that height and centered + instead. """ with Image.open(img_path) as img: img.load() # DecompressionBombError and truncated files surface here, inside `with` @@ -217,9 +225,9 @@ def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image: width, height = img.size new_width = PRINT_WIDTH_PX new_height = max(1, round(PRINT_WIDTH_PX * height / width)) - if new_height > MAX_PRINT_HEIGHT_DOTS: - new_width = max(1, round(MAX_PRINT_HEIGHT_DOTS * width / height)) - new_height = MAX_PRINT_HEIGHT_DOTS + if new_height > max_height: + new_width = max(1, round(max_height * width / height)) + new_height = max_height resized = img.resize((new_width, new_height), Image.LANCZOS) gray = ImageOps.autocontrast(resized.convert("L")) if new_width < PRINT_WIDTH_PX: @@ -237,7 +245,26 @@ def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str: return "\n".join(lines) -def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes: +@dataclass +class Block: + """One piece of a receipt: the paper it takes, its ESC/POS, and what it looks like. + + parts describe the block for previews: {"text", "size", "bold", "center"} + dicts and {"image": PIL.Image} dicts, top to bottom. + """ + + height: int # dots + build: Callable[[printer.Escpos], None] + parts: list[dict] = field(default_factory=list) + + +def text_block( + text: str, + size: int = 1, + timestamp: bool = False, + bold: bool = False, + center: bool = False, +) -> Block: if not text.strip(): raise InvalidJob("Nothing to print.") lines = wrap_text(text, TEXT_COLUMNS // size).split("\n") @@ -247,43 +274,129 @@ def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes: raise InvalidJob( f"Note is too long: {len(lines)} lines at size {size}, the limit is {max_lines}." ) + header = [datetime.now().strftime("%Y-%m-%d %H:%M"), "-" * TEXT_COLUMNS] if timestamp else [] def build(p: printer.Escpos) -> None: - if timestamp: - p.textln(datetime.now().strftime("%Y-%m-%d %H:%M")) - p.textln("-" * TEXT_COLUMNS) + for line in header: + p.textln(line) if size > 1: p.set(custom_size=True, width=size, height=size) + if bold or center: + p.set(bold=bold or None, align="center" if center else None) p.textln("\n".join(lines)) + # Leave the defaults for whatever block comes next. + if bold or center: + p.set(bold=False if bold else None, align="left" if center else None) + if size > 1: + p.set(normal_textsize=True) + + parts = [{"text": "\n".join(header), "size": 1}] if header else [] + parts.append({"text": "\n".join(lines), "size": size, "bold": bold, "center": center}) + return Block((len(lines) * size + header_lines) * LINE_HEIGHT_DOTS, build, parts) + + +def _caption_lines(caption: str | None) -> list[str]: + return wrap_text(caption).split("\n") if caption else [] + + +def image_block(source: Path | BinaryIO | Image.Image, caption: str | None = None) -> Block: + """A full-width dithered image; a prepared 1-bit image is used as it is.""" + lines = _caption_lines(caption) + caption_dots = len(lines) * LINE_HEIGHT_DOTS + if isinstance(source, Image.Image): + prepared = source + else: + try: + prepared = prepare_for_print(source, MAX_PRINT_HEIGHT_DOTS - caption_dots) + except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as e: + raise InvalidJob(f"Not a printable image: {e}") from e + + def build(p: printer.Escpos) -> None: + if lines: + p.textln("\n".join(lines)) + p.image(prepared, impl="bitImageColumn") + + parts = [{"text": "\n".join(lines), "size": 1}] if lines else [] + parts.append({"image": prepared}) + return Block(caption_dots + prepared.height, build, parts) + + +def qr_image(content: str) -> Image.Image: + """The QR code exactly as escpos rasterizes it (module size 8, one-module border).""" + import qrcode # escpos's own dependency for non-native QR + + code = qrcode.QRCode( + version=None, + box_size=QR_MODULE_DOTS, + border=1, + error_correction=qrcode.constants.ERROR_CORRECT_L, + ) + code.add_data(content) + try: + code.make(fit=True) + except ValueError as e: # qrcode's DataOverflowError + raise InvalidJob(f"Too much to fit in a QR code: {e}") from e + return code.make_image()._img.convert("1") + + +def qr_block(content: str, caption: str | None = None) -> Block: + if not content: + raise InvalidJob("Nothing to encode.") + img = qr_image(content) + if img.width > PRINT_WIDTH_PX: + raise InvalidJob( + f"Too much to fit in a QR code: {len(content)} characters make it wider than the paper." + ) + lines = _caption_lines(caption) + + def build(p: printer.Escpos) -> None: + if lines: + p.textln("\n".join(lines)) + p.qr(content, size=QR_MODULE_DOTS, center=True) + + parts = [{"text": "\n".join(lines), "size": 1}] if lines else [] + parts.append({"image": img}) + # escpos prints a blank line above the code and two below it. + return Block((len(lines) + 3) * LINE_HEIGHT_DOTS + img.height, build, parts) + + +def divider_block() -> Block: + rule = "-" * TEXT_COLUMNS + return Block(LINE_HEIGHT_DOTS, lambda p: p.textln(rule), [{"text": rule, "size": 1}]) + + +def receipt_height(blocks: Sequence[Block]) -> int: + return sum(b.height for b in blocks) + + +def render_blocks(blocks: Sequence[Block]) -> bytes: + """Render blocks as one job, refusing one longer than MAX_PRINT_HEIGHT_DOTS.""" + if not blocks: + raise InvalidJob("Nothing to print.") + height = receipt_height(blocks) + if height > MAX_PRINT_HEIGHT_DOTS: + raise InvalidJob( + f"Receipt is too long: about {height // DOTS_PER_MM} mm, " + f"the limit is {MAX_PRINT_HEIGHT_DOTS // DOTS_PER_MM} mm." + ) + + def build(p: printer.Escpos) -> None: + for block in blocks: + block.build(p) return render(build) +def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes: + return render_blocks([text_block(text, size, timestamp)]) + + def render_image(source: Path | BinaryIO, caption: str | None = None) -> bytes: - try: - prepared = prepare_for_print(source) - except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as e: - raise InvalidJob(f"Not a printable image: {e}") from e - - def build(p: printer.Escpos) -> None: - if caption: - p.textln(wrap_text(caption)) - p.image(prepared, impl="bitImageColumn") - - return render(build) + return render_blocks([image_block(source, caption)]) def render_qr(content: str, caption: str | None = None) -> bytes: - if not content: - raise InvalidJob("Nothing to encode.") - - def build(p: printer.Escpos) -> None: - if caption: - p.textln(wrap_text(caption)) - # Size 8 is the largest module size that reliably fits 576px with quiet zones. - p.qr(content, size=8, center=True) - - return render(build) + return render_blocks([qr_block(content, caption)]) def _printable(thread: dict) -> bool: @@ -301,6 +414,25 @@ def _printable(thread: dict) -> bool: ) +def fetch_capped(url: str, max_bytes: int, headers: dict | None = None) -> bytes | None: + """GET a URL into memory; None if the body is over max_bytes. + + The body is streamed so the cap fires before a huge response is fully in + memory. HTTP errors raise requests exceptions. + """ + extra = {"headers": headers} if headers else {} + with requests.get(url, timeout=HTTP_TIMEOUT, stream=True, **extra) as response: + response.raise_for_status() + buf = io.BytesIO() + size = 0 + for chunk in response.iter_content(64 * 1024): + size += len(chunk) + if size > max_bytes: + return None + buf.write(chunk) + return buf.getvalue() + + def download_random_bant_image() -> Path | None: """Download a random OP image from 4chan's /bant/ catalog. @@ -324,26 +456,14 @@ def download_random_bant_image() -> Path | None: if dest.is_file(): return dest - image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=ext) - # Stream the body: the cap must fire before a huge response is fully in memory. - with requests.get(image_url, timeout=HTTP_TIMEOUT, stream=True) as img_response: - img_response.raise_for_status() - buf = io.BytesIO() - size = 0 - oversize = False - for chunk in img_response.iter_content(64 * 1024): - size += len(chunk) - if size > MAX_IMAGE_BYTES: - oversize = True - break - buf.write(chunk) - if oversize: + data = fetch_capped(BANT_IMAGE_URL.format(tim=thread["tim"], ext=ext), MAX_IMAGE_BYTES) + if data is None: print( f"Skipping {dest.name}: exceeds the {MAX_IMAGE_BYTES // 1024} KB cap.", file=sys.stderr, ) return None - dest.write_bytes(buf.getvalue()) + dest.write_bytes(data) return dest diff --git a/receipt_content.py b/receipt_content.py new file mode 100644 index 0000000..2e5ce2e --- /dev/null +++ b/receipt_content.py @@ -0,0 +1,372 @@ +"""Turning a schedule's blocks into printable receipt blocks, fresh each time it fires. + +Text goes through fill(), a whitelist substitution of {name} / {name:format} +tokens. It never uses str.format on user text, which would allow attribute +access ({x.__class__}). Unknown names stay as typed and come back as warnings. +""" + +from __future__ import annotations + +import datetime as dt +import io +import json +import random +import re +import textwrap +from dataclasses import dataclass, field +from typing import Any + +import requests + +import receipt +import receipt_models as models +from receipt_sources import ( + CALENDAR_MAX_AGE, + FEED_MAX_AGE, + Event, + Item, + SourceCache, + SourceError, + parse_events, + parse_items, +) +from receipt_store import Store + +TOKEN = re.compile( + r"\{\{|\}\}|\{([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)*)(?::([^{}\n]{1,60}))?\}" +) +NAMESPACES = ("event", "item", "payload") # missing keys in these print as nothing +MAX_VALUE_CHARS = 2000 +MAX_SEEN = 500 +MAX_AGENDA_EVENTS = 40 +COLUMNS = receipt.TEXT_COLUMNS + +# Shown in the editor's variable picker. +VARIABLES = { + "common": ["date", "time", "weekday", "days_until:12-25", "name"], + "note": ["choice"], + "calendar": ["event.title", "event.start", "event.end", "event.date", "event.location", + "event.minutes"], + "watch_rss": ["item.title", "item.link", "item.summary", "item.source"], + "watch_json": ["value", "old_value"], + "webhook": ["payload.text", "payload.title"], +} + + +class _Unknown(Exception): + pass + + +def event_vars(event: Event, now: dt.datetime) -> dict[str, Any]: + return { + "title": event.title, + "start": event.start, + "end": event.end, + "date": event.start.date(), + "location": event.location, + "description": event.description, + "minutes": max(0, round((event.start - now).total_seconds() / 60)), + "all_day": "yes" if event.all_day else "", + } + + +def item_vars(item: Item) -> dict[str, Any]: + return {"title": item.title, "link": item.link, "summary": item.summary, + "source": item.source} + + +def _days_until(arg: str | None, today: dt.date) -> int: + if not arg: + raise _Unknown + try: + if re.fullmatch(r"\d{4}-\d{2}-\d{2}", arg): + target = dt.date.fromisoformat(arg) + elif re.fullmatch(r"\d{2}-\d{2}", arg): # yearly: the next one + month, day = map(int, arg.split("-")) + target = dt.date(today.year, month, day) + if target < today: + target = target.replace(year=today.year + 1) + else: + raise _Unknown + except ValueError: + raise _Unknown from None + return (target - today).days + + +def _show(value: Any, fmt: str | None, default_fmt: str) -> str: + if isinstance(value, (dt.datetime, dt.date)): + return value.strftime(fmt or default_fmt) + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, (dict, list)): + value = json.dumps(value, ensure_ascii=False) + return "" if value is None else str(value)[:MAX_VALUE_CHARS] + + +def fill(text: str, now: dt.datetime, values: dict[str, Any], warnings: list[str]) -> str: + """Substitute {name} tokens; {{ and }} are literal braces.""" + + def resolve(name: str, arg: str | None) -> str: + if name == "date": + return now.strftime(arg or "%a %d %b %Y") + if name == "time": + return now.strftime(arg or "%H:%M") + if name == "weekday": + return now.strftime("%A") + if name == "days_until": + return str(_days_until(arg, now.date())) + head, _, rest = name.partition(".") + if head in NAMESPACES and rest: + value: Any = values.get(head) or {} + for part in rest.split("."): + if isinstance(value, dict): + value = value.get(part) + elif isinstance(value, list) and part.isdigit() and int(part) < len(value): + value = value[int(part)] + else: + value = None + default = "%a %d %b" if rest == "date" else "%H:%M" + return _show(value, arg, default) + if not rest and name in values: + return _show(values[name], arg, "%H:%M") + raise _Unknown + + def replace(match: re.Match) -> str: + token = match.group(0) + if token in ("{{", "}}"): + return token[0] + try: + return resolve(match.group(1), match.group(2)) + except _Unknown: + warnings.append(f"Unknown variable {token}") + return token + + return TOKEN.sub(replace, text) + + +@dataclass +class Built: + blocks: list[receipt.Block] = field(default_factory=list) + empty: bool = False # it has agenda/headline blocks and all of them came up empty + warnings: list[str] = field(default_factory=list) + state: dict[str, Any] = field(default_factory=dict) # trigger_state to save if it prints + + +class ReceiptBuilder: + """Builds one receipt. preview=True avoids side effects (random downloads) only.""" + + def __init__( + self, + store: Store, + cache: SourceCache, + settings: models.Settings, + now: dt.datetime, + schedule_id: str | None = None, + name: str = "", + preview: bool = False, + ): + self.store = store + self.cache = cache + self.settings = settings + self.now = now.astimezone(settings.tz) + self.schedule_id = schedule_id + self.name = name + self.preview = preview + + def _state(self, key: str, default): + if self.schedule_id is None: + return default + return self.store.state(self.schedule_id, key, default) + + def build(self, blocks: list, values: dict[str, Any] | None = None) -> Built: + built = Built() + values = {"name": self.name, **(values or {})} + dynamic = [] + for index, block in enumerate(blocks): + method = getattr(self, f"_{block.type}") + empty = method(index, block, values, built) + if block.type in models.DYNAMIC_BLOCKS: + dynamic.append(empty) + built.empty = bool(dynamic) and all(dynamic) + return built + + def fill(self, text: str, values: dict[str, Any], built: Built) -> str: + return fill(text, self.now, values, built.warnings) + + # Each block method appends receipt blocks and returns whether it came up empty. + + def _note(self, index: int, block: models.NoteBlock, values: dict, built: Built) -> bool: + if block.choices: + key = f"choice:{index}" + if block.pick == "random": + choice = random.choice(block.choices) # noqa: S311 - not a security decision + else: + position = self._state(key, 0) + choice = block.choices[position % len(block.choices)] + built.state[key] = (position + 1) % len(block.choices) + values = {**values, "choice": choice} + text = block.text if block.text.strip() else "{choice}" + text = self.fill(text, values, built).strip("\n") + if text.strip(): + built.blocks.append( + receipt.text_block(text, block.size, block.timestamp, block.bold, block.center) + ) + return not text.strip() + + def _qr(self, index: int, block: models.QrBlock, values: dict, built: Built) -> bool: + content = self.fill(block.content, values, built).strip() + if content: + caption = self.fill(block.caption, values, built).strip() or None + built.blocks.append(receipt.qr_block(content, caption)) + return not content + + def _image(self, index: int, block: models.ImageBlock, values: dict, built: Built) -> bool: + data = self.store.asset(block.asset_id) + if data is None: + raise receipt.InvalidJob("The image this receipt prints has been deleted.") + caption = self.fill(block.caption, values, built).strip() or None + built.blocks.append(receipt.image_block(io.BytesIO(data), caption)) + return False + + def _random_image(self, index: int, block, values: dict, built: Built) -> bool: + if self.preview: + built.blocks.append(receipt.text_block("[a random /bant/ image]", center=True)) + return False + try: + path = receipt.download_random_bant_image() + except requests.RequestException as e: + path = None + built.warnings.append(f"Random image: download failed ({e})") + if path is None: + built.blocks.append(receipt.text_block("(couldn't fetch a random image)")) + return False + built.blocks.append(receipt.image_block(path, caption=path.stem)) + return False + + def _divider(self, index: int, block, values: dict, built: Built) -> bool: + built.blocks.append(receipt.divider_block()) + return False + + def _sources(self, ids: list[str], kind: str, built: Built) -> list[dict]: + found = [] + for source_id in ids: + source = self.store.source(source_id) + if source is None or source["kind"] != kind: + built.warnings.append("A saved source this receipt reads has been deleted.") + continue + found.append(source) + return found + + def _agenda(self, index: int, block: models.AgendaBlock, values: dict, built: Built) -> bool: + tz = self.settings.tz + first = self.now.date() + dt.timedelta(days=block.start_day) + start = dt.datetime.combine(first, dt.time(), tz) + end = dt.datetime.combine(first + dt.timedelta(days=block.days), dt.time(), tz) + events: list[Event] = [] + errors = [] + for source in self._sources(block.source_ids, "ics", built): + try: + data = self.cache.get(source["url"], CALENDAR_MAX_AGE) + events.extend(parse_events(data, start, end, tz)) + except SourceError as e: + errors.append(f"(couldn't load {source['name']}: {e})") + built.warnings.append(f"{source['name']}: {e}") + if not block.include_all_day: + events = [e for e in events if not e.all_day] + events.sort(key=lambda e: (e.start, not e.all_day, e.title)) + + heading = block.title.strip() or _agenda_title(block.start_day, block.days) + built.blocks.append(receipt.text_block(heading.upper(), bold=True)) + lines: list[str] = [] + shown = 0 + for offset in range(block.days): + day = first + dt.timedelta(days=offset) + day_start = dt.datetime.combine(day, dt.time(), tz) + day_end = day_start + dt.timedelta(days=1) + todays = [e for e in events if _on_day(e, day_start, day_end)] + if block.days > 1: + if lines: + lines.append("") + lines.append(day.strftime("%a %d %b")) + for event in todays: + if shown >= MAX_AGENDA_EVENTS: + break + lines.extend(_event_lines(event, day_start, day_end)) + shown += 1 + if block.days > 1 and not todays: + lines.append(" -") + more = len(events) - shown + if more > 0 and shown >= MAX_AGENDA_EVENTS: + lines.append(f"...and {more} more") + if not events: + lines.append("Nothing on.") + lines.extend(errors) + built.blocks.append(receipt.text_block("\n".join(lines))) + return not events + + def _headlines( + self, index: int, block: models.HeadlinesBlock, values: dict, built: Built + ) -> bool: + seen_key = f"seen:{index}" + seen = set(self._state(seen_key, [])) if block.only_new else set() + sources = self._sources(block.source_ids, "rss", built) + if block.title.strip(): + built.blocks.append(receipt.text_block(block.title.strip().upper(), bold=True)) + shown: list[Item] = [] + for source in sources: + try: + items = parse_items(self.cache.get(source["url"], FEED_MAX_AGE), source["name"]) + except SourceError as e: + built.blocks.append(receipt.text_block(f"(couldn't load {source['name']}: {e})")) + built.warnings.append(f"{source['name']}: {e}") + continue + fresh = [i for i in items if i.id not in seen][: block.count] + if not fresh: + continue + if len(sources) > 1 or not block.title.strip(): + built.blocks.append(receipt.text_block(source["name"], bold=True)) + text = "\n".join( + textwrap.fill(i.title, COLUMNS, initial_indent="* ", subsequent_indent=" ") + for i in fresh + ) + built.blocks.append(receipt.text_block(text)) + shown.extend(fresh) + if not shown: + built.blocks.append(receipt.text_block("No new headlines." if block.only_new + else "No headlines.")) + elif block.qr_first and shown[0].link: + built.blocks.append(receipt.qr_block(shown[0].link)) + if block.only_new and shown: + built.state[seen_key] = ([i.id for i in shown] + list(seen))[:MAX_SEEN] + return not shown + + +def _agenda_title(start_day: int, days: int) -> str: + if days == 1: + return {0: "Today", 1: "Tomorrow"}.get(start_day, f"In {start_day} days") + if start_day == 0: + return f"Next {days} days" + return f"{days} days from {'tomorrow' if start_day == 1 else f'in {start_day} days'}" + + +def _on_day(event: Event, day_start: dt.datetime, day_end: dt.datetime) -> bool: + if event.end <= event.start: # no duration + return day_start <= event.start < day_end + return event.start < day_end and event.end > day_start + + +def _event_lines(event: Event, day_start: dt.datetime, day_end: dt.datetime) -> list[str]: + if event.all_day: + label = "All day" + else: + begin = "" if event.start < day_start else event.start.strftime("%H:%M") + finish = "" if event.end >= day_end else event.end.strftime("%H:%M") + label = f"{begin}-{finish}" if finish and finish != begin else begin or "...-" + indent = " " * 13 + lines = textwrap.wrap( + event.title, COLUMNS, initial_indent=f"{label:<11} ", subsequent_indent=indent + ) or [label] + if event.location: + lines.extend(textwrap.wrap(f"@ {event.location}", COLUMNS, initial_indent=indent, + subsequent_indent=indent + " ")) + return lines diff --git a/receipt_models.py b/receipt_models.py new file mode 100644 index 0000000..603fbde --- /dev/null +++ b/receipt_models.py @@ -0,0 +1,282 @@ +"""Validated shapes for schedules, receipts and settings (web server only). + +A schedule is a trigger (when), blocks (what: one receipt, printed as one job) +and options (what to do about quiet hours, empty receipts, missed runs). +Specs are stored as the JSON of these models. +""" + +from __future__ import annotations + +import datetime as dt +from typing import Annotated, Literal +from urllib.parse import urlparse +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +import receipt + +MAX_NOTE_CHARS = 4000 +MAX_CAPTION_CHARS = 500 +MAX_BLOCKS = 20 +WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] # Monday first, like datetime.weekday() + + +class Model(BaseModel): + model_config = ConfigDict(extra="forbid") + + +def http_url(value: str) -> str: + value = value.strip() + parsed = urlparse(value) + if parsed.scheme not in ("http", "https") or not parsed.netloc: + raise ValueError("must be an http:// or https:// URL") + return value + + +def weekday_list(value: list[int]) -> list[int]: + if any(d not in WEEKDAYS for d in value): + raise ValueError("weekdays are 0 (Monday) to 6 (Sunday)") + return sorted(set(value)) + + +# --- triggers --- + + +class OnceTrigger(Model): + type: Literal["once"] + at: dt.datetime # wall-clock time in the settings timezone + + @field_validator("at") + @classmethod + def _naive(cls, value: dt.datetime) -> dt.datetime: + return value.replace(tzinfo=None, second=0, microsecond=0) + + +class RecurringTrigger(Model): + type: Literal["recurring"] + freq: Literal["daily", "weekly", "monthly", "yearly"] = "daily" + interval: int = Field(default=1, ge=1, le=365) + times: list[dt.time] = Field(min_length=1, max_length=24) + weekdays: list[int] = [] # daily: only these days; weekly: these days (default: start's) + monthday: int | None = Field(default=None, ge=-1, le=31) # -1 is the last day; not 0 + setpos: int | None = Field(default=None, ge=-1, le=5) # with weekdays: 1st..5th, -1 last + month: int | None = Field(default=None, ge=1, le=12) # yearly + start: dt.date | None = None # anchors the interval; filled in on save + until: dt.date | None = None + rrule: str | None = Field(default=None, max_length=500) # advanced: replaces freq..month + + @field_validator("weekdays") + @classmethod + def _weekdays(cls, value: list[int]) -> list[int]: + return weekday_list(value) + + @field_validator("times") + @classmethod + def _minutes(cls, value: list[dt.time]) -> list[dt.time]: + return sorted({t.replace(second=0, microsecond=0, tzinfo=None) for t in value}) + + @model_validator(mode="after") + def _consistent(self) -> RecurringTrigger: + if self.monthday == 0: + raise ValueError("monthday is 1-31, or -1 for the last day") + if self.setpos is not None and not self.weekdays: + raise ValueError("pick the weekday(s) for 'first/second/last …'") + if self.until and self.start and self.until < self.start: + raise ValueError("'until' is before the start date") + if self.rrule is not None and not self.rrule.strip(): + self.rrule = None + return self + + +class SunTrigger(Model): + type: Literal["sun"] + event: Literal["dawn", "sunrise", "noon", "sunset", "dusk"] = "sunrise" + offset_minutes: int = Field(default=0, ge=-720, le=720) + weekdays: list[int] = WEEKDAYS + + @field_validator("weekdays") + @classmethod + def _weekdays(cls, value: list[int]) -> list[int]: + return weekday_list(value) + + +class CalendarTrigger(Model): + type: Literal["calendar"] + source_id: str + minutes_before: int = Field(default=15, ge=0, le=7 * 24 * 60) + contains: str = Field(default="", max_length=200) # title filter, case-insensitive + include_all_day: bool = False + + +class WatchTrigger(Model): + type: Literal["watch"] + kind: Literal["rss", "json"] = "rss" + url: str = Field(max_length=2000) + path: str = Field(default="", max_length=200) # json: dotted path, e.g. "data.price" + condition: Literal["changed", "above", "below"] = "changed" + threshold: float | None = None + every_minutes: int = Field(default=30, ge=5, le=24 * 60) + max_items: int = Field(default=3, ge=1, le=10) # rss: new items per receipt + + @field_validator("url") + @classmethod + def _url(cls, value: str) -> str: + return http_url(value) + + @model_validator(mode="after") + def _json_needs(self) -> WatchTrigger: + if self.kind == "json" and self.condition != "changed" and self.threshold is None: + raise ValueError("set a threshold for 'above'/'below'") + return self + + +class WebhookTrigger(Model): + type: Literal["webhook"] + per_hour: int = Field(default=10, ge=1, le=120) + + +Trigger = Annotated[ + OnceTrigger | RecurringTrigger | SunTrigger | CalendarTrigger | WatchTrigger | WebhookTrigger, + Field(discriminator="type"), +] +TIMED = ("once", "recurring", "sun") # next_run_at is a fixed time +POLLED = ("calendar", "watch") # checked every tick / every few minutes + + +# --- receipt blocks --- + + +class NoteBlock(Model): + type: Literal["note"] + text: str = Field(default="", max_length=MAX_NOTE_CHARS) + size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES)) + timestamp: bool = False + bold: bool = False + center: bool = False + choices: list[Annotated[str, Field(max_length=1000)]] = Field(default=[], max_length=500) + pick: Literal["sequential", "random"] = "sequential" + + @model_validator(mode="after") + def _something(self) -> NoteBlock: + self.choices = [c for c in (c.strip() for c in self.choices) if c] + if not self.text.strip() and not self.choices: + raise ValueError("a note needs text or a list to pick from") + return self + + +class QrBlock(Model): + type: Literal["qr"] + content: str = Field(min_length=1, max_length=2000) + caption: str = Field(default="", max_length=MAX_CAPTION_CHARS) + + +class ImageBlock(Model): + type: Literal["image"] + asset_id: str + caption: str = Field(default="", max_length=MAX_CAPTION_CHARS) + + +class RandomImageBlock(Model): + type: Literal["random_image"] + + +class AgendaBlock(Model): + type: Literal["agenda"] + source_ids: list[str] = Field(min_length=1, max_length=10) + start_day: int = Field(default=0, ge=0, le=7) # 0 today, 1 tomorrow + days: int = Field(default=1, ge=1, le=7) + include_all_day: bool = True + title: str = Field(default="", max_length=100) + + +class HeadlinesBlock(Model): + type: Literal["headlines"] + source_ids: list[str] = Field(min_length=1, max_length=10) + count: int = Field(default=5, ge=1, le=20) + only_new: bool = False + qr_first: bool = False + title: str = Field(default="", max_length=100) + + +class DividerBlock(Model): + type: Literal["divider"] + + +Block = Annotated[ + NoteBlock | QrBlock | ImageBlock | RandomImageBlock | AgendaBlock | HeadlinesBlock + | DividerBlock, + Field(discriminator="type"), +] +DYNAMIC_BLOCKS = ("agenda", "headlines") # can come up empty + + +class Options(Model): + quiet: Literal["hold", "skip", "ignore"] = "hold" + skip_if_empty: bool = False + catch_up_minutes: int = Field(default=15, ge=0, le=24 * 60) + retries: int = Field(default=3, ge=0, le=10) + + +class ScheduleSpec(Model): + trigger: Trigger + blocks: list[Block] = Field(min_length=1, max_length=MAX_BLOCKS) + options: Options = Options() + + +class ScheduleIn(ScheduleSpec): + name: str = Field(min_length=1, max_length=100) + enabled: bool = True + + +# --- settings and sources --- + + +class Location(Model): + latitude: float = Field(ge=-90, le=90) + longitude: float = Field(ge=-180, le=180) + name: str = Field(default="", max_length=100) + + +class Settings(Model): + timezone: str = "Europe/London" + location: Location | None = None + quiet_start: dt.time | None = None + quiet_end: dt.time | None = None + daily_cap: int = Field(default=30, ge=0, le=1000) # automatic prints per day; 0 = no cap + paused: bool = False + paused_until: dt.date | None = None # resumes at the start of this day + + @field_validator("timezone") + @classmethod + def _zone(cls, value: str) -> str: + try: + ZoneInfo(value) + except (ZoneInfoNotFoundError, ValueError): + raise ValueError(f"unknown timezone {value!r}") from None + return value + + @model_validator(mode="after") + def _quiet_pair(self) -> Settings: + if (self.quiet_start is None) != (self.quiet_end is None): + raise ValueError("quiet hours need both a start and an end") + return self + + @property + def tz(self) -> ZoneInfo: + return ZoneInfo(self.timezone) + + +class SourceIn(Model): + name: str = Field(min_length=1, max_length=100) + kind: Literal["ics", "rss"] + url: str = Field(max_length=2000) + + @field_validator("url") + @classmethod + def _url(cls, value: str) -> str: + # Calendar apps hand out webcal:// links for the same https feed. + value = value.strip() + if value.startswith("webcal://"): + value = "https://" + value.removeprefix("webcal://") + return http_url(value) diff --git a/receipt_scheduler.py b/receipt_scheduler.py new file mode 100644 index 0000000..50dcc82 --- /dev/null +++ b/receipt_scheduler.py @@ -0,0 +1,609 @@ +"""Fires schedules: timed ones at their next_run_at, polled ones (calendar, watch) every tick. + +tick(now) does one pass and is what the tests drive with a fake clock; the +thread just calls it, then sleeps until the next due time (at most a minute) +or until wake(). A fire renders the receipt here and hands the bytes to the +print queue, so a slow feed never holds the printer. + +Rules for automatic prints (manual prints and test prints skip all of them): +paused -> skipped; quiet hours -> held to their end, skipped, or ignored per +schedule; over the daily cap -> skipped. A due time missed by more than the +catch-up window (server down) is logged as missed, never replayed. A job +that couldn't connect is retried; one that dropped mid-job is not. +""" + +from __future__ import annotations + +import contextlib +import datetime as dt +import logging +import threading +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Protocol +from urllib.parse import urlparse + +from pydantic import ValidationError + +import receipt +import receipt_models as models +from receipt_content import Built, ReceiptBuilder, event_vars, item_vars +from receipt_sources import ( + CALENDAR_MAX_AGE, + FEED_MAX_AGE, + Event, + Item, + SourceCache, + SourceError, + json_value, + parse_events, + parse_items, +) +from receipt_store import UTC, Store, iso, parse_iso, utcnow +from receipt_triggers import ( + CALENDAR_LOOKAHEAD, + TriggerError, + calendar_fires, + next_fire, + upcoming, +) + +log = logging.getLogger("receipt_web.scheduler") + +AUTO_SOURCES = ("schedule", "calendar", "watch", "webhook") +PRINTED_STATES = ("queued", "printing", "done") +RETRY_DELAY = dt.timedelta(minutes=5) +TICK_SLACK = dt.timedelta(minutes=2) # a tick can run a little after a due time +MAX_SLEEP = 60.0 +MAX_SEEN = 500 +FIRED_MEMORY = dt.timedelta(days=3) # how long fired calendar reminders are remembered + + +class QueueFull(Exception): + """The print queue has no room; a scheduled job tries again next tick.""" + + +class RateLimited(Exception): + """A webhook was called more often than its schedule allows.""" + + +class Jobs(Protocol): + def submit( + self, kind: str, payload: bytes, user: str | None, *, source: str = "manual", + schedule_id: str | None = None, name: str | None = None, + ) -> Any: ... + + +@dataclass +class Pending: + """A queued scheduled job, remembered so a failed connect can be retried.""" + + schedule_id: str + name: str + source: str + payload: bytes + attempt: int + retries: int + at: dt.datetime | None = None # when to retry + + +@dataclass +class Gate: + action: str # "go", "hold" or "skip" + reason: str = "" + until: dt.datetime | None = None + + +def load_settings(store: Store) -> models.Settings: + try: + return models.Settings.model_validate(store.settings()) + except ValidationError: + log.warning("stored settings are invalid; using defaults") + return models.Settings() + + +class Scheduler: + def __init__( + self, + store: Store, + jobs: Jobs, + clock: Callable[[], dt.datetime] = utcnow, + cache: SourceCache | None = None, + ): + self.store = store + self.jobs = jobs + self.clock = clock + self.cache = cache or SourceCache() + self._lock = threading.RLock() # one tick or fire at a time + self._wake = threading.Event() + self._pending: dict[str, Pending] = {} # job id -> its schedule + self._retries: list[Pending] = [] + + # --- thread --- + + def start(self) -> None: + threading.Thread(target=self._run, name="scheduler", daemon=True).start() + + def wake(self) -> None: + self._wake.set() + + def _run(self) -> None: + while True: + try: + self.tick() + except Exception: + log.exception("scheduler tick failed") + self._wake.wait(self.seconds_to_sleep()) + self._wake.clear() + + def seconds_to_sleep(self) -> float: + now = self.clock() + times = [r.at for r in self._retries if r.at] + for row in self.store.schedules(): + due = parse_iso(row["next_run_at"]) + if row["enabled"] and due: + times.append(due) + if not times: + return MAX_SLEEP + return max(1.0, min(MAX_SLEEP, (min(times) - now).total_seconds() + 0.5)) + + # --- helpers --- + + def settings(self) -> models.Settings: + return load_settings(self.store) + + def _status(self, row: dict, status: str, message: str, ran: dt.datetime | None = None): + fields = {"last_status": status, "last_message": message} + if ran is not None: + fields["last_run_at"] = iso(ran) + self.store.update_schedule(row["id"], **fields) + + def _record(self, row: dict, source: str, state: str, message: str, now: dt.datetime): + """History entry for something that didn't reach the printer.""" + self.store.add_run( + "schedule", source, state, schedule_id=row["id"], name=row["name"], message=message, + error=state if state == "failed" else None, created_at=now, + ) + self._status(row, state, message, now) + log.info("schedule %s (%s): %s - %s", row["id"], row["name"], state, message) + + def gate(self, spec: models.ScheduleSpec, now: dt.datetime, settings: models.Settings) -> Gate: + tz = settings.tz + local = now.astimezone(tz) + resumed = settings.paused_until is not None and local.date() >= settings.paused_until + if settings.paused and not resumed: + until = f" until {settings.paused_until:%d %b}" if settings.paused_until else "" + return Gate("skip", f"Automatic printing is paused{until}.") + if settings.quiet_start is not None and spec.options.quiet != "ignore": + end = quiet_end(local, settings.quiet_start, settings.quiet_end) + if end is not None: + if spec.options.quiet == "hold": + return Gate("hold", "Quiet hours", end) + return Gate("skip", "Skipped during quiet hours.") + if settings.daily_cap: + midnight = dt.datetime.combine(local.date(), dt.time(), tz) + printed = self.store.count_runs(midnight, AUTO_SOURCES, PRINTED_STATES) + if printed >= settings.daily_cap: + return Gate("skip", f"Today's limit of {settings.daily_cap} automatic prints " + "was reached.") + return Gate("go") + + def build( + self, + row: dict, + spec: models.ScheduleSpec, + now: dt.datetime, + settings: models.Settings, + value_sets: list[dict] | None = None, + preview: bool = False, + ) -> Built: + """The receipt; with several value sets (new feed items) the blocks repeat per set.""" + builder = ReceiptBuilder(self.store, self.cache, settings, now, row.get("id"), + row.get("name", ""), preview=preview) + sets = value_sets or [{}] + combined = Built() + for i, values in enumerate(sets): + built = builder.build(spec.blocks, values) + if i: + combined.blocks.append(receipt.divider_block()) + combined.blocks.extend(built.blocks) + combined.warnings.extend(w for w in built.warnings if w not in combined.warnings) + combined.state.update(built.state) + combined.empty = built.empty if i == 0 else combined.empty and built.empty + return combined + + def fire( + self, + row: dict, + spec: models.ScheduleSpec, + now: dt.datetime, + settings: models.Settings, + source: str = "schedule", + value_sets: list[dict] | None = None, + test: bool = False, + extra: list[receipt.Block] | None = None, + ): + """Render and queue the receipt. Returns the job, or None if it was skipped as empty. + + Raises QueueFull, and InvalidJob when the receipt can't be printed. + """ + built = self.build(row, spec, now, settings, value_sets) + if built.empty and spec.options.skip_if_empty and not test: + self._record(row, source, "skipped", "Nothing to print today.", now) + return None + try: + payload = receipt.render_blocks(built.blocks + (extra or [])) + except receipt.InvalidJob as e: + if not test: + self._record(row, source, "failed", str(e), now) + raise + job = self.jobs.submit( + "schedule", payload, f"schedule:{row['name']}", source="test" if test else source, + schedule_id=row["id"], name=row["name"], + ) + if not test: + for key, value in built.state.items(): + self.store.set_state(row["id"], key, value) + with self._lock: + self._pending[job.id] = Pending(row["id"], row["name"], source, payload, 0, + 0 if test else spec.options.retries) + self._status(row, "queued", "Queued.", now) + return job + + def _fire_auto(self, *args, **kwargs) -> None: + """fire() for automatic runs: an unprintable receipt is already in the history.""" + with contextlib.suppress(receipt.InvalidJob): + self.fire(*args, **kwargs) + + def job_finished(self, job) -> None: + """Called by the print queue when any job finishes; retries failed connects.""" + with self._lock: + pending = self._pending.pop(job.id, None) + if pending is None: + return + row = self.store.schedule(pending.schedule_id) + if row is None: + return + if job.state == "done": + self._status(row, "done", "Printed.") + elif job.error == "unavailable" and pending.attempt < pending.retries: + pending.attempt += 1 + pending.at = self.clock() + RETRY_DELAY + with self._lock: + self._retries.append(pending) + self._status(row, "retrying", f"{job.message} Trying again in 5 min " + f"(retry {pending.attempt} of {pending.retries}).") + self.wake() + else: + self._status(row, "failed", job.message) + + # --- the tick --- + + def tick(self, now: dt.datetime | None = None) -> None: + now = now or self.clock() + settings = self.settings() + with self._lock: + self._run_retries(now) + for row in self.store.schedules(): + if not row["enabled"]: + continue + try: + spec = models.ScheduleSpec.model_validate(row["spec"]) + except ValidationError: + self._status(row, "error", "This schedule is invalid; edit and save it.") + continue + kind = spec.trigger.type + try: + if kind in models.TIMED: + self._tick_timed(row, spec, now, settings) + elif kind == "calendar": + self._tick_calendar(row, spec, now, settings) + elif kind == "watch": + self._tick_watch(row, spec, now, settings) + except QueueFull: + log.info("schedule %s: print queue full; trying next tick", row["id"]) + except (SourceError, TriggerError) as e: + self._status(row, "error", str(e)) + except receipt.InvalidJob: + pass # recorded by fire() + except Exception as e: + log.exception("schedule %s failed", row["id"]) + self._status(row, "error", f"Error: {e}") + + def _run_retries(self, now: dt.datetime) -> None: + for retry in [r for r in self._retries if r.at and r.at <= now]: + try: + job = self.jobs.submit("schedule", retry.payload, f"schedule:{retry.name}", + source=retry.source, schedule_id=retry.schedule_id, + name=retry.name) + except QueueFull: + continue + self._retries.remove(retry) + retry.at = None + self._pending[job.id] = retry + + def _advance(self, row: dict, spec: models.ScheduleSpec, now: dt.datetime, + settings: models.Settings) -> None: + following = next_fire(spec.trigger, now, settings) + fields: dict = {"next_run_at": iso(following)} + if following is None and spec.trigger.type == "once": + fields["enabled"] = False + self.store.update_schedule(row["id"], **fields) + + def _tick_timed(self, row, spec, now, settings) -> None: + due = parse_iso(row["next_run_at"]) + if due is None: + if row["last_status"] is None: # never scheduled (saved without a next run) + self._advance(row, spec, now, settings) + return + if now < due: + return + catch_up = dt.timedelta(minutes=spec.options.catch_up_minutes) + TICK_SLACK + if now - due > catch_up: + due_local = due.astimezone(settings.tz) + self._record(row, "schedule", "missed", + f"Missed {due_local:%a %d %b %H:%M}: the server wasn't running.", now) + self._advance(row, spec, now, settings) + return + gate = self.gate(spec, now, settings) + if gate.action == "hold": + self.store.update_schedule(row["id"], next_run_at=iso(gate.until)) + until = gate.until.astimezone(settings.tz) + self._status(row, "held", f"Held for quiet hours until {until:%H:%M}.") + return + if gate.action == "skip": + self._record(row, "schedule", "skipped", gate.reason, now) + else: + self._fire_auto(row, spec, now, settings) + self._advance(row, spec, now, settings) + + def calendar_events(self, trigger: models.CalendarTrigger, start: dt.datetime, + end: dt.datetime, settings: models.Settings) -> list[Event]: + source = self.store.source(trigger.source_id) + if source is None: + raise SourceError("its calendar has been deleted") + try: + data = self.cache.get(source["url"], CALENDAR_MAX_AGE) + return parse_events(data, start, end, settings.tz) + except SourceError as e: + raise SourceError(f"{source['name']}: {e}") from None + + def _tick_calendar(self, row, spec, now, settings) -> None: + trigger: models.CalendarTrigger = spec.trigger + catch_up = dt.timedelta(minutes=spec.options.catch_up_minutes) + TICK_SLACK + lead = dt.timedelta(minutes=trigger.minutes_before) + events = self.calendar_events(trigger, now - catch_up + lead - dt.timedelta(days=1), + now + lead + CALENDAR_LOOKAHEAD, settings) + fired: dict[str, str] = self.store.state(row["id"], "fired", {}) + following = None + try: + for at, event in calendar_fires(trigger, events): + if at > now: + following = at + break + if at < now - catch_up or event.key in fired: + continue + gate = self.gate(spec, now, settings) + if gate.action != "go": # a reminder held past its event is no use + reason = gate.reason if gate.action == "skip" else "Skipped during quiet hours." + self._record(row, "calendar", "skipped", f"{event.title}: {reason}", now) + else: + self._fire_auto(row, spec, now, settings, "calendar", + [{"event": event_vars(event, now)}]) + fired[event.key] = iso(at) + finally: + forget = now - FIRED_MEMORY + fired = {k: v for k, v in fired.items() if parse_iso(v) > forget} + self.store.set_state(row["id"], "fired", fired) + self.store.update_schedule(row["id"], next_run_at=iso(following)) + if row["last_status"] in (None, "error"): + self._status(row, "watching", "Watching the calendar.") + + def _tick_watch(self, row, spec, now, settings) -> None: + trigger: models.WatchTrigger = spec.trigger + due = parse_iso(row["next_run_at"]) + if due is not None and now < due: + return + self.store.update_schedule( + row["id"], next_run_at=iso(now + dt.timedelta(minutes=trigger.every_minutes)) + ) + try: + data = self.cache.get(trigger.url, max(60, trigger.every_minutes * 60 - 60)) + found = parse_items(data) if trigger.kind == "rss" else json_value(data, trigger.path) + except SourceError as e: + raise SourceError(f"{urlparse(trigger.url).netloc}: {e}") from None + if trigger.kind == "rss": + self._watch_feed(row, spec, now, settings, found) + else: + self._watch_value(row, spec, now, settings, found) + + def _watch_feed(self, row, spec, now, settings, items: list[Item]) -> None: + seen = self.store.state(row["id"], "seen") + ids = [i.id for i in items] + if seen is None: # first look: remember what's there, print nothing + self.store.set_state(row["id"], "seen", ids[:MAX_SEEN]) + self._status(row, "watching", f"Watching: {len(items)} items so far.") + return + fresh = [i for i in items if i.id not in set(seen)] + if not fresh: + if row["last_status"] in ("error", None): + self._status(row, "watching", "Watching: nothing new.") + return + gate = self.gate(spec, now, settings) + if gate.action == "hold": + return # left unseen, so the next poll after quiet hours prints them + if gate.action == "skip": + self._record(row, "watch", "skipped", f"{len(fresh)} new: {gate.reason}", now) + else: + shown = fresh[: spec.trigger.max_items] + extra = [] + if len(fresh) > len(shown): + extra = [receipt.text_block(f"...and {len(fresh) - len(shown)} more new items")] + self._fire_auto(row, spec, now, settings, "watch", + [{"item": item_vars(i)} for i in reversed(shown)], extra=extra) + self.store.set_state(row["id"], "seen", ([i.id for i in fresh] + seen)[:MAX_SEEN]) + + def _watch_value(self, row, spec, now, settings, value) -> None: + trigger: models.WatchTrigger = spec.trigger + missing = object() + previous = self.store.state(row["id"], "value", missing) + if previous is missing: + self.store.set_state(row["id"], "value", value) + self._status(row, "watching", f"Watching: {trigger.path or 'value'} is {value}.") + return + if not crossed(trigger, previous, value): + if value != previous: + self.store.set_state(row["id"], "value", value) + return + gate = self.gate(spec, now, settings) + if gate.action == "hold": + return # compared again after quiet hours + if gate.action == "skip": + self._record(row, "watch", "skipped", f"{previous} -> {value}: {gate.reason}", now) + else: + self._fire_auto(row, spec, now, settings, "watch", + [{"value": value, "old_value": previous}]) + self.store.set_state(row["id"], "value", value) + + # --- webhooks, tests, previews --- + + def fire_webhook(self, row: dict, payload: dict, now: dt.datetime | None = None): + """Fire a webhook schedule. Returns (job or None, message).""" + now = now or self.clock() + spec = models.ScheduleSpec.model_validate(row["spec"]) + settings = self.settings() + hour_ago = now - dt.timedelta(hours=1) + calls = self.store.count_runs(hour_ago, ("webhook",), PRINTED_STATES, row["id"]) + if calls >= spec.trigger.per_hour: + raise RateLimited(f"This webhook allows {spec.trigger.per_hour} prints an hour.") + gate = self.gate(spec, now, settings) + if gate.action != "go": + reason = gate.reason if gate.action == "skip" else "Skipped during quiet hours." + self._record(row, "webhook", "skipped", reason, now) + return None, reason + with self._lock: + job = self.fire(row, spec, now, settings, "webhook", [{"payload": payload}]) + return job, "Queued." if job else "Nothing to print." + + def test_print(self, row: dict): + now = self.clock() + settings = self.settings() + spec = models.ScheduleSpec.model_validate(row["spec"]) + values = self.sample_values(spec.trigger, now, settings) + with self._lock: + return self.fire(row, spec, now, settings, value_sets=[values], test=True) + + def sample_values(self, trigger, now: dt.datetime, settings: models.Settings) -> dict: + """Values for previews and test prints: the next real event/item where possible.""" + if trigger.type == "calendar": + try: + events = self.calendar_events(trigger, now, now + dt.timedelta(days=14), settings) + fires = calendar_fires(trigger, events) + if fires: + return {"event": event_vars(fires[0][1], fires[0][1].start + - dt.timedelta(minutes=trigger.minutes_before))} + except SourceError: + pass + start = now.astimezone(settings.tz) + dt.timedelta(minutes=trigger.minutes_before) + sample = Event("sample", "Example event", start, start + dt.timedelta(hours=1), False, + "Meeting room") + return {"event": event_vars(sample, now)} + if trigger.type == "watch": + try: + data = self.cache.get(trigger.url, FEED_MAX_AGE) + if trigger.kind == "rss": + items = parse_items(data) + if items: + return {"item": item_vars(items[0])} + else: + value = json_value(data, trigger.path) + return {"value": value, "old_value": value} + except SourceError: + pass + if trigger.kind == "rss": + return {"item": item_vars(Item("sample", "An example headline", + "https://example.com/post", "", "Example feed"))} + return {"value": 42, "old_value": 41} + if trigger.type == "webhook": + return {"payload": {"text": "Hello from a webhook", "title": "Webhook"}} + return {} + + def next_runs(self, row: dict, count: int = 5) -> list[dt.datetime]: + """Upcoming fire times, for the editor and the 'coming up' list.""" + now = self.clock() + settings = self.settings() + spec = models.ScheduleSpec.model_validate(row["spec"]) + return self.trigger_runs(spec.trigger, now, settings, count) + + def trigger_runs(self, trigger, now: dt.datetime, settings: models.Settings, + count: int = 5) -> list[dt.datetime]: + if trigger.type in models.TIMED: + return upcoming(trigger, now, settings, count) + if trigger.type == "calendar": + lead = dt.timedelta(minutes=trigger.minutes_before) + events = self.calendar_events(trigger, now + lead, + now + lead + dt.timedelta(days=7), settings) + return [at for at, _ in calendar_fires(trigger, events) if at > now][:count] + return [] + + def reschedule(self, row: dict, now: dt.datetime | None = None) -> dict: + """Recompute next_run_at after an edit (or a settings change).""" + now = now or self.clock() + settings = self.settings() + spec = models.ScheduleSpec.model_validate(row["spec"]) + kind = spec.trigger.type + following = None + status = None + if kind in models.TIMED: + try: + following = next_fire(spec.trigger, now, settings) + except TriggerError as e: + status = ("error", str(e)) + if following is None and status is None: + status = ("finished", "No more runs.") + elif kind == "watch": + following = now # poll straight away to take a first look + row = self.store.update_schedule(row["id"], next_run_at=iso(following)) + if status: + row = self.store.update_schedule(row["id"], last_status=status[0], + last_message=status[1]) + self.wake() + return row + + def reschedule_all(self) -> None: + for row in self.store.schedules(): + try: + spec = models.ScheduleSpec.model_validate(row["spec"]) + except ValidationError: + continue + if spec.trigger.type in models.TIMED: + self.reschedule(row) + + +def quiet_end(local: dt.datetime, start: dt.time, end: dt.time) -> dt.datetime | None: + """When quiet hours that contain `local` end; None when it's outside them.""" + tz = local.tzinfo + now = local.time().replace(tzinfo=None) + if start == end: + return None + if start < end: # e.g. 13:00-14:00 + inside = start <= now < end + end_day = local.date() + else: # over midnight, e.g. 22:00-07:00 + inside = now >= start or now < end + end_day = local.date() + dt.timedelta(days=1) if now >= start else local.date() + if not inside: + return None + return dt.datetime.combine(end_day, end, tz).astimezone(UTC) + + +def crossed(trigger: models.WatchTrigger, previous, value) -> bool: + if trigger.condition == "changed": + return value != previous + try: + new, old = float(value), float(previous) + except (TypeError, ValueError): + return False + if trigger.condition == "above": + return new > trigger.threshold >= old + return new < trigger.threshold <= old diff --git a/receipt_sources.py b/receipt_sources.py new file mode 100644 index 0000000..0268b79 --- /dev/null +++ b/receipt_sources.py @@ -0,0 +1,186 @@ +"""Fetching and parsing what scheduled receipts read: calendars (ICS), feeds and JSON.""" + +from __future__ import annotations + +import datetime as dt +import html +import json +import re +import threading +import time +from dataclasses import dataclass +from zoneinfo import ZoneInfo + +import requests + +import receipt + +MAX_SOURCE_BYTES = 5 * 1024 * 1024 +USER_AGENT = "receipt-maker/1.0 (thermal receipt printer)" +CALENDAR_MAX_AGE = 15 * 60 # seconds an ICS download is reused +FEED_MAX_AGE = 10 * 60 + + +class SourceError(Exception): + """A calendar or feed couldn't be downloaded or read.""" + + +@dataclass(frozen=True) +class Event: + uid: str + title: str + start: dt.datetime # aware, in the settings timezone; midnight for all-day events + end: dt.datetime + all_day: bool + location: str = "" + description: str = "" + + @property + def key(self) -> str: + """Identifies one occurrence of a (possibly recurring) event.""" + return f"{self.uid}|{self.start.isoformat()}" + + +@dataclass(frozen=True) +class Item: + id: str + title: str + link: str = "" + summary: str = "" + source: str = "" + + +class SourceCache: + """Downloads by URL, reused for max_age seconds so previews and ticks don't refetch.""" + + def __init__(self): + self._lock = threading.Lock() + self._entries: dict[str, tuple[float, bytes]] = {} + + def get(self, url: str, max_age: float) -> bytes: + with self._lock: + entry = self._entries.get(url) + if entry and time.monotonic() - entry[0] < max_age: + return entry[1] + data = fetch(url) + with self._lock: + self._entries[url] = (time.monotonic(), data) + return data + + def forget(self, url: str) -> None: + with self._lock: + self._entries.pop(url, None) + + +def fetch(url: str) -> bytes: + try: + data = receipt.fetch_capped(url, MAX_SOURCE_BYTES, headers={"User-Agent": USER_AGENT}) + except requests.RequestException as e: + raise SourceError(_short_error(e)) from e + if data is None: + raise SourceError(f"over the {MAX_SOURCE_BYTES // 1024 // 1024} MB limit") + return data + + +def _short_error(e: requests.RequestException) -> str: + response = getattr(e, "response", None) + if response is not None and response.status_code: + return f"HTTP {response.status_code}" + if isinstance(e, requests.Timeout): + return "timed out" + if isinstance(e, requests.ConnectionError): + return "couldn't connect" + return type(e).__name__ + + +def _local(value: dt.date | dt.datetime, tz: ZoneInfo) -> tuple[dt.datetime, bool]: + """An ICS start/end as an aware local datetime, and whether it was a whole day.""" + if not isinstance(value, dt.datetime): + return dt.datetime.combine(value, dt.time(), tz), True + if value.tzinfo is None: # "floating" time: the calendar's local time + return value.replace(tzinfo=tz), False + return value.astimezone(tz), False + + +def parse_events(data: bytes, start: dt.datetime, end: dt.datetime, tz: ZoneInfo) -> list[Event]: + """Occurrences overlapping [start, end), recurring events expanded, sorted by start.""" + import icalendar + import recurring_ical_events + + try: + calendar = icalendar.Calendar.from_ical(data) + occurrences = recurring_ical_events.of(calendar, skip_bad_series=True).between(start, end) + except Exception as e: # icalendar raises ValueError, KeyError and its own errors + raise SourceError(f"not a readable calendar ({type(e).__name__})") from e + events = [] + for component in occurrences: + if str(component.get("STATUS", "")).upper() == "CANCELLED": + continue + raw_start = component.get("DTSTART") + if raw_start is None: + continue + event_start, all_day = _local(raw_start.dt, tz) + raw_end = component.get("DTEND") + event_end = _local(raw_end.dt, tz)[0] if raw_end is not None else event_start + events.append( + Event( + uid=str(component.get("UID", "")) or f"{component.get('SUMMARY', '')}", + title=str(component.get("SUMMARY", "")).strip() or "(no title)", + start=event_start, + end=event_end, + all_day=all_day, + location=str(component.get("LOCATION", "")).strip(), + description=str(component.get("DESCRIPTION", "")).strip(), + ) + ) + events.sort(key=lambda e: (e.start, not e.all_day, e.title)) + return events + + +def parse_items(data: bytes, source: str = "") -> list[Item]: + """Feed entries, newest first as the feed lists them.""" + import feedparser + + feed = feedparser.parse(data) + if feed.bozo and not feed.entries: + raise SourceError("not a readable RSS/Atom feed") + items = [] + for entry in feed.entries: + title = " ".join(str(entry.get("title", "")).split()) or "(untitled)" + link = str(entry.get("link", "")) + items.append( + Item( + id=str(entry.get("id") or link or title), + title=title, + link=link, + summary=_plain(str(entry.get("summary", ""))), + source=source or str(feed.feed.get("title", "")), + ) + ) + return items + + +def _plain(markup: str) -> str: + """Feed summaries are HTML; the printer wants text.""" + return " ".join(html.unescape(re.sub(r"<[^>]+>", " ", markup)).split()) + + +def json_value(data: bytes, path: str): + """The value at a dotted path ("data.items.0.price") in a JSON document.""" + try: + value = json.loads(data) + except ValueError as e: + raise SourceError("not valid JSON") from e + for part in (p for p in path.split(".") if p): + if isinstance(value, list) and part.lstrip("-").isdigit(): + index = int(part) + if not -len(value) <= index < len(value): + raise SourceError(f"{path}: index {index} is out of range") + value = value[index] + elif isinstance(value, dict) and part in value: + value = value[part] + else: + raise SourceError(f"{path}: no {part!r} there") + if isinstance(value, (dict, list)): + raise SourceError(f"{path} is a {type(value).__name__}, not a single value") + return value diff --git a/receipt_store.py b/receipt_store.py new file mode 100644 index 0000000..09ef808 --- /dev/null +++ b/receipt_store.py @@ -0,0 +1,409 @@ +"""SQLite storage for the web server: schedules, print history, settings and sources. + +One connection behind a lock: traffic is a person and a scheduler, and it lets +tests use ":memory:". The file lives outside the clone (RECEIPT_DATA_DIR), so +deploys and rollbacks never touch it; migrations are additive only, so code +rolled back by update.sh still reads a newer database. +""" + +from __future__ import annotations + +import json +import os +import secrets +import sqlite3 +import threading +from datetime import datetime, timezone +from pathlib import Path + +DATA_DIR_ENV = "RECEIPT_DATA_DIR" +DB_NAME = "receipt.db" +KEEP_PAYLOADS = 50 # newest runs whose bytes are kept for "Print again" +KEEP_RUNS = 2000 + +# Numbered schema steps; PRAGMA user_version records how many have run. +# Only ever append, and only add tables/columns: see the module docstring. +MIGRATIONS = [ + """ + CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE schedules ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + enabled INTEGER NOT NULL DEFAULT 1, + spec TEXT NOT NULL, + next_run_at TEXT, + last_run_at TEXT, + last_status TEXT, + last_message TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE TABLE runs ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + source TEXT NOT NULL, + schedule_id TEXT, + name TEXT, + user TEXT, + state TEXT NOT NULL, + message TEXT NOT NULL DEFAULT '', + error TEXT, + created_at TEXT NOT NULL, + finished_at TEXT, + payload BLOB + ); + CREATE INDEX runs_created ON runs (created_at); + CREATE INDEX runs_schedule ON runs (schedule_id, created_at); + CREATE TABLE trigger_state ( + schedule_id TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL, + PRIMARY KEY (schedule_id, key) + ); + CREATE TABLE assets ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + data BLOB NOT NULL, + created_at TEXT NOT NULL + ); + CREATE TABLE sources ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + kind TEXT NOT NULL, + url TEXT NOT NULL, + created_at TEXT NOT NULL + ); + """, +] + +ACTIVE_STATES = ("queued", "printing") + + +def default_path() -> Path: + base = os.environ.get(DATA_DIR_ENV) or Path.home() / ".local" / "share" / "receipt-maker" + return Path(base) / DB_NAME + + +UTC = timezone.utc # noqa: UP017 - datetime.UTC needs Python 3.11 + + +def utcnow() -> datetime: + return datetime.now(UTC) + + +def iso(dt: datetime | None) -> str | None: + """UTC ISO-8601 with a Z, the one timestamp format in the database and the API.""" + if dt is None: + return None + return dt.astimezone(UTC).isoformat(timespec="seconds").replace("+00:00", "Z") + + +def parse_iso(value: str | None) -> datetime | None: + if not value: + return None + return datetime.fromisoformat(value.replace("Z", "+00:00")) + + +def new_id() -> str: + return secrets.token_hex(8) + + +class Store: + def __init__(self, path: Path | str = ":memory:"): + self.path = str(path) + if self.path != ":memory:": + Path(self.path).parent.mkdir(parents=True, exist_ok=True) + self._lock = threading.RLock() + self._conn = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None) + self._conn.row_factory = sqlite3.Row + self._conn.execute("PRAGMA foreign_keys = ON") + self.migrate() + + # --- plumbing --- + + def _execute(self, sql: str, params: tuple | dict = ()) -> sqlite3.Cursor: + with self._lock: + return self._conn.execute(sql, params) + + def _rows(self, sql: str, params: tuple | dict = ()) -> list[dict]: + with self._lock: + return [dict(r) for r in self._conn.execute(sql, params).fetchall()] + + def _row(self, sql: str, params: tuple | dict = ()) -> dict | None: + rows = self._rows(sql, params) + return rows[0] if rows else None + + def _transaction(self, statements: list[tuple[str, tuple]]) -> None: + with self._lock: + self._conn.execute("BEGIN") + try: + for sql, params in statements: + self._conn.execute(sql, params) + except BaseException: + self._conn.execute("ROLLBACK") + raise + self._conn.execute("COMMIT") + + @property + def version(self) -> int: + return self._execute("PRAGMA user_version").fetchone()[0] + + def migrate(self) -> None: + with self._lock: + version = self.version + if version >= len(MIGRATIONS): + return + if version > 0 and self.path != ":memory:": + backup = sqlite3.connect(f"{self.path}.bak-v{version}") + with backup: + self._conn.backup(backup) + backup.close() + for number, script in enumerate(MIGRATIONS[version:], start=version + 1): + self._conn.executescript( + f"BEGIN; {script}; PRAGMA user_version = {number}; COMMIT;" + ) + + # --- settings --- + + def settings(self) -> dict: + return {r["key"]: json.loads(r["value"]) for r in self._rows("SELECT * FROM settings")} + + def save_settings(self, values: dict) -> None: + self._transaction( + [ + ("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (k, json.dumps(v))) + for k, v in values.items() + ] + ) + + # --- schedules --- + + @staticmethod + def _schedule(row: dict | None) -> dict | None: + if row is None: + return None + row["enabled"] = bool(row["enabled"]) + row["spec"] = json.loads(row["spec"]) + return row + + def schedules(self) -> list[dict]: + rows = self._rows("SELECT * FROM schedules ORDER BY created_at") + return [self._schedule(r) for r in rows] + + def schedule(self, schedule_id: str) -> dict | None: + return self._schedule(self._row("SELECT * FROM schedules WHERE id = ?", (schedule_id,))) + + def add_schedule(self, name: str, spec: dict, enabled: bool = True) -> dict: + now = iso(utcnow()) + schedule_id = new_id() + self._execute( + "INSERT INTO schedules (id, name, enabled, spec, created_at, updated_at)" + " VALUES (?, ?, ?, ?, ?, ?)", + (schedule_id, name, int(enabled), json.dumps(spec), now, now), + ) + return self.schedule(schedule_id) + + def update_schedule(self, schedule_id: str, **fields) -> dict | None: + """Set columns; spec is stored as JSON. updated_at only moves for user edits.""" + if not fields: + return self.schedule(schedule_id) + if "spec" in fields: + fields["spec"] = json.dumps(fields["spec"]) + if "enabled" in fields: + fields["enabled"] = int(fields["enabled"]) + allowed = { + "name", "enabled", "spec", "next_run_at", "last_run_at", "last_status", + "last_message", "updated_at", + } + unknown = set(fields) - allowed + if unknown: + raise ValueError(f"unknown schedule fields: {sorted(unknown)}") + assignments = ", ".join(f"{k} = :{k}" for k in fields) # keys are whitelisted above + self._execute( + f"UPDATE schedules SET {assignments} WHERE id = :id", # noqa: S608 + {**fields, "id": schedule_id}, + ) + return self.schedule(schedule_id) + + def delete_schedule(self, schedule_id: str) -> bool: + with self._lock: + deleted = self._execute("DELETE FROM schedules WHERE id = ?", (schedule_id,)).rowcount + self._execute("DELETE FROM trigger_state WHERE schedule_id = ?", (schedule_id,)) + return bool(deleted) + + # --- per-schedule trigger state (seen items, fired events, rotations, secrets) --- + + def state(self, schedule_id: str, key: str, default=None): + row = self._row( + "SELECT value FROM trigger_state WHERE schedule_id = ? AND key = ?", (schedule_id, key) + ) + return default if row is None else json.loads(row["value"]) + + def set_state(self, schedule_id: str, key: str, value) -> None: + self._execute( + "INSERT OR REPLACE INTO trigger_state (schedule_id, key, value) VALUES (?, ?, ?)", + (schedule_id, key, json.dumps(value)), + ) + + def clear_state(self, schedule_id: str, keep: tuple[str, ...] = ()) -> None: + marks = ", ".join("?" * len(keep)) or "''" + self._execute( + f"DELETE FROM trigger_state WHERE schedule_id = ? AND key NOT IN ({marks})", # noqa: S608 + (schedule_id, *keep), + ) + + # --- print history --- + + def add_run( + self, + kind: str, + source: str, + state: str, + *, + run_id: str | None = None, + schedule_id: str | None = None, + name: str | None = None, + user: str | None = None, + message: str = "", + error: str | None = None, + payload: bytes | None = None, + created_at: datetime | None = None, + ) -> str: + run_id = run_id or new_id() + created = created_at or utcnow() + finished = iso(created) if state not in ACTIVE_STATES else None + self._transaction( + [ + ( + "INSERT INTO runs (id, kind, source, schedule_id, name, user, state, message," + " error, created_at, finished_at, payload)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (run_id, kind, source, schedule_id, name, user, state, message, error, + iso(created), finished, payload), + ), + ( + "UPDATE runs SET payload = NULL WHERE payload IS NOT NULL AND id NOT IN" + " (SELECT id FROM runs WHERE payload IS NOT NULL" + " ORDER BY created_at DESC LIMIT ?)", + (KEEP_PAYLOADS,), + ), + ( + "DELETE FROM runs WHERE id NOT IN" + " (SELECT id FROM runs ORDER BY created_at DESC LIMIT ?)", + (KEEP_RUNS,), + ), + ] + ) + return run_id + + def finish_run(self, run_id: str, state: str, message: str, error: str | None = None) -> None: + finished = iso(utcnow()) if state not in ACTIVE_STATES else None + self._execute( + "UPDATE runs SET state = ?, message = ?, error = ?, finished_at = ? WHERE id = ?", + (state, message, error, finished, run_id), + ) + + def fail_interrupted_runs(self) -> int: + """Runs left queued/printing by a previous process can't finish any more.""" + return self._execute( + "UPDATE runs SET state = 'failed', error = 'failed', finished_at = ?," + " message = 'The server restarted before this printed.'" + " WHERE state IN ('queued', 'printing')", + (iso(utcnow()),), + ).rowcount + + def runs( + self, + limit: int = 50, + before: str | None = None, + schedule_id: str | None = None, + state: str | None = None, + ) -> list[dict]: + where, params = [], [] + if before: + where.append("created_at < ?") + params.append(before) + if schedule_id: + where.append("schedule_id = ?") + params.append(schedule_id) + if state: + where.append("state = ?") + params.append(state) + clause = f"WHERE {' AND '.join(where)}" if where else "" + sql = ( + "SELECT id, kind, source, schedule_id, name, user, state, message, error," # noqa: S608 + f" created_at, finished_at, payload IS NOT NULL AS has_payload FROM runs {clause}" + " ORDER BY created_at DESC, rowid DESC LIMIT ?" + ) # the clause is fixed text; values are bound + return self._rows(sql, (*params, limit)) + + def run_payload(self, run_id: str) -> tuple[dict, bytes] | None: + row = self._row("SELECT * FROM runs WHERE id = ?", (run_id,)) + if row is None or row["payload"] is None: + return None + payload = row.pop("payload") + return row, payload + + def count_runs( + self, since: datetime, sources: tuple[str, ...], states: tuple[str, ...], + schedule_id: str | None = None, + ) -> int: + params: list = [iso(since), *sources, *states] + extra = "" + if schedule_id: + extra = " AND schedule_id = ?" + params.append(schedule_id) + sql = ( + "SELECT COUNT(*) FROM runs WHERE created_at >= ?" # noqa: S608 + f" AND source IN ({', '.join('?' * len(sources))})" + f" AND state IN ({', '.join('?' * len(states))}){extra}" + ) # only placeholders are interpolated + return self._execute(sql, tuple(params)).fetchone()[0] + + # --- uploaded images for scheduled receipts --- + + def add_asset(self, name: str, data: bytes) -> dict: + asset_id = new_id() + self._execute( + "INSERT INTO assets (id, name, data, created_at) VALUES (?, ?, ?, ?)", + (asset_id, name, data, iso(utcnow())), + ) + return {"id": asset_id, "name": name, "size": len(data)} + + def assets(self) -> list[dict]: + return self._rows( + "SELECT id, name, length(data) AS size, created_at FROM assets ORDER BY created_at DESC" + ) + + def asset(self, asset_id: str) -> bytes | None: + row = self._row("SELECT data FROM assets WHERE id = ?", (asset_id,)) + return None if row is None else row["data"] + + def delete_asset(self, asset_id: str) -> bool: + return bool(self._execute("DELETE FROM assets WHERE id = ?", (asset_id,)).rowcount) + + # --- saved calendar / feed URLs --- + + def sources(self) -> list[dict]: + return self._rows("SELECT * FROM sources ORDER BY name COLLATE NOCASE") + + def source(self, source_id: str) -> dict | None: + return self._row("SELECT * FROM sources WHERE id = ?", (source_id,)) + + def add_source(self, name: str, kind: str, url: str) -> dict: + source_id = new_id() + self._execute( + "INSERT INTO sources (id, name, kind, url, created_at) VALUES (?, ?, ?, ?, ?)", + (source_id, name, kind, url, iso(utcnow())), + ) + return self.source(source_id) + + def update_source(self, source_id: str, name: str, kind: str, url: str) -> dict | None: + self._execute( + "UPDATE sources SET name = ?, kind = ?, url = ? WHERE id = ?", + (name, kind, url, source_id), + ) + return self.source(source_id) + + def delete_source(self, source_id: str) -> bool: + return bool(self._execute("DELETE FROM sources WHERE id = ?", (source_id,)).rowcount) diff --git a/receipt_triggers.py b/receipt_triggers.py new file mode 100644 index 0000000..245f027 --- /dev/null +++ b/receipt_triggers.py @@ -0,0 +1,295 @@ +"""When schedules fire: next fire times, calendar reminders and plain-English summaries. + +Recurrences are evaluated as wall-clock times in the settings timezone and +then made aware: a time in a spring-forward gap fires an hour later, and one +in a fall-back overlap fires on its first pass only. +""" + +from __future__ import annotations + +import datetime as dt +from collections.abc import Callable +from urllib.parse import urlparse +from zoneinfo import ZoneInfo + +from dateutil import rrule as du + +from receipt_models import ( + WEEKDAYS, + CalendarTrigger, + OnceTrigger, + RecurringTrigger, + Settings, + SunTrigger, + WatchTrigger, + WebhookTrigger, +) +from receipt_sources import Event +from receipt_store import UTC + +FREQS = {"daily": du.DAILY, "weekly": du.WEEKLY, "monthly": du.MONTHLY, "yearly": du.YEARLY} +DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] +POSITIONS = {1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", -1: "last"} +MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] +CALENDAR_LOOKAHEAD = dt.timedelta(days=2) + + +class TriggerError(ValueError): + """The trigger can't produce fire times (bad custom rule, no location for sun times).""" + + +def localize(naive: dt.datetime, tz: ZoneInfo) -> dt.datetime: + """A wall-clock time as aware UTC; fold=0, so gaps shift forward and overlaps fire once.""" + return naive.replace(tzinfo=tz).astimezone(UTC) + + +def ruleset(trigger: RecurringTrigger) -> du.rruleset: + start = trigger.start or dt.date(2000, 1, 3) # a Monday; only matters for intervals > 1 + common = { + "dtstart": dt.datetime.combine(start, dt.time()), + "until": dt.datetime.combine(trigger.until, dt.time(23, 59, 59)) if trigger.until else None, + } + rules = du.rruleset() + if trigger.rrule: + text = trigger.rrule.strip().removeprefix("RRULE:") + try: + base = du.rrulestr(text, dtstart=common["dtstart"]) + except (ValueError, TypeError) as e: + raise TriggerError(f"custom rule: {e}") from None + if not isinstance(base, du.rrule): + raise TriggerError("custom rule: give a single RRULE") + if "BYHOUR" in text.upper(): + rules.rrule(base) + else: + for t in trigger.times: + rules.rrule(base.replace(byhour=t.hour, byminute=t.minute, bysecond=0)) + return rules + + kw: dict = {"freq": FREQS[trigger.freq], "interval": trigger.interval, **common} + days = trigger.weekdays + if trigger.freq in ("daily", "weekly"): + if days: + kw["byweekday"] = days + else: + if trigger.freq == "yearly": + kw["bymonth"] = trigger.month or start.month + if days: + kw["byweekday"] = days + if trigger.setpos is not None: + kw["bysetpos"] = trigger.setpos + else: + kw["bymonthday"] = trigger.monthday or start.day + # One rule per time: byhour x byminute would be a cross product (07:30 + 18:00 -> 07:00 too). + for t in trigger.times: + rules.rrule(du.rrule(byhour=t.hour, byminute=t.minute, bysecond=0, **kw)) + return rules + + +def _sun_time(trigger: SunTrigger, day: dt.date, settings: Settings) -> dt.datetime | None: + from astral import Observer, sun + + location = settings.location + observer = Observer(location.latitude, location.longitude) + try: + at = getattr(sun, trigger.event)(observer, date=day, tzinfo=settings.tz) + except ValueError: # the sun never reaches that angle that day (high latitudes) + return None + at += dt.timedelta(minutes=trigger.offset_minutes) + return at.replace(microsecond=0).astimezone(UTC) + + +def next_fire(trigger, after: dt.datetime, settings: Settings) -> dt.datetime | None: + """The first fire time strictly after `after` for a timed trigger; None if there are no more.""" + tz = settings.tz + if isinstance(trigger, OnceTrigger): + at = localize(trigger.at, tz) + return at if at > after else None + if isinstance(trigger, RecurringTrigger): + rules = ruleset(trigger) + # Search from a little earlier in wall-clock terms: around a DST change the + # naive local time of `after` can be an hour off the aware comparison below. + candidate = rules.after(after.astimezone(tz).replace(tzinfo=None) - dt.timedelta(hours=2)) + for _ in range(500): + if candidate is None: + return None + at = localize(candidate, tz) + if at > after: + return at + candidate = rules.after(candidate) + return None + if isinstance(trigger, SunTrigger): + if settings.location is None: + raise TriggerError("sun times need a location in Settings") + first = after.astimezone(tz).date() - dt.timedelta(days=1) + for offset in range(400): # covers polar night/day stretches + day = first + dt.timedelta(days=offset) + if day.weekday() not in trigger.weekdays: + continue + at = _sun_time(trigger, day, settings) + if at is not None and at > after: + return at + return None + return None + + +def upcoming(trigger, after: dt.datetime, settings: Settings, count: int) -> list[dt.datetime]: + times = [] + at = after + while len(times) < count: + at = next_fire(trigger, at, settings) + if at is None: + break + times.append(at) + return times + + +def calendar_fires( + trigger: CalendarTrigger, events: list[Event] +) -> list[tuple[dt.datetime, Event]]: + """(fire time in UTC, event) for each event the trigger reminds about, soonest first.""" + needle = trigger.contains.strip().lower() + fires = [] + for event in events: + if event.all_day and not trigger.include_all_day: + continue + if needle and needle not in event.title.lower(): + continue + at = event.start - dt.timedelta(minutes=trigger.minutes_before) + fires.append((at.astimezone(UTC), event)) + fires.sort(key=lambda f: f[0]) + return fires + + +# --- summaries --- + + +def _join(words: list[str]) -> str: + if len(words) <= 1: + return "".join(words) + return f"{', '.join(words[:-1])} and {words[-1]}" + + +def _days(days: list[int]) -> str: + if not days or sorted(days) == WEEKDAYS: + return "every day" + if sorted(days) == [0, 1, 2, 3, 4]: + return "weekdays" + if sorted(days) == [5, 6]: + return "weekends" + return _join([DAY_NAMES[d] for d in sorted(days)]) + + +def _date(day: dt.date) -> str: + return f"{day.day} {MONTHS[day.month - 1]} {day.year}" + + +def _ordinal(n: int) -> str: + suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") + return f"{n}{suffix}" + + +def _times(times: list[dt.time]) -> str: + return _join([t.strftime("%H:%M") for t in times]) + + +def _every(unit: str, interval: int) -> str: + return f"every {unit}" if interval == 1 else f"every {interval} {unit}s" + + +def _day_of_month(trigger: RecurringTrigger) -> str: + if trigger.weekdays: + if trigger.setpos is None: + return f"every {_join([DAY_NAMES[d] for d in trigger.weekdays])}" + days = trigger.weekdays + what = "weekday" if days == [0, 1, 2, 3, 4] else _join([DAY_NAMES[d] for d in days]) + return f"the {POSITIONS[trigger.setpos]} {what}" + if trigger.monthday == -1: + return "the last day" + day = trigger.monthday or (trigger.start.day if trigger.start else 1) + return f"the {_ordinal(day)}" + + +def _recurring(trigger: RecurringTrigger) -> str: + if trigger.rrule: + rule = trigger.rrule.strip().removeprefix("RRULE:") + return f"Custom rule {rule} at {_times(trigger.times)}" + n = trigger.interval + if trigger.freq == "daily": + when = _days(trigger.weekdays) if n == 1 else f"{_every('day', n)}" + if n > 1 and trigger.weekdays: + when += f" ({_days(trigger.weekdays)})" + elif trigger.freq == "weekly": + on = _join([DAY_NAMES[d] for d in trigger.weekdays]) if trigger.weekdays else None + if on is None and trigger.start: + on = DAY_NAMES[trigger.start.weekday()] + when = _every("week", n) + (f" on {on}" if on else "") + elif trigger.freq == "monthly": + when = f"{_every('month', n)} on {_day_of_month(trigger)}" + else: + month = trigger.month or (trigger.start.month if trigger.start else 1) + if trigger.weekdays: + when = f"{_every('year', n)} on {_day_of_month(trigger)} of {MONTHS[month - 1]}" + elif trigger.monthday == -1: + when = f"{_every('year', n)} on the last day of {MONTHS[month - 1]}" + else: + day = trigger.monthday or (trigger.start.day if trigger.start else 1) + when = f"{_every('year', n)} on {day} {MONTHS[month - 1]}" + text = f"{when[0].upper()}{when[1:]} at {_times(trigger.times)}" + if trigger.until: + text += f", until {_date(trigger.until)}" + return text + + +def _minutes(n: int) -> str: + if n and n % (24 * 60) == 0: + days = n // (24 * 60) + return f"{days} day{'s' if days > 1 else ''}" + if n and n % 60 == 0: + return f"{n // 60} h" + if n > 60: + return f"{n // 60} h {n % 60} min" + return f"{n} min" + + +def describe( + trigger, settings: Settings, source_name: Callable[[str], str] = lambda _id: "a calendar" +) -> str: + if isinstance(trigger, OnceTrigger): + at = trigger.at + return f"Once, {DAY_NAMES[at.weekday()]} {_date(at)} at {at:%H:%M}" + if isinstance(trigger, RecurringTrigger): + return _recurring(trigger) + if isinstance(trigger, SunTrigger): + offset = trigger.offset_minutes + if offset == 0: + when = f"At {trigger.event}" + else: + when = f"{_minutes(abs(offset))} {'before' if offset < 0 else 'after'} {trigger.event}" + if sorted(trigger.weekdays) != WEEKDAYS: + when += f", {_days(trigger.weekdays)}" + if settings.location is None: + when += " (set a location in Settings)" + return when + if isinstance(trigger, CalendarTrigger): + name = source_name(trigger.source_id) + if trigger.minutes_before == 0: + text = f"When events in {name} start" + else: + text = f"{_minutes(trigger.minutes_before)} before events in {name}" + if trigger.contains.strip(): + text += f' matching "{trigger.contains.strip()}"' + if trigger.include_all_day: + text += ", incl. all-day" + return text + if isinstance(trigger, WatchTrigger): + host = urlparse(trigger.url).netloc + every = f"checked every {_minutes(trigger.every_minutes)}" + if trigger.kind == "rss": + return f"New items in {host}, {every}" + path = trigger.path or "the value" + if trigger.condition == "changed": + return f"When {path} at {host} changes, {every}" + return f"When {path} at {host} goes {trigger.condition} {trigger.threshold:g}, {every}" + if isinstance(trigger, WebhookTrigger): + return f"When its webhook is called (up to {trigger.per_hour} an hour)" + return "Unknown trigger" diff --git a/receipt_web.py b/receipt_web.py index 907dc5c..34bd6ad 100644 --- a/receipt_web.py +++ b/receipt_web.py @@ -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 = """ - - - - -Receipt Printer - - - -
-
-

Receipt printer

- -
- -
-

Note

-
- -
- - - -
-
-
- -
-

Image

-
- - - -
- -
-
- Max 16 MB. Printed full width, dithered. - -
-
-
- -
Ready.
-
- - - -""" diff --git a/tests/conftest.py b/tests/conftest.py index e4cad24..49c39e0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ """Shared test fakes.""" import argparse +from pathlib import Path from escpos import printer @@ -54,3 +55,34 @@ def make_args(**overrides): } defaults.update(overrides) return argparse.Namespace(**defaults) + + +FIXTURES = Path(__file__).parent / "fixtures" +CALENDAR_URL = "https://calendar.test/work.ics" +FEED_URL = "https://feed.test/rss.xml" + + +class FakeCache: + """Stands in for receipt_sources.SourceCache: canned bodies by URL, no network.""" + + def __init__(self, bodies=None): + self.bodies = { + CALENDAR_URL: (FIXTURES / "calendar.ics").read_bytes(), + FEED_URL: (FIXTURES / "feed.xml").read_bytes(), + **(bodies or {}), + } + self.gets = [] + + def get(self, url, max_age): + from receipt_sources import SourceError + + self.gets.append(url) + body = self.bodies.get(url) + if isinstance(body, Exception): + raise body + if body is None: + raise SourceError("couldn't connect") + return body + + def forget(self, url): + pass diff --git a/tests/fixtures/calendar.ics b/tests/fixtures/calendar.ics new file mode 100644 index 0000000..d9e4d91 --- /dev/null +++ b/tests/fixtures/calendar.ics @@ -0,0 +1,33 @@ +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//receipt-maker tests//EN +BEGIN:VEVENT +UID:standup@test +DTSTART;TZID=Europe/London:20261019T093000 +DTEND;TZID=Europe/London:20261019T094500 +RRULE:FREQ=DAILY +EXDATE;TZID=Europe/London:20261027T093000 +SUMMARY:Team standup +LOCATION:Room 4 +END:VEVENT +BEGIN:VEVENT +UID:holiday@test +DTSTART;VALUE=DATE:20261028 +DTEND;VALUE=DATE:20261029 +SUMMARY:Bank holiday +END:VEVENT +BEGIN:VEVENT +UID:dentist@test +DTSTART:20261026T140000Z +DTEND:20261026T150000Z +SUMMARY:Dentist +LOCATION:High St +END:VEVENT +BEGIN:VEVENT +UID:cancelled@test +DTSTART:20261026T160000Z +DTEND:20261026T170000Z +SUMMARY:Cancelled thing +STATUS:CANCELLED +END:VEVENT +END:VCALENDAR diff --git a/tests/fixtures/feed.xml b/tests/fixtures/feed.xml new file mode 100644 index 0000000..cc56d01 --- /dev/null +++ b/tests/fixtures/feed.xml @@ -0,0 +1,10 @@ + + + +Test Feed +post-3Third posthttps://example.com/3 +<p>The <b>third</b> one</p> +post-2Second posthttps://example.com/2 +post-1First posthttps://example.com/1 + + diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py new file mode 100644 index 0000000..28d65bb --- /dev/null +++ b/tests/test_scheduler.py @@ -0,0 +1,237 @@ +import datetime as dt +from types import SimpleNamespace + +import pytest +from conftest import CALENDAR_URL, FEED_URL, FakeCache + +pytest.importorskip("dateutil") +pytest.importorskip("pydantic") + +import receipt_content # noqa: E402 +from receipt_scheduler import QueueFull, RateLimited, Scheduler # noqa: E402 +from receipt_store import UTC, Store, iso # noqa: E402 + +MON_0729 = dt.datetime(2026, 10, 26, 7, 29, tzinfo=UTC) # GMT, so local time too + + +class FakeJobs: + def __init__(self, store): + self.store = store + self.submitted = [] + self.full = False + + def submit(self, kind, payload, user, *, source="manual", schedule_id=None, name=None): + if self.full: + raise QueueFull + job = SimpleNamespace(id=f"job{len(self.submitted)}", state="queued", error=None, + message="", payload=payload) + self.store.add_run(kind, source, "queued", run_id=job.id, schedule_id=schedule_id, + created_at=MON_0729) + self.submitted.append(job) + return job + + +@pytest.fixture +def env(): + store = Store() + store.save_settings({"timezone": "Europe/London", "daily_cap": 30}) + jobs = FakeJobs(store) + empty = b"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n" + cache = FakeCache({"https://calendar.test/empty.ics": empty}) + sched = Scheduler(store, jobs, clock=lambda: MON_0729, cache=cache) + return store, jobs, sched + + +def note(text): + return {"type": "note", "text": text} + + +def add(store, sched, trigger, blocks=None, **options): + row = store.add_schedule("test", {"trigger": trigger, "blocks": blocks or [note("hi")], + "options": options}) + return sched.reschedule(row, MON_0729) + + +DAILY_0730 = {"type": "recurring", "times": ["07:30"]} + + +def test_fires_when_due_and_advances(env): + store, jobs, sched = env + row = add(store, sched, DAILY_0730) + + sched.tick(MON_0729) + assert jobs.submitted == [] + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + + assert len(jobs.submitted) == 1 + assert b"hi" in jobs.submitted[0].payload + assert store.schedule(row["id"])["next_run_at"] == "2026-10-27T07:30:00Z" + + +def test_missed_run_is_logged_not_printed(env): + store, jobs, sched = env + row = add(store, sched, DAILY_0730) + + sched.tick(MON_0729 + dt.timedelta(hours=2)) + + assert jobs.submitted == [] + assert store.runs()[0]["state"] == "missed" + assert store.schedule(row["id"])["next_run_at"] == "2026-10-27T07:30:00Z" + + +def test_once_turns_itself_off(env): + store, jobs, sched = env + row = add(store, sched, {"type": "once", "at": "2026-10-26T07:30"}) + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + + assert len(jobs.submitted) == 1 + assert store.schedule(row["id"])["enabled"] is False + + +def test_quiet_hours_hold_until_they_end(env): + store, jobs, sched = env + store.save_settings({"quiet_start": "22:00", "quiet_end": "08:00"}) + row = add(store, sched, DAILY_0730) + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + assert jobs.submitted == [] + assert store.schedule(row["id"])["next_run_at"] == "2026-10-26T08:00:00Z" + + sched.tick(dt.datetime(2026, 10, 26, 8, 0, 30, tzinfo=UTC)) + assert len(jobs.submitted) == 1 + + +def test_quiet_hours_skip_and_pause(env): + store, jobs, sched = env + store.save_settings({"quiet_start": "22:00", "quiet_end": "08:00"}) + add(store, sched, DAILY_0730, quiet="skip") + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + + assert jobs.submitted == [] + assert store.runs()[0]["state"] == "skipped" + + +def test_daily_cap(env): + store, jobs, sched = env + store.save_settings({"daily_cap": 1}) + store.add_run("schedule", "schedule", "done", created_at=MON_0729) + add(store, sched, DAILY_0730) + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + + assert jobs.submitted == [] + assert "limit" in store.runs()[0]["message"] + + +def test_queue_full_retries_next_tick(env): + store, jobs, sched = env + add(store, sched, DAILY_0730) + jobs.full = True + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + jobs.full = False + sched.tick(MON_0729 + dt.timedelta(minutes=2)) + + assert len(jobs.submitted) == 1 + + +@pytest.mark.parametrize("error,retried", [("unavailable", True), ("dropped", False)]) +def test_retries_connect_failures_only(env, error, retried): + store, jobs, sched = env + add(store, sched, DAILY_0730) + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + job = jobs.submitted[0] + job.state, job.error = "failed", error + + sched.job_finished(job) + sched.tick(MON_0729 + dt.timedelta(minutes=10)) + + assert len(jobs.submitted) == (2 if retried else 1) + + +def test_note_choices_rotate(env): + store, jobs, sched = env + add(store, sched, DAILY_0730, blocks=[{"type": "note", "choices": ["A1", "B2"]}]) + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + sched.tick(MON_0729 + dt.timedelta(days=1, minutes=1)) + + assert b"A1" in jobs.submitted[0].payload + assert b"B2" in jobs.submitted[1].payload + + +def test_watcher_primes_then_prints_new_items(env): + store, jobs, sched = env + row = add(store, sched, {"type": "watch", "url": FEED_URL, "every_minutes": 5}, + blocks=[note("{item.title}")]) + + sched.tick(MON_0729) + assert jobs.submitted == [] # first look only records what's there + + seen = store.state(row["id"], "seen") + store.set_state(row["id"], "seen", seen[1:]) # as if "Third post" were new + sched.tick(MON_0729 + dt.timedelta(minutes=6)) + + assert len(jobs.submitted) == 1 + assert b"Third post" in jobs.submitted[0].payload + assert b"Second post" not in jobs.submitted[0].payload + + +def test_calendar_reminders_fire_once_across_restarts(env): + store, jobs, sched = env + source = store.add_source("Work", "ics", CALENDAR_URL) + add(store, sched, {"type": "calendar", "source_id": source["id"], "minutes_before": 10}, + blocks=[note("{event.title} at {event.start}")]) + at = dt.datetime(2026, 10, 26, 9, 20, 30, tzinfo=UTC) # standup 09:30 GMT + + sched.tick(at) + Scheduler(store, jobs, cache=FakeCache()).tick(at + dt.timedelta(seconds=30)) + + assert len(jobs.submitted) == 1 + assert b"Team standup at 09:30" in jobs.submitted[0].payload + + +def test_webhook_rate_limit(env): + store, jobs, sched = env + row = add(store, sched, {"type": "webhook", "per_hour": 1}, blocks=[note("{payload.text}")]) + + job, _ = sched.fire_webhook(row, {"text": "hello"}, MON_0729) + assert b"hello" in job.payload + with pytest.raises(RateLimited): + sched.fire_webhook(row, {"text": "again"}, MON_0729) + + +def test_skip_if_empty(env): + store, jobs, sched = env + source = store.add_source("Empty", "ics", "https://calendar.test/empty.ics") + agenda = {"type": "agenda", "source_ids": [source["id"]]} + add(store, sched, DAILY_0730, blocks=[agenda], skip_if_empty=True) + + sched.tick(MON_0729 + dt.timedelta(minutes=1)) + + assert jobs.submitted == [] + assert store.runs()[0]["state"] == "skipped" + + +def test_template_never_reaches_attributes(): + warnings = [] + now = dt.datetime(2026, 12, 20, tzinfo=UTC) + text = receipt_content.fill( + "{x.__class__} {payload.__class__} {{lit}} {days_until:12-25} {nope}", + now, {"payload": {"a": 1}}, warnings, + ) + + assert text == "{x.__class__} {lit} 5 {nope}" + assert warnings == ["Unknown variable {x.__class__}", "Unknown variable {nope}"] + + +def test_store_keeps_payloads_for_recent_runs_only(monkeypatch): + store = Store() + monkeypatch.setattr("receipt_store.KEEP_PAYLOADS", 2) + for i in range(3): + store.add_run("note", "manual", "done", payload=b"x", + created_at=MON_0729 + dt.timedelta(minutes=i)) + + assert [r["has_payload"] for r in store.runs()] == [1, 1, 0] + assert iso(MON_0729) == "2026-10-26T07:29:00Z" diff --git a/tests/test_triggers.py b/tests/test_triggers.py new file mode 100644 index 0000000..07519d1 --- /dev/null +++ b/tests/test_triggers.py @@ -0,0 +1,180 @@ +import datetime as dt + +import pytest +from conftest import FIXTURES + +pytest.importorskip("dateutil") +pytest.importorskip("pydantic") +from pydantic import TypeAdapter # noqa: E402 + +import receipt_models as models # noqa: E402 +import receipt_triggers as triggers # noqa: E402 +from receipt_sources import parse_events # noqa: E402 +from receipt_store import UTC # noqa: E402 + +TRIGGER = TypeAdapter(models.Trigger) +LONDON = models.Settings(location={"latitude": 51.5, "longitude": -0.12}) +NOON_FRI = dt.datetime(2026, 10, 23, 11, 0, tzinfo=UTC) # 12:00 BST, a Friday + + +def trigger(**spec): + return TRIGGER.validate_python(spec) + + +def local(times): + return [t.astimezone(LONDON.tz).strftime("%a %d %b %H:%M") for t in times] + + +def test_weekdays_at_two_times(): + t = trigger(type="recurring", times=["18:00", "07:30"], weekdays=[0, 1, 2, 3, 4]) + + assert triggers.describe(t, LONDON) == "Weekdays at 07:30 and 18:00" + assert local(triggers.upcoming(t, NOON_FRI, LONDON, 3)) == [ + "Fri 23 Oct 18:00", "Mon 26 Oct 07:30", "Mon 26 Oct 18:00", + ] + + +def test_first_weekday_of_the_month(): + t = trigger(type="recurring", freq="monthly", times=["09:00"], weekdays=[0, 1, 2, 3, 4], + setpos=1) + + assert triggers.describe(t, LONDON) == "Every month on the first weekday at 09:00" + # 1 Nov 2026 is a Sunday, so the first weekday is Monday the 2nd. + assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [ + "Mon 02 Nov 09:00", "Tue 01 Dec 09:00", + ] + + +def test_last_day_of_the_month(): + t = trigger(type="recurring", freq="monthly", times=["09:00"], monthday=-1) + + assert triggers.describe(t, LONDON) == "Every month on the last day at 09:00" + assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [ + "Sat 31 Oct 09:00", "Mon 30 Nov 09:00", + ] + + +def test_every_other_week_counts_from_the_start_date(): + t = trigger(type="recurring", freq="weekly", interval=2, times=["09:00"], weekdays=[0], + start="2026-10-19") + + assert triggers.describe(t, LONDON) == "Every 2 weeks on Mon at 09:00" + assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [ + "Mon 02 Nov 09:00", "Mon 16 Nov 09:00", + ] + + +def test_yearly_and_until(): + t = trigger(type="recurring", freq="yearly", times=["08:00"], month=12, monthday=25, + until="2027-12-31") + + assert triggers.describe(t, LONDON) == "Every year on 25 Dec at 08:00, until 31 Dec 2027" + assert len(triggers.upcoming(t, NOON_FRI, LONDON, 5)) == 2 + + +def test_custom_rule_keeps_the_times(): + t = trigger(type="recurring", times=["09:00"], rrule="FREQ=MONTHLY;BYDAY=-1FR") + + assert local(triggers.upcoming(t, NOON_FRI, LONDON, 1)) == ["Fri 30 Oct 09:00"] + + +def test_bad_custom_rule(): + t = trigger(type="recurring", times=["09:00"], rrule="FREQ=SOMETIMES") + + with pytest.raises(triggers.TriggerError, match="custom rule"): + triggers.next_fire(t, NOON_FRI, LONDON) + + +def test_fall_back_fires_once(): + # 01:30 happens twice in London on 25 Oct 2026; the first (BST) one fires. + t = trigger(type="recurring", times=["01:30"]) + times = triggers.upcoming(t, dt.datetime(2026, 10, 24, 12, tzinfo=UTC), LONDON, 3) + + assert [x.isoformat() for x in times] == [ + "2026-10-25T00:30:00+00:00", "2026-10-26T01:30:00+00:00", "2026-10-27T01:30:00+00:00", + ] + + +def test_spring_forward_shifts_the_missing_time(): + # 01:30 doesn't exist in London on 29 Mar 2026: it fires at 02:30 BST instead. + t = trigger(type="recurring", times=["01:30"]) + first = triggers.next_fire(t, dt.datetime(2026, 3, 28, 12, tzinfo=UTC), LONDON) + + assert first.astimezone(LONDON.tz).strftime("%d %H:%M %Z") == "29 02:30 BST" + + +def test_once(): + t = trigger(type="once", at="2026-10-24T09:00") + + assert triggers.describe(t, LONDON) == "Once, Sat 24 Oct 2026 at 09:00" + assert local([triggers.next_fire(t, NOON_FRI, LONDON)]) == ["Sat 24 Oct 09:00"] + assert triggers.next_fire(t, NOON_FRI + dt.timedelta(days=2), LONDON) is None + + +def test_sun_times(): + t = trigger(type="sun", event="sunrise", offset_minutes=-30) + midsummer = dt.datetime(2026, 6, 20, 12, tzinfo=UTC) + + at = triggers.next_fire(t, midsummer, LONDON).astimezone(LONDON.tz) + + assert triggers.describe(t, LONDON) == "30 min before sunrise" + assert at.date() == dt.date(2026, 6, 21) + assert dt.time(4, 5) <= at.time() <= dt.time(4, 20) # sunrise is about 04:43 BST + + +def test_sun_needs_a_location(): + t = trigger(type="sun", event="sunset") + + assert "set a location" in triggers.describe(t, models.Settings()) + with pytest.raises(triggers.TriggerError, match="location"): + triggers.next_fire(t, NOON_FRI, models.Settings()) + + +def test_calendar_fires_skip_exdates_cancellations_and_all_day(): + start = dt.datetime(2026, 10, 26, tzinfo=LONDON.tz) + events = parse_events((FIXTURES / "calendar.ics").read_bytes(), start, + start + dt.timedelta(days=3), LONDON.tz) + t = trigger(type="calendar", source_id="x", minutes_before=10) + + fires = [(at.astimezone(LONDON.tz).strftime("%a %H:%M"), e.title) + for at, e in triggers.calendar_fires(t, events)] + + assert fires == [ + ("Mon 09:20", "Team standup"), + ("Mon 13:50", "Dentist"), # 14:00 UTC is 14:00 GMT after the clocks change + ("Wed 09:20", "Team standup"), # Tuesday's is an EXDATE + ] + assert triggers.describe(t, LONDON, lambda _id: "Work") == "10 min before events in Work" + + +def test_calendar_filters(): + start = dt.datetime(2026, 10, 26, tzinfo=LONDON.tz) + events = parse_events((FIXTURES / "calendar.ics").read_bytes(), start, + start + dt.timedelta(days=3), LONDON.tz) + + dentist = trigger(type="calendar", source_id="x", contains="DENT") + all_day = trigger(type="calendar", source_id="x", contains="holiday", include_all_day=True) + + assert [e.title for _, e in triggers.calendar_fires(dentist, events)] == ["Dentist"] + assert [e.title for _, e in triggers.calendar_fires(all_day, events)] == ["Bank holiday"] + + +@pytest.mark.parametrize("spec,text", [ + ({"type": "recurring", "times": ["08:00"]}, "Every day at 08:00"), + ({"type": "recurring", "times": ["08:00"], "weekdays": [5, 6]}, "Weekends at 08:00"), + ({"type": "recurring", "times": ["08:00"], "weekdays": [0, 2, 4]}, + "Mon, Wed and Fri at 08:00"), + ({"type": "recurring", "freq": "monthly", "times": ["08:00"], "monthday": 12}, + "Every month on the 12th at 08:00"), + ({"type": "recurring", "freq": "monthly", "times": ["08:00"], "weekdays": [4], + "setpos": -1}, "Every month on the last Fri at 08:00"), + ({"type": "sun", "event": "sunset", "offset_minutes": 90}, "1 h 30 min after sunset"), + ({"type": "watch", "url": "https://example.com/feed"}, + "New items in example.com, checked every 30 min"), + ({"type": "watch", "kind": "json", "url": "https://api.test/x", "path": "price", + "condition": "above", "threshold": 100}, + "When price at api.test goes above 100, checked every 30 min"), + ({"type": "webhook"}, "When its webhook is called (up to 10 an hour)"), +]) +def test_describe(spec, text): + assert triggers.describe(trigger(**spec), LONDON) == text diff --git a/tests/test_web.py b/tests/test_web.py index 936bf42..8ba6fd3 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -219,3 +219,105 @@ def test_serve_refuses_without_token(monkeypatch, capsys): assert rc == 1 assert receipt_web.TOKEN_ENV in capsys.readouterr().err + + +SCHEDULE = {"name": "Chore", "trigger": {"type": "recurring", "times": ["08:00"]}, + "blocks": [{"type": "note", "text": "Water the plants"}]} + + +def test_static_files_need_the_token(client): + assert client.get("/static/app.js").status_code == 401 + res = client.get("/static/app.js", headers=HEADERS) + assert res.status_code == 200 and "javascript" in res.headers["content-type"] + assert client.get("/static/..%2Freceipt.py", headers=HEADERS).status_code == 404 + + +def test_schedule_crud(client): + res = client.post("/api/schedules", headers=HEADERS, json=SCHEDULE) + assert res.status_code == 201, res.text + schedule = res.json()["schedule"] + assert schedule["summary"] == "Every day at 08:00" + assert schedule["next_run_at"] + + edited = {**SCHEDULE, "trigger": {"type": "recurring", "times": ["09:15"], + "weekdays": [5, 6]}} + res = client.put(f"/api/schedules/{schedule['id']}", headers=HEADERS, json=edited) + assert res.json()["schedule"]["summary"] == "Weekends at 09:15" + + res = client.post(f"/api/schedules/{schedule['id']}/duplicate", headers=HEADERS) + assert res.json()["schedule"]["enabled"] is False + assert len(client.get("/api/schedules", headers=HEADERS).json()["schedules"]) == 2 + + assert client.delete(f"/api/schedules/{schedule['id']}", headers=HEADERS).status_code == 200 + assert client.get(f"/api/schedules/{schedule['id']}", headers=HEADERS).status_code == 404 + + +@pytest.mark.parametrize("change,status", [ + ({"blocks": []}, 422), + ({"trigger": {"type": "recurring", "times": []}}, 422), + ({"trigger": {"type": "sun", "event": "sunset"}}, 400), # no location set + ({"trigger": {"type": "calendar", "source_id": "missing"}}, 400), + ({"trigger": {"type": "watch", "url": "file:///etc/passwd"}}, 422), +]) +def test_schedule_validation(client, change, status): + assert client.post("/api/schedules", headers=HEADERS, + json={**SCHEDULE, **change}).status_code == status + + +def test_schedule_test_print(client, fake_printer): + schedule = client.post("/api/schedules", headers=HEADERS, json=SCHEDULE).json()["schedule"] + + res = client.post(f"/api/schedules/{schedule['id']}/run", headers=HEADERS) + + assert finished_job(client, res)["state"] == "done" + assert b"Water the plants" in fake_printer.payloads[0] + + +def test_preview(client): + res = client.post("/api/preview", headers=HEADERS, json={"blocks": [ + {"type": "note", "text": "Hi {nope}"}, {"type": "qr", "content": "https://x.test"}]}) + + body = res.json() + assert body["parts"][0]["text"] == "Hi {nope}" + assert body["parts"][1]["image"].startswith("data:image/png;base64,") + assert body["warnings"] == ["Unknown variable {nope}"] + + +def test_webhook(client, fake_printer): + hook = {**SCHEDULE, "trigger": {"type": "webhook", "per_hour": 1}, + "blocks": [{"type": "note", "text": "{payload.text}"}]} + schedule = client.post("/api/schedules", headers=HEADERS, json=hook).json()["schedule"] + path, secret = f"/{schedule['hook_path']}", schedule["secret"] + token = {"X-Receipt-Token": TOKEN} + + assert client.post(path, content=b"hi").status_code == 401 + assert client.post(path, headers=token, content=b"hi").status_code == 404 + assert client.post(f"{path}?key=wrong", headers=token, content=b"hi").status_code == 404 + res = client.post(path, headers={**token, "X-Hook-Secret": secret}, content=b"Buy milk") + assert finished_job(client, res)["state"] == "done" + assert b"Buy milk" in fake_printer.payloads[0] + res = client.post(f"{path}?key={secret}", headers=token, json={"text": "again"}) + assert res.status_code == 429 + big = b"x" * (receipt_web.MAX_HOOK_BODY + 1) + assert client.post(f"{path}?key={secret}", headers=token, content=big).status_code == 413 + + +def test_history_and_reprint(client, fake_printer): + finished_job(client, client.post("/api/note", headers=HEADERS, json={"text": "again"})) + run = client.get("/api/runs", headers=HEADERS).json()["runs"][0] + assert (run["name"], run["state"], run["has_payload"]) == ("again", "done", 1) + + res = client.post(f"/api/runs/{run['id']}/reprint", headers=HEADERS) + + assert finished_job(client, res)["state"] == "done" + assert fake_printer.payloads[0] == fake_printer.payloads[1] + + +def test_source_in_use_cant_be_deleted(client): + source = client.post("/api/sources", headers=HEADERS, json={ + "name": "Work", "kind": "ics", "url": "webcal://cal.test/x.ics"}).json()["source"] + assert source["url"] == "https://cal.test/x.ics" + client.post("/api/schedules", headers=HEADERS, json={ + **SCHEDULE, "trigger": {"type": "calendar", "source_id": source["id"]}}) + + assert client.delete(f"/api/sources/{source['id']}", headers=HEADERS).status_code == 409 diff --git a/web/api.js b/web/api.js new file mode 100644 index 0000000..8431128 --- /dev/null +++ b/web/api.js @@ -0,0 +1,90 @@ +// Talking to the server: every call is relative, so the /receipt/ prefix nginx adds keeps working. + +function detailText(detail) { + if (!Array.isArray(detail)) return detail; + // Pydantic errors: say where, minus the "body" prefix and union tags. + const tags = ["body", "once", "recurring", "sun", "calendar", "watch", "webhook", "note", "qr", + "image", "random_image", "agenda", "headlines", "divider"]; + return detail.map((d) => { + const where = (d.loc || []) + .filter((p) => !tags.includes(p) && !/[[(]/.test(String(p))) + .map((p) => (typeof p === "number" ? `#${p + 1}` : p.replaceAll("_", " "))); + const msg = String(d.msg || "").replace(/^Value error, /, ""); + return where.length ? `${where.join(" › ")}: ${msg}` : msg; + }).join("; "); +} + +export async function call(path, init = {}) { + init.headers = Object.assign({"X-Requested-With": "receipt"}, init.headers || {}); + let res; + try { + res = await fetch(path, init); + } catch (e) { + return {ok: false, status: 0, text: "Network error: " + e.message, body: {}}; + } + 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, status: res.status, body, + text: offline ? "The printer machine is offline." + : "Signed out? Reload the page and sign in."}; + } + return {ok: res.ok && body.ok !== false, status: res.status, body, + text: body.output || detailText(body.detail) || res.statusText}; +} + +export const get = (path) => call(path); +const withJson = (method) => (path, data) => call(path, { + method, headers: {"Content-Type": "application/json"}, + body: data === undefined ? undefined : JSON.stringify(data), +}); +export const post = withJson("POST"); +export const put = withJson("PUT"); +export const del = withJson("DELETE"); + +// POST something that queues a print, then long-poll the job until it finishes. +// onUpdate(text) reports progress; resolves {ok, text}. +export async function printJob(request, onUpdate = () => {}) { + onUpdate("Sending…"); + let r = await request(); + let job = null; + while (r.ok && r.body.job && !["done", "failed"].includes(r.body.job.state)) { + job = r.body.job; + onUpdate(job.state === "queued" ? "Queued…" : "Printing…"); + r = await call(`api/jobs/${job.id}?wait=20`); + } + if (r.ok && r.body.skipped) return {ok: true, text: r.body.skipped}; + if (!r.ok || !r.body.job) { + return {ok: false, text: r.text + (job && r.status === 0 ? " (the job may still print)" : "")}; + } + return {ok: r.body.job.state === "done", text: r.body.job.message}; +} + +// Lists the editor and settings share; refreshed whenever they change. +export const cache = {sources: null, assets: null, settings: null}; + +export async function sources(refresh = false) { + if (refresh || !cache.sources) { + const r = await get("api/sources"); + cache.sources = r.ok ? r.body.sources : []; + } + return cache.sources; +} + +export async function assets(refresh = false) { + if (refresh || !cache.assets) { + const r = await get("api/assets"); + cache.assets = r.ok ? r.body.assets : []; + } + return cache.assets; +} + +export async function settings(refresh = false) { + if (refresh || !cache.settings) { + const r = await get("api/settings"); + cache.settings = r.ok ? r.body : {settings: {}, timezones: []}; + } + return cache.settings; +} diff --git a/web/app.css b/web/app.css new file mode 100644 index 0000000..d0b4bbf --- /dev/null +++ b/web/app.css @@ -0,0 +1,270 @@ +:root { + --bg: #f6f5f2; --card: #fff; --text: #1d1d1b; --muted: #6b6a66; + --border: #dcdad4; --accent: #2f5bd3; --accent-soft: #e6ecfb; --ok: #1f7a3a; --err: #b42318; + --warn: #9a5b00; --field: #fbfaf8; --shadow: 0 1px 2px rgb(0 0 0 / 6%); + --mono: ui-monospace, "SF Mono", "DejaVu Sans Mono", Menlo, monospace; + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #161615; --card: #20201e; --text: #ecebe7; --muted: #9c9a94; + --border: #3a3936; --accent: #7a9cff; --accent-soft: #263257; --ok: #5cc27c; --err: #ff7a6b; + --warn: #e8a94a; --field: #1a1a19; --shadow: none; + color-scheme: dark; + } +} +* { box-sizing: border-box; } +body { + margin: 0; background: var(--bg); color: var(--text); + font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; +} +a { color: var(--accent); } +h1 { font-size: 1.25rem; margin: 0; } +h2 { font-size: 1.05rem; margin: 0 0 12px; display: flex; align-items: center; gap: 8px; } +h3 { font-size: .95rem; margin: 0 0 10px; } +.small { font-size: .85rem; } +.muted { color: var(--muted); } +.ok { color: var(--ok); } +.err { color: var(--err); } +.warn { color: var(--warn); } +.spacer { flex: 1; } +.indent { margin-left: 24px; } +[hidden] { display: none !important; } + +/* --- frame --- */ +header.top, nav.tabs, main { max-width: 1040px; margin: 0 auto; padding-left: 16px; + padding-right: 16px; } +header.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; + padding-top: 20px; padding-bottom: 8px; } +nav.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); overflow-x: auto; } +nav.tabs a { + padding: 8px 14px; color: var(--muted); text-decoration: none; border-bottom: 2px solid + transparent; margin-bottom: -1px; white-space: nowrap; font-weight: 500; +} +nav.tabs a.on { color: var(--text); border-bottom-color: var(--accent); } +main { padding-top: 18px; padding-bottom: 60px; display: grid; gap: 16px; } +main[aria-busy] { opacity: .6; } + +.card { + background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; + box-shadow: var(--shadow); min-width: 0; +} +.card.flush { padding: 0; } +.toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.toolbar h2 { margin: 0; } +.split { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 16px; + align-items: start; } +.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } +@media (max-width: 820px) { + .split, .grid2 { grid-template-columns: minmax(0, 1fr); } +} +.preview-col h3 { margin: 4px 0 8px; } +.sticky { position: sticky; top: 12px; } +@media (max-width: 820px) { .sticky { position: static; } } + +/* --- controls --- */ +button, .button { + display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px; + border: 1px solid var(--border); border-radius: 6px; background: var(--card); + color: var(--text); font: inherit; font-weight: 500; cursor: pointer; text-decoration: none; +} +button:hover, .button:hover { border-color: var(--muted); } +button:disabled { opacity: .5; cursor: default; } +button.primary { background: var(--accent); border-color: var(--accent); color: #fff; + font-weight: 600; } +@media (prefers-color-scheme: dark) { button.primary { color: #10131c; } } +button.ghost, .button.ghost { background: none; } +button.small, .button.small { padding: 3px 9px; font-size: .85rem; } +button.danger, .danger { color: var(--err); } +textarea, input[type=text], input[type=url], input[type=number], input[type=time], +input[type=date], input[type=datetime-local], input:not([type]), select { + padding: 7px 9px; border: 1px solid var(--border); border-radius: 6px; + background: var(--field); color: var(--text); font: inherit; min-width: 0; max-width: 100%; +} +textarea { width: 100%; min-height: 110px; font-family: var(--mono); font-size: .9rem; + resize: vertical; } +input.narrow { width: 90px; } +input.grow { flex: 1; min-width: 200px; } +input.name { font-size: 1.15rem; font-weight: 600; width: 100%; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.field { display: flex; flex-direction: column; gap: 4px; margin-top: 10px; min-width: 0; } +.field > input[type=text], .field > input:not([type]), .field > input[type=url] { width: 100%; } +.field .caption { font-size: .82rem; color: var(--muted); font-weight: 500; } +.hint { color: var(--muted); font-size: .8rem; } +.check { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; } +.inline { display: inline-flex; align-items: center; gap: 6px; } +.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; + margin-top: 10px; flex-wrap: wrap; } +.row.start { justify-content: flex-start; align-items: end; } +.row.end { justify-content: flex-end; } +.row.center { justify-content: center; } +.row.start > .field { margin-top: 0; } +.row.mid { align-items: center; } +.stack { display: grid; gap: 8px; margin-top: 10px; } + +input.switch { + appearance: none; width: 38px; height: 22px; border-radius: 999px; background: var(--border); + position: relative; cursor: pointer; flex: none; margin: 0; transition: background .15s; +} +input.switch::after { + content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; + border-radius: 50%; background: #fff; transition: transform .15s; +} +input.switch:checked { background: var(--ok); } +input.switch:checked::after { transform: translateX(16px); } + +.segmented { display: inline-flex; flex-wrap: wrap; border: 1px solid var(--border); + border-radius: 8px; padding: 2px; gap: 2px; background: var(--field); } +.segmented button { border: 0; background: none; padding: 5px 12px; color: var(--muted); } +.segmented button.on { background: var(--card); color: var(--text); box-shadow: var(--shadow); + outline: 1px solid var(--border); } +.chips { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { padding: 3px 10px; border-radius: 999px; font-size: .85rem; font-weight: 500; } +.chip.on { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); } +.chip.small { padding: 1px 8px; font-family: var(--mono); font-size: .78rem; } +.vars { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; margin-top: 6px; } + +.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); } +.badge { display: inline-block; font-size: .75rem; font-weight: 600; padding: 1px 8px; + border-radius: 999px; background: var(--field); border: 1px solid var(--border); + color: var(--muted); white-space: nowrap; } +.badge.ok { color: var(--ok); border-color: currentColor; } +.badge.err { color: var(--err); border-color: currentColor; } +.badge.warn { color: var(--warn); border-color: currentColor; } + +#toast { + position: fixed; left: 50%; bottom: 20px; transform: translate(-50%, 20px); opacity: 0; + background: var(--text); color: var(--bg); padding: 9px 16px; border-radius: 8px; + pointer-events: none; transition: all .2s; max-width: calc(100vw - 32px); z-index: 20; +} +#toast.show { opacity: 1; transform: translate(-50%, 0); } +#toast.err { background: var(--err); color: #fff; } + +/* --- print tab --- */ +.drop { + display: block; border: 2px dashed var(--border); border-radius: 8px; padding: 22px 16px; + text-align: center; color: var(--muted); cursor: pointer; margin: 12px 0 8px; +} +.drop.over { border-color: var(--accent); color: var(--accent); } +form > input[type=text] { width: 100%; } +.status { margin: 12px 0 0; font-family: var(--mono); font-size: .85rem; white-space: pre-wrap; } +.status.ok { color: var(--ok); } +.status.err { color: var(--err); } +.card .segmented { margin-bottom: 12px; } + +/* --- paper preview --- */ +.paper-wrap { display: grid; gap: 8px; } +.paper { + background: #fff; color: #161616; padding: 14px 12px 20px; margin: 0 auto 8px; width: 100%; + max-width: 330px; position: relative; box-shadow: 0 1px 4px rgb(0 0 0 / 15%); + border-radius: 2px 2px 0 0; +} +.paper::after { /* the torn edge */ + content: ""; position: absolute; left: 0; right: 0; bottom: -7px; height: 8px; + background: linear-gradient(-45deg, transparent 5px, #fff 0) 0 0 / 10px 8px repeat-x, + linear-gradient(45deg, transparent 5px, #fff 0) 0 0 / 10px 8px repeat-x; +} +.paper-strip { container-type: inline-size; min-height: 60px; } +.paper .t { + margin: 0; font-family: var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; + font-size: calc(100cqw / 48 / .615); line-height: 1.25; +} +.paper .t.s2 { font-size: calc(100cqw / 24 / .615); } +.paper .t.s3 { font-size: calc(100cqw / 16 / .615); } +.paper .t.b { font-weight: 700; } +.paper .t.c { text-align: center; } +.paper .t.placeholder { color: #888; font-family: system-ui, sans-serif; font-size: .85rem; + text-align: center; padding: 20px 0; } +.paper img { display: block; width: 100%; image-rendering: pixelated; margin: 4px 0; } +.paper-wrap.error .paper .placeholder { color: var(--err); } +.paper-meta { text-align: center; font-size: .82rem; } +.paper-meta .warn { margin-top: 2px; } + +/* --- schedules --- */ +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; } +.schedule { display: flex; flex-direction: column; gap: 6px; } +.schedule.off { opacity: .65; } +.card-head { display: flex; align-items: center; gap: 10px; } +.card-head .title { font-weight: 600; color: var(--text); text-decoration: none; flex: 1; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card-head .title:hover { text-decoration: underline; } +.icon { display: inline-grid; place-items: center; width: 30px; height: 30px; flex: none; + border-radius: 8px; background: var(--accent-soft); color: var(--accent); font-size: 1rem; } +.schedule .summary { margin: 0; } +.schedule .meta { margin: 0; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; + font-size: .85rem; color: var(--muted); } +.schedule .meta .last { flex-basis: 100%; } +.actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: auto; + padding-top: 6px; } +.coming:empty { display: none; } +.coming h3 { margin: 0 0 6px; } +.timeline { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 4px; } +.timeline .tick { display: grid; padding: 6px 12px; border: 1px solid var(--border); + border-radius: 8px; background: var(--card); text-decoration: none; color: var(--text); + min-width: 110px; font-size: .85rem; } +.timeline .tick span { color: var(--muted); white-space: nowrap; overflow: hidden; + text-overflow: ellipsis; max-width: 160px; } +.empty { text-align: center; padding: 20px 0; } +.presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: 10px; text-align: left; } +.preset { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; align-items: start; + padding: 12px; text-align: left; font-weight: 400; } +.preset .icon { grid-row: span 2; } +dialog.sheet { border: 1px solid var(--border); border-radius: 12px; background: var(--bg); + color: var(--text); width: min(760px, calc(100vw - 32px)); padding: 16px; } +dialog.sheet::backdrop { background: rgb(0 0 0 / 40%); } +dialog.sheet .toolbar { margin-bottom: 12px; justify-content: space-between; } + +/* --- editor --- */ +.back { text-decoration: none; } +.editor-head { display: grid; gap: 6px; } +.editor-head .meta { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.editor { display: grid; gap: 16px; min-width: 0; } +.step { display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 50%; + background: var(--accent); color: #fff; font-size: .75rem; } +@media (prefers-color-scheme: dark) { .step { color: #10131c; } } +.trigger-form { margin-top: 4px; } +.trigger-info { margin-top: 14px; padding-top: 12px; border-top: 1px dashed var(--border); } +.trigger-info:empty { display: none; } +.trigger-info .summary { margin: 0; font-weight: 600; } +.next-runs { margin: 6px 0 0; padding-left: 18px; font-size: .88rem; } +.times { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.time { display: inline-flex; align-items: center; gap: 2px; } +.blocks { display: grid; gap: 10px; } +.block { border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; + background: var(--field); } +.block-head { display: flex; align-items: center; gap: 4px; } +.block-head strong { font-size: .9rem; } +.add-block { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +details { margin-top: 10px; } +details > summary { cursor: pointer; color: var(--muted); font-size: .9rem; } +details > summary h2 { display: inline-flex; margin: 0; color: var(--text); } +.copyable { display: flex; gap: 6px; align-items: center; min-width: 0; } +.copyable code, pre.code { font-family: var(--mono); font-size: .8rem; background: var(--field); + border: 1px solid var(--border); border-radius: 6px; padding: 5px 8px; overflow-x: auto; + white-space: nowrap; min-width: 0; } +pre.code { white-space: pre; margin: 8px 0; } +.editor-bar { position: sticky; top: 0; z-index: 5; background: var(--bg); + padding: 8px 0; margin: -8px 0 0; border-bottom: 1px solid transparent; } +.editor-bar .actions { margin: 0; padding: 0; } + +/* --- history and settings --- */ +.history .run { display: grid; grid-template-columns: 130px 1fr auto; gap: 12px; + padding: 10px 16px; border-bottom: 1px solid var(--border); align-items: center; } +.history .run:last-child { border-bottom: 0; } +.history .when { color: var(--muted); font-size: .85rem; } +.history .empty { padding: 16px; } +@media (max-width: 600px) { + .history .run { grid-template-columns: 1fr auto; } + .history .when { grid-column: 1 / -1; } +} +.list-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 0; + border-bottom: 1px solid var(--border); } +.list-row code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + max-width: 260px; } +.add-source { margin-top: 12px; } diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..8748c13 --- /dev/null +++ b/web/app.js @@ -0,0 +1,54 @@ +// Hash router and the printer status pill. + +import {get} from "./api.js"; +import {$} from "./dom.js"; +import {editorView} from "./editor.js"; +import {historyView} from "./history.js"; +import {printView} from "./print.js"; +import {schedulesView} from "./schedules.js"; +import {settingsView} from "./settings.js"; + +const view = $("#view"); +let current = null; // what the active view returned: a cleanup function or {canLeave} +let currentHash = location.hash; + +async function route() { + const hash = location.hash || "#print"; + if (current?.canLeave && hash !== currentHash && !current.canLeave()) { + history.replaceState(null, "", currentHash); // stay put + return; + } + if (typeof current === "function") current(); + current = null; + currentHash = hash; + const [tab, arg] = hash.slice(1).split("/"); + document.querySelectorAll("nav.tabs a").forEach((a) => + a.classList.toggle("on", a.getAttribute("href") === `#${tab}`)); + view.setAttribute("aria-busy", "true"); + if (tab === "schedules" && arg) current = await editorView(view, arg); + else if (tab === "schedules") current = await schedulesView(view); + else if (tab === "history") current = await historyView(view, arg); + else if (tab === "settings") current = await settingsView(view); + else current = printView(view); + view.removeAttribute("aria-busy"); + window.scrollTo(0, 0); +} + +window.addEventListener("hashchange", route); +window.addEventListener("beforeunload", (e) => { + if (current?.isDirty?.()) e.preventDefault(); +}); + +async function checkStatus() { + const pill = $("#status"); + pill.textContent = "checking…"; + pill.className = "pill"; + const r = await get("api/status"); + pill.textContent = r.body.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline"; + pill.className = `pill ${r.ok ? "ok" : "err"}`; + pill.title = r.text; +} + +$("#status").addEventListener("click", checkStatus); +checkStatus(); +route(); diff --git a/web/dom.js b/web/dom.js new file mode 100644 index 0000000..cadd74e --- /dev/null +++ b/web/dom.js @@ -0,0 +1,154 @@ +// Small DOM and formatting helpers shared by the tabs. + +export const $ = (selector, root = document) => root.querySelector(selector); + +// h("button", {class: "x", onclick: fn}, "text", child) -> element +export function h(tag, props, ...children) { + const el = document.createElement(tag); + for (const [key, value] of Object.entries(props || {})) { + if (value === null || value === undefined || value === false) continue; + if (key.startsWith("on")) el.addEventListener(key.slice(2), value); + else if (key === "class") el.className = value; + else if (key === "dataset") Object.assign(el.dataset, value); + else if (key === "style") el.style.cssText = value; + else if (key === "value") el.value = value; // a textarea has no value attribute + else if (key in el && typeof value !== "string") el[key] = value; + else el.setAttribute(key, value === true ? "" : value); + } + append(el, children); + return el; +} + +function append(el, children) { + for (const child of children.flat(Infinity)) { + if (child === null || child === undefined || child === false) continue; + el.append(child instanceof Node ? child : String(child)); + } +} + +export function clear(el, ...children) { + el.replaceChildren(); + append(el, children); + return el; +} + +let toastTimer = null; +export function toast(text, kind = "") { + const el = $("#toast"); + el.textContent = text; + el.className = `show ${kind}`; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { el.className = ""; }, kind === "err" ? 6000 : 3000); +} + +export function debounce(fn, ms) { + let timer = null; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), ms); + }; +} + +export const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; +export const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", + "Nov", "Dec"]; + +export function fmtTime(iso) { + if (!iso) return ""; + const d = new Date(iso); + const today = new Date(); + const time = d.toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); + if (d.toDateString() === today.toDateString()) return `Today ${time}`; + const tomorrow = new Date(today); tomorrow.setDate(today.getDate() + 1); + if (d.toDateString() === tomorrow.toDateString()) return `Tomorrow ${time}`; + const opts = {weekday: "short", day: "numeric", month: "short"}; + if (d.getFullYear() !== today.getFullYear()) opts.year = "numeric"; + return `${d.toLocaleDateString([], opts)} ${time}`; +} + +export function relative(iso) { + if (!iso) return ""; + const minutes = Math.round((new Date(iso) - Date.now()) / 60000); + const abs = Math.abs(minutes); + let text; + if (abs < 1) return "now"; + if (abs < 60) text = `${abs} min`; + else if (abs < 60 * 36) text = `${Math.round(abs / 60)} h`; + else text = `${Math.round(abs / 1440)} days`; + return minutes > 0 ? `in ${text}` : `${text} ago`; +} + +// A