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