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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 23:58:26 +01:00
co-authored by Claude Opus 5.5
parent fa99c3076c
commit ba92f1fbda
29 changed files with 5433 additions and 294 deletions
+4 -1
View File
@@ -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)
+20
View File
@@ -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/<id>`) 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/<id> -H 'X-Hook-Secret: <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
+16 -1
View File
@@ -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
+169 -49
View File
@@ -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
+372
View File
@@ -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
+282
View File
@@ -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)
+609
View File
@@ -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
+186
View File
@@ -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
+409
View File
@@ -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)
+295
View File
@@ -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"
+579 -243
View File
@@ -9,40 +9,76 @@ Jobs are rendered and validated in the request (bad input is a 400 at once),
then queued: POST answers 202 with a job id and the page long-polls
/api/jobs/{id}, so no request waits behind another print long enough for
nginx's proxy timeout to report a failure while the job still prints.
Uploads are printed from memory and never written to disk.
Uploads are printed from memory and never written to disk (images for
scheduled receipts are kept in the database).
The same process runs the scheduler (receipt_scheduler) over the schedules
in the database (receipt_store). Webhooks (/hook/{id}) are the one route
for other services: nginx forwards them without the admin login, still
adding the token, and each schedule's own secret authorizes the call.
"""
from __future__ import annotations
import argparse
import base64
import datetime as dt
import hashlib
import hmac
import io
import json
import logging
import os
import queue
import re
import secrets
import sys
import threading
from collections import OrderedDict
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import parse_qsl
from zoneinfo import available_timezones
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Query, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
from fastapi import (
Depends,
FastAPI,
File,
Form,
Header,
HTTPException,
Query,
Request,
UploadFile,
)
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel, Field, ValidationError
from starlette.concurrency import run_in_threadpool
import receipt
import receipt_models as models
from receipt_content import VARIABLES
from receipt_scheduler import QueueFull, RateLimited, Scheduler
from receipt_sources import SourceError, fetch, json_value, parse_events, parse_items
from receipt_store import Store, default_path, iso, utcnow
from receipt_triggers import TriggerError, describe, ruleset
TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret
MIN_TOKEN_CHARS = 16
MAX_NOTE_CHARS = 4000
MAX_CAPTION_CHARS = 500
MAX_NOTE_CHARS = models.MAX_NOTE_CHARS
MAX_CAPTION_CHARS = models.MAX_CAPTION_CHARS
MAX_QUEUED = 10 # jobs waiting for the printer; more is a 503
MAX_JOB_HISTORY = 50 # finished jobs kept for polling
MAX_WAIT_SECONDS = 25 # long-poll cap, well under nginx's 90 s proxy_read_timeout
MAX_HOOK_BODY = 64 * 1024
# Sent by the page's fetch(). A cross-site form can't set it, and a cross-site
# fetch that sets it needs a CORS preflight, which nginx's auth gate refuses.
CSRF_HEADER_VALUE = "receipt"
FINISHED = ("done", "failed")
WEB_DIR = Path(__file__).resolve().parent / "web"
STATIC_NAME = re.compile(r"^[a-z_]+\.(js|css|svg)$")
STATIC_TYPES = {".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml"}
log = logging.getLogger("receipt_web")
@@ -53,6 +89,29 @@ class Note(BaseModel):
size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES))
class Qr(BaseModel):
content: str = Field(min_length=1, max_length=2000)
caption: str = Field(default="", max_length=MAX_CAPTION_CHARS)
class PreviewIn(models.Model):
blocks: list[models.Block] = Field(min_length=1, max_length=models.MAX_BLOCKS)
trigger: models.Trigger | None = None
schedule_id: str | None = None
class TriggerPreviewIn(models.Model):
trigger: models.Trigger
class Toggle(models.Model):
enabled: bool
class SourceTest(models.SourceIn):
name: str = "test"
@dataclass
class Job:
id: str
@@ -60,7 +119,10 @@ class Job:
user: str | None
state: str = "queued" # queued -> printing -> done | failed
message: str = ""
error: str | None = None # "unavailable" or "failed" when state is failed
error: str | None = None # "unavailable", "dropped" or "failed" when state is failed
source: str = "manual"
schedule_id: str | None = None
name: str | None = None
def public(self) -> dict:
return {k: getattr(self, k) for k in ("id", "kind", "state", "message", "error")}
@@ -71,12 +133,15 @@ class PrintQueue:
The printer takes a single connection, so the worker holds printer_lock
for each send; the status check only tries the lock, so it never waits
behind a long print.
behind a long print. With a store, every job is also written to the
print history.
"""
def __init__(self, config: receipt.PrinterConfig):
def __init__(self, config: receipt.PrinterConfig, store: Store | None = None):
self.config = config
self.store = store
self.printer_lock = threading.Lock()
self.listeners: list[Callable[[Job], None]] = [] # called with each finished job
self._changed = threading.Condition()
self._jobs: OrderedDict[str, Job] = OrderedDict()
self._pending: queue.Queue[tuple[Job, bytes]] = queue.Queue(MAX_QUEUED)
@@ -86,16 +151,31 @@ class PrintQueue:
def queued(self) -> int:
return self._pending.qsize()
def submit(self, kind: str, payload: bytes, user: str | None) -> Job:
job = Job(secrets.token_hex(8), kind, user)
try:
self._pending.put_nowait((job, payload))
except queue.Full:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
def submit(
self,
kind: str,
payload: bytes,
user: str | None,
*,
source: str = "manual",
schedule_id: str | None = None,
name: str | None = None,
) -> Job:
job = Job(secrets.token_hex(8), kind, user, source=source, schedule_id=schedule_id,
name=name)
# Under the lock, so the worker can't record a state before the run exists.
with self._changed:
try:
self._pending.put_nowait((job, payload))
except queue.Full:
raise QueueFull from None
self._jobs[job.id] = job
while len(self._jobs) > MAX_JOB_HISTORY:
self._jobs.popitem(last=False)
if self.store is not None:
self.store.add_run(kind, source, "queued", run_id=job.id,
schedule_id=schedule_id, name=name, user=user,
payload=payload)
log.info("job %s: %s queued by %s", job.id, kind, user or "unknown")
return job
@@ -110,6 +190,8 @@ class PrintQueue:
def _update(self, job: Job, state: str, message: str = "", error: str | None = None) -> None:
with self._changed:
job.state, job.message, job.error = state, message, error
if self.store is not None:
self.store.finish_run(job.id, state, message, error)
self._changed.notify_all()
def _work(self) -> None:
@@ -119,6 +201,8 @@ class PrintQueue:
with self.printer_lock:
try:
receipt.send(self.config, payload)
except receipt.PrinterDropped as e:
self._update(job, "failed", f"Printer unavailable: {e}", "dropped")
except receipt.PrinterUnavailable as e:
self._update(job, "failed", f"Printer unavailable: {e}", "unavailable")
except Exception as e:
@@ -127,12 +211,66 @@ class PrintQueue:
else:
self._update(job, "done", "Printed.")
log.info("job %s: %s %s", job.id, job.state, job.message)
for listener in self.listeners:
try:
listener(job)
except Exception:
log.exception("job listener failed")
def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
jobs = PrintQueue(config)
def hash_secret(secret: str) -> str:
return hashlib.sha256(secret.encode()).hexdigest()
def png_data_url(image) -> str:
buf = io.BytesIO()
image.save(buf, "PNG", optimize=True)
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
def preview_json(blocks: list[receipt.Block], warnings: list[str]) -> dict:
parts = []
for block in blocks:
for part in block.parts:
if "image" in part:
parts.append({"image": png_data_url(part["image"])})
else:
parts.append({k: part.get(k) for k in ("text", "size", "bold", "center")})
height = receipt.receipt_height(blocks)
return {
"ok": True,
"parts": parts,
"height_mm": round(height / receipt.DOTS_PER_MM),
"max_mm": receipt.MAX_PRINT_HEIGHT_DOTS // receipt.DOTS_PER_MM,
"too_long": height > receipt.MAX_PRINT_HEIGHT_DOTS,
"warnings": warnings,
}
def run_name(text: str, limit: int = 60) -> str:
"""A one-line label for the history list."""
line = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
return line if len(line) <= limit else line[: limit - 1] + "…"
def create_app(
config: receipt.PrinterConfig,
token: str,
store: Store | None = None,
clock: Callable[[], dt.datetime] | None = None,
start_scheduler: bool = True,
) -> FastAPI:
store = store or Store()
store.fail_interrupted_runs()
jobs = PrintQueue(config, store)
scheduler = Scheduler(store, jobs, clock or utcnow)
jobs.listeners.append(scheduler.job_finished)
if start_scheduler:
scheduler.start()
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.state.jobs = jobs
app.state.store = store
app.state.scheduler = scheduler
def require_token(x_receipt_token: str | None = Header(default=None)) -> None:
if x_receipt_token is None or not hmac.compare_digest(
@@ -150,19 +288,105 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
def queue_job(kind: str, payload: bytes, user: str | None, name: str) -> JSONResponse:
try:
job = jobs.submit(kind, payload, user, name=name)
except QueueFull:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
return accepted(job)
def accepted(job: Job) -> JSONResponse:
return JSONResponse({"ok": True, "job": job.public()}, status_code=202)
def settings() -> models.Settings:
return scheduler.settings()
def source_name(source_id: str) -> str:
source = store.source(source_id)
return source["name"] if source else "a deleted calendar"
def schedule_out(row: dict, secret: str | None = None) -> dict:
out = {k: row[k] for k in ("id", "name", "enabled", "spec", "next_run_at", "last_run_at",
"last_status", "last_message", "created_at", "updated_at")}
try:
spec = models.ScheduleSpec.model_validate(row["spec"])
out["summary"] = describe(spec.trigger, settings(), source_name)
except ValidationError:
out["summary"] = "Invalid schedule"
return out
if spec.trigger.type == "webhook":
out["hook_path"] = f"hook/{row['id']}"
out["has_secret"] = store.state(row["id"], "hook_secret") is not None
if secret:
out["secret"] = secret
return out
def get_schedule(schedule_id: str) -> dict:
row = store.schedule(schedule_id)
if row is None:
raise HTTPException(404, "No such schedule.")
return row
def check_spec(spec: models.ScheduleSpec) -> None:
"""References and rules the models can't check alone; raises a 400."""
trigger = spec.trigger
if trigger.type == "recurring":
if trigger.start is None:
trigger.start = utcnow().astimezone(settings().tz).date()
try:
ruleset(trigger)
except TriggerError as e:
raise HTTPException(400, str(e)) from None
if trigger.type == "sun" and settings().location is None:
raise HTTPException(400, "Sun times need a location: set one in Settings first.")
if trigger.type == "calendar":
source = store.source(trigger.source_id)
if source is None or source["kind"] != "ics":
raise HTTPException(400, "Pick a saved calendar for the reminders.")
for block in spec.blocks:
if block.type in ("agenda", "headlines"):
kind = "ics" if block.type == "agenda" else "rss"
for source_id in block.source_ids:
source = store.source(source_id)
if source is None or source["kind"] != kind:
raise HTTPException(400, f"A {block.type} block reads a missing source.")
if block.type == "image" and store.asset(block.asset_id) is None:
raise HTTPException(400, "An image block's picture has been deleted.")
def spec_dict(body: models.ScheduleSpec) -> dict:
return body.model_dump(mode="json", include={"trigger", "blocks", "options"})
def new_secret(schedule_id: str) -> str:
secret = secrets.token_urlsafe(24)
store.set_state(schedule_id, "hook_secret", hash_secret(secret))
return secret
def uses(predicate: Callable[[dict], bool]) -> list[str]:
"""Names of schedules whose spec matches (to refuse deleting what they use)."""
return [row["name"] for row in store.schedules() if predicate(row["spec"])]
authed = [Depends(require_token)]
posting = [Depends(require_token), Depends(require_page_request)]
# --- page ---
@app.get("/healthz")
def healthz() -> dict:
return {"ok": True}
@app.get("/", response_class=HTMLResponse, dependencies=authed)
def page() -> str:
return PAGE
@app.get("/", dependencies=authed)
def page() -> FileResponse:
return FileResponse(WEB_DIR / "index.html", headers={"Cache-Control": "no-cache"})
@app.get("/static/{name}", dependencies=authed)
def static(name: str) -> FileResponse:
path = WEB_DIR / name
if not STATIC_NAME.match(name) or not path.is_file():
raise HTTPException(404, "Not found.")
return FileResponse(path, media_type=STATIC_TYPES[path.suffix],
headers={"Cache-Control": "no-cache"})
# --- printing now ---
@app.get("/api/status", dependencies=authed)
def status() -> JSONResponse:
@@ -191,7 +415,20 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
@app.post("/api/note", dependencies=posting)
def note(body: Note, x_remote_user: str | None = Header(default=None)) -> JSONResponse:
payload = render(receipt.render_note, body.text, body.timestamp, body.size)
return accepted(jobs.submit("note", payload, x_remote_user or None))
return queue_job("note", payload, x_remote_user or None, run_name(body.text))
@app.post("/api/qr", dependencies=posting)
def qr(body: Qr, x_remote_user: str | None = Header(default=None)) -> JSONResponse:
payload = render(receipt.render_qr, body.content, body.caption.strip() or None)
return queue_job("qr", payload, x_remote_user or None, run_name(body.content))
def read_upload(file: UploadFile) -> bytes:
data = file.file.read(receipt.MAX_IMAGE_BYTES + 1)
if len(data) > receipt.MAX_IMAGE_BYTES:
raise HTTPException(
413, f"Image exceeds the {receipt.MAX_IMAGE_BYTES // 1024 // 1024} MB cap."
)
return data
@app.post("/api/image", dependencies=posting)
def image(
@@ -199,17 +436,329 @@ def create_app(config: receipt.PrinterConfig, token: str) -> FastAPI:
message: str = Form(default="", max_length=MAX_CAPTION_CHARS),
x_remote_user: str | None = Header(default=None),
) -> JSONResponse:
data = file.file.read(receipt.MAX_IMAGE_BYTES + 1)
if len(data) > receipt.MAX_IMAGE_BYTES:
raise HTTPException(
413, f"Image exceeds the {receipt.MAX_IMAGE_BYTES // 1024 // 1024} MB cap."
)
data = read_upload(file)
payload = render(receipt.render_image, io.BytesIO(data), message.strip() or None)
return accepted(jobs.submit("image", payload, x_remote_user or None))
return queue_job("image", payload, x_remote_user or None,
run_name(message) or file.filename or "image")
@app.post("/api/preview/image", dependencies=posting)
def preview_image(
file: UploadFile = File(...), # noqa: B008
message: str = Form(default="", max_length=MAX_CAPTION_CHARS),
) -> dict:
data = read_upload(file)
block = render(receipt.image_block, io.BytesIO(data), message.strip() or None)
return preview_json([block], [])
@app.post("/api/preview", dependencies=posting)
def preview(body: PreviewIn) -> dict:
now = scheduler.clock()
current = settings()
row = {"id": body.schedule_id, "name": ""}
if body.schedule_id and (saved := store.schedule(body.schedule_id)):
row["name"] = saved["name"]
values = scheduler.sample_values(body.trigger, now, current) if body.trigger else {}
spec = models.ScheduleSpec.model_construct(blocks=body.blocks, options=models.Options())
try:
built = scheduler.build(row, spec, now, current, [values], preview=True)
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
if not built.blocks:
raise HTTPException(400, "Nothing to print.")
return preview_json(built.blocks, built.warnings)
# --- history ---
@app.get("/api/runs", dependencies=authed)
def runs(
limit: int = Query(default=50, ge=1, le=200),
before: str | None = Query(default=None, max_length=40),
schedule_id: str | None = Query(default=None, max_length=40),
state: str | None = Query(default=None, max_length=20),
) -> dict:
return {"ok": True, "runs": store.runs(limit, before, schedule_id, state)}
@app.post("/api/runs/{run_id}/reprint", dependencies=posting)
def reprint(run_id: str, x_remote_user: str | None = Header(default=None)) -> JSONResponse:
found = store.run_payload(run_id)
if found is None:
raise HTTPException(404, "That print is too old to print again.")
row, payload = found
return queue_job(row["kind"], payload, x_remote_user or None, row["name"] or row["kind"])
# --- schedules ---
@app.get("/api/schedules", dependencies=authed)
def list_schedules() -> dict:
return {"ok": True, "schedules": [schedule_out(r) for r in store.schedules()]}
@app.get("/api/schedules/{schedule_id}", dependencies=authed)
def read_schedule(schedule_id: str) -> dict:
return {"ok": True, "schedule": schedule_out(get_schedule(schedule_id))}
@app.post("/api/schedules", dependencies=posting)
def add_schedule(body: models.ScheduleIn) -> JSONResponse:
check_spec(body)
row = store.add_schedule(body.name, spec_dict(body), body.enabled)
secret = new_secret(row["id"]) if body.trigger.type == "webhook" else None
row = scheduler.reschedule(row)
log.info("schedule %s (%s) added", row["id"], row["name"])
return JSONResponse({"ok": True, "schedule": schedule_out(row, secret)}, status_code=201)
@app.put("/api/schedules/{schedule_id}", dependencies=posting)
def edit_schedule(schedule_id: str, body: models.ScheduleIn) -> dict:
old = get_schedule(schedule_id)
check_spec(body)
spec = spec_dict(body)
fields = {"name": body.name, "enabled": body.enabled, "spec": spec,
"updated_at": iso(utcnow())}
if spec["trigger"] != old["spec"].get("trigger"):
store.clear_state(schedule_id, keep=("hook_secret",))
fields.update(last_status=None, last_message=None)
row = store.update_schedule(schedule_id, **fields)
secret = None
if body.trigger.type == "webhook" and store.state(schedule_id, "hook_secret") is None:
secret = new_secret(schedule_id)
row = scheduler.reschedule(row)
return {"ok": True, "schedule": schedule_out(row, secret)}
@app.delete("/api/schedules/{schedule_id}", dependencies=posting)
def delete_schedule(schedule_id: str) -> dict:
if not store.delete_schedule(schedule_id):
raise HTTPException(404, "No such schedule.")
return {"ok": True}
@app.post("/api/schedules/{schedule_id}/toggle", dependencies=posting)
def toggle_schedule(schedule_id: str, body: Toggle) -> dict:
get_schedule(schedule_id)
row = store.update_schedule(schedule_id, enabled=body.enabled)
if body.enabled:
row = scheduler.reschedule(row)
return {"ok": True, "schedule": schedule_out(row)}
@app.post("/api/schedules/{schedule_id}/duplicate", dependencies=posting)
def duplicate_schedule(schedule_id: str) -> JSONResponse:
old = get_schedule(schedule_id)
row = store.add_schedule(f"{old['name']} (copy)"[:100], old["spec"], enabled=False)
return JSONResponse({"ok": True, "schedule": schedule_out(row)}, status_code=201)
@app.post("/api/schedules/{schedule_id}/run", dependencies=posting)
def test_schedule(schedule_id: str) -> JSONResponse:
row = get_schedule(schedule_id)
try:
job = scheduler.test_print(row)
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
except ValidationError:
raise HTTPException(400, "This schedule is invalid; edit and save it.") from None
except QueueFull:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
return accepted(job)
@app.post("/api/schedules/{schedule_id}/secret", dependencies=posting)
def regenerate_secret(schedule_id: str) -> dict:
row = get_schedule(schedule_id)
if row["spec"].get("trigger", {}).get("type") != "webhook":
raise HTTPException(400, "Only webhook schedules have a secret.")
return {"ok": True, "schedule": schedule_out(row, new_secret(schedule_id))}
@app.post("/api/triggers/preview", dependencies=posting)
def preview_trigger(body: TriggerPreviewIn) -> dict:
trigger = body.trigger
current = settings()
if trigger.type == "recurring" and trigger.start is None:
trigger.start = scheduler.clock().astimezone(current.tz).date()
out = {"ok": True, "summary": describe(trigger, current, source_name), "next": [],
"error": None}
try:
out["next"] = [iso(t) for t in scheduler.trigger_runs(trigger, scheduler.clock(),
current, 5)]
except (TriggerError, SourceError) as e:
out["error"] = str(e)
return out
@app.get("/api/upcoming", dependencies=authed)
def upcoming(hours: int = Query(default=24, ge=1, le=24 * 7)) -> dict:
now = scheduler.clock()
horizon = now + dt.timedelta(hours=hours)
items = []
for row in store.schedules():
if not row["enabled"]:
continue
try:
times = scheduler.next_runs(row, 20)
except (TriggerError, SourceError, ValidationError):
continue
items.extend({"schedule_id": row["id"], "name": row["name"], "at": iso(t)}
for t in times if t <= horizon)
items.sort(key=lambda i: i["at"])
return {"ok": True, "upcoming": items[:50]}
@app.get("/api/variables", dependencies=authed)
def variables() -> dict:
return {"ok": True, "variables": VARIABLES}
# --- images for scheduled receipts ---
@app.get("/api/assets", dependencies=authed)
def list_assets() -> dict:
return {"ok": True, "assets": store.assets()}
@app.post("/api/assets", dependencies=posting)
def add_asset(file: UploadFile = File(...)) -> JSONResponse: # noqa: B008
data = read_upload(file)
render(receipt.image_block, io.BytesIO(data)) # refuse what wouldn't print
asset = store.add_asset((file.filename or "image")[:100], data)
return JSONResponse({"ok": True, "asset": asset}, status_code=201)
@app.delete("/api/assets/{asset_id}", dependencies=posting)
def delete_asset(asset_id: str) -> dict:
users = uses(lambda spec: any(b.get("asset_id") == asset_id
for b in spec.get("blocks", [])))
if users:
raise HTTPException(409, f"Used by: {', '.join(users)}.")
if not store.delete_asset(asset_id):
raise HTTPException(404, "No such image.")
return {"ok": True}
# --- saved calendars and feeds ---
@app.get("/api/sources", dependencies=authed)
def list_sources() -> dict:
return {"ok": True, "sources": store.sources()}
@app.post("/api/sources", dependencies=posting)
def add_source(body: models.SourceIn) -> JSONResponse:
source = store.add_source(body.name, body.kind, body.url)
return JSONResponse({"ok": True, "source": source}, status_code=201)
@app.put("/api/sources/{source_id}", dependencies=posting)
def edit_source(source_id: str, body: models.SourceIn) -> dict:
old = store.source(source_id)
if old is None:
raise HTTPException(404, "No such source.")
scheduler.cache.forget(old["url"])
return {"ok": True, "source": store.update_source(source_id, body.name, body.kind,
body.url)}
@app.delete("/api/sources/{source_id}", dependencies=posting)
def delete_source(source_id: str) -> dict:
def reads(spec: dict) -> bool:
if spec.get("trigger", {}).get("source_id") == source_id:
return True
return any(source_id in b.get("source_ids", []) for b in spec.get("blocks", []))
users = uses(reads)
if users:
raise HTTPException(409, f"Used by: {', '.join(users)}.")
if not store.delete_source(source_id):
raise HTTPException(404, "No such source.")
return {"ok": True}
@app.post("/api/sources/test", dependencies=posting)
def test_source(body: SourceTest) -> dict:
try:
data = fetch(body.url)
if body.kind == "ics":
now = scheduler.clock()
events = parse_events(data, now, now + dt.timedelta(days=7), settings().tz)
first = f" Next: {events[0].title}." if events else ""
return {"ok": True, "output": f"{len(events)} events in the next 7 days.{first}"}
items = parse_items(data)
first = f" Latest: {items[0].title}" if items else ""
return {"ok": True, "output": f"{len(items)} items.{first}"}
except SourceError as e:
return {"ok": False, "output": f"Couldn't read it: {e}"}
@app.post("/api/watch/test", dependencies=posting)
def test_watch(trigger: models.WatchTrigger) -> dict:
try:
data = fetch(trigger.url)
if trigger.kind == "rss":
items = parse_items(data)
latest = f" Latest: {items[0].title}" if items else ""
return {"ok": True, "output": f"{len(items)} items.{latest}"}
value = json_value(data, trigger.path)
return {"ok": True, "output": f"{trigger.path or 'Value'} is {value!r}."}
except SourceError as e:
return {"ok": False, "output": f"Couldn't read it: {e}"}
# --- settings ---
@app.get("/api/settings", dependencies=authed)
def read_settings() -> dict:
return {"ok": True, "settings": settings().model_dump(mode="json"),
"timezones": sorted(available_timezones())}
@app.put("/api/settings", dependencies=posting)
def save_settings(body: models.Settings) -> dict:
store.save_settings(body.model_dump(mode="json"))
scheduler.reschedule_all()
return {"ok": True, "settings": body.model_dump(mode="json")}
# --- webhooks (no page header: called by other services) ---
@app.post("/hook/{schedule_id}", dependencies=authed)
async def hook(
schedule_id: str,
request: Request,
key: str | None = Query(default=None, max_length=200),
x_hook_secret: str | None = Header(default=None),
) -> JSONResponse:
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > MAX_HOOK_BODY:
raise HTTPException(413, f"Body over {MAX_HOOK_BODY // 1024} KB.")
return await run_in_threadpool(
call_hook, schedule_id, x_hook_secret or key, bytes(body),
request.headers.get("content-type", ""),
)
def call_hook(schedule_id: str, secret: str | None, body: bytes,
content_type: str) -> JSONResponse:
row = store.schedule(schedule_id)
stored = store.state(schedule_id, "hook_secret") if row else None
if (row is None or stored is None or not secret
or row["spec"].get("trigger", {}).get("type") != "webhook"
or not hmac.compare_digest(hash_secret(secret), stored)):
raise HTTPException(404, "No such webhook, or the wrong secret.")
if not row["enabled"]:
raise HTTPException(409, "This webhook's schedule is turned off.")
try:
job, message = scheduler.fire_webhook(row, hook_payload(body, content_type))
except RateLimited as e:
raise HTTPException(429, str(e)) from None
except receipt.InvalidJob as e:
raise HTTPException(400, str(e)) from None
except QueueFull:
raise HTTPException(503, "The print queue is full; try again shortly.") from None
if job is None:
return JSONResponse({"ok": True, "skipped": message})
return accepted(job)
return app
def hook_payload(body: bytes, content_type: str) -> dict:
"""A webhook body as template values: JSON objects as they are, forms as fields, else text."""
text = body.decode("utf-8", errors="replace")
if not text.strip():
return {}
if "json" in content_type or text.lstrip().startswith(("{", "[")):
try:
data = json.loads(text)
except ValueError:
data = None
if isinstance(data, dict):
return data
if data is not None:
return {"value": data}
if "x-www-form-urlencoded" in content_type:
return dict(parse_qsl(text))
return {"text": text}
def serve(args: argparse.Namespace) -> int:
import uvicorn
@@ -234,220 +783,7 @@ def serve(args: argparse.Namespace) -> int:
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False
uvicorn.run(create_app(config, token), host=host.strip("[]"), port=int(port))
store = Store(default_path())
log.info("data in %s", store.path)
uvicorn.run(create_app(config, token, store), host=host.strip("[]"), port=int(port))
return 0
PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Receipt Printer</title>
<style>
:root {
--bg: #f6f5f2; --card: #fff; --text: #1d1d1b; --muted: #6b6a66;
--border: #dcdad4; --accent: #2f5bd3; --ok: #1f7a3a; --err: #b42318;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161615; --card: #20201e; --text: #ecebe7; --muted: #9c9a94;
--border: #3a3936; --accent: #7a9cff; --ok: #5cc27c; --err: #ff7a6b;
}
}
* { box-sizing: border-box; }
body {
margin: 0; padding: 24px 16px; background: var(--bg); color: var(--text);
font: 15px/1.5 system-ui, sans-serif;
}
main { max-width: 560px; margin: 0 auto; display: grid; gap: 16px; }
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
h1 { font-size: 1.3rem; margin: 0; }
h2 { font-size: 1rem; margin: 0 0 10px; }
section {
background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px;
}
textarea, input[type=text], select {
width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px;
background: var(--bg); color: var(--text); font: inherit;
}
select { width: auto; padding: 4px 6px; margin-left: 4px; }
textarea { min-height: 140px; font-family: ui-monospace, monospace; resize: vertical; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px;
margin-top: 10px; flex-wrap: wrap; }
button {
padding: 8px 16px; border: 0; border-radius: 6px; background: var(--accent); color: #fff;
font: inherit; font-weight: 600; cursor: pointer;
}
button:disabled { opacity: .5; cursor: progress; }
.pill {
font-size: .85rem; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--border);
color: var(--muted); background: none; cursor: pointer; font-weight: 400;
}
.pill.ok { color: var(--ok); border-color: var(--ok); }
.pill.err { color: var(--err); border-color: var(--err); }
#drop {
display: block; border: 2px dashed var(--border); border-radius: 8px; padding: 16px;
text-align: center; color: var(--muted); cursor: pointer;
}
#drop.over { border-color: var(--accent); }
#preview { max-width: 100%; max-height: 260px; display: none; margin: 10px auto 0;
filter: grayscale(1); }
#file { display: none; }
#log { white-space: pre-wrap; font-family: ui-monospace, monospace; font-size: .85rem;
margin: 0; color: var(--muted); }
#log.ok { color: var(--ok); }
#log.err { color: var(--err); }
.muted { color: var(--muted); font-size: .85rem; }
</style>
</head>
<body>
<main>
<header>
<h1>Receipt printer</h1>
<button id="status" class="pill" title="Check again">checking…</button>
</header>
<section>
<h2>Note</h2>
<form id="note-form">
<textarea id="note" maxlength="4000" placeholder="Your note" required></textarea>
<div class="row">
<label class="muted"><input type="checkbox" id="timestamp"> Date/time header</label>
<label class="muted">Size
<select id="size">
<option value="1">Normal (48 per line)</option>
<option value="2" selected>Large (24 per line)</option>
<option value="3">Huge (16 per line)</option>
</select>
</label>
<button type="submit">Print note</button>
</div>
</form>
</section>
<section>
<h2>Image</h2>
<form id="image-form">
<label id="drop" for="file">Choose, drop or paste an image</label>
<input type="file" id="file" accept="image/*">
<img id="preview" alt="">
<div class="row">
<input type="text" id="caption" maxlength="500" placeholder="Caption (optional)">
</div>
<div class="row">
<span class="muted">Max 16 MB. Printed full width, dithered.</span>
<button type="submit">Print image</button>
</div>
</form>
</section>
<section><pre id="log">Ready.</pre></section>
</main>
<script>
const $ = (id) => document.getElementById(id);
const log = $("log");
let picked = null;
function show(text, cls) { log.textContent = text; log.className = cls || ""; }
async function call(path, init) {
init = init || {};
init.headers = Object.assign({"X-Requested-With": "receipt"}, init.headers || {});
const res = await fetch(path, init);
let body = {};
try { body = await res.json(); } catch (e) { /* nginx pages aren't JSON */ }
if (!("ok" in body) && !("detail" in body)) {
// Not from this server: nginx's offline page, or its login redirect.
const offline = [502, 503, 504].includes(res.status);
return {ok: false, text: offline ? "The printer machine is offline."
: "Signed out? Reload the page and sign in."};
}
let detail = body.detail;
if (Array.isArray(detail)) detail = detail.map((d) => d.msg).join("; ");
return {ok: res.ok && body.ok !== false, text: body.output || detail || res.statusText,
job: body.job, busy: body.busy};
}
async function checkStatus() {
const pill = $("status");
pill.textContent = "checking…"; pill.className = "pill";
const r = await call("api/status");
pill.textContent = r.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline";
pill.className = "pill " + (r.ok ? "ok" : "err");
pill.title = r.text;
}
// POST answers 202 with a queued job; long-poll it until it finishes.
async function submit(path, init) {
const buttons = document.querySelectorAll("button");
buttons.forEach((b) => b.disabled = true);
show("Sending…");
let job = null;
try {
let r = await call(path, init);
while (r.ok && r.job && !["done", "failed"].includes(r.job.state)) {
job = r.job;
show(job.state === "queued" ? "Queued…" : "Printing…");
r = await call("api/jobs/" + job.id + "?wait=20");
}
if (!r.ok || !r.job) { show(r.text, "err"); return false; }
const ok = r.job.state === "done";
show(r.job.message, ok ? "ok" : "err");
return ok;
} catch (e) {
show("Request failed: " + e + (job ? " (the job may still print)" : ""), "err");
return false;
} finally {
buttons.forEach((b) => b.disabled = false);
}
}
$("note-form").addEventListener("submit", async (e) => {
e.preventDefault();
const ok = await submit("api/note", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked,
size: Number($("size").value)}),
});
if (ok) $("note").value = "";
});
function pick(file) {
if (!file || !file.type.startsWith("image/")) return;
picked = file;
const preview = $("preview");
if (preview.src) URL.revokeObjectURL(preview.src);
preview.src = URL.createObjectURL(file);
preview.style.display = "block";
$("drop").textContent = file.name || "Pasted image";
}
$("file").addEventListener("change", (e) => pick(e.target.files[0]));
const drop = $("drop");
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => {
e.preventDefault(); drop.classList.remove("over"); pick(e.dataTransfer.files[0]);
});
document.addEventListener("paste", (e) => {
const item = [...e.clipboardData.items].find((i) => i.type.startsWith("image/"));
if (item) pick(item.getAsFile());
});
$("image-form").addEventListener("submit", async (e) => {
e.preventDefault();
if (!picked) { show("Choose an image first.", "err"); return; }
const data = new FormData();
data.append("file", picked, picked.name || "pasted.png");
data.append("message", $("caption").value);
await submit("api/image", {method: "POST", body: data});
});
$("status").addEventListener("click", checkStatus);
checkStatus();
</script>
</body>
</html>
"""
+32
View File
@@ -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
+33
View File
@@ -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
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Test Feed</title>
<item><guid>post-3</guid><title>Third post</title><link>https://example.com/3</link>
<description>&lt;p&gt;The &lt;b&gt;third&lt;/b&gt; one&lt;/p&gt;</description></item>
<item><guid>post-2</guid><title>Second post</title><link>https://example.com/2</link></item>
<item><guid>post-1</guid><title>First post</title><link>https://example.com/1</link></item>
</channel>
</rss>
+237
View File
@@ -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"
+180
View File
@@ -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
+102
View File
@@ -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
+90
View File
@@ -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;
}
+270
View File
@@ -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; }
+54
View File
@@ -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();
+154
View File
@@ -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 <label> wrapping a control, with the caption above it.
export function labelled(caption, control, hint) {
return h("label", {class: "field"}, h("span", {class: "caption"}, caption), control,
hint ? h("small", {class: "hint"}, hint) : null);
}
// A checkbox bound to obj[key].
export function checkbox(obj, key, caption, onchange) {
const input = h("input", {type: "checkbox", checked: !!obj[key], onchange: () => {
obj[key] = input.checked; onchange && onchange();
}});
return h("label", {class: "check"}, input, " ", caption);
}
// Text / number / time / date input bound to obj[key].
export function input(obj, key, props = {}, onchange) {
const type = props.type || "text";
const parse = props.parse || (type === "number"
? (v) => (v === "" ? null : Number(v)) : (v) => v);
const el = h(props.multiline ? "textarea" : "input", {
...props, type: props.multiline ? null : type, multiline: null, parse: null,
value: obj[key] ?? "",
oninput: () => { obj[key] = parse(el.value); onchange && onchange(); },
});
return el;
}
// <select> bound to obj[key]; options are [value, label] pairs.
export function select(obj, key, options, onchange, parse = (v) => v) {
const el = h("select", {onchange: () => { obj[key] = parse(el.value); onchange && onchange(); }},
options.map(([value, label]) => h("option", {value: String(value)}, label)));
el.value = String(obj[key] ?? "");
return el;
}
// Toggle chips for a list of numbers (weekdays).
export function chips(list, labels, onchange) {
return h("div", {class: "chips"}, labels.map((label, i) => {
const chip = h("button", {type: "button", class: list.includes(i) ? "chip on" : "chip",
"aria-pressed": String(list.includes(i)),
onclick: () => {
const at = list.indexOf(i);
if (at >= 0) list.splice(at, 1); else { list.push(i); list.sort((a, b) => a - b); }
chip.classList.toggle("on", at < 0);
chip.setAttribute("aria-pressed", String(at < 0));
onchange && onchange();
}}, label);
return chip;
}));
}
// Segmented control: one of options [value, label].
export function segmented(current, options, onpick) {
return h("div", {class: "segmented", role: "tablist"}, options.map(([value, label]) =>
h("button", {type: "button", role: "tab", class: value === current ? "on" : "",
"aria-selected": String(value === current),
onclick: () => onpick(value)}, label)));
}
// Insert text at the cursor of an input/textarea and fire its input event.
export function insertAtCursor(el, text) {
const start = el.selectionStart ?? el.value.length;
const end = el.selectionEnd ?? el.value.length;
el.value = el.value.slice(0, start) + text + el.value.slice(end);
el.selectionStart = el.selectionEnd = start + text.length;
el.focus();
el.dispatchEvent(new Event("input"));
}
export function localDateTimeValue(date) {
const pad = (n) => String(n).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T` +
`${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
+591
View File
@@ -0,0 +1,591 @@
// Schedule editor: When (trigger), What (blocks), Options, with a live receipt preview.
import {assets, call, del, get, post, printJob, put, settings, sources} from "./api.js";
import {
DAYS, MONTHS, checkbox, chips, clear, debounce, fmtTime, h, input, insertAtCursor, labelled,
relative, segmented, select, toast,
} from "./dom.js";
import {paper} from "./paper.js";
import {OPTIONS, blockDefaults, triggerDefaults} from "./presets.js";
import {STATUS_LABELS, pending} from "./schedules.js";
const TRIGGER_TYPES = [["once", "Once"], ["recurring", "Repeat"], ["sun", "Sun"],
["calendar", "Calendar"], ["watch", "Feed / URL"], ["webhook", "Webhook"]];
const BLOCK_TYPES = [["note", "Note"], ["qr", "QR code"], ["image", "Image"],
["agenda", "Agenda"], ["headlines", "Headlines"],
["random_image", "Random image"], ["divider", "Divider"]];
const BLOCK_NAMES = Object.fromEntries(BLOCK_TYPES);
const POSITIONS = [["1", "first"], ["2", "second"], ["3", "third"], ["4", "fourth"],
["-1", "last"]];
const FREQ_UNITS = {daily: "day", weekly: "week", monthly: "month", yearly: "year"};
// Variables offered as chips, by trigger type (and for every trigger).
const VARS = {
common: ["{date}", "{time}", "{weekday}", "{date:%d/%m/%Y}", "{days_until:12-25}"],
calendar: ["{event.title}", "{event.start}", "{event.end}", "{event.location}",
"{event.minutes}"],
watch_rss: ["{item.title}", "{item.link}", "{item.summary}", "{item.source}"],
watch_json: ["{value}", "{old_value}"],
webhook: ["{payload.text}", "{payload.title}"],
};
function hhmm(t) { return (t || "").slice(0, 5); }
function freshDraft() {
return {name: "", enabled: true, trigger: triggerDefaults("recurring"),
blocks: [blockDefaults("note")], options: {...OPTIONS}};
}
function normalise(spec) {
// Server times come back as HH:MM:SS; the inputs want HH:MM.
const t = spec.trigger;
if (t.type === "recurring") t.times = t.times.map(hhmm);
if (t.type === "once") t.at = (t.at || "").slice(0, 16);
return spec;
}
export async function editorView(view, id) {
let saved = null;
let draft;
let secret = null;
if (id === "new") {
draft = pending.draft || freshDraft();
pending.draft = null;
} else {
const r = await get(`api/schedules/${id}`);
if (!r.ok) return clear(view, h("p", {class: "err"}, r.text));
saved = r.body.schedule;
draft = {name: saved.name, enabled: saved.enabled, ...normalise(structuredClone(saved.spec))};
}
const [srcs, imgs, conf] = await Promise.all([sources(), assets(), settings()]);
let dirty = id === "new";
const preview = paper();
const triggerBox = h("div");
const triggerInfo = h("div", {class: "trigger-info"});
const blocksBox = h("div", {class: "blocks"});
const optionsBox = h("div");
const hookBox = h("div");
const headerStatus = h("div", {class: "meta"});
const saveButton = h("button", {class: "primary", onclick: () => save()}, "Save");
const testButton = h("button", {onclick: () => testPrint()}, "Test print");
let lastFocused = null; // the text field variable chips insert into
function changed() {
dirty = true;
saveButton.textContent = "Save";
refreshPreview();
}
// --- preview + next runs ---
const refreshPreview = debounce(async () => {
const blank = (b) => b.type === "note" && !b.text.trim() && !b.choices.length;
if (draft.blocks.every(blank)) {
refreshTrigger();
return preview.empty("Write something to print.");
}
const r = await post("api/preview", {blocks: draft.blocks, trigger: draft.trigger,
schedule_id: saved?.id || null});
r.ok ? preview.show(r.body) : preview.error(r.text);
refreshTrigger();
}, 500);
let triggerSeq = 0;
async function refreshTrigger() {
const seq = ++triggerSeq;
if (draft.trigger.type === "watch" && !draft.trigger.url.trim()) {
return clear(triggerInfo, h("p", {class: "muted small"}, "Enter the address to watch."));
}
const r = await post("api/triggers/preview", {trigger: draft.trigger});
if (seq !== triggerSeq) return;
if (!r.ok) return clear(triggerInfo, h("p", {class: "err small"}, r.text));
const {summary, next, error} = r.body;
clear(triggerInfo,
h("p", {class: "summary"}, summary),
error ? h("p", {class: "err small"}, error) : null,
next.length ? h("ul", {class: "next-runs"}, next.map((t) =>
h("li", {}, fmtTime(t), h("span", {class: "muted"}, ` · ${relative(t)}`)))) :
!error && ["once", "recurring", "sun"].includes(draft.trigger.type)
? h("p", {class: "warn small"}, "This never runs again.") : null);
}
// --- When ---
function renderTrigger() {
const t = draft.trigger;
const form = {once: onceForm, recurring: recurringForm, sun: sunForm,
calendar: calendarForm, watch: watchForm, webhook: webhookForm}[t.type](t);
clear(triggerBox,
segmented(t.type, TRIGGER_TYPES, (type) => {
if (type === draft.trigger.type) return;
draft.trigger = triggerDefaults(type, srcs);
renderTrigger(); renderBlocks(); changed();
}),
h("div", {class: "trigger-form"}, form));
renderHook();
}
function onceForm(t) {
return labelled("Date and time", input(t, "at", {type: "datetime-local"}, changed),
`In ${conf.settings.timezone}.`);
}
function recurringForm(t) {
const box = h("div");
const rerender = () => { clear(box, inner()); changed(); };
function inner() {
const unit = FREQ_UNITS[t.freq];
const parts = [
h("div", {class: "row start mid"}, h("span", {}, "Every"),
input(t, "interval", {type: "number", min: 1, max: 365, class: "narrow",
parse: (v) => Math.max(1, Number(v) || 1)}, changed),
select(t, "freq", [["daily", `day${t.interval > 1 ? "s" : ""}`],
["weekly", `week${t.interval > 1 ? "s" : ""}`],
["monthly", `month${t.interval > 1 ? "s" : ""}`],
["yearly", `year${t.interval > 1 ? "s" : ""}`]], () => {
t.weekdays = []; t.setpos = null; t.monthday = null; t.month = null; rerender();
})),
];
if (t.freq === "daily" || t.freq === "weekly") {
parts.push(labelled(t.freq === "daily" ? "Only on (none = every day)" : "On",
h("div", {}, chips(t.weekdays, DAYS, changed),
t.freq === "daily" ? h("div", {class: "row start"},
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 0, 1, 2, 3, 4); rerender();
}}, "Weekdays"),
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 5, 6); rerender();
}}, "Weekends")) : null)));
} else {
const byWeekday = t.setpos !== null && t.setpos !== undefined;
const mode = h("div", {class: "stack"},
h("label", {class: "check"}, h("input", {type: "radio", name: "monthmode",
checked: !byWeekday, onchange: () => { t.setpos = null; t.weekdays = []; rerender(); }}),
" On day ",
select(t, "monthday", [["", "(start date's)"],
...Array.from({length: 31}, (_, i) => [i + 1, String(i + 1)]), ["-1", "last"]],
changed, (v) => (v === "" ? null : Number(v)))),
h("label", {class: "check"}, h("input", {type: "radio", name: "monthmode",
checked: byWeekday, onchange: () => {
t.setpos = 1; t.monthday = null; if (!t.weekdays.length) t.weekdays.push(0);
rerender();
}}), " On the ",
select(t, "setpos", POSITIONS, changed, (v) => Number(v))),
byWeekday ? h("div", {class: "indent"}, chips(t.weekdays, DAYS, changed),
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 0, 1, 2, 3, 4); rerender();
}}, "Any weekday")) : null);
parts.push(mode);
if (t.freq === "yearly") {
parts.push(labelled("Month", select(t, "month",
[["", "(start date's)"], ...MONTHS.map((m, i) => [i + 1, m])], changed,
(v) => (v === "" ? null : Number(v)))));
}
}
parts.push(labelled("At", h("div", {class: "times"},
t.times.map((time, i) => h("span", {class: "time"},
h("input", {type: "time", value: time, oninput: (e) => {
t.times[i] = e.target.value; changed();
}}),
t.times.length > 1 ? h("button", {type: "button", class: "ghost small",
"aria-label": "Remove time", onclick: () => { t.times.splice(i, 1); rerender(); }},
"×") : null)),
t.times.length < 24 ? h("button", {type: "button", class: "ghost small", onclick: () => {
t.times.push("12:00"); rerender();
}}, "+ time") : null)));
parts.push(h("div", {class: "row start"},
labelled("Starting", input(t, "start", {type: "date", parse: (v) => v || null}, changed),
t.interval > 1 ? `Counts every ${t.interval} ${unit}s from here.` : null),
labelled("Until (optional)", input(t, "until", {type: "date",
parse: (v) => v || null}, changed))));
parts.push(h("details", {open: !!t.rrule},
h("summary", {}, "Advanced: custom rule"),
labelled("RRULE", input(t, "rrule", {placeholder: "FREQ=MONTHLY;BYDAY=-1FR",
parse: (v) => v || null}, changed),
"An iCalendar RRULE. It replaces the settings above; the times still apply.")));
return parts;
}
clear(box, inner());
return box;
}
function sunForm(t) {
const direction = {value: t.offset_minutes < 0 ? "before" : "after"};
const minutes = {value: Math.abs(t.offset_minutes)};
const apply = () => {
t.offset_minutes = (direction.value === "before" ? -1 : 1) * (Number(minutes.value) || 0);
changed();
};
return h("div", {},
conf.settings.location ? null
: h("p", {class: "warn"}, "Sun times need a location. ",
h("a", {href: "#settings"}, "Set one in Settings.")),
h("div", {class: "row start mid"},
input(minutes, "value", {type: "number", min: 0, max: 720, class: "narrow"}, apply),
h("span", {}, "min"),
select(direction, "value", [["before", "before"], ["after", "after"]], apply),
select(t, "event", [["dawn", "dawn"], ["sunrise", "sunrise"], ["noon", "solar noon"],
["sunset", "sunset"], ["dusk", "dusk"]], changed)),
labelled("On", chips(t.weekdays, DAYS, changed)));
}
function sourceOptions(kind) {
return srcs.filter((s) => s.kind === kind).map((s) => [s.id, s.name]);
}
function noSources(kind) {
return h("p", {class: "warn"}, `No saved ${kind === "ics" ? "calendars" : "feeds"} yet. `,
h("a", {href: "#settings"}, "Add one in Settings."));
}
function calendarForm(t) {
const options = sourceOptions("ics");
if (!options.length) return noSources("ics");
if (!t.source_id) t.source_id = options[0][0];
return h("div", {},
labelled("Calendar", select(t, "source_id", options, changed)),
h("div", {class: "row start"},
labelled("Minutes before", input(t, "minutes_before", {type: "number", min: 0,
max: 10080, class: "narrow", parse: (v) => Number(v) || 0}, changed)),
labelled("Only titles containing", input(t, "contains", {placeholder: "(any)"},
changed))),
checkbox(t, "include_all_day", "Include all-day events", changed));
}
function watchForm(t) {
const result = h("p", {class: "small muted"});
const box = h("div");
const rerender = () => { clear(box, inner()); changed(); };
function inner() {
return [
segmented(t.kind, [["rss", "RSS / Atom feed"], ["json", "JSON value"]], (kind) => {
t.kind = kind; rerender(); renderBlocks();
}),
labelled("URL", input(t, "url", {type: "url", placeholder: "https://…"}, changed)),
t.kind === "json" ? h("div", {class: "row start"},
labelled("Path", input(t, "path", {placeholder: "data.price"}, changed),
"Dotted path; numbers index lists (items.0.price)."),
labelled("Print when it", select(t, "condition", [["changed", "changes"],
["above", "goes above"], ["below", "goes below"]], rerender)),
t.condition !== "changed" ? labelled("Threshold", input(t, "threshold",
{type: "number", step: "any", class: "narrow"}, changed)) : null) : null,
h("div", {class: "row start"},
labelled("Check every (min)", input(t, "every_minutes", {type: "number", min: 5,
max: 1440, class: "narrow", parse: (v) => Number(v) || 30}, changed)),
t.kind === "rss" ? labelled("Items per receipt", input(t, "max_items",
{type: "number", min: 1, max: 10, class: "narrow", parse: (v) => Number(v) || 1},
changed)) : null),
h("div", {class: "row start"},
h("button", {type: "button", onclick: async () => {
result.textContent = "Checking…";
const r = await post("api/watch/test", t);
result.textContent = r.text;
result.className = `small ${r.ok ? "ok" : "err"}`;
}}, "Try it"), result),
h("p", {class: "muted small"}, t.kind === "rss"
? "The first check only notes what's there; after that, new items print."
: "The first check only notes the value; after that, changes print."),
];
}
clear(box, inner());
return box;
}
function webhookForm(t) {
return h("div", {},
labelled("Most prints per hour", input(t, "per_hour", {type: "number", min: 1, max: 120,
class: "narrow", parse: (v) => Number(v) || 1}, changed)),
hookBox);
}
function renderHook() {
if (draft.trigger.type !== "webhook") return;
if (!saved || saved.spec.trigger.type !== "webhook") {
return clear(hookBox, h("p", {class: "muted"}, "Save to get this webhook's URL and secret."));
}
const base = new URL(".", location.href).href;
const url = `${base}${saved.hook_path}`;
const copy = (text) => () => navigator.clipboard.writeText(text).then(() => toast("Copied."));
const example = `curl -X POST '${url}' \\\n -H 'X-Hook-Secret: ${secret || "<secret>"}' \\\n` +
` -H 'Content-Type: application/json' \\\n -d '{"text": "Hello"}'`;
clear(hookBox,
labelled("URL", h("div", {class: "copyable"}, h("code", {}, url),
h("button", {type: "button", class: "ghost small", onclick: copy(url)},
"Copy"))),
secret
? labelled("Secret (shown once: copy it now)",
h("div", {class: "copyable"}, h("code", {}, secret),
h("button", {type: "button", class: "ghost small", onclick: copy(secret)},
"Copy")))
: h("p", {class: "muted small"},
saved.has_secret ? "The secret was shown when it was made. " : "No secret yet. ",
h("button", {type: "button", class: "ghost small", onclick: async () => {
if (saved.has_secret && !confirm("Make a new secret? The old one stops working.")) {
return;
}
const r = await post(`api/schedules/${saved.id}/secret`);
if (!r.ok) return toast(r.text, "err");
saved = r.body.schedule; secret = r.body.schedule.secret; renderHook();
}}, saved.has_secret ? "Make a new secret" : "Make a secret")),
h("details", {}, h("summary", {}, "Example"), h("pre", {class: "code"}, example),
h("p", {class: "muted small"},
"Send the secret as X-Hook-Secret or ?key=. JSON fields become {payload.…}; a " +
"plain-text body is {payload.text}. Over Tailscale, or from anywhere once nginx " +
"forwards /receipt/hook/.")));
}
// --- What ---
function varChips() {
const t = draft.trigger;
const extra = t.type === "watch" ? VARS[`watch_${t.kind}`] : VARS[t.type] || [];
return h("div", {class: "vars"}, h("span", {class: "muted small"}, "Insert:"),
[...extra, ...VARS.common].map((v) => h("button", {type: "button", class: "chip small",
onmousedown: (e) => e.preventDefault(), // keep the field's cursor
onclick: () => { if (lastFocused) insertAtCursor(lastFocused, v); }}, v)));
}
function track(el) {
el.addEventListener("focus", () => (lastFocused = el));
return el;
}
function renderBlocks() {
clear(blocksBox,
draft.blocks.map((block, i) => blockCard(block, i)),
h("div", {class: "add-block"}, h("span", {class: "muted small"}, "Add:"),
BLOCK_TYPES.map(([type, label]) => h("button", {type: "button", class: "ghost small",
onclick: () => {
draft.blocks.push(blockDefaults(type, srcs)); renderBlocks(); changed();
}}, `+ ${label}`))));
}
function blockCard(block, i) {
const move = (delta) => () => {
const [b] = draft.blocks.splice(i, 1);
draft.blocks.splice(i + delta, 0, b);
renderBlocks(); changed();
};
const form = {note: noteBlock, qr: qrBlock, image: imageBlock, agenda: agendaBlock,
headlines: headlinesBlock}[block.type];
return h("div", {class: "block"},
h("div", {class: "block-head"},
h("strong", {}, BLOCK_NAMES[block.type]),
h("span", {class: "spacer"}),
h("button", {type: "button", class: "ghost small", disabled: i === 0,
"aria-label": "Move up", onclick: move(-1)}, "↑"),
h("button", {type: "button", class: "ghost small", disabled: i === draft.blocks.length - 1,
"aria-label": "Move down", onclick: move(1)}, "↓"),
h("button", {type: "button", class: "ghost small", disabled: draft.blocks.length === 1,
"aria-label": "Remove", onclick: () => {
draft.blocks.splice(i, 1); renderBlocks(); changed();
}}, "×")),
form ? form(block) : block.type === "random_image"
? h("p", {class: "muted small"}, "A random image from /bant/, downloaded when it prints.")
: null);
}
function noteBlock(b) {
const choices = {text: b.choices.join("\n")};
return h("div", {},
track(input(b, "text", {multiline: true, rows: 4, maxlength: 4000,
placeholder: b.choices.length ? "{choice}" : "Text; variables like {date} fill in when it prints"},
changed)),
varChips(),
h("div", {class: "row start"},
labelled("Size", select(b, "size", [[1, "Normal"], [2, "Large"], [3, "Huge"]], changed,
Number)),
checkbox(b, "bold", "Bold", changed),
checkbox(b, "center", "Centered", changed),
checkbox(b, "timestamp", "Date/time header", changed)),
h("details", {open: b.choices.length > 0},
h("summary", {}, "Pick from a list ({choice})"),
labelled("One item per line", input(choices, "text", {multiline: true, rows: 4},
() => { b.choices = choices.text.split("\n").filter((c) => c.trim()); changed(); })),
labelled("Pick", select(b, "pick", [["sequential", "In order, one per print"],
["random", "At random"]], changed))));
}
function qrBlock(b) {
return h("div", {},
labelled("Text or link", track(input(b, "content", {placeholder: "https://…"}, changed))),
labelled("Caption", track(input(b, "caption", {}, changed))),
varChips());
}
function imageBlock(b) {
const picker = h("div");
const draw = () => clear(picker,
imgs.length ? select(b, "asset_id", [["", "(choose an image)"],
...imgs.map((a) => [a.id, a.name])], changed)
: h("span", {class: "muted small"}, "No saved images yet."),
h("label", {class: "button ghost small"}, "Upload…",
h("input", {type: "file", accept: "image/*", hidden: true, onchange: async (e) => {
const file = e.target.files[0];
if (!file) return;
const data = new FormData();
data.append("file", file, file.name || "image.png");
const r = await call("api/assets", {method: "POST", body: data});
if (!r.ok) return toast(r.text, "err");
imgs.splice(0, imgs.length, ...await assets(true));
b.asset_id = r.body.asset.id;
draw(); changed();
}})));
draw();
return h("div", {},
labelled("Image", picker),
labelled("Caption", track(input(b, "caption", {}, changed))), varChips());
}
function sourceChecks(b, kind) {
const options = sourceOptions(kind);
if (!options.length) return noSources(kind);
return h("div", {class: "chips"}, options.map(([sid, name]) => {
const on = b.source_ids.includes(sid);
const chip = h("button", {type: "button", class: on ? "chip on" : "chip", onclick: () => {
const at = b.source_ids.indexOf(sid);
if (at >= 0) b.source_ids.splice(at, 1); else b.source_ids.push(sid);
chip.classList.toggle("on", at < 0); changed();
}}, name);
return chip;
}));
}
function agendaBlock(b) {
return h("div", {},
labelled("Calendars", sourceChecks(b, "ics")),
h("div", {class: "row start"},
labelled("From", select(b, "start_day", [[0, "Today"], [1, "Tomorrow"],
...[2, 3, 4, 5, 6, 7].map((n) => [n, `In ${n} days`])], changed, Number)),
labelled("For", select(b, "days", [1, 2, 3, 4, 5, 6, 7].map((n) =>
[n, n === 1 ? "1 day" : `${n} days`]), changed, Number)),
labelled("Heading", input(b, "title", {placeholder: "(automatic)"}, changed))),
checkbox(b, "include_all_day", "Include all-day events", changed));
}
function headlinesBlock(b) {
return h("div", {},
labelled("Feeds", sourceChecks(b, "rss")),
h("div", {class: "row start"},
labelled("Items per feed", input(b, "count", {type: "number", min: 1, max: 20,
class: "narrow", parse: (v) => Number(v) || 1}, changed)),
labelled("Heading", input(b, "title", {placeholder: "(feed name)"}, changed))),
h("div", {class: "row start"},
checkbox(b, "only_new", "Only items not printed before", changed),
checkbox(b, "qr_first", "QR code for the top item", changed)));
}
// --- Options ---
function renderOptions() {
const o = draft.options;
clear(optionsBox,
labelled("During quiet hours", select(o, "quiet", [
["hold", "Wait, and print when they end"], ["skip", "Skip it"],
["ignore", "Print anyway"]], changed),
conf.settings.quiet_start
? `Quiet hours are ${hhmm(conf.settings.quiet_start)}–${hhmm(conf.settings.quiet_end)}.`
: h("span", {}, "No quiet hours are set. ", h("a", {href: "#settings"}, "Settings"))),
checkbox(o, "skip_if_empty", "Skip when the agenda/headlines have nothing in them",
changed),
h("div", {class: "row start"},
labelled("Catch up if late by up to (min)", input(o, "catch_up_minutes",
{type: "number", min: 0, max: 1440, class: "narrow", parse: (v) => Number(v) || 0},
changed), "After a restart; anything later is logged as missed."),
labelled("Retries if the printer is off", input(o, "retries", {type: "number", min: 0,
max: 10, class: "narrow", parse: (v) => Number(v) || 0}, changed),
"5 minutes apart.")));
}
// --- actions ---
async function save() {
if (!draft.name.trim()) { nameInput.focus(); return toast("Give it a name.", "err"); }
saveButton.disabled = true;
const r = saved ? await put(`api/schedules/${saved.id}`, draft)
: await post("api/schedules", draft);
saveButton.disabled = false;
if (!r.ok) return toast(r.text, "err");
const isNew = !saved;
saved = r.body.schedule;
secret = saved.secret || secret;
draft = {name: saved.name, enabled: saved.enabled,
...normalise(structuredClone(saved.spec))};
dirty = false;
saveButton.textContent = "Saved";
toast("Saved.");
if (isNew) history.replaceState(null, "", `#schedules/${saved.id}`);
renderAll();
}
async function testPrint() {
if (dirty || !saved) {
await save();
if (dirty || !saved) return;
}
testButton.disabled = true;
const result = await printJob(() => post(`api/schedules/${saved.id}/run`),
(text) => (testButton.textContent = text));
testButton.disabled = false;
testButton.textContent = "Test print";
toast(result.text, result.ok ? "" : "err");
}
async function remove() {
if (!saved) { dirty = false; location.hash = "#schedules"; return; }
if (!confirm(`Delete "${saved.name}"?`)) return;
const r = await del(`api/schedules/${saved.id}`);
if (!r.ok) return toast(r.text, "err");
dirty = false;
location.hash = "#schedules";
}
const nameInput = h("input", {type: "text", class: "name", maxlength: 100,
placeholder: "Name this schedule", oninput: () => { draft.name = nameInput.value; changed(); }});
const enabled = h("input", {type: "checkbox", class: "switch", onchange: () => {
draft.enabled = enabled.checked; changed();
}});
function renderAll() {
nameInput.value = draft.name;
enabled.checked = draft.enabled;
clear(headerStatus, saved?.last_status
? [h("span", {class: "badge"}, STATUS_LABELS[saved.last_status] || saved.last_status),
" ", h("span", {class: "muted small"}, saved.last_message || ""),
saved.last_run_at ? h("span", {class: "muted small"}, ` · ${fmtTime(saved.last_run_at)}`)
: null,
" ", h("a", {class: "small", href: `#history/${saved.id}`}, "History")]
: null);
renderTrigger(); renderBlocks(); renderOptions(); refreshPreview();
}
clear(view,
h("div", {class: "toolbar editor-bar"},
h("a", {href: "#schedules", class: "back"}, "← Schedules"),
h("span", {class: "spacer"}),
h("label", {class: "check"}, enabled, " On"),
h("div", {class: "actions"},
h("button", {class: "danger ghost", onclick: remove}, saved ? "Delete" : "Discard"),
testButton, saveButton)),
h("div", {class: "editor-head"}, nameInput, headerStatus),
h("div", {class: "split"},
h("div", {class: "editor"},
h("section", {class: "card"}, h("h2", {}, h("span", {class: "step"}, "1"), "When"),
triggerBox, triggerInfo),
h("section", {class: "card"}, h("h2", {}, h("span", {class: "step"}, "2"), "What it prints"),
blocksBox),
h("section", {class: "card"}, h("details", {},
h("summary", {}, h("h2", {}, h("span", {class: "step"}, "3"), "Options")), optionsBox))),
h("aside", {class: "preview-col sticky"},
h("h3", {class: "muted small"}, "Preview"),
preview.root)));
renderAll();
if (id === "new") nameInput.focus();
// Leaving with unsaved changes: the router asks this before switching views.
return {
canLeave: () => !dirty || confirm("Leave without saving your changes?"),
isDirty: () => dirty,
};
}
+69
View File
@@ -0,0 +1,69 @@
// History tab: everything printed, skipped or missed, newest first.
import {get, post, printJob} from "./api.js";
import {clear, fmtTime, h, select, toast} from "./dom.js";
import {STATUS_LABELS} from "./schedules.js";
const SOURCE_LABELS = {manual: "Printed by hand", schedule: "Scheduled", calendar: "Calendar",
watch: "Watcher", webhook: "Webhook", test: "Test print"};
const STATE_CLASS = {done: "ok", failed: "err", missed: "warn", skipped: "warn"};
const PAGE = 50;
export async function historyView(view, scheduleId) {
const filters = {state: "", schedule_id: scheduleId || ""};
const list = h("div", {class: "history"});
const more = h("button", {class: "ghost", hidden: true}, "Older");
let oldest = null;
const schedules = await get("api/schedules");
const scheduleOptions = [["", "All schedules and prints"],
...(schedules.ok ? schedules.body.schedules.map((s) => [s.id, s.name]) : [])];
async function load(reset) {
if (reset) { clear(list); oldest = null; }
const params = new URLSearchParams({limit: String(PAGE)});
if (filters.state) params.set("state", filters.state);
if (filters.schedule_id) params.set("schedule_id", filters.schedule_id);
if (oldest) params.set("before", oldest);
const r = await get(`api/runs?${params}`);
if (!r.ok) return list.append(h("p", {class: "err"}, r.text));
const runs = r.body.runs;
if (!runs.length && !oldest) list.append(h("p", {class: "muted empty"}, "Nothing yet."));
runs.forEach((run) => list.append(row(run)));
oldest = runs.length ? runs[runs.length - 1].created_at : oldest;
more.hidden = runs.length < PAGE;
}
function row(run) {
const again = run.has_payload ? h("button", {class: "ghost small", onclick: async () => {
const result = await printJob(() => post(`api/runs/${run.id}/reprint`),
(text) => (again.textContent = text));
again.textContent = "Print again";
toast(result.text, result.ok ? "" : "err");
if (result.ok) load(true);
}}, "Print again") : null;
const title = run.schedule_id
? h("a", {href: `#schedules/${run.schedule_id}`}, run.name || "Schedule")
: h("span", {}, run.name || run.kind);
return h("div", {class: "run"},
h("div", {class: "when"}, fmtTime(run.created_at)),
h("div", {class: "what"},
h("div", {}, title, " ",
h("span", {class: `badge ${STATE_CLASS[run.state] || ""}`},
STATUS_LABELS[run.state] || run.state)),
h("div", {class: "muted small"}, SOURCE_LABELS[run.source] || run.source,
run.user && !run.user.startsWith("schedule:") ? ` · ${run.user}` : "",
run.message && run.state !== "done" ? ` · ${run.message}` : "")),
again);
}
more.addEventListener("click", () => load(false));
clear(view,
h("div", {class: "toolbar"}, h("h2", {}, "History"), h("span", {class: "spacer"}),
select(filters, "schedule_id", scheduleOptions, () => load(true)),
select(filters, "state", [["", "Any result"], ["done", "Printed"], ["failed", "Failed"],
["skipped", "Skipped"], ["missed", "Missed"]], () => load(true))),
h("section", {class: "card flush"}, list),
h("div", {class: "row center"}, more));
load(true);
}
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Receipt Printer</title>
<link rel="stylesheet" href="static/app.css">
<script type="module" src="static/app.js"></script>
</head>
<body>
<header class="top">
<h1>Receipt printer</h1>
<button id="status" class="pill" title="Check again">checking…</button>
</header>
<nav class="tabs" aria-label="Sections">
<a href="#print">Print</a>
<a href="#schedules">Schedules</a>
<a href="#history">History</a>
<a href="#settings">Settings</a>
</nav>
<main id="view"></main>
<div id="toast" role="status" aria-live="polite"></div>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
// The receipt preview: a strip of thermal paper drawn from /api/preview's parts.
import {h, clear} from "./dom.js";
export function paper() {
const strip = h("div", {class: "paper-strip"});
const meta = h("div", {class: "paper-meta"});
const root = h("div", {class: "paper-wrap"}, h("div", {class: "paper"}, strip), meta);
return {
root,
show(preview) {
clear(strip, preview.parts.map((part) => {
if (part.image) return h("img", {src: part.image, alt: ""});
const cls = ["t", `s${part.size || 1}`, part.bold ? "b" : "", part.center ? "c" : ""];
return h("pre", {class: cls.join(" ")}, part.text);
}));
const length = `${preview.height_mm} mm of paper`;
clear(meta,
h("span", {class: preview.too_long ? "err" : "muted"},
preview.too_long ? `${length}: over the ${preview.max_mm} mm limit` : length),
(preview.warnings || []).map((w) => h("div", {class: "warn"}, w)));
root.classList.remove("error");
},
error(text) {
clear(strip, h("pre", {class: "t s1 placeholder"}, text));
clear(meta);
root.classList.add("error");
},
empty(text) {
clear(strip, h("pre", {class: "t s1 placeholder"}, text));
clear(meta);
root.classList.remove("error");
},
};
}
+163
View File
@@ -0,0 +1,163 @@
// Starting points for new schedules. Source ids are filled with the first saved one that fits.
import {localDateTimeValue} from "./dom.js";
const WEEKDAYS = [0, 1, 2, 3, 4];
const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];
export const OPTIONS = {quiet: "hold", skip_if_empty: false, catch_up_minutes: 15, retries: 3};
export function recurring(extra = {}) {
return {type: "recurring", freq: "daily", interval: 1, times: ["08:00"], weekdays: [],
monthday: null, setpos: null, month: null, start: null, until: null, rrule: null,
...extra};
}
export function triggerDefaults(type, sources = []) {
const first = (kind) => (sources.find((s) => s.kind === kind) || {}).id || "";
const inAnHour = new Date(Date.now() + 3600e3);
inAnHour.setMinutes(0);
return {
once: () => ({type: "once", at: localDateTimeValue(inAnHour)}),
recurring: () => recurring(),
sun: () => ({type: "sun", event: "sunset", offset_minutes: 0, weekdays: [...ALL_DAYS]}),
calendar: () => ({type: "calendar", source_id: first("ics"), minutes_before: 15,
contains: "", include_all_day: false}),
watch: () => ({type: "watch", kind: "rss", url: "", path: "", condition: "changed",
threshold: null, every_minutes: 30, max_items: 3}),
webhook: () => ({type: "webhook", per_hour: 10}),
}[type]();
}
export function blockDefaults(type, sources = []) {
const ids = (kind) => {
const found = sources.find((s) => s.kind === kind);
return found ? [found.id] : [];
};
return {
note: () => ({type: "note", text: "", size: 1, timestamp: false, bold: false, center: false,
choices: [], pick: "sequential"}),
qr: () => ({type: "qr", content: "", caption: ""}),
image: () => ({type: "image", asset_id: "", caption: ""}),
random_image: () => ({type: "random_image"}),
agenda: () => ({type: "agenda", source_ids: ids("ics"), start_day: 0, days: 1,
include_all_day: true, title: ""}),
headlines: () => ({type: "headlines", source_ids: ids("rss"), count: 5, only_new: false,
qr_first: false, title: ""}),
divider: () => ({type: "divider"}),
}[type]();
}
function note(text, extra = {}) {
return {...blockDefaults("note"), text, ...extra};
}
export const PRESETS = [
{
id: "brief", icon: "☀", title: "Morning brief",
blurb: "Today's date, your calendar and the headlines, every weekday morning.",
make: (sources) => ({
name: "Morning brief",
trigger: recurring({times: ["07:30"], weekdays: [...WEEKDAYS]}),
blocks: [
note("{date:%A %d %B}", {size: 2, bold: true, center: true}),
blockDefaults("agenda", sources),
blockDefaults("divider"),
{...blockDefaults("headlines", sources), title: "Headlines"},
],
options: {...OPTIONS},
}),
},
{
id: "chores", icon: "✓", title: "Chore rotation",
blurb: "A different chore each day, taking turns through your list.",
make: () => ({
name: "Today's chore",
trigger: recurring({times: ["08:00"]}),
blocks: [note("TODAY'S CHORE\n\n{choice}", {size: 2, center: true,
choices: ["Hoover the living room", "Clean the bathroom", "Laundry", "Water the plants",
"Take the bins out", "Change the bed", "Clear out the fridge"]})],
options: {...OPTIONS},
}),
},
{
id: "countdown", icon: "⏳", title: "Countdown",
blurb: "Days left until a date, printed every morning.",
make: () => ({
name: "Christmas countdown",
trigger: recurring({times: ["09:00"]}),
blocks: [note("{days_until:12-25} days\nuntil Christmas", {size: 3, bold: true,
center: true})],
options: {...OPTIONS},
}),
},
{
id: "reminders", icon: "⏰", title: "Event reminders",
blurb: "A slip before each event in a calendar.",
make: (sources) => ({
name: "Event reminders",
trigger: triggerDefaults("calendar", sources),
blocks: [
note("IN {event.minutes} MIN", {bold: true, center: true}),
note("{event.title}", {size: 2, center: true}),
note("{event.start} - {event.end}\n{event.location}", {center: true}),
],
options: {...OPTIONS, quiet: "skip"},
}),
},
{
id: "feed", icon: "✉", title: "New post alert",
blurb: "Prints each new item in an RSS feed, with a QR code to open it.",
make: () => ({
name: "New posts",
trigger: triggerDefaults("watch"),
blocks: [
note("{item.source}", {bold: true}),
note("{item.title}", {size: 2}),
{type: "qr", content: "{item.link}", caption: ""},
],
options: {...OPTIONS},
}),
},
{
id: "price", icon: "↗", title: "Value watch",
blurb: "Watches a number in a JSON API and prints when it crosses a threshold.",
make: () => ({
name: "Price alert",
trigger: {...triggerDefaults("watch"), kind: "json", path: "price", condition: "above",
threshold: 100},
blocks: [note("Now {value} (was {old_value})", {size: 2, center: true})],
options: {...OPTIONS},
}),
},
{
id: "webhook", icon: "⚡", title: "Webhook",
blurb: "Other services (Home Assistant, phone shortcuts) print by calling a URL.",
make: () => ({
name: "Webhook print",
trigger: triggerDefaults("webhook"),
blocks: [note("{payload.title}", {bold: true}), note("{payload.text}", {size: 2})],
options: {...OPTIONS, quiet: "skip"},
}),
},
{
id: "sunset", icon: "☾", title: "Sunset nudge",
blurb: "A note half an hour before sunset.",
make: () => ({
name: "Sunset soon",
trigger: {...triggerDefaults("sun"), event: "sunset", offset_minutes: -30},
blocks: [note("Sunset in 30 minutes.\nGo and look outside.", {size: 2, center: true})],
options: {...OPTIONS},
}),
},
{
id: "blank", icon: "+", title: "Start from scratch",
blurb: "A one-off note, an hour from now.",
make: () => ({
name: "Reminder",
trigger: triggerDefaults("once"),
blocks: [note("")],
options: {...OPTIONS},
}),
},
];
+149
View File
@@ -0,0 +1,149 @@
// Print tab: a note, an image or a QR code, right now, with a live preview.
import {call, post, printJob} from "./api.js";
import {h, clear, debounce, segmented, toast} from "./dom.js";
import {paper} from "./paper.js";
const draft = {mode: "note", text: "", timestamp: false, size: 2, caption: "", qr: "",
qrCaption: "", file: null};
export function printView(view) {
const preview = paper();
const status = h("p", {class: "status muted"}, "Ready.");
const formBox = h("div");
const modes = h("div");
function setStatus(text, cls = "muted") { status.textContent = text; status.className = `status ${cls}`; }
const refreshPreview = debounce(async () => {
if (draft.mode === "image") {
if (!draft.file) return preview.empty("Choose an image to see how it prints.");
const data = new FormData();
data.append("file", draft.file, draft.file.name || "pasted.png");
data.append("message", draft.caption);
const r = await call("api/preview/image", {method: "POST", body: data});
return r.ok ? preview.show(r.body) : preview.error(r.text);
}
let block;
if (draft.mode === "note") {
if (!draft.text.trim()) return preview.empty("Type a note to see how it prints.");
block = {type: "note", text: draft.text, size: draft.size, timestamp: draft.timestamp};
} else {
if (!draft.qr.trim()) return preview.empty("Enter text or a link to encode.");
block = {type: "qr", content: draft.qr, caption: draft.qrCaption};
}
// Plain prints have no template variables: {{ }} keeps braces literal in the preview.
if (block.type === "note") block.text = block.text.replaceAll("{", "{{").replaceAll("}", "}}");
if (block.type === "qr") {
block.content = block.content.replaceAll("{", "{{").replaceAll("}", "}}");
block.caption = block.caption.replaceAll("{", "{{").replaceAll("}", "}}");
}
const r = await post("api/preview", {blocks: [block]});
r.ok ? preview.show(r.body) : preview.error(r.text);
}, 350);
async function send(request, after) {
const buttons = view.querySelectorAll("button.primary");
buttons.forEach((b) => (b.disabled = true));
const result = await printJob(request, (text) => setStatus(text));
buttons.forEach((b) => (b.disabled = false));
setStatus(result.text, result.ok ? "ok" : "err");
if (result.ok) { toast("Printed."); after && after(); }
}
function noteForm() {
const text = h("textarea", {maxlength: 4000, placeholder: "Your note", value: draft.text,
oninput: () => { draft.text = text.value; refreshPreview(); }});
const size = h("select", {onchange: () => { draft.size = Number(size.value); refreshPreview(); }},
h("option", {value: "1"}, "Normal (48 per line)"),
h("option", {value: "2"}, "Large (24 per line)"),
h("option", {value: "3"}, "Huge (16 per line)"));
size.value = String(draft.size);
const stamp = h("input", {type: "checkbox", checked: draft.timestamp,
onchange: () => { draft.timestamp = stamp.checked; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.text.trim()) return setStatus("Type something first.", "err");
send(() => post("api/note", {text: draft.text, timestamp: draft.timestamp, size: draft.size}),
() => { draft.text = ""; text.value = ""; refreshPreview(); });
}},
text,
h("div", {class: "row"},
h("label", {class: "check"}, stamp, " Date/time header"),
h("label", {class: "inline"}, "Size ", size),
h("button", {type: "submit", class: "primary"}, "Print note")));
}
function imageForm() {
const fileInput = h("input", {type: "file", accept: "image/*", hidden: true,
onchange: () => pick(fileInput.files[0])});
const drop = h("label", {class: "drop"}, draft.file ? draft.file.name || "Pasted image"
: "Choose, drop or paste an image");
drop.append(fileInput);
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => {
e.preventDefault(); drop.classList.remove("over"); pick(e.dataTransfer.files[0]);
});
function pick(file) {
if (!file || !file.type.startsWith("image/")) return;
draft.file = file;
drop.firstChild.textContent = file.name || "Pasted image";
refreshPreview();
}
view._pick = pick;
const caption = h("input", {type: "text", maxlength: 500, placeholder: "Caption (optional)",
value: draft.caption, oninput: () => { draft.caption = caption.value; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.file) return setStatus("Choose an image first.", "err");
const data = new FormData();
data.append("file", draft.file, draft.file.name || "pasted.png");
data.append("message", draft.caption);
send(() => call("api/image", {method: "POST", body: data}));
}},
drop, caption,
h("div", {class: "row"},
h("span", {class: "muted"}, "Max 16 MB. Printed full width, dithered."),
h("button", {type: "submit", class: "primary"}, "Print image")));
}
function qrForm() {
const content = h("input", {type: "text", maxlength: 2000, placeholder: "https://example.com",
value: draft.qr, oninput: () => { draft.qr = content.value; refreshPreview(); }});
const caption = h("input", {type: "text", maxlength: 500, placeholder: "Caption (optional)",
value: draft.qrCaption,
oninput: () => { draft.qrCaption = caption.value; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.qr.trim()) return setStatus("Enter something to encode.", "err");
send(() => post("api/qr", {content: draft.qr, caption: draft.qrCaption}));
}},
h("label", {class: "field"}, h("span", {class: "caption"}, "Text or link"), content),
h("label", {class: "field"}, h("span", {class: "caption"}, "Caption"), caption),
h("div", {class: "row end"}, h("button", {type: "submit", class: "primary"}, "Print QR code")));
}
function render() {
clear(modes, segmented(draft.mode, [["note", "Note"], ["image", "Image"], ["qr", "QR code"]],
(mode) => { draft.mode = mode; render(); }));
clear(formBox, {note: noteForm, image: imageForm, qr: qrForm}[draft.mode]());
refreshPreview();
}
// Pasting an image anywhere on this tab picks it.
const onPaste = (e) => {
const item = [...(e.clipboardData?.items || [])].find((i) => i.type.startsWith("image/"));
if (!item) return;
if (draft.mode !== "image") { draft.mode = "image"; render(); }
view._pick(item.getAsFile());
};
document.addEventListener("paste", onPaste);
clear(view,
h("div", {class: "split"},
h("section", {class: "card"}, h("h2", {}, "Print now"), modes, formBox, status),
h("aside", {class: "preview-col"}, h("h3", {class: "muted small"}, "Preview"), preview.root)));
render();
return () => document.removeEventListener("paste", onPaste);
}
+126
View File
@@ -0,0 +1,126 @@
// Schedules tab: what's coming up, every schedule as a card, and the preset picker.
import {get, post, del, printJob, sources} from "./api.js";
import {h, clear, fmtTime, relative, toast} from "./dom.js";
import {PRESETS} from "./presets.js";
export const STATUS_LABELS = {
queued: "Queued", printing: "Printing", done: "Printed", failed: "Failed",
skipped: "Skipped", missed: "Missed", error: "Problem", retrying: "Retrying",
held: "Held", watching: "Watching", finished: "Finished",
};
const STATUS_CLASS = {done: "ok", watching: "ok", failed: "err", error: "err", missed: "warn",
skipped: "warn", retrying: "warn", held: "warn"};
export const TRIGGER_ICONS = {once: "◷", recurring: "↻", sun: "☀", calendar: "▦", watch: "◉",
webhook: "⚡"};
// Set by the editor so a preset or a duplicate opens pre-filled.
export const pending = {draft: null};
export async function schedulesView(view) {
const list = h("div", {class: "cards"});
const coming = h("div", {class: "coming"});
clear(view,
h("div", {class: "toolbar"},
h("h2", {}, "Schedules"),
h("button", {class: "primary", onclick: () => showPresets(view)}, "New schedule")),
coming, list);
const [r, up] = await Promise.all([get("api/schedules"), get("api/upcoming?hours=24")]);
if (!r.ok) return clear(list, h("p", {class: "err"}, r.text));
const schedules = r.body.schedules;
if (up.ok && up.body.upcoming.length) {
clear(coming, h("h3", {class: "small muted"}, "Next 24 hours"),
h("div", {class: "timeline"}, up.body.upcoming.slice(0, 12).map((u) =>
h("a", {class: "tick", href: `#schedules/${u.schedule_id}`},
h("strong", {}, new Date(u.at).toLocaleTimeString([], {hour: "2-digit",
minute: "2-digit"})),
h("span", {}, u.name)))));
}
if (!schedules.length) {
clear(list, h("div", {class: "empty"},
h("p", {}, "Nothing scheduled yet. Pick a starting point:"), presetGrid()));
return;
}
clear(list, schedules.map((s) => card(s, () => schedulesView(view))));
}
function card(s, reload) {
const type = s.spec?.trigger?.type;
const toggle = h("input", {type: "checkbox", class: "switch", checked: s.enabled,
"aria-label": s.enabled ? "Turn off" : "Turn on",
onchange: async () => {
const r = await post(`api/schedules/${s.id}/toggle`, {enabled: toggle.checked});
if (!r.ok) { toggle.checked = !toggle.checked; return toast(r.text, "err"); }
toast(toggle.checked ? `${s.name} is on.` : `${s.name} is off.`);
reload();
}});
const next = s.enabled && s.next_run_at
? `Next: ${fmtTime(s.next_run_at)} (${relative(s.next_run_at)})`
: s.enabled ? (type === "webhook" ? "Waits for its webhook" : "") : "Off";
const status = s.last_status
? h("span", {class: `badge ${STATUS_CLASS[s.last_status] || ""}`,
title: s.last_message || ""}, STATUS_LABELS[s.last_status] || s.last_status)
: null;
const busy = h("span", {class: "muted small"});
async function testPrint() {
const result = await printJob(() => post(`api/schedules/${s.id}/run`),
(text) => (busy.textContent = text));
busy.textContent = "";
toast(result.text, result.ok ? "" : "err");
}
async function duplicate() {
const r = await post(`api/schedules/${s.id}/duplicate`);
if (!r.ok) return toast(r.text, "err");
location.hash = `#schedules/${r.body.schedule.id}`;
}
async function remove() {
if (!confirm(`Delete "${s.name}"?`)) return;
const r = await del(`api/schedules/${s.id}`);
if (!r.ok) return toast(r.text, "err");
toast("Deleted.");
reload();
}
return h("article", {class: `card schedule ${s.enabled ? "" : "off"}`},
h("div", {class: "card-head"},
h("span", {class: "icon", "aria-hidden": "true"}, TRIGGER_ICONS[type] || "?"),
h("a", {class: "title", href: `#schedules/${s.id}`}, s.name),
toggle),
h("p", {class: "summary"}, s.summary),
h("p", {class: "meta"}, next ? h("span", {}, next) : null, status,
s.last_message && s.last_status !== "done"
? h("span", {class: "muted small last"}, s.last_message) : null),
h("div", {class: "actions"},
h("a", {class: "button small", href: `#schedules/${s.id}`}, "Edit"),
h("button", {class: "small", onclick: testPrint}, "Test print"),
h("button", {class: "ghost small", onclick: duplicate}, "Duplicate"),
h("button", {class: "danger ghost small", onclick: remove}, "Delete"),
busy));
}
function presetGrid() {
return h("div", {class: "presets"}, PRESETS.map((p) =>
h("button", {class: "preset", onclick: async () => {
pending.draft = p.make(await sources());
location.hash = "#schedules/new";
}},
h("span", {class: "icon", "aria-hidden": "true"}, p.icon),
h("strong", {}, p.title),
h("span", {class: "muted small"}, p.blurb))));
}
function showPresets(view) {
const dialog = h("dialog", {class: "sheet", onclose: () => dialog.remove()},
h("div", {class: "toolbar"}, h("h2", {}, "New schedule"),
h("button", {class: "ghost", onclick: () => dialog.close()}, "Close")),
presetGrid());
view.append(dialog);
dialog.showModal();
}
+173
View File
@@ -0,0 +1,173 @@
// Settings tab: time zone and location, quiet hours, limits, pause, saved sources and images.
import {assets, call, del, post, put, settings, sources} from "./api.js";
import {checkbox, clear, h, input, labelled, select, toast} from "./dom.js";
export async function settingsView(view) {
const conf = await settings(true);
const s = structuredClone(conf.settings);
const quiet = {on: !!s.quiet_start, start: (s.quiet_start || "22:00").slice(0, 5),
end: (s.quiet_end || "07:00").slice(0, 5)};
const loc = {latitude: s.location?.latitude ?? "", longitude: s.location?.longitude ?? "",
name: s.location?.name ?? ""};
const sourcesBox = h("div");
const assetsBox = h("div");
async function save() {
const body = {
timezone: s.timezone,
location: loc.latitude === "" || loc.longitude === "" || loc.latitude === null
? null : {latitude: Number(loc.latitude), longitude: Number(loc.longitude),
name: loc.name || ""},
quiet_start: quiet.on ? quiet.start : null,
quiet_end: quiet.on ? quiet.end : null,
daily_cap: Number(s.daily_cap) || 0,
paused: !!s.paused,
paused_until: s.paused && s.paused_until ? s.paused_until : null,
};
const r = await put("api/settings", body);
if (!r.ok) return toast(r.text, "err");
await settings(true);
toast("Settings saved.");
}
const latInput = input(loc, "latitude", {type: "number", step: "any", class: "narrow",
placeholder: "51.5"});
const lonInput = input(loc, "longitude", {type: "number", step: "any", class: "narrow",
placeholder: "-0.12"});
const locate = h("button", {type: "button", class: "ghost small", onclick: () => {
if (!navigator.geolocation) return toast("This browser can't share its location.", "err");
locate.textContent = "Locating…";
navigator.geolocation.getCurrentPosition((pos) => {
loc.latitude = Number(pos.coords.latitude.toFixed(4));
loc.longitude = Number(pos.coords.longitude.toFixed(4));
latInput.value = loc.latitude; lonInput.value = loc.longitude;
locate.textContent = "Use my location";
}, (err) => { locate.textContent = "Use my location"; toast(err.message, "err"); });
}}, "Use my location");
const tzList = h("datalist", {id: "tz-list"}, conf.timezones.map((z) => h("option", {value: z})));
const pauseUntil = labelled("Until (optional)", input(s, "paused_until", {type: "date",
parse: (v) => v || null}), "Printing resumes at the start of that day.");
clear(view,
h("div", {class: "toolbar"}, h("h2", {}, "Settings"), h("span", {class: "spacer"}),
h("button", {class: "primary", onclick: save}, "Save settings")),
h("div", {class: "grid2"},
h("section", {class: "card"},
h("h3", {}, "Time and place"),
labelled("Time zone", input(s, "timezone", {list: "tz-list"}), null), tzList,
labelled("Location (for sunrise and sunset)",
h("div", {class: "row start"}, latInput, lonInput, locate)),
labelled("Place name", input(loc, "name", {placeholder: "(optional)"}))),
h("section", {class: "card"},
h("h3", {}, "Automatic printing"),
checkbox(quiet, "on", "Quiet hours"),
h("div", {class: "row start indent"},
input(quiet, "start", {type: "time"}), h("span", {}, "to"),
input(quiet, "end", {type: "time"})),
h("p", {class: "muted small"}, "Each schedule chooses whether to wait, skip or print anyway."),
labelled("Most automatic prints per day", input(s, "daily_cap", {type: "number", min: 0,
max: 1000, class: "narrow"}), "0 for no limit. Prints by hand don't count."),
checkbox(s, "paused", "Pause all schedules (holiday mode)"),
pauseUntil)),
h("section", {class: "card"},
h("h3", {}, "Calendars and feeds"),
h("p", {class: "muted small"},
"Saved once, used by agenda and headline blocks and calendar reminders. For Google " +
"Calendar, use the calendar's secret address in iCal format."),
sourcesBox),
h("section", {class: "card"}, h("h3", {}, "Images for schedules"), assetsBox));
renderSources(sourcesBox);
renderAssets(assetsBox);
}
function mask(url) {
try {
const u = new URL(url);
return `${u.protocol}//${u.host}${u.pathname.length > 1 ? "/…" : ""}`;
} catch (e) { return url; }
}
async function renderSources(box) {
const list = await sources(true);
const draft = {name: "", kind: "ics", url: ""};
const result = h("span", {class: "small muted"});
async function test(body, out) {
out.textContent = "Checking…";
const r = await post("api/sources/test", body);
out.textContent = r.text;
out.className = `small ${r.ok ? "ok" : "err"}`;
}
function item(source) {
const out = h("span", {class: "small muted"});
return h("div", {class: "list-row"},
h("span", {class: "badge"}, source.kind === "ics" ? "Calendar" : "Feed"),
h("strong", {}, source.name),
h("code", {class: "muted small", title: "The full address is hidden"}, mask(source.url)),
h("span", {class: "spacer"}),
out,
h("button", {class: "ghost small", onclick: () => test(
{name: source.name, kind: source.kind, url: source.url}, out)}, "Test"),
h("button", {class: "ghost small", onclick: async () => {
const url = prompt(`New address for ${source.name}:`, "");
if (!url) return;
const r = await put(`api/sources/${source.id}`, {...source, url, id: undefined,
created_at: undefined});
if (!r.ok) return toast(r.text, "err");
renderSources(box);
}}, "Change URL"),
h("button", {class: "ghost small danger", onclick: async () => {
if (!confirm(`Delete ${source.name}?`)) return;
const r = await del(`api/sources/${source.id}`);
if (!r.ok) return toast(r.text, "err");
renderSources(box);
}}, "Delete"));
}
clear(box,
list.length ? list.map(item) : h("p", {class: "muted"}, "None yet."),
h("form", {class: "add-source", onsubmit: async (e) => {
e.preventDefault();
const r = await post("api/sources", draft);
if (!r.ok) return toast(r.text, "err");
toast(`Added ${draft.name}.`);
renderSources(box);
}},
h("div", {class: "row start"},
select(draft, "kind", [["ics", "Calendar (ICS)"], ["rss", "Feed (RSS/Atom)"]]),
input(draft, "name", {placeholder: "Name", required: true, maxlength: 100}),
input(draft, "url", {placeholder: "https://… or webcal://…", required: true,
class: "grow"})),
h("div", {class: "row start"},
h("button", {type: "button", class: "ghost", onclick: () => test(draft, result)}, "Test"),
h("button", {type: "submit"}, "Add"), result)));
}
async function renderAssets(box) {
const list = await assets(true);
clear(box,
list.length ? list.map((a) => h("div", {class: "list-row"},
h("strong", {}, a.name), h("span", {class: "muted small"}, `${Math.ceil(a.size / 1024)} KB`),
h("span", {class: "spacer"}),
h("button", {class: "ghost small danger", onclick: async () => {
if (!confirm(`Delete ${a.name}?`)) return;
const r = await del(`api/assets/${a.id}`);
if (!r.ok) return toast(r.text, "err");
renderAssets(box);
}}, "Delete")))
: h("p", {class: "muted"}, "None yet. Upload one from an image block in a schedule, or here."),
h("label", {class: "button ghost"}, "Upload image…",
h("input", {type: "file", accept: "image/*", hidden: true, onchange: async (e) => {
const file = e.target.files[0];
if (!file) return;
const data = new FormData();
data.append("file", file, file.name || "image.png");
const r = await call("api/assets", {method: "POST", body: data});
if (!r.ok) return toast(r.text, "err");
renderAssets(box);
}})));
}