Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.
- receipt: box, rule and kv elements, laid out when the job renders from
the printer profile, size and font (never fixed widths). Boxes take a
title (inline or capped), a footer, padding, fit and columns, and a
body of text or children (text, feed, kv, and rules as dividers joined
to the borders). Glyphs a code page lacks fall back per set: double-h
and double-v to double, then single, then ascii; a missing junction
switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
checks fields per block type, allows one level of children and counts
them toward the 500-element limit. Block fields on the older types are
problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
trademark), as the owner approved on 2026-11-29. An emoji sequence
prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
command stream back as the printer would print it. It takes the
profile so that it can follow the printer's own wrapping and
alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
too_many_lines on preview; printer.box_line_spacing (default 0).
Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9fdea32b4f
commit
4562f0cebb
109 files changed
+6383
-487
No files matched your search
@@ -64,6 +64,7 @@ func newRootCommand(build BuildInfo) *cobra.Command {
|
||||
newVersionCommand(build),
|
||||
newSecretCommand(),
|
||||
newTokenCommand(&configPath),
|
||||
newPreviewCommand(&configPath),
|
||||
)
|
||||
return root
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
func newPreviewCommand(configPath *string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "preview [file.json|-]",
|
||||
Short: "Shows the lines a job would print, without printing it.",
|
||||
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
|
||||
"lays it out for the printer in the config and writes the lines it would print.\n" +
|
||||
"On a terminal, bold, underlined and inverted text is shown as such. Images are\n" +
|
||||
"not loaded; each shows as a placeholder.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := readJobInput(cmd.InOrStdin(), args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out := cmd.OutOrStdout()
|
||||
return preview(cmd.Context(), cfg, data, out, cmd.ErrOrStderr(), isTerminal(out))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// readJobInput reads the job from the file named in args, or from stdin when
|
||||
// there is none or it is "-".
|
||||
func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
|
||||
if len(args) == 0 || args[0] == "-" {
|
||||
data, err := io.ReadAll(stdin)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the job from standard input: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
data, err := os.ReadFile(args[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the job: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// preview writes the lines the job in data would print on the printer cfg
|
||||
// describes to out, styled when styled is set, and its warnings to errOut.
|
||||
func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut io.Writer, styled bool) error {
|
||||
job, err := receipt.DecodeJob(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("not a valid job: %w", err)
|
||||
}
|
||||
options, err := rendererOptions(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job)
|
||||
var ve *receipt.ValidationError
|
||||
switch {
|
||||
case errors.As(err, &ve):
|
||||
return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n "))
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
if err := writePreview(out, p, styled); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, w := range p.Warnings {
|
||||
if _, err := fmt.Fprintln(errOut, "warning:", w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// noFetch refuses image fetches. A preview loads no images, but a renderer
|
||||
// needs a fetcher.
|
||||
type noFetch struct{}
|
||||
|
||||
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("previews do not fetch images")
|
||||
}
|
||||
|
||||
// writePreview writes the preview's lines. When styled is set, bold,
|
||||
// underlined and inverted runs are shown with terminal attributes through
|
||||
// tml. Only the tags pass through tml's parser, never the printed text, so
|
||||
// a '<' in the text is not read as a tag.
|
||||
func writePreview(w io.Writer, p receipt.Preview, styled bool) error {
|
||||
ew := &errWriter{w: w}
|
||||
styler := tml.NewParser(ew)
|
||||
styler.IncludeLeadingResets = false
|
||||
styler.IncludeTrailingResets = false
|
||||
for _, line := range p.Lines {
|
||||
runes := []rune(line.Text)
|
||||
pos := 0
|
||||
for _, r := range line.Runs {
|
||||
tags := runTags(r)
|
||||
if !styled || tags == "" {
|
||||
continue
|
||||
}
|
||||
ew.write(string(runes[pos:r.From]))
|
||||
ew.check(styler.Parse(strings.NewReader(tags)))
|
||||
ew.write(string(runes[r.From:r.To]))
|
||||
ew.check(styler.Parse(strings.NewReader(strings.ReplaceAll(tags, "<", "</"))))
|
||||
pos = r.To
|
||||
}
|
||||
ew.write(string(runes[pos:]) + "\n")
|
||||
}
|
||||
return ew.err
|
||||
}
|
||||
|
||||
// runTags returns the tml tags for a run's styles.
|
||||
func runTags(r escpos.Run) string {
|
||||
var tags string
|
||||
if r.Bold {
|
||||
tags += "<bold>"
|
||||
}
|
||||
if r.Underline != escpos.UnderlineNone {
|
||||
tags += "<underline>"
|
||||
}
|
||||
if r.Invert {
|
||||
tags += "<reverse>"
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
// errWriter keeps the first write error so that a loop of writes can check
|
||||
// it once.
|
||||
type errWriter struct {
|
||||
w io.Writer
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *errWriter) Write(p []byte) (int, error) {
|
||||
if e.err != nil {
|
||||
return 0, e.err
|
||||
}
|
||||
n, err := e.w.Write(p)
|
||||
e.err = err
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (e *errWriter) write(s string) {
|
||||
_, _ = io.WriteString(e, s) // the error is kept in e.err
|
||||
}
|
||||
|
||||
func (e *errWriter) check(err error) {
|
||||
if e.err == nil {
|
||||
e.err = err
|
||||
}
|
||||
}
|
||||
|
||||
// isTerminal reports whether w is a terminal, which shows text attributes.
|
||||
func isTerminal(w io.Writer) bool {
|
||||
f, ok := w.(*os.File)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
info, err := f.Stat()
|
||||
return err == nil && info.Mode()&os.ModeCharDevice != 0
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
var update = flag.Bool("update", false, "rewrite testdata/*.txt from the current output")
|
||||
|
||||
// writePreviewConfig writes a config for the TM-T88 at the default code page
|
||||
// and returns its path.
|
||||
func writePreviewConfig(t *testing.T, extra string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
body := "[api]\nsecret = \"test-only-secret-test-only-secret-0123\"\n[printer]\naddress = \"192.168.1.245\"\n" + extra
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// TestPreviewCommand compares the command's output for testdata's job with
|
||||
// testdata/preview.txt. Run with -update to rewrite it.
|
||||
func TestPreviewCommand(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{Version: "1.2.3"})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), filepath.Join("testdata", "preview-job.json")})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
golden := filepath.Join("testdata", "preview.txt")
|
||||
if *update {
|
||||
if err := os.WriteFile(golden, out.Bytes(), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want, err := os.ReadFile(golden)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.String() != string(want) {
|
||||
t.Errorf("output:\n%s\nwant:\n%s", out.String(), want)
|
||||
}
|
||||
if got := errOut.String(); got != "warning: elements[4]: 1 character not in cp437 printed as ?\n" {
|
||||
t.Errorf("warnings = %q", got)
|
||||
}
|
||||
if strings.Contains(out.String(), "\x1b[") {
|
||||
t.Error("output that is not a terminal must not be styled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCommandReadsStdin(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetIn(strings.NewReader(`{"elements":[{"type":"rule","text":"stdin","columns":11}]}`))
|
||||
cmd.SetArgs([]string{"preview", "--config", writePreviewConfig(t, ""), "-"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := " ── stdin ──\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
|
||||
t.Errorf("output = %q, want %q", out.String(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCommandUsesTheConfig(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetIn(strings.NewReader(`{"elements":[{"type":"box","text":"x"}]}`))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, "model = \"generic-58mm\"\ncodepage = \"cp1252\"\n")})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lines := strings.Split(out.String(), "\n"); lines[0] != "+"+strings.Repeat("-", 30)+"+" {
|
||||
t.Errorf("first line = %q, want an ascii border 32 columns wide", lines[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCommandErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, job, config, want string
|
||||
}{
|
||||
{"malformed", `{"elements":`, "", "not a valid job"},
|
||||
{"unknown field", `{"elements":[{"type":"rule","colour":"red"}]}`, "", `unknown field "colour"`},
|
||||
{"invalid", `{"elements":[{"type":"box"},{"type":"kv"}]}`, "",
|
||||
"invalid job:\n elements[0] (box): text or children is required\n elements[1] (kv): pairs: at least one pair is required"},
|
||||
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 20 lines, limit is 10"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetIn(strings.NewReader(tt.job))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, tt.config)})
|
||||
err := cmd.Execute()
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("err = %v, want it to contain %q", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritePreviewStyled(t *testing.T) {
|
||||
p := receipt.Preview{Lines: []escpos.PreviewLine{
|
||||
{Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{
|
||||
{From: 2, To: 5, Bold: true, Invert: true, W: 1, H: 1},
|
||||
}},
|
||||
{Kind: escpos.LineText, Text: "font b only", Runs: []escpos.Run{{From: 0, To: 11, Font: escpos.FontB, W: 1, H: 1}}},
|
||||
{Kind: escpos.LineText, Text: "under", Runs: []escpos.Run{{From: 0, To: 5, Underline: escpos.UnderlineThick, W: 1, H: 1}}},
|
||||
}}
|
||||
var out bytes.Buffer
|
||||
if err := writePreview(&out, p, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"a \x1b[1m", "<b>", "\x1b[7m", "\x1b[0m c\n", "font b only\n", "\x1b[4munder"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("output %q lacks %q", got, want)
|
||||
}
|
||||
}
|
||||
out.Reset()
|
||||
if err := writePreview(&out, p, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := "a <b> c\nfont b only\nunder\n"; out.String() != want {
|
||||
t.Errorf("plain output = %q, want %q", out.String(), want)
|
||||
}
|
||||
}
|
||||
@@ -50,17 +50,11 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
logger := newLogger(cfg.Log, os.Stderr)
|
||||
printBanner(out, build)
|
||||
|
||||
profile, err := escpos.LookupProfile(cfg.Printer.Model)
|
||||
options, err := rendererOptions(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config printer.model: %w", err)
|
||||
}
|
||||
if cfg.Printer.PaperWidth > 0 {
|
||||
profile.DotsPerLine = cfg.Printer.PaperWidth
|
||||
}
|
||||
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config printer.codepage: %w", err)
|
||||
return err
|
||||
}
|
||||
profile, codePage := options.Profile, options.CodePage
|
||||
|
||||
flushSentry, err := initSentry(cfg.Sentry, build, logger)
|
||||
if err != nil {
|
||||
@@ -74,13 +68,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
AllowPrivate: cfg.Images.AllowPrivateNetworks,
|
||||
AllowedHosts: cfg.Images.AllowedHosts,
|
||||
})
|
||||
renderer := receipt.NewRenderer(receipt.Options{
|
||||
Profile: profile,
|
||||
CodePage: codePage,
|
||||
Columns: cfg.Printer.Columns,
|
||||
MaxPixels: cfg.Images.MaxPixels,
|
||||
MaxHeight: cfg.Images.MaxHeight,
|
||||
}, fetcher)
|
||||
renderer := receipt.NewRenderer(options, fetcher)
|
||||
printerClient := printer.NewClient(
|
||||
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
|
||||
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
|
||||
@@ -109,7 +97,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
WriteTimeout: cfg.WebServer.WriteTimeout,
|
||||
IdleTimeout: cfg.WebServer.IdleTimeout,
|
||||
RequestID: newRequestID,
|
||||
}, queue, printerClient, logger)
|
||||
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
ln, err := listen(ctx, addr)
|
||||
@@ -131,6 +119,31 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
return err
|
||||
}
|
||||
|
||||
// rendererOptions returns the receipt layout cfg describes: the printer
|
||||
// profile, with any paper width override, the code page and the limits.
|
||||
func rendererOptions(cfg *config.Config) (receipt.Options, error) {
|
||||
profile, err := escpos.LookupProfile(cfg.Printer.Model)
|
||||
if err != nil {
|
||||
return receipt.Options{}, fmt.Errorf("config printer.model: %w", err)
|
||||
}
|
||||
if cfg.Printer.PaperWidth > 0 {
|
||||
profile.DotsPerLine = cfg.Printer.PaperWidth
|
||||
}
|
||||
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
|
||||
if err != nil {
|
||||
return receipt.Options{}, fmt.Errorf("config printer.codepage: %w", err)
|
||||
}
|
||||
return receipt.Options{
|
||||
Profile: profile,
|
||||
CodePage: codePage,
|
||||
Columns: cfg.Printer.Columns,
|
||||
MaxPixels: cfg.Images.MaxPixels,
|
||||
MaxHeight: cfg.Images.MaxHeight,
|
||||
MaxLines: cfg.Format.MaxLines,
|
||||
BoxLineSpacing: cfg.Printer.BoxLineSpacing,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// newLogger builds the structured logger described by cfg.
|
||||
func newLogger(cfg config.LogConfig, w io.Writer) *slog.Logger {
|
||||
var level slog.Level
|
||||
|
||||
@@ -33,6 +33,7 @@ var (
|
||||
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
|
||||
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
|
||||
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
|
||||
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
|
||||
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
|
||||
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
|
||||
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -38,17 +36,10 @@ func handleRobots(c fiber.Ctx) error {
|
||||
|
||||
// handlePrint validates and queues a job.
|
||||
func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
job, err := decodeJob(c.Body())
|
||||
job, err := decodeValidJob(c.Body())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := job.Validate(); err != nil {
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
return newAPIError(codeInvalidJob, ve.Problems...)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
status, err := s.jobs.Submit(job)
|
||||
switch {
|
||||
@@ -64,26 +55,53 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusAccepted).JSON(status)
|
||||
}
|
||||
|
||||
// decodeValidJob strictly decodes and validates a job body, answering
|
||||
// invalid_job with every problem.
|
||||
func decodeValidJob(body []byte) (receipt.Job, error) {
|
||||
job, err := decodeJob(body)
|
||||
if err != nil {
|
||||
return job, err
|
||||
}
|
||||
if err := job.Validate(); err != nil {
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
return job, newAPIError(codeInvalidJob, ve.Problems...)
|
||||
}
|
||||
return job, err
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
// decodeJob strictly decodes a job body. Unknown fields are rejected so that
|
||||
// typos fail loudly. An unknown "data" field gets a message that points to
|
||||
// "elements" and the README instead of the decoder's text.
|
||||
// typos fail loudly. A body with a top-level "data" key gets a message that
|
||||
// points to "elements" and the README instead of the decoder's text.
|
||||
func decodeJob(body []byte) (receipt.Job, error) {
|
||||
var job receipt.Job
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&job); err != nil {
|
||||
job, err := receipt.DecodeJob(body)
|
||||
switch {
|
||||
case errors.Is(err, receipt.ErrTrailingData):
|
||||
return job, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
|
||||
case err != nil:
|
||||
msg := "request body is not a valid job: " + err.Error()
|
||||
if strings.Contains(err.Error(), `unknown field "data"`) {
|
||||
if strings.Contains(err.Error(), `unknown field "data"`) && hasTopLevelData(body) {
|
||||
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
|
||||
}
|
||||
return job, newAPIError(codeInvalidJob.withMessage(msg))
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return job, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
// hasTopLevelData reports whether body is a JSON object with a "data" key.
|
||||
// Only that key earns the hint about "elements"; a "data" field refused
|
||||
// deeper down, say in a kv pair, is an ordinary typo.
|
||||
func hasTopLevelData(body []byte) bool {
|
||||
var top map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &top); err != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := top["data"]
|
||||
return ok
|
||||
}
|
||||
|
||||
// handleJob returns the status of one job.
|
||||
func (s *Server) handleJob(c fiber.Ctx) error {
|
||||
// Clone: fasthttp reuses the buffer behind route params.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// handlePreview answers with the lines a job would print, without printing
|
||||
// it: plain text by default, or JSON with styles when the client accepts
|
||||
// application/json.
|
||||
func (s *Server) handlePreview(c fiber.Ctx) error {
|
||||
job, err := decodeValidJob(c.Body())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
preview, err := s.previewer.Preview(c.Context(), job)
|
||||
var limit *receipt.LineLimitError
|
||||
switch {
|
||||
case errors.As(err, &limit):
|
||||
return newAPIError(codeTooManyLines.withMessage(limit.Error()))
|
||||
case err != nil:
|
||||
return fmt.Errorf("previewing job: %w", err)
|
||||
}
|
||||
if c.Accepts(fiber.MIMETextPlain, fiber.MIMEApplicationJSON) == fiber.MIMEApplicationJSON {
|
||||
return c.JSON(newPreviewResponse(preview))
|
||||
}
|
||||
var text strings.Builder
|
||||
for _, line := range preview.Lines {
|
||||
text.WriteString(line.Text)
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
|
||||
return c.SendString(text.String())
|
||||
}
|
||||
|
||||
// previewResponse is the JSON form of a preview.
|
||||
type previewResponse struct {
|
||||
Columns int `json:"columns"`
|
||||
CodePage string `json:"codepage"`
|
||||
LineCount int `json:"line_count"`
|
||||
Lines []previewLine `json:"lines"`
|
||||
Warnings []string `json:"warnings"`
|
||||
}
|
||||
|
||||
type previewLine struct {
|
||||
Kind string `json:"kind"`
|
||||
Text string `json:"text"`
|
||||
Runs []previewRun `json:"runs,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// previewRun is a styled range of a line's text, in characters [from, to).
|
||||
// Width and height are omitted at scale 1, font when it is a.
|
||||
type previewRun struct {
|
||||
From int `json:"from"`
|
||||
To int `json:"to"`
|
||||
Bold bool `json:"bold,omitempty"`
|
||||
Underline int `json:"underline,omitempty"`
|
||||
Invert bool `json:"invert,omitempty"`
|
||||
Font string `json:"font,omitempty"`
|
||||
Width int `json:"width,omitempty"`
|
||||
Height int `json:"height,omitempty"`
|
||||
}
|
||||
|
||||
func newPreviewResponse(p receipt.Preview) previewResponse {
|
||||
resp := previewResponse{
|
||||
Columns: p.Columns,
|
||||
CodePage: p.CodePage.String(),
|
||||
LineCount: p.LineCount,
|
||||
Lines: make([]previewLine, len(p.Lines)),
|
||||
Warnings: append([]string{}, p.Warnings...),
|
||||
}
|
||||
scale := func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
for i, l := range p.Lines {
|
||||
line := previewLine{Kind: l.Kind, Text: l.Text, Data: l.Data}
|
||||
for _, r := range l.Runs {
|
||||
run := previewRun{
|
||||
From: r.From, To: r.To, Bold: r.Bold, Underline: int(r.Underline), Invert: r.Invert,
|
||||
Width: scale(r.W), Height: scale(r.H),
|
||||
}
|
||||
if r.Font == escpos.FontB {
|
||||
run.Font = "b"
|
||||
}
|
||||
line.Runs = append(line.Runs, run)
|
||||
}
|
||||
resp.Lines[i] = line
|
||||
}
|
||||
return resp
|
||||
}
|
||||
@@ -36,6 +36,18 @@ type Printer interface {
|
||||
Status(ctx context.Context) (escpos.Status, error)
|
||||
}
|
||||
|
||||
// Previewer renders a job as the lines it would print, without printing it.
|
||||
type Previewer interface {
|
||||
Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error)
|
||||
}
|
||||
|
||||
// Deps are the services the handlers use.
|
||||
type Deps struct {
|
||||
Jobs Jobs
|
||||
Printer Printer
|
||||
Previewer Previewer
|
||||
}
|
||||
|
||||
// Info describes the running build for the index route.
|
||||
type Info struct {
|
||||
Project string
|
||||
@@ -79,18 +91,19 @@ const defaultHealthRecheckDelay = 750 * time.Millisecond
|
||||
|
||||
// Server is the HTTP API.
|
||||
type Server struct {
|
||||
app *fiber.App
|
||||
config Config
|
||||
jobs Jobs
|
||||
printer Printer
|
||||
logger *slog.Logger
|
||||
app *fiber.App
|
||||
config Config
|
||||
jobs Jobs
|
||||
printer Printer
|
||||
previewer Previewer
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// New builds the server and its routes.
|
||||
func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server {
|
||||
func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
||||
switch {
|
||||
case jobs == nil || printer == nil || logger == nil:
|
||||
panic("server.New: jobs, printer and logger must not be nil")
|
||||
case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil:
|
||||
panic("server.New: jobs, printer, previewer and logger must not be nil")
|
||||
case len(config.Secret) == 0:
|
||||
panic("server.New: secret must not be empty")
|
||||
case config.RequestID == nil:
|
||||
@@ -99,7 +112,7 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
|
||||
if config.HealthRecheckDelay <= 0 {
|
||||
config.HealthRecheckDelay = defaultHealthRecheckDelay
|
||||
}
|
||||
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
|
||||
s := &Server{config: config, jobs: deps.Jobs, printer: deps.Printer, previewer: deps.Previewer, logger: logger}
|
||||
|
||||
s.app = fiber.New(fiber.Config{
|
||||
AppName: config.Info.Project,
|
||||
@@ -142,6 +155,7 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
|
||||
requireBearerToken(config.Secret),
|
||||
)
|
||||
api.Post("/print", s.handlePrint)
|
||||
api.Post("/preview", s.handlePreview)
|
||||
api.Get("/jobs/:id", s.handleJob)
|
||||
|
||||
return s
|
||||
|
||||
@@ -135,7 +135,26 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
return New(cfg, jobs, p, logger)
|
||||
return New(cfg, Deps{Jobs: jobs, Printer: p, Previewer: testRenderer(2000)}, logger)
|
||||
}
|
||||
|
||||
// testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to
|
||||
// maxLines lines.
|
||||
func testRenderer(maxLines int) *receipt.Renderer {
|
||||
return receipt.NewRenderer(receipt.Options{
|
||||
Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9},
|
||||
CodePage: escpos.CodePage437,
|
||||
MaxPixels: 1000,
|
||||
MaxHeight: 1000,
|
||||
MaxLines: maxLines,
|
||||
}, refuseFetch{})
|
||||
}
|
||||
|
||||
// refuseFetch fails every image fetch; previews never fetch.
|
||||
type refuseFetch struct{}
|
||||
|
||||
func (refuseFetch) Fetch(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("previews must not fetch images")
|
||||
}
|
||||
|
||||
// logBuffer collects the server's JSON log lines.
|
||||
@@ -408,6 +427,121 @@ func TestPrintValidationDetails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintOldFormatHintOnlyForTopLevelData(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
body := `{"elements":[{"type":"kv","pairs":[{"key":"a","data":"x"}]}]}`
|
||||
resp, raw := send(t, s, printRequest(t, body, "Bearer "+validToken(t)))
|
||||
e := expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
|
||||
if !strings.Contains(e.Error, `unknown field "data"`) || strings.Contains(e.Error, "replaced") {
|
||||
t.Errorf("error = %q, want the decoder's message", e.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func previewRequest(t *testing.T, body, accept string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/preview", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
if accept != "" {
|
||||
req.Header.Set("Accept", accept)
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
const boxJob = `{"elements":[{"type":"box","style":"double","title":"ACHTUNG","title_style":"capped","align":"center",` +
|
||||
`"text":"The coffee machine is being descaled.\nDo not use until 10:30."},` +
|
||||
`{"type":"text","text":"Bold ✓","bold":true}]}`
|
||||
|
||||
func TestPreviewText(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
for _, accept := range []string{"", "*/*", "text/plain", "text/html"} {
|
||||
resp, body := send(t, s, previewRequest(t, boxJob, accept))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("Accept %q: status = %d (%s)", accept, resp.StatusCode, body)
|
||||
}
|
||||
if ct := resp.Header.Get(fiber.HeaderContentType); ct != fiber.MIMETextPlainCharsetUTF8 {
|
||||
t.Errorf("Accept %q: Content-Type = %q", accept, ct)
|
||||
}
|
||||
want := "╔═╡ ACHTUNG ╞════════════════════════════╗\n" +
|
||||
"║ The coffee machine is being descaled. ║\n" +
|
||||
"║ Do not use until 10:30. ║\n" +
|
||||
"╚════════════════════════════════════════╝\n" +
|
||||
"Bold √\n" +
|
||||
" - - - - - - - partial cut - - - - - - - -\n"
|
||||
if string(body) != want {
|
||||
t.Errorf("Accept %q: body =\n%s\nwant\n%s", accept, body, want)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a preview was queued for printing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewJSON(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
job := `{"elements":[{"type":"text","text":"Hi 🎉","bold":true,"size":2,"font":"b"},{"type":"qr","data":"https://example.com"}]}`
|
||||
resp, body := send(t, s, previewRequest(t, job, "application/json"))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := `{"columns":42,"codepage":"cp437","line_count":2,"lines":[` +
|
||||
`{"kind":"text","text":"Hi ?","runs":[{"from":0,"to":4,"bold":true,"font":"b","width":2,"height":2}]},` +
|
||||
`{"kind":"qr","text":"[qr: https://example.com]","data":"https://example.com"},` +
|
||||
`{"kind":"cut","text":" - - - - - - - partial cut - - - - - - - -","data":"partial"}],` +
|
||||
`"warnings":["elements[0]: 1 character not in cp437 printed as ?"]}`
|
||||
if string(body) != want {
|
||||
t.Errorf("body =\n%s\nwant\n%s", body, want)
|
||||
}
|
||||
|
||||
resp, body = send(t, s, previewRequest(t, validJob, "application/json"))
|
||||
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), `"warnings":[]`) {
|
||||
t.Errorf("status %d, body %s; want an empty warnings list", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewRefusals(t *testing.T) {
|
||||
t.Run("invalid job", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
resp, raw := send(t, s, previewRequest(t, `{"elements":[{"type":"box","text":"x","children":[{"type":"qr","data":"x"}]}]}`, ""))
|
||||
e := expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
|
||||
want := []string{
|
||||
"elements[0] (box): set text or children, not both",
|
||||
"elements[0].children[0] (qr): not allowed inside a box; place it after the box",
|
||||
}
|
||||
if strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
|
||||
t.Errorf("details = %q, want %q", e.Details, want)
|
||||
}
|
||||
})
|
||||
t.Run("malformed body", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
resp, raw := send(t, s, previewRequest(t, `{"elements":[{"type":"rule","colour":"red"}]}`, ""))
|
||||
expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
|
||||
})
|
||||
t.Run("no token", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
req := previewRequest(t, validJob, "")
|
||||
req.Header.Del("Authorization")
|
||||
resp, raw := send(t, s, req)
|
||||
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
|
||||
})
|
||||
t.Run("too many lines", func(t *testing.T) {
|
||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
s.previewer = testRenderer(10)
|
||||
resp, raw := send(t, s, previewRequest(t, `{"copies":2,"elements":[{"type":"feed","lines":6}]}`, "application/json"))
|
||||
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
|
||||
if e.Error != "receipt would print 12 lines, limit is 10" {
|
||||
t.Errorf("error = %q", e.Error)
|
||||
}
|
||||
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
|
||||
t.Errorf("a refusal was logged as a failure: %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPrintQueueRefusals(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -575,6 +709,7 @@ func TestRoutesConform(t *testing.T) {
|
||||
// Each authenticated route maps to a path that reaches it.
|
||||
authenticated := map[string]string{
|
||||
"POST /api/v1/print": "/api/v1/print",
|
||||
"POST /api/v1/preview": "/api/v1/preview",
|
||||
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{"elements": [
|
||||
{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center",
|
||||
"text": "The coffee machine is being descaled.\nDo not use until 10:30."},
|
||||
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
|
||||
{"type": "rule", "style": "dark", "text": "URGENT", "bold": true},
|
||||
{"type": "kv", "pairs": [{"key": "Used", "value": "94%", "bold": true}]},
|
||||
{"type": "text", "text": "Inverted <b>not a tag</b> 🎉", "invert": true},
|
||||
{"type": "image", "url": "https://images.example/logo.png", "width": 384, "align": "center"},
|
||||
{"type": "qr", "data": "https://example.com"}
|
||||
]}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
╔═╡ ACHTUNG ╞════════════════════════════╗
|
||||
║ The coffee machine is being descaled. ║
|
||||
║ Do not use until 10:30. ║
|
||||
╚════════════════════════════════════════╝
|
||||
┌─────────────────────┐
|
||||
│ !!! ACHTUNG !!! │
|
||||
└─────────────────────┘
|
||||
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
|
||||
Used ................................. 94%
|
||||
Inverted <b>not a tag</b> ?
|
||||
[image 384 dots: logo.png]
|
||||
[qr: https://example.com]
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
Reference in new issue
Block a user