Files
uberbringer/internal/pkg/receipt/render.go
T
57_WolveandClaude Opus 5.5 1335ed0687
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s
Add the notify and ntfy modules and scoped tokens
Breaking: a job with a raw element prints only with a token issued with
uberbringer token --raw. Every other token, every existing one included,
gets 403 token_scope for it, with the raw elements in details, and keeps
every other route.

The notify module prints a notification card from a title, message,
priority and tags, with topic, click, up to three actions, image,
markdown and time as options; it decodes strictly and refuses a payload
over its length caps. The ntfy module takes one ntfy message as ntfy
sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does
not know, cuts text over the caps, and answers 204 for other events and
binary bodies. Both print every message plain: one message cannot tell
the first of a sequence from a replacement, since a publisher may choose
the sequence ID. internal/pkg/ntfy holds ntfy's message types.

Both print the same card. The priority picks the form: a dark URGENT
rule and a double box, a double box headed HIGH, a single box with the
title in its border, or a rule with no box. Tags print as markers in
front of the title, the rest on a Tags row; links print as QR codes with
their labels; attached PNG, JPEG, GIF and WebP images print after the
card. A line-level markdown subset is laid out without a dependency,
keeping marks inside code spans and URLs, and emoji are removed after a
few typed ones become markers. A card that cannot be laid out prints as
a plain receipt, and the server logs the fault once at ERROR and reports
it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the
markers table is a setting with the user's own keys, also settable as
UBERBRINGER_NTFY_MARKERS=name=value,...

uberbringer token --modules issues a token limited to those modules'
print and preview routes, job status and the module list; each route in
the table says which tokens it takes, and a scope claim that could read
as absent makes the token invalid. image elements take optional, which
also shrinks a too-wide image to the paper; a QR code that could be too
wide for the paper prints with smaller modules; box takes title_bold.
Submit takes a Meta whose source shows in job status and, with a copy
of the request ID, in every worker log line of the job.

The four ntfy cards passed on the TM-T88IV, posted as the client recipe
posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md
describes the modules, the card and the client recipe, with tokens read
from a header file; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:57:08 -06:00

511 lines
13 KiB
Go

