Add a web server for printing from the site, deployed on stppi
`./receipt.py serve` (receipt_web.py, the new [web] extra) serves a page for printing a note or an uploaded image. The site's nginx gates /receipt/ on the admin session and proxies to it over Tailscale, adding X-Receipt-Token; nothing but /healthz answers without it, and POSTs also need X-Requested-With: receipt. Jobs run one at a time behind a lock around run_action(), and uploads print from memory. run_action(), _dispatch() and setup_network_quiet() move from the TUI to receipt.py so the server doesn't need textual. --no-setup (needs_setup()) skips the sudo connect script everywhere it would run; serve always sets it. cmd_print takes in-memory `data`. deploy/ has the systemd user units. receipt-update.timer runs update.sh every 5 minutes: it fast-forwards the clone from Gitea, runs the tests and restarts receipt-web, rolling back if they fail. Also included from earlier uncommitted work: the CI matrix moved to the right place, connect_receipt.sh no longer re-parses CLI values in bash -c, RECEIPT_PRINTER_IP/PORT are validated, pyusb is declared, the ruff S rules are on, and the img/ cache and junk/ are no longer tracked. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+210
-28
@@ -5,6 +5,8 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import io
|
||||
import ipaddress
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
@@ -12,20 +14,44 @@ import sys
|
||||
import textwrap
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
import requests
|
||||
from escpos import exceptions as escpos_exceptions
|
||||
from escpos import printer
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
DEFAULT_PRINTER_IP = os.environ.get("RECEIPT_PRINTER_IP", "192.168.192.168")
|
||||
DEFAULT_PRINTER_PORT = int(os.environ.get("RECEIPT_PRINTER_PORT", "9100"))
|
||||
FALLBACK_PRINTER_IP = "192.168.192.168"
|
||||
|
||||
|
||||
def _env_ip() -> str:
|
||||
raw = os.environ.get("RECEIPT_PRINTER_IP", FALLBACK_PRINTER_IP).strip()
|
||||
try:
|
||||
ipaddress.ip_address(raw)
|
||||
except ValueError:
|
||||
print(f"Ignoring invalid RECEIPT_PRINTER_IP={raw!r}.", file=sys.stderr)
|
||||
return FALLBACK_PRINTER_IP
|
||||
return raw
|
||||
|
||||
|
||||
def _env_port() -> int:
|
||||
raw = os.environ.get("RECEIPT_PRINTER_PORT", "9100")
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
print(f"Ignoring invalid RECEIPT_PRINTER_PORT={raw!r}; using 9100.", file=sys.stderr)
|
||||
return 9100
|
||||
|
||||
|
||||
DEFAULT_PRINTER_IP = _env_ip()
|
||||
DEFAULT_PRINTER_PORT = _env_port()
|
||||
USB_VENDOR_ID = 0x04B8
|
||||
USB_PRODUCT_ID = 0x0202
|
||||
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
|
||||
TEXT_COLUMNS = 48 # font A columns on 80mm paper
|
||||
HTTP_TIMEOUT = 15 # seconds
|
||||
MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded image
|
||||
MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image
|
||||
DEFAULT_WEB_LISTEN = "100.107.152.119:8765" # stppi's Tailscale IP; nginx on stpvm proxies here
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
IMG_DIR = BASE_DIR / "img"
|
||||
@@ -36,6 +62,9 @@ BANT_CATALOG_URL = "https://a.4cdn.org/bant/catalog.json"
|
||||
BANT_IMAGE_URL = "https://i.4cdn.org/bant/{tim}{ext}"
|
||||
PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
||||
|
||||
# Untrusted 4chan bytes: refuse absurd pixel counts (decode bomb) before Image.open.
|
||||
Image.MAX_IMAGE_PIXELS = 32_000_000
|
||||
|
||||
|
||||
def setup_network(args: argparse.Namespace | None = None) -> None:
|
||||
"""Bring up the printer's network interface via the connect script."""
|
||||
@@ -43,7 +72,34 @@ def setup_network(args: argparse.Namespace | None = None) -> None:
|
||||
if args and not getattr(args, "usb", False):
|
||||
env["RECEIPT_PRINTER_IP"] = args.ip
|
||||
env["RECEIPT_PRINTER_PORT"] = str(args.port)
|
||||
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True)
|
||||
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607
|
||||
|
||||
|
||||
def setup_network_quiet(args: argparse.Namespace) -> None:
|
||||
"""Run the connect script with output captured, so callers can redirect it (TUI, web)."""
|
||||
env = os.environ.copy()
|
||||
env["RECEIPT_PRINTER_IP"] = args.ip
|
||||
env["RECEIPT_PRINTER_PORT"] = str(args.port)
|
||||
bash_path = str(CONNECT_SCRIPT) # noqa: S607 - fixed project script
|
||||
result = subprocess.run( # noqa: S603
|
||||
["/bin/bash", bash_path],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
stdin=subprocess.DEVNULL,
|
||||
timeout=60,
|
||||
)
|
||||
if result.stdout:
|
||||
print(result.stdout, end="")
|
||||
if result.stderr:
|
||||
print(result.stderr, end="")
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"connect script failed (exit {result.returncode})")
|
||||
|
||||
|
||||
def needs_setup(args: argparse.Namespace) -> bool:
|
||||
"""Ethernet needs the connect script, unless --no-setup says the link is already up."""
|
||||
return not args.usb and not getattr(args, "no_setup", False)
|
||||
|
||||
|
||||
def get_printer(args: argparse.Namespace) -> printer.Escpos:
|
||||
@@ -52,19 +108,20 @@ def get_printer(args: argparse.Namespace) -> printer.Escpos:
|
||||
return printer.Network(args.ip, port=args.port)
|
||||
|
||||
|
||||
def prepare_for_print(img_path: Path) -> Image.Image:
|
||||
def prepare_for_print(img_path: Path | BinaryIO) -> 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.
|
||||
"""
|
||||
with Image.open(img_path) as img:
|
||||
img.load() # DecompressionBombError and truncated files surface here, inside `with`
|
||||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||
rgba = img.convert("RGBA")
|
||||
background = Image.new("RGBA", rgba.size, "white")
|
||||
img = Image.alpha_composite(background, rgba)
|
||||
width, height = img.size
|
||||
new_height = round(PRINT_WIDTH_PX * height / width)
|
||||
new_height = max(1, round(PRINT_WIDTH_PX * height / width))
|
||||
resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
|
||||
return ImageOps.autocontrast(resized.convert("L")).convert("1")
|
||||
|
||||
@@ -81,11 +138,12 @@ def _printable(thread: dict) -> bool:
|
||||
"""True when the thread's OP image is safe to cache and print.
|
||||
|
||||
Whitelist the extension (remote data, never trusted) and require a
|
||||
numeric tim so the filename can't escape IMG_DIR.
|
||||
positive integer tim so the filename can't escape IMG_DIR.
|
||||
"""
|
||||
tim, ext = thread.get("tim"), thread.get("ext", "")
|
||||
return (
|
||||
isinstance(tim, int)
|
||||
and tim > 0
|
||||
and isinstance(ext, str)
|
||||
and ext.lower() in PRINTABLE_EXTENSIONS
|
||||
)
|
||||
@@ -107,23 +165,33 @@ def download_random_bant_image() -> Path | None:
|
||||
if not image_threads:
|
||||
return None
|
||||
|
||||
thread = random.choice(image_threads)
|
||||
dest = IMG_DIR / f"{thread['tim']}{thread['ext'].lower()}"
|
||||
# noqa: S311 — random pick is a convenience choice among catalog entries, not a security decision
|
||||
thread = random.choice(image_threads) # noqa: S311 - non-security choice
|
||||
ext = thread["ext"].lower()
|
||||
dest = IMG_DIR / f"{thread['tim']}{ext}"
|
||||
if dest.is_file():
|
||||
return dest
|
||||
|
||||
image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"])
|
||||
img_response = requests.get(image_url, timeout=HTTP_TIMEOUT)
|
||||
img_response.raise_for_status()
|
||||
data = img_response.content
|
||||
if len(data) > MAX_IMAGE_BYTES:
|
||||
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:
|
||||
print(
|
||||
f"Skipping {dest.name}: {len(data) // 1024} KB exceeds the "
|
||||
f"{MAX_IMAGE_BYTES // 1024} KB cap.",
|
||||
f"Skipping {dest.name}: exceeds the {MAX_IMAGE_BYTES // 1024} KB cap.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
dest.write_bytes(data)
|
||||
dest.write_bytes(buf.getvalue())
|
||||
|
||||
return dest
|
||||
|
||||
@@ -139,7 +207,15 @@ def cached_images() -> list[Path]:
|
||||
)
|
||||
|
||||
|
||||
def print_image(p: printer.Escpos, img_path: Path, args: argparse.Namespace) -> printer.Escpos:
|
||||
def close_quietly(p: printer.Escpos) -> None:
|
||||
"""Close a printer handle, ignoring errors from an already-dead socket."""
|
||||
with contextlib.suppress(Exception):
|
||||
p.close()
|
||||
|
||||
|
||||
def print_image(
|
||||
p: printer.Escpos, img_path: Path | BinaryIO, args: argparse.Namespace
|
||||
) -> printer.Escpos:
|
||||
"""Print an image, reconnecting and retrying once if the printer drops.
|
||||
|
||||
Returns the (possibly reconnected) printer so the caller keeps a live handle.
|
||||
@@ -149,22 +225,31 @@ def print_image(p: printer.Escpos, img_path: Path, args: argparse.Namespace) ->
|
||||
p.image(prepared, impl="bitImageColumn")
|
||||
except (OSError, escpos_exceptions.Error) as e:
|
||||
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
|
||||
if not args.usb:
|
||||
close_quietly(p)
|
||||
if needs_setup(args):
|
||||
setup_network(args)
|
||||
p = get_printer(args)
|
||||
# Record it so main() closes the live handle, not the one it opened.
|
||||
args._printer = p
|
||||
p.image(prepared, impl="bitImageColumn")
|
||||
return p
|
||||
|
||||
|
||||
def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
printed = 0
|
||||
for _ in range(args.count):
|
||||
img = download_random_bant_image()
|
||||
if img is None:
|
||||
print("No images found on /bant/.", file=sys.stderr)
|
||||
return 1
|
||||
# Keep going: one skipped image shouldn't discard the rest of the run.
|
||||
print("No printable image found; skipping.", file=sys.stderr)
|
||||
continue
|
||||
p.textln(img.stem)
|
||||
p = print_image(p, img, args)
|
||||
p.cut()
|
||||
printed += 1
|
||||
if printed == 0:
|
||||
print("No images printed.", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
@@ -184,12 +269,18 @@ def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
|
||||
|
||||
def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
if not args.path.is_file():
|
||||
# `data` is an in-memory upload (web server); it is never written to disk.
|
||||
data = getattr(args, "data", None)
|
||||
if data is not None:
|
||||
source: Path | BinaryIO = io.BytesIO(data)
|
||||
elif args.path.is_file():
|
||||
source = args.path
|
||||
else:
|
||||
print(f"File not found: {args.path}", file=sys.stderr)
|
||||
return 1
|
||||
if args.message:
|
||||
p.textln(wrap_text(args.message))
|
||||
p = print_image(p, args.path, args)
|
||||
p = print_image(p, source, args)
|
||||
p.cut()
|
||||
return 0
|
||||
|
||||
@@ -224,7 +315,7 @@ def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
|
||||
def cmd_status(args: argparse.Namespace) -> int:
|
||||
try:
|
||||
if not args.usb:
|
||||
if needs_setup(args):
|
||||
setup_network(args)
|
||||
p = get_printer(args)
|
||||
p.close()
|
||||
@@ -258,7 +349,9 @@ def cmd_clean(yes: bool = False) -> int:
|
||||
"""
|
||||
images = cached_images()
|
||||
legacy_files = (
|
||||
list(LEGACY_FULLWIDTH_DIR.iterdir()) if LEGACY_FULLWIDTH_DIR.is_dir() else []
|
||||
[f for f in LEGACY_FULLWIDTH_DIR.iterdir() if f.is_file()]
|
||||
if LEGACY_FULLWIDTH_DIR.is_dir()
|
||||
else []
|
||||
)
|
||||
if not images and not legacy_files:
|
||||
print("Nothing to clean.")
|
||||
@@ -278,6 +371,63 @@ def cmd_clean(yes: bool = False) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]:
|
||||
"""Run a command handler, capturing its terminal output (used by the TUI and web server).
|
||||
|
||||
Mirrors main(): every action connects fresh, so a dropped printer never
|
||||
leaves the caller holding a dead handle. redirect_stdout is process-global,
|
||||
so concurrent callers must serialize.
|
||||
"""
|
||||
args = argparse.Namespace(**{**vars(base), **params, "command": command})
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
|
||||
try:
|
||||
rc = _dispatch(command, args)
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
rc = 1
|
||||
return rc, buf.getvalue().rstrip()
|
||||
|
||||
|
||||
def _dispatch(command: str, args: argparse.Namespace) -> int:
|
||||
if command == "list":
|
||||
return cmd_list()
|
||||
# No TTY to prompt on: the button press is the confirmation.
|
||||
if command == "clean":
|
||||
return cmd_clean(yes=True)
|
||||
if command == "status":
|
||||
if needs_setup(args):
|
||||
setup_network_quiet(args)
|
||||
# Already up; cmd_status must not rerun the script with uncaptured output.
|
||||
args = argparse.Namespace(**{**vars(args), "no_setup": True})
|
||||
return cmd_status(args)
|
||||
if needs_setup(args):
|
||||
setup_network_quiet(args)
|
||||
handlers = {
|
||||
"image": cmd_image,
|
||||
"note": cmd_note,
|
||||
"print": cmd_print,
|
||||
"qr": cmd_qr,
|
||||
"reprint": cmd_reprint,
|
||||
}
|
||||
p = get_printer(args)
|
||||
# print_image() may reconnect and stash the new handle here; close whichever is live.
|
||||
args._printer = p
|
||||
try:
|
||||
return handlers[command](p, args)
|
||||
finally:
|
||||
close_quietly(args._printer)
|
||||
|
||||
|
||||
def _valid_ip(value: str) -> str:
|
||||
# The IP is interpolated into the connect script's environment; reject shell metacharacters.
|
||||
try:
|
||||
ipaddress.ip_address(value.strip())
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(f"not a valid IP address: {value!r}") from None
|
||||
return value.strip()
|
||||
|
||||
|
||||
def positive_int(value: str) -> int:
|
||||
n = int(value)
|
||||
if n < 1:
|
||||
@@ -294,6 +444,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ip",
|
||||
type=_valid_ip,
|
||||
default=DEFAULT_PRINTER_IP,
|
||||
help=f"Printer IP address (default: {DEFAULT_PRINTER_IP}, env RECEIPT_PRINTER_IP)",
|
||||
)
|
||||
@@ -303,6 +454,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
default=DEFAULT_PRINTER_PORT,
|
||||
help=f"Printer port (default: {DEFAULT_PRINTER_PORT}, env RECEIPT_PRINTER_PORT)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-setup",
|
||||
action="store_true",
|
||||
help="Don't run the connect script (the printer link is already configured)",
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
image_p = subparsers.add_parser("image", help="Print random /bant/ images")
|
||||
@@ -351,6 +507,12 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
"-y", "--yes", action="store_true", help="Skip the confirmation prompt"
|
||||
)
|
||||
subparsers.add_parser("tui", help="Open the interactive terminal UI")
|
||||
serve_p = subparsers.add_parser("serve", help="Run the web server for printing from the site")
|
||||
serve_p.add_argument(
|
||||
"--listen",
|
||||
default=os.environ.get("RECEIPT_WEB_LISTEN", DEFAULT_WEB_LISTEN),
|
||||
help=f"host:port to bind (default: {DEFAULT_WEB_LISTEN}, env RECEIPT_WEB_LISTEN)",
|
||||
)
|
||||
|
||||
return parser
|
||||
|
||||
@@ -369,6 +531,17 @@ def main() -> int:
|
||||
)
|
||||
return 1
|
||||
return run_tui(args)
|
||||
if args.command == "serve":
|
||||
try:
|
||||
from receipt_web import serve
|
||||
except ModuleNotFoundError as e:
|
||||
print(
|
||||
f"The web server needs extra packages ({e}). "
|
||||
"Install them with: pip install 'receipt-maker[web]'",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
return serve(args)
|
||||
if args.command == "list":
|
||||
return cmd_list()
|
||||
if args.command == "clean":
|
||||
@@ -377,7 +550,7 @@ def main() -> int:
|
||||
return cmd_status(args)
|
||||
|
||||
try:
|
||||
if not args.usb:
|
||||
if needs_setup(args):
|
||||
setup_network(args)
|
||||
p = get_printer(args)
|
||||
except Exception as e:
|
||||
@@ -391,12 +564,21 @@ def main() -> int:
|
||||
"qr": cmd_qr,
|
||||
"reprint": cmd_reprint,
|
||||
}
|
||||
# print_image() may reconnect and stash the new handle on args; close whichever is live.
|
||||
args._printer = p
|
||||
try:
|
||||
with contextlib.closing(p):
|
||||
return commands[args.command](p, args)
|
||||
return commands[args.command](p, args)
|
||||
except requests.RequestException as e:
|
||||
print(f"Download failed: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
print("Aborted.", file=sys.stderr)
|
||||
return 130
|
||||
except (OSError, escpos_exceptions.Error, Image.UnidentifiedImageError) as e:
|
||||
print(f"Print failed: {e}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
close_quietly(args._printer)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user