Files
receipt_maker/receipt_content.py
T
adamfandClaude Opus 5.5 ba92f1fbda
CI / test (3.10) (push) Successful in 1m20s
CI / test (3.12) (push) Successful in 1m49s
CI / test (3.13) (push) Successful in 1m5s
Add scheduled and event-driven printing with a new web UI
The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:

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

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

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

373 lines
14 KiB
Python

"""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