Add a web server for printing from the site, deployed on stppi
CI / test (3.12) (push) Failing after 43s
CI / test (3.10) (push) Failing after 6m6s
CI / test (3.13) (push) Failing after 36s

`./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:
2026-10-23 21:22:31 +01:00
co-authored by Claude Opus 5.5
parent e333d6729f
commit f55b20fb82
65 changed files with 1142 additions and 124712 deletions
+3 -3
View File
@@ -7,14 +7,14 @@ on:
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
python: ["3.10", "3.12", "3.13"]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: ${{ matrix.python }} python-version: ${{ matrix.python }}
strategy:
matrix:
python: ["3.10", "3.12", "3.13"]
- run: pip install -e '.[dev]' - run: pip install -e '.[dev]'
- run: ruff check . - run: ruff check .
- run: pytest - run: pytest
+3
View File
@@ -6,3 +6,6 @@ __pycache__/
*.pyo *.pyo
.env .env
.venv/ .venv/
build/
*.egg-info/
.pytest_cache/
+5 -2
View File
@@ -5,7 +5,9 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt
## Layout ## Layout
- `receipt.py` — the CLI; subcommand per `cmd_*` function - `receipt.py` — the CLI; subcommand per `cmd_*` function
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `run_action()`, which connects fresh per action and captures stdout/stderr for the log panel. `textual` is an optional dependency (`[tui]` extra); the CLI works without it - `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which connects fresh per action and captures stdout/stderr for the log panel. `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. Serializes jobs with a lock around `run_action()`; uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which reaches the printer on the home Wi-Fi (192.168.178.250)
- `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) fast-forwards the server's clone from Gitea, runs the tests, and restarts `receipt-web`, rolling back if they fail. 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 (`setup_network_quiet`) so it can't corrupt the screen - `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 (`setup_network_quiet`) so it can't corrupt the screen
- `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network - `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
- Printer/network constants live at the top of `receipt.py`; IP/port overridable via `--ip`/`--port` or `RECEIPT_PRINTER_IP`/`RECEIPT_PRINTER_PORT` - Printer/network constants live at the top of `receipt.py`; IP/port overridable via `--ip`/`--port` or `RECEIPT_PRINTER_IP`/`RECEIPT_PRINTER_PORT`
- 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 - 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
- `print_image()` reconnects and retries once on failure and returns the (possibly new) printer handle — callers must rebind `p` - `print_image()` reconnects and retries once on failure and returns the (possibly new) printer handle — callers must rebind `p`
- Commands that don't need the printer (`list`, `clean`) or handle their own connection (`status`) are dispatched in `main()` before connecting - Commands that don't need the printer (`list`, `clean`) or handle their own connection (`status`, `tui`, `serve`) are dispatched in `main()` before connecting
- `--no-setup` (`args.no_setup`) skips the connect script everywhere it would run; check it with `needs_setup(args)`
## Checks ## Checks
+64 -1
View File
@@ -14,6 +14,7 @@ The CLI runs the connect script automatically before printing (unless `--usb` is
- Python 3.10+ - Python 3.10+
- `python-escpos`, `Pillow`, `requests` (see `pyproject.toml`) - `python-escpos`, `Pillow`, `requests` (see `pyproject.toml`)
- `textual` (optional, only for the `tui` subcommand; `pip install '.[tui]'`) - `textual` (optional, only for the `tui` subcommand; `pip install '.[tui]'`)
- `fastapi`, `uvicorn`, `python-multipart` (optional, only for the `serve` subcommand; `pip install '.[web]'`)
- Epson TM-T20II connected via a USB-to-Ethernet adapter (or directly over USB with `--usb`) - Epson TM-T20II connected via a USB-to-Ethernet adapter (or directly over USB with `--usb`)
Install the dependencies (or `pip install .` to also get a `receipt` command on your PATH): Install the dependencies (or `pip install .` to also get a `receipt` command on your PATH):
@@ -64,6 +65,65 @@ fortune | ./receipt.py note
Images are prepared for thermal output automatically: transparency is composited onto white, then the image is resized to full width, autocontrast-stretched, and Floyd-Steinberg dithered. Images are prepared for thermal output automatically: transparency is composited onto white, then the image is resized to full width, autocontrast-stretched, and Floyd-Steinberg dithered.
## Printing from the website
`./receipt.py serve` runs a small web server (`receipt_web.py`, needs `pip install '.[web]'`) with a page for printing a note or an uploaded image. It runs on stppi (the Raspberry Pi). The printer is on the home Wi-Fi at a fixed `192.168.178.250`, so the Pi reaches it over the LAN. The site's nginx on stpvm gates `https://www.adam-french.co.uk/receipt/` on the admin login, then forwards over Tailscale to this server and adds an `X-Receipt-Token` header. The server answers nothing but `/healthz` without that token.
```
browser ─https─> nginx (stpvm, admin auth_request) ─Tailscale─> receipt serve (stppi:8765) ─LAN─> printer
```
`serve` never runs the sudo connect script (`--no-setup` does the same for other commands), so the printer must already be reachable. On Wi-Fi it is. A printer cabled to the server's own Ethernet port instead needs a permanent address on that port:
```bash
sudo nmcli con add type ethernet ifname <port> con-name receipt-printer \
ipv4.method manual ipv4.addresses 192.168.192.10/24 ipv4.never-default yes ipv6.method disabled
```
### Setting up the server machine
1. Clone from Gitea to `~/Coding/receipt_maker` (the path the units use), and install into a venv there:
```bash
git clone ssh://[email protected]:2222/adamf/receipt_maker.git ~/Coding/receipt_maker
cd ~/Coding/receipt_maker
python3 -m venv .venv && .venv/bin/pip install '.[web,dev]'
```
2. Create the settings file. Put the same token in the web_server `.env` as `RECEIPT_WEB_TOKEN`:
```bash
(umask 077; printf 'RECEIPT_WEB_TOKEN=%s\nRECEIPT_WEB_LISTEN=%s:8765\nRECEIPT_PRINTER_IP=192.168.178.250\n' \
"$(openssl rand -hex 32)" "$(tailscale ip -4)" > ~/.config/receipt-web.env)
```
3. Install the units, point the server at the venv, and start everything at boot:
```bash
cp deploy/receipt-web.service deploy/receipt-update.{service,timer} ~/.config/systemd/user/
mkdir -p ~/.config/systemd/user/receipt-web.service.d
printf '[Service]\nExecStart=\nExecStart=%%h/Coding/receipt_maker/.venv/bin/python %%h/Coding/receipt_maker/receipt.py serve\n' \
> ~/.config/systemd/user/receipt-web.service.d/venv.conf
systemctl --user daemon-reload
systemctl --user enable --now receipt-web receipt-update.timer
sudo loginctl enable-linger "$USER"
```
4. On stpvm, set `RECEIPT_WEB_UPSTREAM=<tailscale ip>:8765` in web_server's `.env`, then `docker compose up -d nginx`.
Jobs run one at a time. If the server machine is off, the site shows "printer machine offline".
### Automatic updates
`receipt-update.timer` runs `deploy/update.sh` every 5 minutes. When `master` on Gitea has moved, the script:
1. fast-forwards the clone
2. reinstalls the dependencies if `pyproject.toml` changed
3. runs the tests
4. restarts `receipt-web`
If the tests fail, the clone goes back to the previous commit, the old code keeps serving, and that commit is skipped until a newer one is pushed. Its output is in `journalctl --user -u receipt-update`. Pushing to Gitea is the whole deploy.
## Development ## Development
```bash ```bash
@@ -78,6 +138,9 @@ Both checks also run in CI on every push and pull request (`.github/workflows/ci
- `receipt.py` — main script - `receipt.py` — main script
- `receipt_tui.py` — Textual terminal UI (`./receipt.py tui`) - `receipt_tui.py` — Textual terminal UI (`./receipt.py tui`)
- `receipt_web.py` — web server for printing from the site (`./receipt.py serve`)
- `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 - `connect_receipt.sh` — network setup for the USB Ethernet adapter
- `tests/` — pytest suite for the CLI and TUI (no printer or network needed) - `tests/` — pytest suite for the CLI, TUI and web server (no printer or network needed)
- `img/` — downloaded images cache (gitignored; clear with `./receipt.py clean`) - `img/` — downloaded images cache (gitignored; clear with `./receipt.py clean`)
+3 -2
View File
@@ -27,13 +27,14 @@ fi
sudo ip link set "$iface" up sudo ip link set "$iface" up
# Assign our address on the printer's subnet if not already set # Assign our address on the printer's subnet if not already set
if ! ip addr show dev "$iface" | grep -q "${HOST_ADDR%/*}"; then if ! ip -o addr show dev "$iface" | grep -qw "${HOST_ADDR%/*}"; then
sudo ip addr add "$HOST_ADDR" dev "$iface" sudo ip addr add "$HOST_ADDR" dev "$iface"
fi fi
# Wait for the printer port to become reachable (interface may need a moment) # Wait for the printer port to become reachable (interface may need a moment)
for attempt in {1..5}; do for attempt in {1..5}; do
if timeout 2 bash -c "exec 3<>/dev/tcp/$PRINTER_IP/$PRINTER_PORT" 2>/dev/null; then # No `bash -c "...$VAR..."`: the values come from the CLI and must never be re-parsed.
if timeout 2 bash -c 'exec 3<>/dev/tcp/"$0"/"$1"' "$PRINTER_IP" "$PRINTER_PORT" 2>/dev/null; then
echo "Printer reachable at $PRINTER_IP:$PRINTER_PORT" echo "Printer reachable at $PRINTER_IP:$PRINTER_PORT"
exit 0 exit 0
fi fi
+10
View File
@@ -0,0 +1,10 @@
# Pulls new commits for the receipt printer web server (see deploy/update.sh).
# Installed alongside receipt-web.service; started by receipt-update.timer.
[Unit]
Description=Update the receipt printer web server from Gitea
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=%h/Coding/receipt_maker/deploy/update.sh
+13
View File
@@ -0,0 +1,13 @@
# Checks Gitea for receipt_maker updates every 5 minutes.
# cp deploy/receipt-update.{service,timer} ~/.config/systemd/user/
# systemctl --user daemon-reload && systemctl --user enable --now receipt-update.timer
[Unit]
Description=Check for receipt printer web server updates
[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
RandomizedDelaySec=30
[Install]
WantedBy=timers.target
+24
View File
@@ -0,0 +1,24 @@
# Web server for printing from the site (see README "Printing from the website").
#
# Install as a user unit on the machine the printer is cabled to:
# cp deploy/receipt-web.service ~/.config/systemd/user/
# systemctl --user daemon-reload && systemctl --user enable --now receipt-web
# sudo loginctl enable-linger "$USER" # start at boot, without logging in
#
# ~/.config/receipt-web.env holds RECEIPT_WEB_TOKEN=<secret> (chmod 600); the
# site's nginx sends the same value. RECEIPT_WEB_LISTEN overrides the default
# bind address (this machine's Tailscale IP).
[Unit]
Description=Receipt printer web server
After=network-online.target
Wants=network-online.target
[Service]
EnvironmentFile=%h/.config/receipt-web.env
ExecStart=/usr/bin/python3 %h/Coding/receipt_maker/receipt.py serve
# Binding fails until Tailscale has brought its address up; just retry.
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
# Fast-forward this clone to its upstream (Gitea) and restart the web server
# when the code changed. Run every few minutes by receipt-update.timer on the
# machine the service runs on.
#
# The tests gate the restart: if they fail on the new commit, the clone goes
# back to the old one, the service keeps running the old code, and that
# commit is skipped until a newer one lands.
set -euo pipefail
cd "$(dirname "$0")/.."
git fetch --quiet
old=$(git rev-parse HEAD)
new=$(git rev-parse '@{upstream}')
[ "$old" = "$new" ] && exit 0
failed_marker="$(git rev-parse --git-dir)/receipt-update-failed"
if [ "$(cat "$failed_marker" 2>/dev/null)" = "$new" ]; then
exit 0
fi
git merge --ff-only --quiet "$new"
if ! git diff --quiet "$old" "$new" -- pyproject.toml; then
.venv/bin/pip install --quiet '.[web,dev]'
fi
if ! output=$(.venv/bin/python -m pytest -q -p no:cacheprovider 2>&1); then
echo "$output" | tail -n 20
echo "Tests failed on $(git rev-parse --short "$new"); staying on $(git rev-parse --short "$old")." >&2
git reset --quiet --hard "$old"
echo "$new" >"$failed_marker"
exit 1
fi
systemctl --user restart receipt-web
echo "Updated $(git rev-parse --short "$old") -> $(git rev-parse --short "$new")."
Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 292 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 291 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1022 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 249 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 705 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

-124456
View File
File diff suppressed because it is too large Load Diff
-36
View File
@@ -1,36 +0,0 @@
from escpos.printer import Network
from PIL import Image
import os
def resize_image_to_fullwidth(img_src_name, target_width=580):
# Open the image
img = Image.open(img_src_name)
# Get original dimensions
width, height = img.size
# Calculate new height to maintain aspect ratio
aspect_ratio = height / width
new_height = int(target_width * aspect_ratio)
# Resize the image
resized_img = img.resize((target_width, new_height), Image.LANCZOS)
# Save the resized image
name, ext = os.path.splitext(img_src_name)
# Build destination filename
dest_name = f"{name}_fullwidth{ext}"
resized_img.save(dest_name)
return dest_name
# Replace with your printer's IP address and port
p = Network("192.168.192.168", port=9100)
# Example printing
# p.set_with_default(align='center', font='a', bold=False, width=2, height=2, custom_size=True, smooth=True)
p.textln("Thanks babes")
img_names = ["img/1754661985256965s.jpg", "img/1754658917785283.png"]
img_name = resize_image_to_fullwidth(img_names[1])
p.image(img_name, impl='graphics');
# p.image("img/" + img_names[1], impl='bitImageColumn', center=True, high_density_horizontal=False, high_density_vertical=False);
p.cut()
+16 -2
View File
@@ -7,16 +7,27 @@ dependencies = [
"python-escpos>=3.0", "python-escpos>=3.0",
"Pillow>=10.0", "Pillow>=10.0",
"requests>=2.31", "requests>=2.31",
"pyusb>=1.2", # printer.Usb backend for --usb
] ]
[project.optional-dependencies] [project.optional-dependencies]
tui = [ tui = [
"textual>=1.0", "textual>=1.0",
"rich>=13.0", # imported directly by receipt_tui
]
web = [
"fastapi>=0.110",
"uvicorn>=0.29",
"python-multipart>=0.0.9", # FastAPI's form/upload parsing
] ]
dev = [ dev = [
"pytest>=8.0", "pytest>=8.0",
"ruff>=0.4", "ruff>=0.4",
"textual>=1.0", "textual>=1.0",
"rich>=13.0",
"fastapi>=0.110",
"python-multipart>=0.0.9",
"httpx>=0.27", # FastAPI's TestClient
] ]
[project.scripts] [project.scripts]
@@ -27,14 +38,17 @@ requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[tool.setuptools] [tool.setuptools]
py-modules = ["receipt", "receipt_tui"] py-modules = ["receipt", "receipt_tui", "receipt_web"]
[tool.ruff] [tool.ruff]
line-length = 100 line-length = 100
target-version = "py310" target-version = "py310"
[tool.ruff.lint] [tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B", "SIM"] select = ["E", "F", "W", "I", "UP", "B", "SIM", "S"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"] # asserts are the point
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]
+210 -28
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
import argparse import argparse
import contextlib import contextlib
import io
import ipaddress
import os import os
import random import random
import subprocess import subprocess
@@ -12,20 +14,44 @@ import sys
import textwrap import textwrap
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import BinaryIO
import requests import requests
from escpos import exceptions as escpos_exceptions from escpos import exceptions as escpos_exceptions
from escpos import printer from escpos import printer
from PIL import Image, ImageOps from PIL import Image, ImageOps
DEFAULT_PRINTER_IP = os.environ.get("RECEIPT_PRINTER_IP", "192.168.192.168") FALLBACK_PRINTER_IP = "192.168.192.168"
DEFAULT_PRINTER_PORT = int(os.environ.get("RECEIPT_PRINTER_PORT", "9100"))
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_VENDOR_ID = 0x04B8
USB_PRODUCT_ID = 0x0202 USB_PRODUCT_ID = 0x0202
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
TEXT_COLUMNS = 48 # font A columns on 80mm paper TEXT_COLUMNS = 48 # font A columns on 80mm paper
HTTP_TIMEOUT = 15 # seconds 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 BASE_DIR = Path(__file__).resolve().parent
IMG_DIR = BASE_DIR / "img" 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}" BANT_IMAGE_URL = "https://i.4cdn.org/bant/{tim}{ext}"
PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} 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: def setup_network(args: argparse.Namespace | None = None) -> None:
"""Bring up the printer's network interface via the connect script.""" """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): if args and not getattr(args, "usb", False):
env["RECEIPT_PRINTER_IP"] = args.ip env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port) 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: 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) 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. """Load an image resized to full printer width and dithered for thermal output.
Transparency is composited onto white (thermal paper), then the image is Transparency is composited onto white (thermal paper), then the image is
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit. autocontrast-stretched and Floyd-Steinberg dithered to 1-bit.
""" """
with Image.open(img_path) as img: 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): if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA") rgba = img.convert("RGBA")
background = Image.new("RGBA", rgba.size, "white") background = Image.new("RGBA", rgba.size, "white")
img = Image.alpha_composite(background, rgba) img = Image.alpha_composite(background, rgba)
width, height = img.size 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) resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
return ImageOps.autocontrast(resized.convert("L")).convert("1") 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. """True when the thread's OP image is safe to cache and print.
Whitelist the extension (remote data, never trusted) and require a 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", "") tim, ext = thread.get("tim"), thread.get("ext", "")
return ( return (
isinstance(tim, int) isinstance(tim, int)
and tim > 0
and isinstance(ext, str) and isinstance(ext, str)
and ext.lower() in PRINTABLE_EXTENSIONS and ext.lower() in PRINTABLE_EXTENSIONS
) )
@@ -107,23 +165,33 @@ def download_random_bant_image() -> Path | None:
if not image_threads: if not image_threads:
return None return None
thread = random.choice(image_threads) # noqa: S311 — random pick is a convenience choice among catalog entries, not a security decision
dest = IMG_DIR / f"{thread['tim']}{thread['ext'].lower()}" 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(): if dest.is_file():
return dest return dest
image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"]) image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=ext)
img_response = requests.get(image_url, timeout=HTTP_TIMEOUT) # Stream the body: the cap must fire before a huge response is fully in memory.
img_response.raise_for_status() with requests.get(image_url, timeout=HTTP_TIMEOUT, stream=True) as img_response:
data = img_response.content img_response.raise_for_status()
if len(data) > MAX_IMAGE_BYTES: 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( print(
f"Skipping {dest.name}: {len(data) // 1024} KB exceeds the " f"Skipping {dest.name}: exceeds the {MAX_IMAGE_BYTES // 1024} KB cap.",
f"{MAX_IMAGE_BYTES // 1024} KB cap.",
file=sys.stderr, file=sys.stderr,
) )
return None return None
dest.write_bytes(data) dest.write_bytes(buf.getvalue())
return dest 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. """Print an image, reconnecting and retrying once if the printer drops.
Returns the (possibly reconnected) printer so the caller keeps a live handle. 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") p.image(prepared, impl="bitImageColumn")
except (OSError, escpos_exceptions.Error) as e: except (OSError, escpos_exceptions.Error) as e:
print(f"Print failed ({e}); reconnecting...", file=sys.stderr) print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
if not args.usb: close_quietly(p)
if needs_setup(args):
setup_network(args) setup_network(args)
p = get_printer(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") p.image(prepared, impl="bitImageColumn")
return p return p
def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int: def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
printed = 0
for _ in range(args.count): for _ in range(args.count):
img = download_random_bant_image() img = download_random_bant_image()
if img is None: if img is None:
print("No images found on /bant/.", file=sys.stderr) # Keep going: one skipped image shouldn't discard the rest of the run.
return 1 print("No printable image found; skipping.", file=sys.stderr)
continue
p.textln(img.stem) p.textln(img.stem)
p = print_image(p, img, args) p = print_image(p, img, args)
p.cut() p.cut()
printed += 1
if printed == 0:
print("No images printed.", file=sys.stderr)
return 1
return 0 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: 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) print(f"File not found: {args.path}", file=sys.stderr)
return 1 return 1
if args.message: if args.message:
p.textln(wrap_text(args.message)) p.textln(wrap_text(args.message))
p = print_image(p, args.path, args) p = print_image(p, source, args)
p.cut() p.cut()
return 0 return 0
@@ -224,7 +315,7 @@ def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_status(args: argparse.Namespace) -> int: def cmd_status(args: argparse.Namespace) -> int:
try: try:
if not args.usb: if needs_setup(args):
setup_network(args) setup_network(args)
p = get_printer(args) p = get_printer(args)
p.close() p.close()
@@ -258,7 +349,9 @@ def cmd_clean(yes: bool = False) -> int:
""" """
images = cached_images() images = cached_images()
legacy_files = ( 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: if not images and not legacy_files:
print("Nothing to clean.") print("Nothing to clean.")
@@ -278,6 +371,63 @@ def cmd_clean(yes: bool = False) -> int:
return 0 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: def positive_int(value: str) -> int:
n = int(value) n = int(value)
if n < 1: if n < 1:
@@ -294,6 +444,7 @@ def build_parser() -> argparse.ArgumentParser:
) )
parser.add_argument( parser.add_argument(
"--ip", "--ip",
type=_valid_ip,
default=DEFAULT_PRINTER_IP, default=DEFAULT_PRINTER_IP,
help=f"Printer IP address (default: {DEFAULT_PRINTER_IP}, env RECEIPT_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, default=DEFAULT_PRINTER_PORT,
help=f"Printer port (default: {DEFAULT_PRINTER_PORT}, env RECEIPT_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) subparsers = parser.add_subparsers(dest="command", required=True)
image_p = subparsers.add_parser("image", help="Print random /bant/ images") 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" "-y", "--yes", action="store_true", help="Skip the confirmation prompt"
) )
subparsers.add_parser("tui", help="Open the interactive terminal UI") 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 return parser
@@ -369,6 +531,17 @@ def main() -> int:
) )
return 1 return 1
return run_tui(args) 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": if args.command == "list":
return cmd_list() return cmd_list()
if args.command == "clean": if args.command == "clean":
@@ -377,7 +550,7 @@ def main() -> int:
return cmd_status(args) return cmd_status(args)
try: try:
if not args.usb: if needs_setup(args):
setup_network(args) setup_network(args)
p = get_printer(args) p = get_printer(args)
except Exception as e: except Exception as e:
@@ -391,12 +564,21 @@ def main() -> int:
"qr": cmd_qr, "qr": cmd_qr,
"reprint": cmd_reprint, "reprint": cmd_reprint,
} }
# print_image() may reconnect and stash the new handle on args; close whichever is live.
args._printer = p
try: try:
with contextlib.closing(p): return commands[args.command](p, args)
return commands[args.command](p, args)
except requests.RequestException as e: except requests.RequestException as e:
print(f"Download failed: {e}", file=sys.stderr) print(f"Download failed: {e}", file=sys.stderr)
return 1 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__": if __name__ == "__main__":
+2 -61
View File
@@ -4,10 +4,6 @@
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import contextlib
import io
import os
import subprocess
from pathlib import Path from pathlib import Path
from rich.text import Text from rich.text import Text
@@ -41,60 +37,6 @@ ACTIONS = [
] ]
def setup_network_quiet(args: argparse.Namespace) -> None:
"""Run the connect script with output captured so it can't corrupt the TUI."""
env = os.environ.copy()
env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port)
result = subprocess.run(
["bash", str(receipt.CONNECT_SCRIPT)], env=env, capture_output=True, text=True
)
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 run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]:
"""Run a receipt.py command handler, capturing its terminal output.
Mirrors main(): every action connects fresh, so a dropped printer never
leaves the TUI holding a dead handle.
"""
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 receipt.cmd_list()
# No TTY in the worker thread: the button press is the confirmation.
if command == "clean":
return receipt.cmd_clean(yes=True)
if command == "status":
return receipt.cmd_status(args)
if not args.usb:
setup_network_quiet(args)
handlers = {
"image": receipt.cmd_image,
"note": receipt.cmd_note,
"print": receipt.cmd_print,
"qr": receipt.cmd_qr,
"reprint": receipt.cmd_reprint,
}
with contextlib.closing(receipt.get_printer(args)) as p:
return handlers[command](p, args)
class ReceiptApp(App): class ReceiptApp(App):
TITLE = "Receipt Maker" TITLE = "Receipt Maker"
BINDINGS = [("q", "quit", "Quit")] BINDINGS = [("q", "quit", "Quit")]
@@ -257,7 +199,7 @@ class ReceiptApp(App):
self.call_from_thread(self.set_buttons_disabled, True) self.call_from_thread(self.set_buttons_disabled, True)
self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]") self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]")
try: try:
rc, output = run_action(command, self.base_args, **params) rc, output = receipt.run_action(command, self.base_args, **params)
finally: finally:
self.call_from_thread(self.set_buttons_disabled, False) self.call_from_thread(self.set_buttons_disabled, False)
self.call_from_thread(self.report, command, rc, output) self.call_from_thread(self.report, command, rc, output)
@@ -270,8 +212,7 @@ class ReceiptApp(App):
self.log_panel.write("[green]done[/green]") self.log_panel.write("[green]done[/green]")
else: else:
self.log_panel.write(f"[red]failed (exit {rc})[/red]") self.log_panel.write(f"[red]failed (exit {rc})[/red]")
if rc != 0: self.last_failure = rc # only the most recent action decides the exit code
self.last_failure = rc
if command in ("image", "clean"): if command in ("image", "clean"):
self.refresh_cache_list() self.refresh_cache_list()
+319
View File
@@ -0,0 +1,319 @@
"""Web server for printing from the website; launched via `./receipt.py serve`.
Runs on the machine the printer is cabled to. nginx on the web host gates
/receipt/ on the site's admin session (auth_request), strips the prefix and
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
without that token, so reaching this port directly is not enough.
Uploads are printed from memory and never written to disk.
"""
from __future__ import annotations
import argparse
import hmac
import io
import os
import sys
import threading
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse
from PIL import Image
from pydantic import BaseModel, Field
import receipt
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
# 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"
class Note(BaseModel):
text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS)
timestamp: bool = False
def create_app(base: argparse.Namespace, token: str) -> FastAPI:
# One job at a time: run_action's stdout capture is process-global and the
# printer takes a single connection.
lock = threading.Lock()
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
def require_token(x_receipt_token: str | None = Header(default=None)) -> None:
if x_receipt_token is None or not hmac.compare_digest(
x_receipt_token.encode(), token.encode()
):
raise HTTPException(401, "Missing or invalid token.")
def require_page_request(x_requested_with: str | None = Header(default=None)) -> None:
if x_requested_with != CSRF_HEADER_VALUE:
raise HTTPException(403, "Requests must come from the receipt page.")
def run(command: str, **params) -> JSONResponse:
with lock:
rc, output = receipt.run_action(command, base, **params)
return JSONResponse({"ok": rc == 0, "output": output}, status_code=200 if rc == 0 else 502)
authed = [Depends(require_token)]
posting = [Depends(require_token), Depends(require_page_request)]
@app.get("/healthz")
def healthz() -> dict:
return {"ok": True}
@app.get("/", response_class=HTMLResponse, dependencies=authed)
def page() -> str:
return PAGE
@app.get("/api/status", dependencies=authed)
def status() -> JSONResponse:
return run("status")
@app.post("/api/note", dependencies=posting)
def note(body: Note) -> JSONResponse:
if not body.text.strip():
raise HTTPException(400, "Nothing to print.")
return run("note", text=body.text, timestamp=body.timestamp)
@app.post("/api/image", dependencies=posting)
def image(
file: UploadFile = File(...), # noqa: B008 - FastAPI's declaration idiom
message: str = Form(default="", max_length=MAX_CAPTION_CHARS),
) -> 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."
)
# Reject non-images here, as a 400, rather than as a print failure.
try:
with Image.open(io.BytesIO(data)) as img:
img.verify()
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError) as e:
raise HTTPException(400, f"Not a printable image: {e}") from None
return run("print", path=None, data=data, message=message.strip() or None)
return app
def serve(args: argparse.Namespace) -> int:
import uvicorn
token = os.environ.get(TOKEN_ENV, "")
if len(token) < MIN_TOKEN_CHARS:
print(
f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters "
"(e.g. `openssl rand -hex 32`); nginx on the web host sends the same value.",
file=sys.stderr,
)
return 1
host, sep, port = args.listen.rpartition(":")
if not sep or not port.isdigit():
print(f"--listen must be host:port, got {args.listen!r}.", file=sys.stderr)
return 1
# Never run the sudo connect script from a request: the service expects the
# printer link to be configured persistently (see README).
base = argparse.Namespace(**{**vars(args), "no_setup": True})
uvicorn.run(create_app(base, token), 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] {
width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px;
background: var(--bg); color: var(--text); font: inherit;
}
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="Wrapped to 48 columns" required></textarea>
<div class="row">
<label class="muted"><input type="checkbox" id="timestamp"> Date/time header</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};
}
async function checkStatus() {
const pill = $("status");
pill.textContent = "checking…"; pill.className = "pill";
const r = await call("api/status");
pill.textContent = r.ok ? "printer ready" : "printer offline";
pill.className = "pill " + (r.ok ? "ok" : "err");
pill.title = r.text;
}
async function submit(form, path, init) {
const buttons = document.querySelectorAll("button");
buttons.forEach((b) => b.disabled = true);
show("Printing…");
try {
const r = await call(path, init);
show(r.ok ? (r.text || "Printed.") : r.text, r.ok ? "ok" : "err");
return r.ok;
} catch (e) {
show("Request failed: " + e, "err");
return false;
} finally {
buttons.forEach((b) => b.disabled = false);
}
}
$("note-form").addEventListener("submit", async (e) => {
e.preventDefault();
const ok = await submit(e.target, "api/note", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked}),
});
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(e.target, "api/image", {method: "POST", body: data});
});
$("status").addEventListener("click", checkStatus);
checkStatus();
</script>
</body>
</html>
"""
+38
View File
@@ -0,0 +1,38 @@
"""Shared test fakes."""
import argparse
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def make_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": "192.168.192.168",
"port": 9100,
"timestamp": False,
"message": None,
"name": None,
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
+249 -35
View File
@@ -1,6 +1,8 @@
import argparse import argparse
import io
import pytest import pytest
from conftest import FakePrinter, make_args
from PIL import Image from PIL import Image
import receipt import receipt
@@ -17,46 +19,21 @@ class FakeResponse:
def json(self): def json(self):
return self._json return self._json
def __enter__(self):
return self
class FakePrinter: def __exit__(self, *exc):
"""Records escpos calls instead of talking to hardware.""" return False
def __init__(self): def iter_content(self, chunk_size):
self.calls = [] for i in range(0, len(self.content), chunk_size):
yield self.content[i : i + chunk_size]
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def make_catalog(threads): def make_catalog(threads):
return [{"threads": threads}] return [{"threads": threads}]
def make_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": receipt.DEFAULT_PRINTER_IP,
"port": receipt.DEFAULT_PRINTER_PORT,
"timestamp": False,
"message": None,
"name": None,
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
def test_prepare_for_print_resizes_and_dithers(tmp_path): def test_prepare_for_print_resizes_and_dithers(tmp_path):
src = tmp_path / "wide.png" src = tmp_path / "wide.png"
Image.new("RGB", (200, 100), "gray").save(src) Image.new("RGB", (200, 100), "gray").save(src)
@@ -100,7 +77,7 @@ def test_download_saves_image(tmp_path, monkeypatch):
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}]) catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = [] calls = []
def fake_get(url, timeout): def fake_get(url, timeout, stream=False):
calls.append(url) calls.append(url)
if url == receipt.BANT_CATALOG_URL: if url == receipt.BANT_CATALOG_URL:
return FakeResponse(json_data=catalog) return FakeResponse(json_data=catalog)
@@ -123,7 +100,7 @@ def test_download_reuses_cached_image(tmp_path, monkeypatch):
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}]) catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = [] calls = []
def fake_get(url, timeout): def fake_get(url, timeout, stream=False):
calls.append(url) calls.append(url)
return FakeResponse(json_data=catalog) return FakeResponse(json_data=catalog)
@@ -248,5 +225,242 @@ def test_parser_handles_all_subcommands():
args = parser.parse_args(["reprint", "12345"]) args = parser.parse_args(["reprint", "12345"])
assert args.name == "12345" assert args.name == "12345"
for cmd in ("status", "list", "clean", "reprint"): for cmd in ("status", "list", "clean", "reprint", "serve"):
assert parser.parse_args([cmd]).command == cmd assert parser.parse_args([cmd]).command == cmd
args = parser.parse_args(["--no-setup", "serve", "--listen", "127.0.0.1:9000"])
assert args.no_setup and args.listen == "127.0.0.1:9000"
def test_cmd_clean_removes_files_but_not_dirs(tmp_path, monkeypatch, capsys):
img_dir = tmp_path / "img"
legacy = tmp_path / "img_fullwidth"
img_dir.mkdir()
legacy.mkdir()
(img_dir / "1.png").write_bytes(b"x")
(img_dir / "subdir").mkdir() # must not crash the sweep
(legacy / "2.png").write_bytes(b"x")
(legacy / "subdir").mkdir()
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
monkeypatch.setattr(receipt, "LEGACY_FULLWIDTH_DIR", legacy)
assert receipt.cmd_clean(yes=True) == 0
assert list(img_dir.iterdir()) == [img_dir / "subdir"]
assert list(legacy.iterdir()) == [legacy / "subdir"]
def test_cmd_clean_nothing_to_do(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(receipt, "LEGACY_FULLWIDTH_DIR", tmp_path / "legacy")
assert receipt.cmd_clean(yes=True) == 0
def test_cmd_image_continues_past_failures(monkeypatch):
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: None)
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 1 # nothing printed
assert p.calls == []
def test_cmd_image_prints_and_cuts(monkeypatch, tmp_path):
from PIL import Image
img = tmp_path / "1.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 0
kinds = [c[0] for c in p.calls]
assert kinds.count("image") == 2
assert kinds.count("cut") == 2
def test_download_size_cap(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog([{"tim": 7, "ext": ".png"}])
class BigBody(FakeResponse):
def iter_content(self, chunk_size):
yield b"x" * (receipt.MAX_IMAGE_BYTES // 2)
yield b"x" * (receipt.MAX_IMAGE_BYTES + 1) # push over the cap
def fake_get(url, timeout, stream=False):
return BigBody(json_data=catalog) if url == receipt.BANT_CATALOG_URL else BigBody()
monkeypatch.setattr(receipt.requests, "get", fake_get)
assert receipt.download_random_bant_image() is None
assert not (tmp_path / "img" / "7.png").exists()
def test_valid_ip_rejects_metacharacters():
import argparse as ap
with pytest.raises(ap.ArgumentTypeError):
receipt._valid_ip("$(id)")
with pytest.raises(ap.ArgumentTypeError):
receipt._valid_ip("999.1.1.1")
assert receipt._valid_ip(" 10.0.0.5 ") == "10.0.0.5"
def test_wrap_unbreakable_long_token():
token = "x" * 80
wrapped = receipt.wrap_text(token)
assert all(len(line) <= receipt.TEXT_COLUMNS for line in wrapped.split("\n"))
def test_print_image_retries_once_on_failure(monkeypatch, tmp_path):
class Flaky:
def __init__(self, tag):
self.tag = tag
self.calls = []
def image(self, img, **kwargs):
self.calls.append("image")
if self.tag == 1:
raise OSError("dropped")
def close(self):
self.calls.append("close")
def textln(self, t):
self.calls.append(("textln", t))
def cut(self):
self.calls.append("cut")
first = Flaky(1)
second = Flaky(2)
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(receipt, "setup_network", lambda args: None)
args = make_args()
img = tmp_path / "x.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(first, img, args)
assert p is second # caller keeps the live handle
assert "close" in first.calls
assert second.calls == ["image"]
assert args._printer is second # main() closes this one
def test_print_image_retry_skips_setup_with_no_setup(monkeypatch):
class Flaky(FakePrinter):
def image(self, img, **kwargs):
raise OSError("dropped")
second = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(
receipt, "setup_network", lambda args: pytest.fail("should not run the connect script")
)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(Flaky(), "unused", make_args(usb=False, no_setup=True))
assert p is second
def test_cmd_print_from_memory(tmp_path):
buf = io.BytesIO()
Image.new("RGBA", (40, 20), (0, 0, 0, 0)).save(buf, "PNG")
p = FakePrinter()
rc = receipt.cmd_print(p, make_args(path=None, data=buf.getvalue(), message="cap"))
assert rc == 0
assert [c[0] for c in p.calls] == ["textln", "image", "cut"]
assert p.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
assert list(tmp_path.iterdir()) == []
# ---- run_action (shared by the TUI and the web server) ----
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_run_action_note(fake_printer):
rc, output = receipt.run_action("note", make_args(), text="hello", timestamp=False)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2] == ("cut", None)
assert fake_printer.calls[-1] == ("close", None) # handle released after action
def test_run_action_qr(fake_printer):
rc, _ = receipt.run_action("qr", make_args(), content="https://example.com", message=None)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt.run_action("reprint", make_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
rc, output = receipt.run_action("note", make_args(), text="hi", timestamp=False)
assert rc == 1
assert "no printer" in output
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(receipt, "get_printer", lambda args: pytest.fail("should not connect"))
rc, output = receipt.run_action("list", make_args())
assert rc == 0
assert "empty" in output
def test_run_action_no_setup_skips_connect_script(fake_printer, monkeypatch):
def fail(args):
pytest.fail("should not run the connect script")
monkeypatch.setattr(receipt, "setup_network", fail)
monkeypatch.setattr(receipt, "setup_network_quiet", fail)
rc, _ = receipt.run_action(
"note", make_args(usb=False, no_setup=True), text="hi", timestamp=False
)
assert rc == 0
def test_run_action_status_runs_connect_script_once(fake_printer, monkeypatch):
calls = []
monkeypatch.setattr(receipt, "setup_network_quiet", lambda args: calls.append("quiet"))
monkeypatch.setattr(receipt, "setup_network", lambda args: calls.append("loud"))
rc, output = receipt.run_action("status", make_args(usb=False))
assert rc == 0
assert calls == ["quiet"] # captured; cmd_status doesn't rerun it uncaptured
assert "reachable" in output
-86
View File
@@ -1,33 +1,12 @@
import argparse import argparse
import pytest import pytest
from PIL import Image
import receipt import receipt
receipt_tui = pytest.importorskip("receipt_tui") receipt_tui = pytest.importorskip("receipt_tui")
class FakePrinter:
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def make_base_args(**overrides): def make_base_args(**overrides):
defaults = { defaults = {
"usb": True, # avoids the network setup script in tests "usb": True, # avoids the network setup script in tests
@@ -39,70 +18,5 @@ def make_base_args(**overrides):
return argparse.Namespace(**defaults) return argparse.Namespace(**defaults)
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_run_action_note(fake_printer):
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hello", timestamp=False
)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2] == ("cut", None)
assert fake_printer.calls[-1] == ("close", None) # handle released after action
def test_run_action_qr(fake_printer):
rc, _ = receipt_tui.run_action(
"qr", make_base_args(), content="https://example.com", message=None
)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt_tui.run_action("reprint", make_base_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hi", timestamp=False
)
assert rc == 1
assert "no printer" in output
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(
receipt, "get_printer", lambda args: pytest.fail("should not connect")
)
rc, output = receipt_tui.run_action("list", make_base_args())
assert rc == 0
assert "empty" in output
def test_parser_accepts_tui(): def test_parser_accepts_tui():
assert receipt.build_parser().parse_args(["tui"]).command == "tui" assert receipt.build_parser().parse_args(["tui"]).command == "tui"
+147
View File
@@ -0,0 +1,147 @@
import io
import pytest
from conftest import FakePrinter, make_args
from PIL import Image
import receipt
pytest.importorskip("fastapi")
pytest.importorskip("multipart")
from fastapi.testclient import TestClient # noqa: E402
import receipt_web # noqa: E402
TOKEN = "t" * 32
HEADERS = {"X-Receipt-Token": TOKEN, "X-Requested-With": "receipt"}
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
@pytest.fixture
def client():
base = make_args(usb=False, no_setup=True)
return TestClient(receipt_web.create_app(base, TOKEN))
def png_bytes(size=(20, 10)):
buf = io.BytesIO()
Image.new("RGB", size, "gray").save(buf, "PNG")
return buf.getvalue()
def test_healthz_is_open(client):
assert client.get("/healthz").json() == {"ok": True}
@pytest.mark.parametrize("token", [None, "wrong"])
@pytest.mark.parametrize("method,path", [("get", "/"), ("get", "/api/status"),
("post", "/api/note")])
def test_token_required(client, fake_printer, token, method, path):
headers = {"X-Requested-With": "receipt"}
if token:
headers["X-Receipt-Token"] = token
res = client.request(method, path, headers=headers, json={"text": "hi"})
assert res.status_code == 401
assert fake_printer.calls == []
def test_page_served_with_token(client):
res = client.get("/", headers={"X-Receipt-Token": TOKEN})
assert res.status_code == 200
assert "Receipt printer" in res.text
def test_post_needs_page_header(client, fake_printer):
res = client.post("/api/note", headers={"X-Receipt-Token": TOKEN}, json={"text": "hi"})
assert res.status_code == 403
assert fake_printer.calls == []
def test_note_prints(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "timestamp": False})
assert res.status_code == 200
assert res.json()["ok"] is True
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2:] == [("cut", None), ("close", None)]
@pytest.mark.parametrize("text", ["", " ", "x" * (receipt_web.MAX_NOTE_CHARS + 1)])
def test_note_rejects_empty_and_long(client, fake_printer, text):
res = client.post("/api/note", headers=HEADERS, json={"text": text})
assert res.status_code in (400, 422)
assert fake_printer.calls == []
def test_status_reports_reachable(client, fake_printer):
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 200
assert "reachable" in res.json()["output"]
def test_image_prints_from_memory(client, fake_printer):
res = client.post(
"/api/image",
headers=HEADERS,
files={"file": ("x.png", png_bytes(), "image/png")},
data={"message": "caption"},
)
assert res.status_code == 200, res.text
kinds = [c[0] for c in fake_printer.calls]
assert kinds == ["textln", "image", "cut", "close"]
assert fake_printer.calls[0] == ("textln", "caption")
assert fake_printer.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
def test_image_rejects_non_image(client, fake_printer):
res = client.post(
"/api/image", headers=HEADERS, files={"file": ("x.png", b"not an image", "image/png")}
)
assert res.status_code == 400
assert fake_printer.calls == []
def test_image_rejects_oversize(client, fake_printer, monkeypatch):
monkeypatch.setattr(receipt, "MAX_IMAGE_BYTES", 100)
res = client.post(
"/api/image", headers=HEADERS, files={"file": ("x.png", png_bytes((200, 200)), "image/png")}
)
assert res.status_code == 413
assert fake_printer.calls == []
def test_printer_error_is_502(client, monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 502
assert res.json() == {"ok": False, "output": "Error: no printer"}
def test_serve_refuses_without_token(monkeypatch, capsys):
monkeypatch.delenv(receipt_web.TOKEN_ENV, raising=False)
rc = receipt_web.serve(make_args(listen="127.0.0.1:8765"))
assert rc == 1
assert receipt_web.TOKEN_ENV in capsys.readouterr().err