package receipt
import (
"bytes"
"context"
"fmt"
"image"
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/raster"
)
// unavailableImage is the line printed in place of an optional image that
// failed to load.
const unavailableImage = "[image unavailable]"
// Fetcher downloads remote image data.
type Fetcher interface {
Fetch(ctx context.Context, url string) ([]byte, error)
}
// Options configures a Renderer.
type Options struct {
// Profile describes the printer; its DotsPerLine is the image width.
Profile escpos.Profile
// CodePage is the character table text is transcoded to.
CodePage escpos.CodePage
// Columns, when positive, overrides the Font A characters per line used
// for word wrapping and block widths.
Columns int
// MaxPixels caps decoded image size; MaxHeight caps printed image height
// in dots.
MaxPixels int
MaxHeight int
// MaxLines, when positive, fails a job that would print more lines,
// all copies counted. It is a backstop against runaway text.
MaxLines int
// BoxLineSpacing, when positive, is the line spacing in motion units
// (ESC 3) used while a box prints, to close the gaps in its vertical
// borders. Zero keeps the printer's default spacing.
BoxLineSpacing int
}
// LineLimitError is returned for a job that would print more lines than
// Options.MaxLines allows.
type LineLimitError struct {
Lines, Limit int
}
// Error implements error.
func (e *LineLimitError) Error() string {
return fmt.Sprintf("receipt would print %d lines, limit is %d", e.Lines, e.Limit)
}
// Renderer turns jobs into ESC/POS command streams. It is safe for concurrent
// use.
type Renderer struct {
options Options
fetcher Fetcher
}
// NewRenderer returns a Renderer. fetcher loads images given by URL.
func NewRenderer(options Options, fetcher Fetcher) *Renderer {
if fetcher == nil {
panic("receipt.NewRenderer: fetcher must not be nil")
}
if options.Profile.DotsPerLine <= 0 || options.Profile.FontAWidth <= 0 || options.Profile.FontBWidth <= 0 {
panic("receipt.NewRenderer: profile must be set")
}
if options.MaxPixels <= 0 || options.MaxHeight <= 0 {
panic("receipt.NewRenderer: image limits must be positive")
}
if options.MaxLines < 0 || options.BoxLineSpacing < 0 || options.BoxLineSpacing > escpos.MaxLineSpacing {
panic("receipt.NewRenderer: MaxLines must not be negative and BoxLineSpacing must be 0-255")
}
return &Renderer{options: options, fetcher: fetcher}
}
// Render validates job, loads its images and returns the complete command
// stream. Nothing is returned unless the whole receipt rendered, so a failure
// never reaches the printer half-done.
func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
if err := job.Validate(); err != nil {
return nil, err
}
images, err := r.loadImages(ctx, job)
if err != nil {
return nil, err
}
out, err := r.render(job, images)
if err != nil {
return nil, err
}
return out.stream, nil
}
// rendered is a job's command stream and what Preview needs to read it back.
type rendered struct {
stream []byte
// raw holds the byte range of every raw element in stream.
raw []escpos.Span
// lines is the number of lines the stream prints.
lines int
// unknown counts, by element index, the characters printed as '?'.
unknown map[int]int
}
// render lays out a validated job with its images loaded.
func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, error) {
var body escpos.Builder
p := printer{
b: &body,
lineDots: r.textLineDots(),
profile: r.options.Profile,
codePage: r.options.CodePage,
lineSpacing: r.options.BoxLineSpacing,
}
unknown := make(map[int]int)
for i, el := range job.Elements {
if err := p.element(el, images[i]); err != nil {
return rendered{}, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
}
if p.unknown > 0 {
unknown[i] = p.unknown
p.unknown = 0
}
}
p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
body.Cut(escpos.CutPartial, 0)
}
lines := p.lines * job.copies()
if limit := r.options.MaxLines; limit > 0 && lines > limit {
return rendered{}, &LineLimitError{Lines: lines, Limit: limit}
}
var out escpos.Builder
out.Initialize()
out.SelectCodePage(r.options.CodePage)
var spans []escpos.Span
for range job.copies() {
offset := out.Len()
for _, s := range p.raw {
spans = append(spans, escpos.Span{From: s.From + offset, To: s.To + offset})
}
out.Raw(body.Bytes())
}
return rendered{stream: bytes.Clone(out.Bytes()), raw: spans, lines: lines, unknown: unknown}, nil
}
// textLineDots is the line width used for text layout.
func (r *Renderer) textLineDots() int {
if r.options.Columns > 0 {
return r.options.Columns * r.options.Profile.FontAWidth
}
return r.options.Profile.DotsPerLine
}
// loadImages fetches, decodes and dithers every image before anything is
// rendered, keyed by element index. An optional image that fails to load
// has no entry, and prints as unavailableImage.
func (r *Renderer) loadImages(ctx context.Context, job Job) (map[int]*image.Paletted, error) {
images := make(map[int]*image.Paletted)
for i, el := range job.Elements {
if el.Type != TypeImage {
continue
}
img, err := r.loadImage(ctx, el)
if err != nil && el.Optional {
continue
}
if err != nil {
return nil, fmt.Errorf("elements[%d] (image): %w", i, err)
}
images[i] = img
}
return images, nil
}
func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted, error) {
spec, err := el.imageSpec()
if err != nil {
return nil, err
}
data := spec.data
if spec.url != "" {
if data, err = r.fetcher.Fetch(ctx, spec.url); err != nil {
return nil, err
}
}
src, err := raster.Decode(data, r.options.MaxPixels)
if err != nil {
return nil, err
}
paper := r.options.Profile.DotsPerLine
width := min(src.Bounds().Dx(), paper)
if spec.width > 0 {
if spec.width > paper && !el.Optional {
return nil, fmt.Errorf("width %d is wider than the %d-dot paper", spec.width, paper)
}
// An optional image never fails for its width: it shrinks to the
// paper.
width = min(spec.width, paper)
}
mono, err := raster.Monochrome(src, width)
if err != nil {
return nil, err
}
if h := mono.Bounds().Dy(); h > r.options.MaxHeight {
return nil, fmt.Errorf("image is %d dots tall after scaling, limit is %d", h, r.options.MaxHeight)
}
var x int
switch spec.align {
case escpos.JustifyCenter:
x = (paper - width) / 2
case escpos.JustifyRight:
x = paper - width
}
return raster.Place(mono, paper, x)
}
// printer writes elements to a Builder while tracking the horizontal print
// position, in dots, so inline text can continue and wrap across elements.
type printer struct {
b *escpos.Builder
lineDots int
profile escpos.Profile
codePage escpos.CodePage
lineSpacing int
x int
// lines counts printed lines: text lines, fed lines, and one for each
// QR code, barcode and image.
lines int
// unknown counts the characters of the current element printed as '?'.
unknown int
// raw holds the byte range of each raw element in the Builder.
raw []escpos.Span
}
func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeBox, TypeRule, TypeKV, TypeList:
return p.block(el)
case TypeFeed:
lines, err := el.feedLines()
if err != nil {
return err
}
p.b.Feed(lines)
p.lines += int(lines)
p.x = 0
case TypeQR:
spec, err := el.qrSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.lines++
return p.b.QRCode([]byte(el.Data), p.qrSize(len(el.Data), spec), spec.correction)
case TypeBarcode:
spec, err := el.barcodeSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.b.BarcodeHeight(uint8(spec.height))
if err := p.b.BarcodeWidth(spec.width); err != nil {
return err
}
p.b.BarcodeHRI(spec.hri)
p.lines++
return p.b.Barcode(spec.symbology, el.Data)
case TypeImage:
p.endLine()
if img == nil {
return p.text(Element{Type: TypeText, Text: unavailableImage, Align: el.Align})
}
// Alignment is baked into the image; see Renderer.loadImage.
p.b.Justify(escpos.JustifyLeft)
p.lines++
return p.b.RasterImage(img)
case TypeRaw:
data, err := el.rawBytes()
if err != nil {
return err
}
from := p.b.Len()
p.b.Raw(data)
p.raw = append(p.raw, escpos.Span{From: from, To: p.b.Len()})
// The position after arbitrary bytes is unknown; assume a fresh line.
p.x = 0
case TypeCut:
mode, err := el.cutMode()
if err != nil {
return err
}
p.endLine()
p.b.Cut(mode, 0)
default:
return fmt.Errorf("unknown type %q", el.Type)
}
return nil
}
// qrSize returns the module size of a QR code holding n bytes: the size
// spec asks for, made smaller, down to one dot, while the code could be
// wider than the paper. The width is worked out as if the data were bytes,
// so a code of digits may shrink before it strictly has to.
func (p *printer) qrSize(n int, spec qrSpec) int {
size := spec.size
modules := escpos.QRModules(n, spec.correction)
for modules > 0 && size > escpos.MinQRModuleSize && modules*size > p.profile.DotsPerLine {
size--
}
return size
}
func (p *printer) text(el Element) error {
spec, err := el.textSpec()
if err != nil {
return err
}
glyph := p.profile.GlyphWidth(spec.font) * spec.width
p.b.Justify(spec.align)
p.b.Font(spec.font)
if err := p.b.Size(spec.width, spec.height); err != nil {
return err
}
p.b.Bold(spec.bold)
p.b.Underline(spec.underline)
p.b.Reverse(spec.invert)
text, unknown := normalize(el.Text, p.codePage)
p.unknown += unknown
if spec.wrap {
text = expandTabs(text, p.x/glyph)
lines := wrap(text, (p.lineDots-p.x)/glyph, p.lineDots/glyph)
for i, line := range lines {
if i > 0 {
p.lineFeed()
}
p.b.Text(p.codePage.Encode(line))
p.x += utf8.RuneCountInString(line) * glyph
}
} else {
p.b.Text(p.codePage.Encode(text))
p.lines += strings.Count(text, "\n")
p.advance(text, glyph)
}
if spec.newline {
p.lineFeed()
}
return p.resetStyle()
}
// resetStyle restores plain Font A at scale 1, so styles cannot leak into
// barcodes, QR codes or raw data.
func (p *printer) resetStyle() error {
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
if err := p.b.Size(1, 1); err != nil {
return err
}
p.b.Font(escpos.FontA)
return nil
}
// block lays out a box, rule, kv or list element and prints it line by
// line, each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage}
var (
lines []blockLine
size int
font escpos.Font
box bool
)
switch el.Type {
case TypeBox:
spec, err := el.boxSpec()
if err != nil {
return err
}
size, font, box = spec.size, spec.font, true
lines = lo.box(el, spec, p.blockColumns(font, size))
case TypeRule:
spec, err := el.ruleSpec(false)
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(el, spec, p.blockColumns(font, size))
default:
spec, err := el.kvSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.kv(el, spec, p.blockColumns(font, size))
}
p.unknown += lo.unknown
p.endLine()
spaced := box && p.lineSpacing > 0
if spaced {
p.b.LineSpacing(uint8(p.lineSpacing))
}
p.b.Justify(escpos.JustifyLeft)
p.b.Font(font)
if err := p.b.Size(size, size); err != nil {
return err
}
var current textStyle
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
for _, line := range lines {
for _, r := range line {
if r.text == "" {
continue
}
p.changeStyle(current, r.style)
current = r.style
p.b.Text(p.codePage.Encode(r.text))
}
p.lineFeed()
}
if err := p.resetStyle(); err != nil {
return err
}
if spaced {
p.b.DefaultLineSpacing()
}
return nil
}
// blockColumns is how many characters of font at size fit on a text line.
func (p *printer) blockColumns(font escpos.Font, size int) int {
return max(p.lineDots/(p.profile.GlyphWidth(font)*size), 1)
}
// changeStyle sends the commands that turn style from into style to.
func (p *printer) changeStyle(from, to textStyle) {
if from.bold != to.bold {
p.b.Bold(to.bold)
}
if from.underline != to.underline {
p.b.Underline(to.underline)
}
if from.invert != to.invert {
p.b.Reverse(to.invert)
}
}
// lineFeed ends the current line.
func (p *printer) lineFeed() {
p.b.LineFeed()
p.lines++
p.x = 0
}
// advance updates the position after unwrapped text, which the printer wraps
// by itself when it overflows.
func (p *printer) advance(text string, glyph int) {
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
p.x = 0
text = text[i+1:]
}
p.x += utf8.RuneCountInString(text) * glyph
if p.lineDots > 0 {
p.x %= p.lineDots
}
}
// endLine finishes a partially printed line so the next element starts at
// the left margin.
func (p *printer) endLine() {
if p.x > 0 {
p.lineFeed()
}
}