Add the notify and ntfy modules and scoped tokens
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s

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>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 13:57:08 -06:00
1 parent fa15cb27b1
commit 1335ed0687
119 files changed
+5626 -468

No files matched your search

+412
View File
@@ -0,0 +1,412 @@
package modules
import (
"errors"
"fmt"
"runtime/debug"
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/receipt"
)
// Card styles and QR modes of CardOptions.
const (
StyleAuto = "auto"
StyleBox = "box"
StyleCompact = "compact"
QRAll = "all"
QRFirst = "first"
QRNone = "none"
)
// Card layout.
const (
// DefaultCardLines is how many lines of a message a card prints when
// CardOptions.MaxLines is 0.
DefaultCardLines = 40
// maxLinks is how many links a card prints.
maxLinks = 3
// maxQRLink is the longest link, in bytes, printed as a QR code; a
// longer one prints as text. At correction M it is QR version 17, 85
// modules, which the renderer narrows to fit the paper.
maxQRLink = 500
// qrSize and qrCorrection are the module size and error correction of
// a link's QR code.
qrSize = 5
qrCorrection = "M"
// imageWidth is the width, in dots, an attached image prints at; the
// renderer shrinks it to a narrower paper.
imageWidth = 384
)
// CardOptions shapes the cards of notifications. The zero value is the
// default.
type CardOptions struct {
// Style is auto, box or compact. auto chooses the form from the
// priority: urgent and high get double boxes, default a single box,
// and low and min a rule with no box. box and compact force those forms
// for every priority. "" means auto.
Style string
// MaxLines is how many lines of the message print, as written, before
// "... N more lines". 0 means DefaultCardLines.
MaxLines int
// QR is all, to print every link as a QR code, first, for only the
// first, or none. "" means all.
QR string
// NoImages prints attached images as file rows.
NoImages bool
// NoMarkdown prints a markdown message as written.
NoMarkdown bool
// Markers are the tag markers; nil means the built-in ones.
Markers Markers
}
// FallbackError reports that a card could not be laid out, and that the
// plain fallback receipt was built in its place. The job returned with it
// still prints. Its message never quotes the notification.
type FallbackError struct {
// Cause says what went wrong.
Cause string
// Stack is the stack of the panic that stopped the layout, if one did.
Stack string
}
// Error implements error.
func (e *FallbackError) Error() string {
return "the card fell back to the plain receipt: " + e.Cause
}
// form is the layout of a card.
type form int
const (
formUrgent form = iota
formHigh
formNormal
formCompact
)
// formFor returns the layout of a card of priority under style.
func formFor(priority int, style string) form {
switch {
case strings.EqualFold(style, StyleCompact):
return formCompact
case priority == maxPriority:
return formUrgent
case priority == highPriority:
return formHigh
case priority == defaultPriority || strings.EqualFold(style, StyleBox):
return formNormal
}
return formCompact
}
// cardFault runs at the start of building a card. Tests set it to make
// the build fail.
var cardFault = func() {}
// Card lays out n as a receipt. The priority picks the form: a dark rule
// "URGENT" and a double box for 5, a double box headed "HIGH" for 4, a
// single box with the title in its border for 3, and a rule with the topic
// and time over the title and message for 1 and 2. Tag markers go in front
// of the title, the other tags on a row of their own, and the topic and
// time in the bottom border. Links print as QR codes after the box, then
// the attached image. Text longer than the notice limits is cut.
//
// The job always prints: if laying out the card goes wrong, Card returns
// the plain fallback receipt with a *FallbackError, so that the caller can
// report the fault.
func Card(n Notice, o CardOptions, env Env) (job receipt.Job, err error) {
defer func() {
if r := recover(); r != nil {
job = fallback(n, env)
err = &FallbackError{Cause: fmt.Sprintf("panic: %v", r), Stack: string(debug.Stack())}
}
}()
job = card(n, o, env)
if verr := job.Validate(); verr != nil {
problems := 1
var ve *receipt.ValidationError
if errors.As(verr, &ve) {
problems = len(ve.Problems)
}
return fallback(n, env), &FallbackError{Cause: fmt.Sprintf("the card failed validation with %d problems", problems)}
}
return job, nil
}
// card is Card without the fallback.
func card(n Notice, o CardOptions, env Env) receipt.Job {
cardFault()
markers := o.Markers
if markers == nil {
markers = NewMarkers(nil)
}
priority := n.priority()
f := formFor(priority, o.Style)
titleMarkers, tagText := markers.sortTags(n.Tags)
head := strings.Join(append(titleMarkers, noticeTitle(n, markers.clean)), " ")
if n.Updated {
head += " (updated)"
}
stamp := env.Format(n.Time)
if topic := cut(strings.TrimSpace(markers.clean(n.Topic)), MaxTopic); topic != "" {
stamp = topic + " · " + stamp
}
body, links := cardBody(n, o, markers)
var extra []receipt.Element
if len(tagText) > 0 {
extra = append(extra, receipt.Element{Type: receipt.TypeText, Text: "Tags: " + strings.Join(tagText, ", ")})
}
image, file := cardAttachment(n, o, env)
if file = strings.TrimSpace(markers.clean(file)); file != "" {
extra = append(extra, receipt.Element{Type: receipt.TypeKV, Pairs: []receipt.Pair{{Key: "File", Value: file}}})
}
content := body
if len(extra) > 0 {
if len(content) > 0 {
content = append(content, receipt.Element{Type: receipt.TypeFeed})
}
content = append(content, extra...)
}
var elements []receipt.Element
switch f {
case formUrgent:
children := []receipt.Element{{Type: receipt.TypeText, Text: head, Bold: true, Invert: true}}
if len(content) > 0 {
children = append(children, receipt.Element{Type: receipt.TypeRule, Style: "double"})
children = append(children, content...)
}
elements = []receipt.Element{
{Type: receipt.TypeRule, Style: "dark", Text: "URGENT", Bold: true},
{Type: receipt.TypeBox, Style: "double", Footer: stamp, Children: children},
{Type: receipt.TypeRule, Style: "dark"},
}
case formHigh:
children := []receipt.Element{{Type: receipt.TypeText, Text: head, Bold: true}}
if len(content) > 0 {
children = append(children, receipt.Element{Type: receipt.TypeRule})
children = append(children, content...)
}
elements = []receipt.Element{
{Type: receipt.TypeBox, Style: "double", Title: "HIGH", TitleBold: true, Footer: stamp, Children: children},
}
case formNormal:
if len(content) == 0 {
content = []receipt.Element{{Type: receipt.TypeText}}
}
elements = []receipt.Element{
{Type: receipt.TypeBox, Title: head, TitleBold: true, Footer: stamp, Children: content},
}
default:
switch priority {
case maxPriority:
stamp = "URGENT · " + stamp
case highPriority:
stamp = "HIGH · " + stamp
}
elements = append([]receipt.Element{
{Type: receipt.TypeRule, Text: stamp, Align: "left"},
{Type: receipt.TypeText, Text: head, Bold: true},
}, content...)
}
elements = append(elements, linkElements(mergeLinks(n.Links, links), o, markers)...)
if image != "" {
elements = append(elements,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeImage, URL: image, Width: imageWidth, Align: "center", Optional: true})
}
return receipt.Job{Elements: elements}
}
// noticeTitle is n's title as clean leaves it, or else its topic, or else
// "Notification", cut to MaxTitle.
func noticeTitle(n Notice, clean func(string) string) string {
for _, s := range []string{n.Title, n.Topic} {
if s = strings.TrimSpace(clean(s)); s != "" {
return cut(s, MaxTitle)
}
}
return "Notification"
}
// cut returns s, or its first limit characters with "..." in place of the
// last three when it is longer.
func cut(s string, limit int) string {
if utf8.RuneCountInString(s) <= limit {
return s
}
r := []rune(s)
return string(r[:max(limit-3, 0)]) + "..."
}
// cutBytes returns s, or its first bytes up to limit, ending on a whole
// character, with "..." in place of the rest when it is longer.
func cutBytes(s string, limit int) string {
if len(s) <= limit {
return s
}
end := max(limit-3, 0)
for end > 0 && !utf8.RuneStart(s[end]) {
end--
}
return s[:end] + "..."
}
// cardBody lays out n's message, its first lines up to the limit, as
// markdown when it is written in it, and returns the links it names.
func cardBody(n Notice, o CardOptions, markers Markers) ([]receipt.Element, []Link) {
text, more := capLines(markers.clean(cutBytes(n.Message, MaxMessage)), o.MaxLines)
var (
body []receipt.Element
links []Link
)
switch {
case strings.TrimSpace(text) == "":
case n.Markdown && !o.NoMarkdown:
body, links = markdownBody(text)
default:
body = []receipt.Element{{Type: receipt.TypeText, Text: text}}
}
if more > 0 {
noun := "lines"
if more == 1 {
noun = "line"
}
body = append(body, receipt.Element{Type: receipt.TypeText, Text: fmt.Sprintf("... %d more %s", more, noun)})
}
return body, links
}
// capLines returns the first limit lines of text, without the empty lines
// at its end, and how many lines it left out. A limit of 0 means
// DefaultCardLines.
func capLines(text string, limit int) (string, int) {
if limit <= 0 {
limit = DefaultCardLines
}
text = strings.ReplaceAll(text, "\r\n", "\n")
lines := strings.Split(strings.TrimRight(text, " \t\n"), "\n")
if len(lines) <= limit {
return strings.Join(lines, "\n"), 0
}
return strings.Join(lines[:limit], "\n"), len(lines) - limit
}
// cardAttachment returns the URL of the image the card prints, if any,
// and the text of its file row, if any.
func cardAttachment(n Notice, o CardOptions, env Env) (image, file string) {
if n.Image != "" && len(n.Image) <= MaxURL {
if o.NoImages {
file = cut(fileName(n.Image), MaxFileName)
} else {
image = n.Image
}
}
if f := n.File; f != nil {
if !o.NoImages && image == "" && webURL(f.URL) && len(f.URL) <= MaxURL && f.printableImage() && !f.expired(env.Now) {
return f.URL, file
}
name := strings.TrimSpace(f.Name)
if name == "" {
name = fileName(f.URL)
}
name = cut(name, MaxFileName)
if f.Size > 0 {
name += " (" + fileSize(f.Size) + ")"
}
file = name
}
return image, file
}
// fileSize is n bytes in B, KB or MB, as 980 B, 33 KB or 1.4 MB.
func fileSize(n int64) string {
const kb, mb = 1024, 1024 * 1024
switch {
case n < kb:
return fmt.Sprintf("%d B", n)
case n < mb:
return fmt.Sprintf("%d KB", (n+kb/2)/kb)
}
return fmt.Sprintf("%.1f MB", float64(n)/mb)
}
// mergeLinks returns the http and https links of first, then of more, with
// each URL once, at most maxLinks. A URL given twice keeps the first label
// it was given. A URL longer than MaxURL is left out.
func mergeLinks(first, more []Link) []Link {
var links []Link
index := make(map[string]int)
for _, l := range append(append([]Link(nil), first...), more...) {
if !webURL(l.URL) || len(l.URL) > MaxURL {
continue
}
if i, ok := index[l.URL]; ok {
if links[i].Label == "" {
links[i].Label = l.Label
}
continue
}
if len(links) == maxLinks {
continue
}
index[l.URL] = len(links)
links = append(links, l)
}
return links
}
// linkElements prints links after the card: each as a centred QR code with
// its label, or host and path, below it in the small font, or as a line
// "» label" and the URL, as o.QR chooses.
func linkElements(links []Link, o CardOptions, markers Markers) []receipt.Element {
var elements []receipt.Element
// Each QR code has an empty line before it; a run of text links has
// one before the first.
textRun := false
for i, l := range links {
label := cut(strings.TrimSpace(markers.clean(l.Label)), MaxLabel)
qr := len(l.URL) <= maxQRLink &&
(o.QR == "" || strings.EqualFold(o.QR, QRAll) || (strings.EqualFold(o.QR, QRFirst) && i == 0))
if !qr {
if !textRun {
elements = append(elements, receipt.Element{Type: receipt.TypeFeed})
textRun = true
}
if label == "" {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: "» " + l.URL})
continue
}
elements = append(elements,
receipt.Element{Type: receipt.TypeText, Text: "» " + label},
receipt.Element{Type: receipt.TypeText, Text: l.URL})
continue
}
if label == "" {
label = shortURL(l.URL)
}
textRun = false
elements = append(elements,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeQR, Data: l.URL, Size: qrSize, Correction: qrCorrection, Align: "center"},
receipt.Element{Type: receipt.TypeText, Text: label, Font: "b", Align: "center"})
}
return elements
}
+803
View File
@@ -0,0 +1,803 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the
// jobs whose printed result was checked on the TM-T88IV, and whose bytes
// the receipt package pins: the four messages in testdata/paper, built on
// a host at UTC-6 with the default card options.
func TestNtfyBuildsThePaperJobs(t *testing.T) {
for _, name := range []string{"high", "urgent", "default", "min"} {
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
env := modules.Env{
Now: time.Unix(1796063393, 0),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
job, err := modules.Ntfy().Build(context.Background(), body, env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the module builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
})
}
}
// ntfyEnv is the time the example ntfy messages were sent, 29 Nov 2025
// 21:04:05 UTC, in Europe/London, which is on GMT then.
func ntfyEnv(t *testing.T) modules.Env {
t.Helper()
env := fixedEnv(t)
env.Now = time.Unix(1764450245, 0)
return env
}
// checkGolden compares got with the file at path, or rewrites the file
// with -update.
func checkGolden(t *testing.T, path, got string) {
t.Helper()
if *update {
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("%v (run go test -run %s -update)", err, strings.Split(t.Name(), "/")[0])
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", path, got, want)
}
}
// buildGoldens builds each payload in testdata/DIR/*.json with module and
// compares its preview with NAME.txt.
func buildGoldens(t *testing.T, dir string, module modules.Module, env modules.Env) {
t.Helper()
paths, err := filepath.Glob(filepath.Join("testdata", dir, "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatalf("no payloads in testdata/%s", dir)
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := module.Build(context.Background(), body, env)
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("built an invalid job: %v", err)
}
checkGolden(t, filepath.Join("testdata", dir, name+".txt"), previewText(t, job))
})
}
}
// TestNtfyGoldens previews each testdata/ntfy/*.json message at the time
// it was sent. Run with -update to rewrite the .txt files, then review the
// diff.
func TestNtfyGoldens(t *testing.T) {
buildGoldens(t, "ntfy", modules.Ntfy(), ntfyEnv(t))
}
// TestNotifyGoldens previews each testdata/notify/*.json payload.
func TestNotifyGoldens(t *testing.T) {
buildGoldens(t, "notify", modules.Notify(), fixedEnv(t))
}
// TestCardStyles previews the example message at every priority in every
// style, in testdata/card/p<priority>-<style>.txt.
func TestCardStyles(t *testing.T) {
for _, style := range []string{modules.StyleAuto, modules.StyleBox, modules.StyleCompact} {
for priority := 1; priority <= 5; priority++ {
name := fmt.Sprintf("p%d-%s", priority, style)
t.Run(name, func(t *testing.T) {
n := modules.Notice{
Topic: "alerts",
Title: "Disk almost full",
Message: "/var is at 94% on nas01",
Priority: priority,
Tags: []string{"warning", "nas01"},
Links: []modules.Link{{Label: "Open dashboard", URL: "https://grafana.lan/d/disk"}},
}
job, _ := modules.Card(n, modules.CardOptions{Style: style}, fixedEnv(t))
checkGolden(t, filepath.Join("testdata", "card", name+".txt"), previewText(t, job))
})
}
}
}
// TestNtfyPriorities pins the card of an example message at priorities 5,
// 4, 3 and 1: the four forms.
func TestNtfyPriorities(t *testing.T) {
tests := []struct {
file string
want []string
}{
{"priority-high", []string{
"╔═ HIGH ═════════════════════════════════╗",
"║ [!] Disk almost full ║",
"╟────────────────────────────────────────╢",
"║ /var is at 94% on nas01 ║",
"║ ║",
"║ Tags: nas01 ║",
"╚═══════════════ alerts · 29 Nov 21:04 ══╝",
"",
"[qr: https://grafana.lan/d/disk]",
" Open dashboard",
"",
"[image 384 dots: sPs71M8A2Tq9.png]",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-urgent", []string{
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"╔════════════════════════════════════════╗",
"║ (!) Backup FAILED on nas01 ║",
"╠════════════════════════════════════════╣",
"║ Job nightly-offsite exited with code 2 ║",
"║ after 3h12m. Last good run: 2 days ║",
"║ ago. ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-default", []string{
"┌─ [√] Nightly backup ───────────────────┐",
"│ restic: 2.1 GB added in 14m 02s, 0 │",
"│ errors. │",
"│ │",
"│ Tags: restic │",
"└────────────── backups · 29 Nov 03:12 ──┘",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-min", []string{
"── backups · 29 Nov 03:12 ────────────────",
"Prune finished",
"41 snapshots kept, 3 removed.",
" - - - - - - - partial cut - - - - - - - -",
}},
}
for _, tt := range tests {
t.Run(tt.file, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", tt.file+".json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
want := strings.Join(tt.want, "\n") + "\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
})
}
}
// TestCardTitleStyles checks how each form styles the title: the title row of
// a high card is bold, of an urgent card bold and inverted, and the title
// in a default card's border is bold, as is the title line of a low card.
func TestCardTitleStyles(t *testing.T) {
tests := []struct {
priority int
check func(job receipt.Job) bool
}{
{5, func(j receipt.Job) bool { c := j.Elements[1].Children[0]; return c.Bold && c.Invert }},
{4, func(j receipt.Job) bool { c := j.Elements[0].Children[0]; return c.Bold && !c.Invert }},
{3, func(j receipt.Job) bool { return j.Elements[0].TitleBold }},
{1, func(j receipt.Job) bool { return j.Elements[1].Bold }},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: tt.priority}, modules.CardOptions{}, fixedEnv(t))
if !tt.check(job) {
t.Errorf("priority %d: title styled wrongly: %+v", tt.priority, job.Elements)
}
}
}
func TestMarkers(t *testing.T) {
tests := []struct {
name string
overrides map[string]string
tags []string
head string // the title row of a high card
tagRow string // "" for none
}{
{"built in", nil, []string{"warning", "nas01"}, "[!] T", "Tags: nas01"},
{"two markers at most", nil, []string{"warning", "fire", "tada"}, "[!] (!) T", "Tags: tada"},
{"a marker once", nil, []string{"fire", "boom", "rotating_light"}, "(!) T", ""},
{"case", nil, []string{"Warning"}, "[!] T", ""},
{"override", map[string]string{"backup": "[B]", "warning": "/!\\"}, []string{"backup", "warning"}, "[B] /!\\ T", ""},
{"hidden", map[string]string{"nas01": ""}, []string{"warning", "nas01"}, "[!] T", ""},
{"hide a built-in", map[string]string{"warning": ""}, []string{"warning"}, "T", ""},
{"unmapped", nil, []string{"backup", "nas01", " "}, "T", "Tags: backup, nas01"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o := modules.CardOptions{Markers: modules.NewMarkers(tt.overrides)}
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: 4, Tags: tt.tags}, o, fixedEnv(t))
children := job.Elements[0].Children
if got := children[0].Text; got != tt.head {
t.Errorf("title row %q, want %q", got, tt.head)
}
last := children[len(children)-1]
gotRow := ""
if strings.HasPrefix(last.Text, "Tags: ") {
gotRow = last.Text
}
if gotRow != tt.tagRow {
t.Errorf("tag row %q, want %q", gotRow, tt.tagRow)
}
})
}
}
func TestTypedEmoji(t *testing.T) {
n := modules.Notice{Title: "⚠\uFE0F Disk ✅ done ❌ 🚨 👍", Message: "🎉 Party\nBackup 🎉 done\nDone 🎉\n👨\u200D👩\u200D👧 family 🇬🇧 flag 1\uFE0F\u20E3 ■ → ✓", Priority: 4}
job, _ := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
if got, want := children[0].Text, "[!] Disk [√] done [x] (!) (+1)"; got != want {
t.Errorf("title %q, want %q", got, want)
}
if got, want := children[2].Text, "Party\nBackup done\nDone\nfamily flag 1 ■ → ✓"; got != want {
t.Errorf("message %q, want %q", got, want)
}
hidden := modules.CardOptions{Markers: modules.NewMarkers(map[string]string{"warning": ""})}
job, _ = modules.Card(modules.Notice{Title: "⚠\uFE0F Disk", Message: "m", Priority: 4}, hidden, fixedEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("hidden marker: title %q, want %q", got, "Disk")
}
}
func TestCardLinks(t *testing.T) {
links := []modules.Link{
{URL: "https://a.example.com/x"},
{Label: "A", URL: "https://a.example.com/x"},
{Label: "Mail", URL: "mailto:someone@example.com"},
{Label: "B", URL: "https://b.example.com/"},
{Label: "C", URL: "http://c.example.com/c"},
{Label: "D", URL: "https://d.example.com/d"},
}
n := modules.Notice{Title: "T", Message: "m", Priority: 3, Links: links}
tests := []struct {
qr string
want []string
}{
{"all", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "[qr: https://b.example.com/]", " B",
"", "[qr: http://c.example.com/c]", " C",
}},
{"first", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
{"none", []string{
"", "» A", "https://a.example.com/x", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
}
for _, tt := range tests {
t.Run(tt.qr, func(t *testing.T) {
job, _ := modules.Card(n, modules.CardOptions{QR: tt.qr}, fixedEnv(t))
lines := strings.Split(previewText(t, job), "\n")
// The card is a box of three lines; the cut and a final empty
// string follow the links.
got := lines[3 : len(lines)-2]
if strings.Join(got, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("links:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(tt.want, "\n"))
}
})
}
t.Run("caption without a label", func(t *testing.T) {
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: "https://grafana.lan/d/disk/?from=now"}}},
modules.CardOptions{}, fixedEnv(t))
last := job.Elements[len(job.Elements)-1]
if last.Text != "grafana.lan/d/disk" || last.Font != "b" || last.Align != "center" {
t.Errorf("caption %+v", last)
}
})
t.Run("a long link prints as text", func(t *testing.T) {
long := "https://example.com/" + strings.Repeat("x", 600)
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: long}}}, modules.CardOptions{}, fixedEnv(t))
for _, el := range job.Elements {
if el.Type == receipt.TypeQR {
t.Fatal("a 620-byte link printed as a QR code")
}
}
})
}
// TestNtfyActionsNeverPrint checks that nothing of an http, broadcast or
// copy action reaches the receipt: their URLs, headers, bodies and values
// can hold secrets.
func TestNtfyActionsNeverPrint(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", "actions-private.json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
preview := previewText(t, job)
for _, secret := range []string{"SECRET", "hooks.example.com", "Close door", "Tasker", "Copy code"} {
if strings.Contains(preview, secret) || strings.Contains(string(encoded), secret) {
t.Errorf("%q from an action that is not a view action reached the receipt", secret)
}
}
if !strings.Contains(preview, "[qr: https://cam.example.com/garage]") {
t.Errorf("the view action did not print:\n%s", preview)
}
}
func TestCardBodyCap(t *testing.T) {
lines := make([]string, 45)
for i := range lines {
lines[i] = fmt.Sprint("line ", i+1)
}
tests := []struct {
maxLines int
message string
last string
}{
{0, strings.Join(lines, "\n"), "... 5 more lines"},
{44, strings.Join(lines, "\n"), "... 1 more line"},
{45, strings.Join(lines, "\n"), "line 45"},
{2, "a\nb\n\n\n", "b"},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Message: tt.message, Priority: 3}, modules.CardOptions{MaxLines: tt.maxLines}, fixedEnv(t))
children := job.Elements[0].Children
text := children[len(children)-1].Text
rows := strings.Split(text, "\n")
if got := rows[len(rows)-1]; got != tt.last {
t.Errorf("max_lines %d: last line %q, want %q", tt.maxLines, got, tt.last)
}
}
}
func TestCardAttachments(t *testing.T) {
env := ntfyEnv(t)
image := &modules.File{Name: "graph.png", Type: "image/png", Size: 33848, URL: "https://ntfy.example.com/file/g.png"}
tests := []struct {
name string
n modules.Notice
o modules.CardOptions
image string
fileValue string
}{
{"image", modules.Notice{File: image}, modules.CardOptions{}, image.URL, ""},
{"images off", modules.Notice{File: image}, modules.CardOptions{NoImages: true}, "", "graph.png (33 KB)"},
{"expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now}},
modules.CardOptions{}, "", "a.png"},
{"not yet expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now.Add(time.Second)}},
modules.CardOptions{}, image.URL, ""},
{"no type, image name", modules.Notice{File: &modules.File{Name: "door.JPG", URL: "https://x.example.com/f/abc"}},
modules.CardOptions{}, "https://x.example.com/f/abc", ""},
{"no type, image URL", modules.Notice{File: &modules.File{Name: "door", URL: "https://x.example.com/f/abc.webp"}},
modules.CardOptions{}, "https://x.example.com/f/abc.webp", ""},
{"an image the printer cannot decode", modules.Notice{File: &modules.File{Name: "logo.svg", Type: "image/svg+xml", Size: 2048, URL: "https://x.example.com/logo.svg"}},
modules.CardOptions{}, "", "logo.svg (2 KB)"},
{"another file", modules.Notice{File: &modules.File{Name: "report.pdf", Type: "application/pdf", Size: 1468006, URL: "https://x.example.com/r.pdf"}},
modules.CardOptions{}, "", "report.pdf (1.4 MB)"},
{"a small file", modules.Notice{File: &modules.File{Name: "a.txt", Size: 980, URL: "https://x.example.com/a.txt"}},
modules.CardOptions{}, "", "a.txt (980 B)"},
{"notify image", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{}, "https://x.example.com/i.png", ""},
{"notify image, images off", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{NoImages: true}, "", "i.png"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.n.Message, tt.n.Priority = "m", 3
job, _ := modules.Card(tt.n, tt.o, env)
var gotImage, gotFile string
for _, el := range job.Elements {
if el.Type == receipt.TypeImage {
gotImage = el.URL
if !el.Optional || el.Width != 384 || el.Align != "center" {
t.Errorf("image %+v, want optional, 384 dots and centred", el)
}
}
}
for _, el := range job.Elements[0].Children {
if el.Type == receipt.TypeKV && el.Pairs[0].Key == "File" {
gotFile = el.Pairs[0].Value
}
}
if gotImage != tt.image || gotFile != tt.fileValue {
t.Errorf("image %q and file row %q, want %q and %q", gotImage, gotFile, tt.image, tt.fileValue)
}
})
}
}
func TestFromNtfy(t *testing.T) {
tests := []struct {
name string
body string
skip bool
want func(modules.Notice) bool
}{
{"unknown fields are ignored", `{"event":"message","message":"x","colour":"red","attachment":{"url":"https://a/b.png","name":"b.png","new":1}}`,
false, func(n modules.Notice) bool { return n.Message == "x" && n.File != nil }},
{"no priority is 3", `{"event":"message","message":"x"}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority 0 is 3", `{"event":"message","message":"x","priority":0}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority out of range is 3", `{"event":"message","message":"x","priority":9}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"no event is a message", `{"message":"x","priority":5}`, false, func(n modules.Notice) bool { return n.Priority == 5 }},
{"markdown", `{"event":"message","message":"x","content_type":"text/markdown"}`, false, func(n modules.Notice) bool { return n.Markdown }},
{"time", `{"event":"message","message":"x","time":1764450245}`, false,
func(n modules.Notice) bool { return n.Time.Equal(time.Unix(1764450245, 0)) }},
{"file placeholder", `{"event":"message","message":"You received a file: a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "" && n.File.Name == "a.pdf" }},
{"other text stays", `{"event":"message","message":"See a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "See a.pdf" }},
{"sequence id equal to id", `{"id":"a","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
// A publisher may choose the sequence ID, so one message cannot
// tell the first of its sequence from a replacement.
{"sequence id other than id", `{"id":"b","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
{"view actions and click are links", `{"event":"message","message":"x","click":"https://c/",` +
`"actions":[{"action":"view","label":"V","url":"https://v/"},{"action":"http","label":"H","url":"https://h/"}]}`,
false, func(n modules.Notice) bool {
return len(n.Links) == 2 && n.Links[0].URL == "https://c/" && n.Links[1] == modules.Link{Label: "V", URL: "https://v/"}
}},
{"open", `{"id":"x","time":1,"event":"open","topic":"alerts"}`, true, nil},
{"keepalive", `{"id":"x","time":1,"event":"keepalive","topic":"alerts"}`, true, nil},
{"poll request", `{"event":"poll_request","message":"New message"}`, true, nil},
{"delete", `{"event":"message_delete","sequence_id":"a"}`, true, nil},
{"clear", `{"event":"message_clear","sequence_id":"a"}`, true, nil},
{"base64", `{"event":"message","message":"iVBORw0KGgo=","encoding":"base64"}`, true, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var m ntfy.Message
if err := json.Unmarshal([]byte(tt.body), &m); err != nil {
t.Fatal(err)
}
n, err := modules.FromNtfy(m)
if tt.skip {
if !errors.Is(err, modules.ErrSkip) {
t.Errorf("err = %v, want ErrSkip", err)
}
return
}
if err != nil {
t.Fatal(err)
}
if !tt.want(n) {
t.Errorf("notice %+v", n)
}
})
}
}
func TestNtfyBuild(t *testing.T) {
ctx := context.Background()
if _, err := modules.Ntfy().Build(ctx, []byte(`{"event":"keepalive","time":1}`), ntfyEnv(t)); !errors.Is(err, modules.ErrSkip) {
t.Errorf("keepalive: err = %v, want ErrSkip", err)
}
sequence := []byte(`{"id":"b","sequence_id":"a","event":"message","title":"Disk","message":"x","priority":4}`)
job, err := modules.Ntfy().Build(ctx, sequence, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("a message of a sequence: title %q, want it unmarked", got)
}
// A notice known to replace an earlier one, as the subscriber can
// tell, is marked.
job, _ = modules.Card(modules.Notice{Title: "Disk", Message: "x", Priority: 4, Updated: true}, modules.CardOptions{}, ntfyEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk (updated)" {
t.Errorf("an update: title %q", got)
}
problems := []struct{ body, want string }{
{``, "body: empty; expected a JSON object"},
{`null`, "body: expected a JSON object, got null"},
{`[1]`, "body: expected a JSON object, got array"},
{`{"message":"x"} {}`, "body: trailing data after the payload"},
{`{"priority":"high"}`, "priority: expected a whole number"},
{`{"attachment":{"size":"big"}}`, "attachment.size: expected a whole number"},
}
for _, p := range problems {
_, err := modules.Ntfy().Build(ctx, []byte(p.body), ntfyEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) || strings.Join(pe.Problems, "; ") != p.want {
t.Errorf("%s: err = %v, want the problem %q", p.body, err, p.want)
}
}
}
func TestNotifyPayloadProblems(t *testing.T) {
tests := []struct {
name, body string
want []string
}{
{"unknown field", `{"message":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"wrong types", `{"message":1,"tags":"a","markdown":"yes","actions":{}}`,
[]string{"actions: expected an array", "markdown: expected true or false", "message: expected a string", "tags: expected an array of strings"}},
{"missing message", `{"title":"T"}`, []string{"message: required"}},
{"long message", `{"message":"` + strings.Repeat("x", modules.MaxMessage+1) + `"}`, []string{"message: 4097 bytes, limit is 4096"}},
{"long title and topic", `{"message":"x","title":"` + strings.Repeat("é", modules.MaxTitle+1) + `","topic":"` + strings.Repeat("t", modules.MaxTopic+1) + `"}`,
[]string{"title: 251 characters, limit is 250", "topic: 65 characters, limit is 64"}},
{"too many tags", `{"message":"x","tags":[` + strings.Repeat(`"a",`, modules.MaxTags) + `"b"]}`, []string{"tags: 21 tags, limit is 20"}},
{"long tag", `{"message":"x","tags":["a","` + strings.Repeat("t", modules.MaxTag+1) + `"]}`, []string{"tags[1]: 65 characters, limit is 64"}},
{"long label and URLs", `{"message":"x","click":"https://a/` + strings.Repeat("x", modules.MaxURL) + `","image":"https://i/` + strings.Repeat("x", modules.MaxURL) +
`","actions":[{"label":"` + strings.Repeat("l", modules.MaxLabel+1) + `","url":"https://b/` + strings.Repeat("x", modules.MaxURL) + `"}]}`,
[]string{"click: 2010 bytes, limit is 2000", "image: 2010 bytes, limit is 2000",
"actions[0].label: 65 characters, limit is 64", "actions[0].url: 2010 bytes, limit is 2000"}},
{"priority number", `{"message":"x","priority":6}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority fraction", `{"message":"x","priority":2.5}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority name", `{"message":"x","priority":"loud"}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority type", `{"message":"x","priority":true}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"time", `{"message":"x","time":"yesterday"}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"negative time", `{"message":"x","time":-5}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"click", `{"message":"x","click":"mailto:a@example.com"}`, []string{"click: must be an http or https URL"}},
{"image", `{"message":"x","image":"/local.png"}`, []string{"image: must be an http or https URL"}},
{"too many actions", `{"message":"x","actions":[{"url":"https://a/"},{"url":"https://b/"},{"url":"https://c/"},{"url":"https://d/"}]}`,
[]string{"actions: 4 actions, limit is 3"}},
{"action problems", `{"message":"x","actions":[{"label":"A"},{"url":"ftp://x/"},{"url":"https://x/","lable":"B"},"https://y/"]}`,
[]string{"actions: 4 actions, limit is 3", "actions[0].url: required", "actions[1].url: must be an http or https URL",
"actions[2].lable: unknown field", "actions[3]: expected a JSON object, got string"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestNotifyPriorityAndTime(t *testing.T) {
tests := []struct {
body string
priority int // 5: an URGENT rule first, 4: a HIGH box, 3: a box, 1 and 2: a rule
stamp string
}{
{`{"message":"x"}`, 3, "29 Nov 21:04"},
{`{"message":"x","priority":"urgent"}`, 5, ""},
{`{"message":"x","priority":"MAX"}`, 5, ""},
{`{"message":"x","priority":"high"}`, 4, ""},
{`{"message":"x","priority":"default"}`, 3, ""},
{`{"message":"x","priority":"low"}`, 2, ""},
{`{"message":"x","priority":"min"}`, 1, ""},
{`{"message":"x","priority":"4"}`, 4, ""},
{`{"message":"x","priority":1}`, 1, ""},
{`{"message":"x","time":1764450245}`, 3, "29 Nov 21:04"},
{`{"message":"x","time":"2026-07-01T12:30:00+02:00"}`, 3, "01 Jul 11:30"},
}
for _, tt := range tests {
job, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", tt.body, err)
continue
}
first := job.Elements[0]
var got int
switch {
case first.Type == receipt.TypeRule && first.Text == "URGENT":
got = 5
case first.Type == receipt.TypeBox && first.Title == "HIGH":
got = 4
case first.Type == receipt.TypeBox:
got = 3
default:
got = 1
}
want := tt.priority
if want <= 2 {
want = 1
}
if got != want {
t.Errorf("%s: printed as priority %d, want %d", tt.body, got, tt.priority)
}
if tt.stamp != "" && !strings.HasSuffix(first.Footer, tt.stamp) {
t.Errorf("%s: footer %q, want the time %s", tt.body, first.Footer, tt.stamp)
}
}
}
// TestCardFallback checks that a card that fails to lay out still prints:
// the plain fallback receipt, which passes validation.
func TestCardFallback(t *testing.T) {
restore := modules.SetCardFault(func() { panic("layout bug") })
defer restore()
n := modules.Notice{Topic: "alerts", Title: "Disk 🎉", Message: "/var is at 94%", Priority: 5}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
var fallbackErr *modules.FallbackError
if !errors.As(err, &fallbackErr) || !strings.Contains(fallbackErr.Cause, "layout bug") || fallbackErr.Stack == "" {
t.Errorf("err = %#v, want a *FallbackError with the panic and its stack", err)
}
if strings.Contains(fmt.Sprint(err), "94%") {
t.Error("the error quotes the notification")
}
if err := job.Validate(); err != nil {
t.Fatalf("fallback is invalid: %v", err)
}
// The module returns the fallback with the error, for its caller to
// report.
built, err := modules.Notify().Build(context.Background(), []byte(`{"message":"x"}`), fixedEnv(t))
if !errors.As(err, &fallbackErr) || len(built.Elements) == 0 || built.Validate() != nil {
t.Errorf("notify: job %+v, err %v; want the fallback and a *FallbackError", built, err)
}
want := "Disk\n/var is at 94%\nalerts · 29 Nov 21:04\n - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("fallback:\n%s\nwant:\n%s", got, want)
}
if !job.Elements[0].Bold {
t.Error("the fallback's title is not bold")
}
}
// TestCardsAreValid builds cards from awkward notices, which must all pass
// validation without falling back.
func TestCardsAreValid(t *testing.T) {
many := make([]string, 300)
for i := range many {
many[i] = "- item"
}
notices := []modules.Notice{
{},
{Message: " \n "},
{Message: "x", Priority: -1},
{Message: "x", Priority: 3, Tags: []string{"", "warning", "x", "tada", "skull"}},
{Message: strings.Join(many, "\n"), Markdown: true, Priority: 3},
{Message: "```\nunclosed fence", Markdown: true},
{Message: "- 🎉\n# \n> \n---", Markdown: true, Priority: 1},
{Title: "\u001b@", Message: "\u0007\u001bd", Topic: "\t"},
{Message: "x", Links: []modules.Link{{URL: "https://a/"}, {URL: "https://b/"}, {URL: "https://c/"}, {URL: "https://d/"}}},
}
for _, o := range []modules.CardOptions{{}, {MaxLines: 400}, {Style: "compact", QR: "none"}, {Style: "box", QR: "first"}} {
for i, n := range notices {
job, err := modules.Card(n, o, fixedEnv(t))
if err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
if err := job.Validate(); err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
// A card starts with a box or a rule; the fallback with text.
if job.Elements[0].Type == receipt.TypeText {
t.Errorf("notice %d, options %+v: fell back to the plain receipt", i, o)
}
}
}
}
// TestCardLimits builds a card from a notice far over every limit, as an
// ntfy message may be: it is cut to a length that prints well inside
// format.max_lines, even on 58 mm paper.
func TestCardLimits(t *testing.T) {
long := strings.Repeat("word ", 20_000)
tags := make([]string, 9000)
for i := range tags {
tags[i] = fmt.Sprint("tag", i, strings.Repeat("x", 100))
}
n := modules.Notice{
Title: long,
Topic: long,
Message: strings.Repeat("x", 1_000_000),
Priority: 5,
Tags: tags,
Links: []modules.Link{
{Label: long, URL: "https://a.example.com/" + strings.Repeat("x", 300)},
{URL: "https://b.example.com/" + strings.Repeat("x", 5000)},
},
File: &modules.File{Name: long, URL: "https://f.example.com/report.pdf"},
}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
if err != nil {
t.Fatal(err)
}
for _, model := range []string{"tm-t88", "generic-58mm"} {
profile, err := escpos.LookupProfile(model)
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("%s: %v", model, err)
}
if p.LineCount > 400 {
t.Errorf("%s: the card prints %d lines", model, p.LineCount)
}
}
box := job.Elements[1]
if head := box.Children[0].Text; utf8.RuneCountInString(head) > modules.MaxTitle+4 || !strings.HasSuffix(head, "...") {
t.Errorf("title row of %d characters", utf8.RuneCountInString(head))
}
for _, el := range job.Elements {
if el.Type == receipt.TypeQR && len(el.Data) > 1000 {
t.Errorf("a %d-byte link printed", len(el.Data))
}
}
}
// TestCardTitleFallback checks that a title or tags that cleaning leaves
// empty fall back as a missing title does, and leave no empty tag.
func TestCardTitleFallback(t *testing.T) {
tests := []struct {
n modules.Notice
head string
row string
}{
{modules.Notice{Title: "🎉🎉", Topic: "alerts", Tags: []string{"warning"}}, "[!] alerts", ""},
{modules.Notice{Title: "🎉", Topic: "🎉"}, "Notification", ""},
{modules.Notice{Title: "T", Tags: []string{"🎉", "a", " ", "🧺"}}, "T", "Tags: a"},
{modules.Notice{Title: "T", Tags: []string{"🎉"}}, "T", ""},
}
for _, tt := range tests {
tt.n.Message, tt.n.Priority = "m", 4
job, _ := modules.Card(tt.n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
row := ""
if last := children[len(children)-1].Text; strings.HasPrefix(last, "Tags:") {
row = last
}
if children[0].Text != tt.head || row != tt.row {
t.Errorf("%q with tags %q: title row %q and tags row %q, want %q and %q",
tt.n.Title, tt.n.Tags, children[0].Text, row, tt.head, tt.row)
}
}
}
+12
View File
@@ -0,0 +1,12 @@
package modules
// SetCardFault makes every card run fault first, and returns a func that
// undoes it.
func SetCardFault(fault func()) (restore func()) {
old := cardFault
cardFault = fault
return func() { cardFault = old }
}
// MarkdownBody exposes markdownBody to the tests.
var MarkdownBody = markdownBody
+23
View File
@@ -0,0 +1,23 @@
package modules
import (
"strings"
"uberbringer/internal/pkg/receipt"
)
// fallback is the plain receipt Card returns when laying out a card goes
// wrong: the title in bold, the message as written, then the topic and
// time, each cut to the notice limits.
func fallback(n Notice, env Env) receipt.Job {
elements := []receipt.Element{{Type: receipt.TypeText, Text: noticeTitle(n, receipt.StripEmoji), Bold: true}}
if message := strings.TrimSpace(receipt.StripEmoji(cutBytes(n.Message, MaxMessage))); message != "" {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: message})
}
stamp := env.Format(n.Time)
if topic := cut(strings.TrimSpace(receipt.StripEmoji(n.Topic)), MaxTopic); topic != "" {
stamp = topic + " · " + stamp
}
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: stamp})
return receipt.Job{Elements: elements}
}
+263
View File
@@ -0,0 +1,263 @@
package modules
import (
"regexp"
"strings"
"uberbringer/internal/pkg/receipt"
)
// Line-level markdown: headings, bullet and numbered items, quotes, code
// fences and thematic breaks.
var (
mdHeading = regexp.MustCompile(`^\s{0,3}#{1,6}\s+(.*?)(\s+#+)?\s*$`)
mdBreak = regexp.MustCompile(`^\s{0,3}([-*_])(\s*([-*_])){2,}\s*$`)
mdBullet = regexp.MustCompile(`^\s*[-*+]\s+(\S.*)$`)
mdNumbered = regexp.MustCompile(`^\s*\d{1,9}[.)]\s+(\S.*)$`)
mdQuote = regexp.MustCompile(`^\s{0,3}>\s?(.*)$`)
mdFence = regexp.MustCompile("^\\s{0,3}(```|~~~)")
)
// Inline markdown, applied in this order: images, links, code spans and
// bare URLs, which are kept as written, then emphasis and strikethrough.
var (
mdImage = regexp.MustCompile(`!\[([^\]]*)\]\(([^)\s]*)(\s+"[^"]*")?\)`)
mdLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)(\s+"[^"]*")?\)`)
mdCode = regexp.MustCompile("`([^`]+)`")
mdURL = regexp.MustCompile("\\b(?:https?|ftp)://[^\\s<>`\\x{E100}-\\x{E7FF}]+")
mdStrong = regexp.MustCompile(`\*\*([^\s*](?:.*?[^\s*])?)\*\*`)
mdStrongU = regexp.MustCompile(`\b__([^\s_](?:.*?[^\s_])?)__\b`)
mdStrike = regexp.MustCompile(`~~([^\s~](?:.*?[^\s~])?)~~`)
mdEmphasis = regexp.MustCompile(`\*([^\s*](?:[^*]*?[^\s*])?)\*`)
mdEmphasisU = regexp.MustCompile(`(^|[^\pL\pN_])_([^\s_](?:[^_]*?[^\s_])?)_($|[^\pL\pN_])`)
mdEscape = regexp.MustCompile("\\\\([\\\\`*_{}\\[\\]()#+\\-.!>~|])")
)
// escapeBase is where markdownInline sets aside escaped ASCII characters,
// in the private use area: '*' is escapeBase+'*'. keptBase is where it
// numbers the code spans and URLs it keeps as written, up to maxKept.
const (
escapeBase = rune(0xE000)
keptBase = rune(0xE100)
maxKept = 0x700
)
// markdownBody lays out text written in a subset of markdown as elements
// that fit inside a box as well as on their own:
//
// - #, ## and ### headings print as bold lines;
// - -, * and + items as a dot list, and 1. items as a numbered list;
// - > quotes with "│ " in front;
// - lines between ``` fences as written;
// - --- as a divider;
// - **bold**, __bold__, *italic*, _italic_, `code` and ~~struck~~ text
// without the marks;
// - [text](url) as its text, with url added to links;
// - ![alt](url) as [image: alt].
//
// Every other line prints as written, and a run of empty lines as one.
func markdownBody(text string) (elements []receipt.Element, links []Link) {
var (
para []string
list *receipt.Element
fence []string
inFence bool
blankRun bool
)
flushPara := func() {
if len(para) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(para, "\n")})
para = nil
}
}
flushList := func() {
if list != nil {
elements = append(elements, *list)
list = nil
}
}
flush := func() {
flushPara()
flushList()
}
inline := func(s string) string {
s, found := markdownInline(s)
links = append(links, found...)
return s
}
addItem := func(bullet, item string) {
item = inline(item)
if strings.TrimSpace(item) == "" {
return
}
if list != nil && (list.Bullet != bullet || len(list.Items) == receipt.MaxItems) {
flushList()
}
flushPara()
if list == nil {
list = &receipt.Element{Type: receipt.TypeList, Bullet: bullet}
}
list.Items = append(list.Items, item)
}
for _, line := range strings.Split(text, "\n") {
if inFence {
if mdFence.MatchString(line) {
inFence = false
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)})
fence = nil
continue
}
fence = append(fence, line)
continue
}
if strings.TrimSpace(line) == "" {
flush()
if !blankRun && len(elements) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeFeed})
}
blankRun = true
continue
}
blankRun = false
switch {
case mdFence.MatchString(line):
flush()
inFence = true
case mdBreak.MatchString(line):
flush()
elements = append(elements, receipt.Element{Type: receipt.TypeRule})
case mdHeading.MatchString(line):
flush()
heading := inline(mdHeading.FindStringSubmatch(line)[1])
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: heading, Bold: true})
case mdBullet.MatchString(line):
addItem("dot", mdBullet.FindStringSubmatch(line)[1])
case mdNumbered.MatchString(line):
addItem("number", mdNumbered.FindStringSubmatch(line)[1])
case mdQuote.MatchString(line):
flushList()
para = append(para, "│ "+inline(mdQuote.FindStringSubmatch(line)[1]))
default:
flushList()
para = append(para, inline(line))
}
}
if inFence && len(fence) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)})
}
flush()
// A trailing empty line prints nothing useful.
for len(elements) > 0 && elements[len(elements)-1].Type == receipt.TypeFeed {
elements = elements[:len(elements)-1]
}
return elements, links
}
// markdownInline removes the inline marks from s and returns the http and
// https links it names.
func markdownInline(s string) (string, []Link) {
// The characters that number what is kept as written are dropped from
// the text first, so that none is taken for a number; no code page
// prints them.
s = strings.Map(func(r rune) rune {
if r >= keptBase && r < keptBase+maxKept {
return -1
}
return r
}, s)
// Escaped characters are set aside, so that they are not read as marks.
s = mdEscape.ReplaceAllStringFunc(s, func(m string) string {
return string(escapeBase + rune(m[1]))
})
s = mdImage.ReplaceAllStringFunc(s, func(m string) string {
alt := strings.TrimSpace(mdImage.FindStringSubmatch(m)[1])
if alt == "" {
return "[image]"
}
return "[image: " + alt + "]"
})
var links []Link
s = mdLink.ReplaceAllStringFunc(s, func(m string) string {
parts := mdLink.FindStringSubmatch(m)
text, target := parts[1], parts[2]
if webURL(target) {
links = append(links, Link{Label: restoreEscapes(text), URL: target})
}
return text
})
// Code spans, without their backticks, and bare URLs are set aside,
// so that marks inside them, as in __init__.py, print as written.
var kept []string
keep := func(text string) string {
if len(kept) == maxKept {
return text
}
kept = append(kept, text)
return string(keptBase + rune(len(kept)-1))
}
s = mdCode.ReplaceAllStringFunc(s, func(m string) string { return keep(m[1 : len(m)-1]) })
s = mdURL.ReplaceAllStringFunc(s, func(m string) string {
url, rest := trimURL(m)
return keep(url) + rest
})
s = mdStrong.ReplaceAllString(s, "$1")
s = mdStrongU.ReplaceAllString(s, "$1")
s = mdStrike.ReplaceAllString(s, "$1")
s = mdEmphasis.ReplaceAllString(s, "$1")
// Twice: a match takes the character after it, which the next one
// may need before it.
for range 2 {
s = mdEmphasisU.ReplaceAllString(s, "$1$2$3")
}
return restoreEscapes(restoreKept(s, kept)), links
}
// trimURL splits the punctuation that ends a sentence, or closes emphasis,
// off the end of a bare URL, as GitHub's autolinks do: trailing . , : ; !
// ? ' " _ * and ~, and a ) that has no ( in the URL to close. The same
// marks inside the URL stay part of it. It returns the URL and what
// followed it.
func trimURL(m string) (url, rest string) {
url = m
for url != "" {
last := url[len(url)-1]
switch {
case strings.IndexByte(".,:;!?'\"_*~", last) >= 0:
case last == ')' && strings.Count(url, ")") > strings.Count(url, "("):
default:
return url, m[len(url):]
}
url = url[:len(url)-1]
}
return url, m
}
// restoreKept puts back the code spans and URLs markdownInline set aside
// in kept.
func restoreKept(s string, kept []string) string {
if len(kept) == 0 {
return s
}
var b strings.Builder
for _, r := range s {
if i := int(r - keptBase); r >= keptBase && i < len(kept) {
b.WriteString(kept[i])
continue
}
b.WriteRune(r)
}
return b.String()
}
// restoreEscapes puts back the characters markdownInline set aside.
func restoreEscapes(s string) string {
return strings.Map(func(r rune) rune {
if r >= escapeBase && r < escapeBase+0x80 {
return r - escapeBase
}
return r
}, s)
}
func boolPtr(b bool) *bool { return &b }
+197
View File
@@ -0,0 +1,197 @@
package modules_test
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// markdownBox lays out text as markdown inside a box, as a card does.
func markdownBox(text string) (receipt.Job, []modules.Link) {
body, links := modules.MarkdownBody(text)
if len(body) == 0 {
body = []receipt.Element{{Type: receipt.TypeText}}
}
return receipt.Job{Elements: []receipt.Element{{Type: receipt.TypeBox, Children: body}}}, links
}
// TestMarkdownGoldens previews testdata/markdown/*.md inside a box.
func TestMarkdownGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "markdown", "*.md"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no texts in testdata/markdown")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".md")
t.Run(name, func(t *testing.T) {
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
text := string(data)
job, links := markdownBox(text)
got := previewText(t, job)
for _, l := range links {
got += "link: " + l.Label + " -> " + l.URL + "\n"
}
checkGolden(t, filepath.Join("testdata", "markdown", name+".txt"), got)
})
}
}
func TestMarkdownInline(t *testing.T) {
tests := []struct{ in, want string }{
{"**/var** is at *94%* on nas01", "/var is at 94% on nas01"},
{"__bold__ and _it_ and ~~gone~~ and `code`", "bold and it and gone and code"},
{"snake_case_name and 2 * 3 * 4", "snake_case_name and 2 * 3 * 4"},
{"_a_ _b_", "a b"},
{`\*not italic\* and \_kept\_`, "*not italic* and _kept_"},
{"see [docs](https://example.com/docs) and [local](/x)", "see docs and local"},
{"![chart](https://example.com/c.png) and ![](x.png)", "[image: chart] and [image]"},
{"** not bold **", "** not bold **"},
// Code spans and bare URLs keep their marks.
{"run `__init__.py` and `**/*.go`", "run __init__.py and **/*.go"},
{"see https://host/__debug__/ or *now*", "see https://host/__debug__/ or now"},
{"`a` **b** `c_d_e` _f_", "a b c_d_e f"},
// A URL ends before the marks and punctuation that follow it.
{"**https://example.com/status**", "https://example.com/status"},
{"**Down: https://status.lan**", "Down: https://status.lan"},
{"*https://example.com*", "https://example.com"},
{"_https://example.com/x_", "https://example.com/x"},
{"~~https://old.example.com~~ moved", "https://old.example.com moved"},
{"Run https://ci.example.com/job/`nightly` now", "Run https://ci.example.com/job/nightly now"},
{"see https://example.com/a_(b) and (https://example.com/c).", "see https://example.com/a_(b) and (https://example.com/c)."},
{"Is it https://example.com?", "Is it https://example.com?"},
// Marks inside a URL stay part of it.
{"Home: https://example.com/~bob/__init__.py", "Home: https://example.com/~bob/__init__.py"},
{"https://example.com/~alice/_drafts_/post", "https://example.com/~alice/_drafts_/post"},
{"https://example.com/a*b*c", "https://example.com/a*b*c"},
{"Logs: https://kibana.lan/app/discover#/?_a=(index:'logs-*',query:(language:kuery,query:'host:*'))",
"Logs: https://kibana.lan/app/discover#/?_a=(index:'logs-*',query:(language:kuery,query:'host:*'))"},
{"\uE100 literal", " literal"},
}
for _, tt := range tests {
body, _ := modules.MarkdownBody(tt.in)
if len(body) != 1 || body[0].Text != tt.want {
t.Errorf("%q: %+v, want the text %q", tt.in, body, tt.want)
}
}
_, links := modules.MarkdownBody("[docs](https://example.com/docs) [local](/x) [mail](mailto:a@b)")
if len(links) != 1 || links[0] != (modules.Link{Label: "docs", URL: "https://example.com/docs"}) {
t.Errorf("links %+v, want only the https one", links)
}
}
func TestMarkdownLines(t *testing.T) {
tests := []struct {
in string
want []receipt.Element
}{
{"# H1\n## H2\n### H3 ###", []receipt.Element{
{Type: "text", Text: "H1", Bold: true}, {Type: "text", Text: "H2", Bold: true}, {Type: "text", Text: "H3", Bold: true}}},
{"- a\n* b\n+ c", []receipt.Element{{Type: "list", Bullet: "dot", Items: []string{"a", "b", "c"}}}},
{"1. a\n2) b\n10. c", []receipt.Element{{Type: "list", Bullet: "number", Items: []string{"a", "b", "c"}}}},
{"- a\n1. b", []receipt.Element{
{Type: "list", Bullet: "dot", Items: []string{"a"}}, {Type: "list", Bullet: "number", Items: []string{"b"}}}},
{"> one\n> two", []receipt.Element{{Type: "text", Text: "│ one\n│ two"}}},
{"---\n***\n- - -", []receipt.Element{{Type: "rule"}, {Type: "rule"}, {Type: "rule"}}},
{"a\n\n\n\nb\n\n", []receipt.Element{{Type: "text", Text: "a"}, {Type: "feed"}, {Type: "text", Text: "b"}}},
{"\n\na", []receipt.Element{{Type: "text", Text: "a"}}},
{"plain\nlines", []receipt.Element{{Type: "text", Text: "plain\nlines"}}},
{"-not a list\n#not a heading", []receipt.Element{{Type: "text", Text: "-not a list\n#not a heading"}}},
}
for _, tt := range tests {
got, _ := modules.MarkdownBody(tt.in)
if !sameElements(got, tt.want) {
t.Errorf("%q:\n got %+v\nwant %+v", tt.in, got, tt.want)
}
}
fence, _ := modules.MarkdownBody("```sh\n**kept** as written\n- not a list\n```")
if len(fence) != 1 || fence[0].Text != "**kept** as written\n- not a list" || fence[0].Wrap == nil || *fence[0].Wrap {
t.Errorf("fence: %+v", fence)
}
}
func sameElements(a, b []receipt.Element) bool {
if len(a) != len(b) {
return false
}
for i := range a {
x, y := a[i], b[i]
if x.Type != y.Type || x.Text != y.Text || x.Bold != y.Bold || x.Bullet != y.Bullet ||
strings.Join(x.Items, "|") != strings.Join(y.Items, "|") {
return false
}
}
return true
}
// FuzzMarkdown lays out any text as markdown in a box: it must never
// panic, always build a valid job, and every line it prints must fit the
// paper.
func FuzzMarkdown(f *testing.F) {
for _, seed := range []string{
"# H\n- a\n1. b\n> q\n---\n```\ncode\n```\n**b** _i_ [l](https://x/) ![a](u)",
"```\nunclosed",
"- \n#\n>\n- [ ] task",
strings.Repeat("- item\n", 250),
"\\*\\_\\`\\\\",
"\uE02A literal private use",
"**https://example.com/status** ~~https://old.example.com~~ Run https://ci.example.com/job/`nightly` (https://example.com/c).",
} {
f.Add(seed)
}
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
f.Fatal(err)
}
renderer := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000,
}, noFetch{})
columns := profile.Columns(escpos.FontA)
env := modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
f.Fuzz(func(t *testing.T, text string) {
modules.MarkdownBody(text)
for _, priority := range []int{1, 3, 5} {
n := modules.Notice{Title: "T", Message: text, Markdown: true, Priority: priority}
job, _ := modules.Card(n, modules.CardOptions{MaxLines: 400}, env)
if job.Elements[0].Type == receipt.TypeText {
t.Fatalf("priority %d: the card fell back to the plain receipt", priority)
}
p, err := renderer.Preview(context.Background(), job)
if err != nil {
t.Fatalf("priority %d: Preview: %v", priority, err)
}
for _, line := range p.Lines {
if line.Kind != escpos.LineText || smallFont(line) {
continue
}
if utf8.RuneCountInString(line.Text) > columns {
t.Fatalf("priority %d: line %q is longer than %d columns", priority, line.Text, columns)
}
}
}
})
}
// smallFont reports whether line prints in Font B, whose lines are longer.
func smallFont(line escpos.PreviewLine) bool {
for _, r := range line.Runs {
if r.Font == escpos.FontB {
return true
}
}
return false
}
+112
View File
@@ -0,0 +1,112 @@
package modules
import (
"maps"
"strings"
"uberbringer/internal/pkg/receipt"
)
// maxTitleMarkers is how many tag markers go in front of a title.
const maxTitleMarkers = 2
// tagMarkers are the markers printed for ntfy's emoji tags, by tag. Every
// glyph prints on CP437.
var tagMarkers = map[string]string{
"warning": "[!]",
"rotating_light": "(!)",
"fire": "(!)",
"boom": "(!)",
"white_check_mark": "[√]",
"heavy_check_mark": "[√]",
"ballot_box_with_check": "[√]",
"x": "[x]",
"negative_squared_cross_mark": "[x]",
"no_entry": "[x]",
"no_entry_sign": "[x]",
"information_source": "(i)",
"question": "(?)",
"+1": "(+1)",
"thumbsup": "(+1)",
"-1": "(-1)",
"thumbsdown": "(-1)",
"loudspeaker": "<!>",
"mega": "<!>",
"tada": `\o/`,
"skull": "x_x",
"hourglass": "(...)",
}
// typedEmoji are emoji typed into a text that print as the marker of a
// tag. A variation selector after one is removed with the other emoji.
var typedEmoji = []struct{ emoji, tag string }{
{"⚠", "warning"},
{"✅", "white_check_mark"},
{"❌", "x"},
{"🚨", "rotating_light"},
{"👍", "+1"},
}
// Markers maps tags to the markers printed for them. A tag with an empty
// marker is hidden.
type Markers map[string]string
// NewMarkers returns the built-in markers with overrides applied. A key of
// overrides is a tag; an empty value hides it.
func NewMarkers(overrides map[string]string) Markers {
m := maps.Clone(tagMarkers)
for tag, marker := range overrides {
m[strings.ToLower(tag)] = marker
}
return m
}
// lookup returns the marker for tag, matched in lower case, and whether
// the tag has one: an empty marker hides the tag.
func (m Markers) lookup(tag string) (string, bool) {
marker, ok := m[strings.ToLower(tag)]
return marker, ok
}
// clean prepares text from a notification for the card: the typed emoji
// that have markers become them, and the other emoji are removed, those
// whose tag is hidden too.
func (m Markers) clean(s string) string {
for _, e := range typedEmoji {
if !strings.Contains(s, e.emoji) {
continue
}
if marker, _ := m.lookup(e.tag); marker != "" {
s = strings.ReplaceAll(s, e.emoji, marker)
}
}
return receipt.StripEmoji(s)
}
// sortTags splits the first MaxTags tags into the markers for the title,
// at most maxTitleMarkers of them and each once, and the tags printed as
// text: those without a marker and those with one when the title has no
// room for it, cleaned and cut to MaxTag. Hidden tags, and tags that
// cleaning leaves empty, appear in neither.
func (m Markers) sortTags(tags []string) (markers, text []string) {
seen := make(map[string]bool)
for _, tag := range tags[:min(len(tags), MaxTags)] {
tag = strings.TrimSpace(tag)
if tag == "" {
continue
}
marker, ok := m.lookup(tag)
switch {
case ok && marker == "":
case ok && seen[marker]:
case ok && len(markers) < maxTitleMarkers:
seen[marker] = true
markers = append(markers, marker)
default:
if tag = cut(strings.TrimSpace(m.clean(tag)), MaxTag); tag != "" {
text = append(text, tag)
}
}
}
return markers, text
}
+3 -3
View File
@@ -20,7 +20,7 @@ import (
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
var update = flag.Bool("update", false, "rewrite the golden previews in testdata/*/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
@@ -117,8 +117,8 @@ func TestNoteGoldens(t *testing.T) {
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
// TestNoteShoppingList pins the preview of a titled note with a checklist.
func TestNoteShoppingList(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
+171
View File
@@ -0,0 +1,171 @@
package modules
import (
"net/url"
"path"
"strings"
"time"
)
// Priorities of a Notice.
const (
minPriority = 1
defaultPriority = 3
highPriority = 4
maxPriority = 5
)
// Notice limits. notify refuses a payload over them, and a card cuts what
// is longer, so that a notification from any source prints at a bounded
// length. Lengths are in characters, except where they say bytes.
const (
MaxTitle = 250
MaxTopic = 64 // as ntfy's topic names
MaxTags = 20
MaxTag = 64
MaxLabel = 64
MaxFileName = 128
MaxMessage = 4096 // bytes, as ntfy's default message limit
MaxURL = 2000 // bytes
)
// priorityNames are the names a priority may be given by, as ntfy takes
// them.
var priorityNames = map[string]int{
"min": 1,
"low": 2,
"default": 3,
"high": 4,
"max": 5,
"urgent": 5,
}
// Notice is a notification to print: what the notify module takes, and
// what an ntfy message carries.
type Notice struct {
// ID is the notification's ID at its source, if it has one.
ID string
Topic string
Title string
Message string
// Markdown is set when Message is written in markdown.
Markdown bool
// Priority is 1-5; any other value counts as 3.
Priority int
Tags []string
// Time is when the notification was sent. The zero time means the
// time the card is built.
Time time.Time
// Links are the URLs the notification points to, in order.
Links []Link
// Image is the URL of an image to print.
Image string
// File is an attached file. An image the printer can print is printed;
// any other file is named.
File *File
// Updated is set when the notification is known to replace one printed
// before; its title is then marked "(updated)". One message on its own
// cannot tell, so the notify and ntfy modules never set it.
Updated bool
}
// Link is a URL a notification points to, with its label if it has one.
type Link struct {
Label string
URL string
}
// File is a file attached to a notification.
type File struct {
Name string
// Type is the media type, e.g. image/png; it may be empty.
Type string
// Size is in bytes; 0 when unknown.
Size int64
URL string
// Expires is when the file stops being available; the zero time means
// never.
Expires time.Time
}
// priority returns n's priority, with a value outside 1-5 counted as the
// default.
func (n Notice) priority() int {
if n.Priority < minPriority || n.Priority > maxPriority {
return defaultPriority
}
return n.Priority
}
// printableImageTypes are the media types the renderer decodes, and
// printableImageExts the file name extensions it takes as them.
var (
printableImageTypes = []string{"image/png", "image/jpeg", "image/gif", "image/webp"}
printableImageExts = []string{".png", ".jpg", ".jpeg", ".gif", ".webp"}
)
// printableImage reports whether f is an image the renderer can print:
// its type says so, or it has no type and its name or URL ends in an image
// extension.
func (f File) printableImage() bool {
if f.Type != "" {
media, _, _ := strings.Cut(strings.ToLower(f.Type), ";")
return containsFold(printableImageTypes, strings.TrimSpace(media))
}
for _, name := range []string{f.Name, urlPath(f.URL)} {
if containsFold(printableImageExts, path.Ext(name)) {
return true
}
}
return false
}
// expired reports whether f is no longer available at now.
func (f File) expired(now time.Time) bool {
return !f.Expires.IsZero() && !now.Before(f.Expires)
}
// webURL reports whether s is an absolute http or https URL.
func webURL(s string) bool {
u, err := url.Parse(s)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
}
// urlPath returns the path of the URL s, or "" if it is not one.
func urlPath(s string) string {
u, err := url.Parse(s)
if err != nil {
return ""
}
return u.Path
}
// shortURL is the host and path of the URL s, without a trailing slash,
// e.g. grafana.lan/d/disk.
func shortURL(s string) string {
u, err := url.Parse(s)
if err != nil || u.Host == "" {
return s
}
return strings.TrimSuffix(u.Host+u.Path, "/")
}
// fileName is the last path segment of the URL s, or its host.
func fileName(s string) string {
if name := path.Base(urlPath(s)); name != "." && name != "/" && name != "" {
return name
}
return shortURL(s)
}
+230
View File
@@ -0,0 +1,230 @@
package modules
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/receipt"
)
// Notify payload limits, besides the notice limits.
const (
// MaxNotifyActions is how many actions a notification may have. With
// click, at most maxLinks links print in all.
MaxNotifyActions = 3
// maxUnixSeconds is the last second of the year 9999.
maxUnixSeconds = 253402300799
)
// Notify returns the notify module: a notification card from a title,
// message, priority and tags, for scripts, cron jobs and phone shortcuts.
func Notify() Module {
return notify{}
}
type notify struct{}
// notifyPayload is the body of a notification. priority and time take a
// number or a string, so they are checked after decoding.
type notifyPayload struct {
Title string `json:"title"`
Message string `json:"message"`
Priority any `json:"priority"`
Tags []string `json:"tags"`
Topic string `json:"topic"`
Click string `json:"click"`
Markdown bool `json:"markdown"`
Time any `json:"time"`
Actions []json.RawMessage `json:"actions"`
Image string `json:"image"`
}
// notifyAction is a link of a notification.
type notifyAction struct {
Label string `json:"label"`
URL string `json:"url"`
}
func (notify) Name() string { return "notify" }
func (notify) Description() string {
return "Notification card from title, message, priority and tags"
}
// Build lays the notification out as a card.
func (notify) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notifyPayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
n, problems := p.notice()
if len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
return noticeJob(n, env)
}
// notice checks the payload and turns it into a Notice.
func (p notifyPayload) notice() (Notice, []string) {
n := Notice{
Topic: p.Topic,
Title: p.Title,
Message: p.Message,
Markdown: p.Markdown,
Tags: p.Tags,
Image: p.Image,
}
var problems []string
switch size := len(p.Message); {
case strings.TrimSpace(p.Message) == "":
problems = append(problems, "message: required")
case size > MaxMessage:
problems = append(problems, fmt.Sprintf("message: %d bytes, limit is %d", size, MaxMessage))
}
problems = append(problems, tooLong("title", p.Title, MaxTitle)...)
problems = append(problems, tooLong("topic", p.Topic, MaxTopic)...)
if count := len(p.Tags); count > MaxTags {
problems = append(problems, fmt.Sprintf("tags: %d tags, limit is %d", count, MaxTags))
}
for i, tag := range p.Tags {
problems = append(problems, tooLong(fmt.Sprintf("tags[%d]", i), tag, MaxTag)...)
}
var err error
if n.Priority, err = parsePriority(p.Priority); err != nil {
problems = append(problems, "priority: "+err.Error())
}
if n.Time, err = parseTime(p.Time); err != nil {
problems = append(problems, "time: "+err.Error())
}
if p.Click != "" {
if problem := urlProblem("click", p.Click); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link{URL: p.Click})
}
}
if p.Image != "" {
if problem := urlProblem("image", p.Image); problem != "" {
problems = append(problems, problem)
}
}
if count := len(p.Actions); count > MaxNotifyActions {
problems = append(problems, fmt.Sprintf("actions: %d actions, limit is %d", count, MaxNotifyActions))
}
for i, raw := range p.Actions {
field := fmt.Sprintf("actions[%d]", i)
var a notifyAction
if err := DecodeStrict(raw, &a); err != nil {
problems = append(problems, nestedProblems(field, err)...)
continue
}
problems = append(problems, tooLong(field+".label", a.Label, MaxLabel)...)
if a.URL == "" {
problems = append(problems, field+".url: required")
} else if problem := urlProblem(field+".url", a.URL); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link(a))
}
}
return n, problems
}
// tooLong returns a problem for field when s is longer than limit
// characters.
func tooLong(field, s string, limit int) []string {
if n := utf8.RuneCountInString(s); n > limit {
return []string{fmt.Sprintf("%s: %d characters, limit is %d", field, n, limit)}
}
return nil
}
// urlProblem returns the problem with field's URL s, or "".
func urlProblem(field, s string) string {
switch {
case !webURL(s):
return field + ": must be an http or https URL"
case len(s) > MaxURL:
return fmt.Sprintf("%s: %d bytes, limit is %d", field, len(s), MaxURL)
}
return ""
}
// nestedProblems prefixes each problem of a nested object's *PayloadError
// with field, the object's place in the payload.
func nestedProblems(field string, err error) []string {
var pe *PayloadError
if !errors.As(err, &pe) {
return []string{field + ": " + err.Error()}
}
problems := make([]string, len(pe.Problems))
for i, problem := range pe.Problems {
if rest, ok := strings.CutPrefix(problem, "body: "); ok {
problems[i] = field + ": " + rest
continue
}
problems[i] = field + "." + problem
}
return problems
}
// parsePriority reads a priority given as 1-5 or by name. nil is the
// default priority.
func parsePriority(v any) (int, error) {
bad := fmt.Errorf("must be 1-5, or min, low, default, high, max or urgent")
switch p := v.(type) {
case nil:
return defaultPriority, nil
case float64:
if p != math.Trunc(p) || p < minPriority || p > maxPriority {
return 0, bad
}
return int(p), nil
case string:
s := strings.ToLower(strings.TrimSpace(p))
if n, ok := priorityNames[s]; ok {
return n, nil
}
if n, err := strconv.Atoi(s); err == nil && n >= minPriority && n <= maxPriority {
return n, nil
}
}
return 0, bad
}
// parseTime reads a time given as Unix seconds or in RFC 3339. nil is the
// zero time, which stands for the time the card is built.
func parseTime(v any) (time.Time, error) {
bad := fmt.Errorf("must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z")
switch t := v.(type) {
case nil:
return time.Time{}, nil
case float64:
if t != math.Trunc(t) || t <= 0 || t > maxUnixSeconds {
return time.Time{}, bad
}
return time.Unix(int64(t), 0), nil
case string:
parsed, err := time.Parse(time.RFC3339, strings.TrimSpace(t))
if err == nil {
return parsed, nil
}
}
return time.Time{}, bad
}
// noticeJob lays out n as a card with the options in env. A *FallbackError
// comes with the plain receipt, which still prints.
func noticeJob(n Notice, env Env) (receipt.Job, error) {
return Card(n, env.Card, env)
}
+124
View File
@@ -0,0 +1,124 @@
package modules
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// Ntfy returns the ntfy module: the card of one ntfy message, as the ntfy
// command line client passes it to a command in $NTFY_RAW.
func Ntfy() Module {
return ntfyModule{}
}
type ntfyModule struct{}
func (ntfyModule) Name() string { return "ntfy" }
func (ntfyModule) Description() string {
return "One ntfy message object, e.g. the CLI's $NTFY_RAW"
}
// Build lays out the message as a card. The body is decoded leniently:
// fields it does not know are ignored, so that messages from newer ntfy
// versions still print. Events other than message, and messages with a
// binary body, give ErrSkip.
func (ntfyModule) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
m, err := decodeNtfy(body)
if err != nil {
return receipt.Job{}, err
}
n, err := FromNtfy(m)
if err != nil {
return receipt.Job{}, err
}
return noticeJob(n, env)
}
// decodeNtfy decodes body, one JSON object, as an ntfy message, ignoring
// unknown fields. A problem is returned as a *PayloadError.
func decodeNtfy(body []byte) (ntfy.Message, error) {
var (
object map[string]json.RawMessage
m ntfy.Message
)
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return m, &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return m, &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return m, &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
if err := json.Unmarshal(body, &m); err != nil {
var typeErr *json.UnmarshalTypeError
if errors.As(err, &typeErr) && typeErr.Field != "" {
return m, &PayloadError{Problems: []string{fmt.Sprintf("%s: expected %s", typeErr.Field, describe(typeErr.Type))}}
}
return m, &PayloadError{Problems: []string{"body: " + err.Error()}}
}
return m, nil
}
// FromNtfy turns an ntfy message into a Notice. It returns ErrSkip for an
// event other than message, such as open or keepalive, and for a message
// whose body is binary (encoding base64). A message without an event
// counts as a message.
//
// The links are the click URL and the view actions' URLs; the other
// actions are left out, since their headers, bodies and values can hold
// secrets. The text ntfy gives a file sent without a message is dropped,
// since the file prints on its own. The notice is never marked as an
// update: a publisher may choose a message's sequence ID, so one message
// cannot tell the first of its sequence from one that replaces it.
func FromNtfy(m ntfy.Message) (Notice, error) {
switch m.Event {
case "", ntfy.EventMessage:
default:
return Notice{}, ErrSkip
}
if strings.EqualFold(m.Encoding, ntfy.EncodingBase64) {
return Notice{}, ErrSkip
}
n := Notice{
ID: m.ID,
Topic: m.Topic,
Title: m.Title,
Message: m.Message,
Markdown: strings.EqualFold(m.ContentType, ntfy.ContentTypeMarkdown),
Priority: m.Priority(),
Tags: m.Tags,
}
if m.Time > 0 {
n.Time = time.Unix(m.Time, 0)
}
if m.Click != "" {
n.Links = append(n.Links, Link{URL: m.Click})
}
for _, a := range m.Actions {
if strings.EqualFold(a.Action, ntfy.ActionView) {
n.Links = append(n.Links, Link{Label: a.Label, URL: a.URL})
}
}
if a := m.Attachment; a != nil && a.URL != "" {
if n.Message == fmt.Sprintf(ntfy.AttachmentMessage, a.Name) {
n.Message = ""
}
n.File = &File{Name: a.Name, Type: a.Type, Size: a.Size, URL: a.URL}
if a.Expires > 0 {
n.File.Expires = time.Unix(a.Expires, 0)
}
}
return n, nil
}
+19 -4
View File
@@ -32,8 +32,9 @@ func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
// Env is what a module may know when it builds a receipt: the time it is
// built at, how times print and how notifications are laid out. A module
// never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
@@ -44,15 +45,27 @@ type Env struct {
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
// Card shapes the cards of the notification modules.
Card CardOptions
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
return e.Format(e.Now)
}
// Format returns t in Location, formatted with TimeLayout. The zero time
// stands for Now.
func (e Env) Format(t time.Time) string {
if t.IsZero() {
t = e.Now
}
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
return t.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
@@ -67,7 +80,9 @@ type Module interface {
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
// Job.Validate; one that does not is a bug in the module. A
// *FallbackError comes with a plain job that still prints: the module
// met a bug of its own and printed what it could.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+11
View File
@@ -0,0 +1,11 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+11
View File
@@ -0,0 +1,11 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── HIGH · alerts · 29 Nov 21:04 ──────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+13
View File
@@ -0,0 +1,13 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ [!] Disk almost full ║
╠════════════════════════════════════════╣
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+13
View File
@@ -0,0 +1,13 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ [!] Disk almost full ║
╠════════════════════════════════════════╣
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── URGENT · alerts · 29 Nov 21:04 ────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+22
View File
@@ -0,0 +1,22 @@
# Deployed
The **web** and __api__ services are *live* on ~~staging~~ production.
## Changes
- Faster `search`
* New [status page](https://status.example.com)
+ Fixed _login_ loop in snake_case_name, a long item that wraps onto a second line
1. Drain
2. Migrate
3. Restart
> Rollback with make rollback if anything breaks, quoted on two lines
> of its own.
---
```
$ kubectl get pods
web-7d9f-very-long-pod-name-that-is-longer-than-the-box 1/1 Running
```
![chart](https://example.com/chart.png)
Escaped \*stars\* stay.
+29
View File
@@ -0,0 +1,29 @@
┌────────────────────────────────────────┐
│ Deployed │
│ The web and api services are live on │
│ staging production. │
│ │
│ Changes │
│ · Faster search │
│ · New status page │
│ · Fixed login loop in snake_case_name, │
│ a long item that wraps onto a second │
│ line │
│ │
│ 1. Drain │
│ 2. Migrate │
│ 3. Restart │
│ │
│ │ Rollback with make rollback if │
│ anything breaks, quoted on two lines │
│ │ of its own. │
│ │
├────────────────────────────────────────┤
│ $ kubectl get pods │
│ web-7d9f-very-long-pod-name-that-is-lo │
│ nger-than-the-box 1/1 Running │
│ [image: chart] │
│ Escaped *stars* stay. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
link: status page -> https://status.example.com
+4
View File
@@ -0,0 +1,4 @@
{"title":"Disk almost full","message":"/var is at 94% on nas01","priority":"high","tags":["warning","nas01"],
"topic":"alerts","click":"https://grafana.lan/d/disk","markdown":false,"time":"2025-11-29T21:04:05Z",
"actions":[{"label":"Open dashboard","url":"https://grafana.lan/d/disk"},{"label":"Runbook","url":"https://wiki.lan/runbooks/disk-full"}],
"image":"https://grafana.lan/render/disk.png"}
+16
View File
@@ -0,0 +1,16 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
[qr: https://wiki.lan/runbooks/disk-full]
Runbook
[image 384 dots: disk.png]
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title":"Log tail","topic":"logs","priority":3,"message":"line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\nline 13\nline 14\nline 15\nline 16\nline 17\nline 18\nline 19\nline 20\nline 21\nline 22\nline 23\nline 24\nline 25\nline 26\nline 27\nline 28\nline 29\nline 30\nline 31\nline 32\nline 33\nline 34\nline 35\nline 36\nline 37\nline 38\nline 39\nline 40\nline 41\nline 42\nline 43\n\n"}
+44
View File
@@ -0,0 +1,44 @@
┌─ Log tail ─────────────────────────────┐
│ line 1 │
│ line 2 │
│ line 3 │
│ line 4 │
│ line 5 │
│ line 6 │
│ line 7 │
│ line 8 │
│ line 9 │
│ line 10 │
│ line 11 │
│ line 12 │
│ line 13 │
│ line 14 │
│ line 15 │
│ line 16 │
│ line 17 │
│ line 18 │
│ line 19 │
│ line 20 │
│ line 21 │
│ line 22 │
│ line 23 │
│ line 24 │
│ line 25 │
│ line 26 │
│ line 27 │
│ line 28 │
│ line 29 │
│ line 30 │
│ line 31 │
│ line 32 │
│ line 33 │
│ line 34 │
│ line 35 │
│ line 36 │
│ line 37 │
│ line 38 │
│ line 39 │
│ line 40 │
│ ... 3 more lines │
└───────────────── logs · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title":"Shopping","message":"## Today\n- milk\n- **eggs**\n\nSee [the list](https://lists.example.com/shopping)","markdown":true,"priority":2,"time":1764450245}
+11
View File
@@ -0,0 +1,11 @@
── 29 Nov 21:04 ──────────────────────────
Shopping
Today
· milk
· eggs
See the list
[qr: https://lists.example.com/shopping]
the list
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"message":"Back at 3"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Notification ─────────────────────────┐
│ Back at 3 │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,6 @@
{"id":"Act0Private1","time":1764450245,"event":"message","topic":"home","title":"Garage open","message":"The garage door has been open for 10 minutes.","priority":4,
"actions":[
{"id":"a1","action":"http","label":"Close door","url":"https://hooks.example.com/garage/close-SECRETPATH","method":"POST","headers":{"Authorization":"Bearer SECRETHEADER"},"body":"SECRETBODY","clear":true},
{"id":"a2","action":"broadcast","label":"Tasker","intent":"io.example.SECRETINTENT","extras":{"cmd":"SECRETEXTRA"},"clear":false},
{"id":"a3","action":"copy","label":"Copy code","value":"SECRETVALUE","clear":false},
{"id":"a4","action":"view","label":"Camera","url":"https://cam.example.com/garage","clear":false}]}
+10
View File
@@ -0,0 +1,10 @@
╔═ HIGH ═════════════════════════════════╗
║ Garage open ║
╟────────────────────────────────────────╢
║ The garage door has been open for 10 ║
║ minutes. ║
╚═════════════════ home · 29 Nov 21:04 ══╝
[qr: https://cam.example.com/garage]
Camera
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Att0Expired1","time":1764400000,"event":"message","topic":"cams","title":"Doorbell","message":"Someone is at the door",
"attachment":{"name":"door.jpg","size":980,"expires":1764410000,"url":"https://ntfy.example.com/file/Att0Expired1.jpg"}}
@@ -0,0 +1,6 @@
┌─ Doorbell ─────────────────────────────┐
│ Someone is at the door │
│ │
│ File ................ door.jpg (980 B) │
└───────────────── cams · 29 Nov 07:06 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,3 @@
{"id":"Att0File0001","time":1764450245,"event":"message","topic":"reports","priority":3,
"message":"You received a file: report.pdf",
"attachment":{"name":"report.pdf","type":"application/pdf","size":1468006,"expires":1764461045,"url":"https://ntfy.example.com/file/Att0File0001.pdf"}}
@@ -0,0 +1,4 @@
┌─ reports ──────────────────────────────┐
│ File ............. report.pdf (1.4 MB) │
└────────────── reports · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Att0Untyped1","time":1764450245,"event":"message","topic":"cams","title":"Doorbell","message":"Someone is at the door",
"attachment":{"name":"door.jpg","url":"https://ntfy.example.com/file/Att0Untyped1.jpg"}}
@@ -0,0 +1,6 @@
┌─ Doorbell ─────────────────────────────┐
│ Someone is at the door │
└───────────────── cams · 29 Nov 21:04 ──┘
[image 384 dots: Att0Untyped1.jpg]
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Emoji0000001","time":1764450245,"event":"message","topic":"home","title":"✅ Laundry done 🎉","message":"⚠️ Empty the lint filter 🧺\n👍 Thanks!","priority":3,"tags":["tada","skull","fire","hourglass","custom tag"]}
+7
View File
@@ -0,0 +1,7 @@
┌─ \o/ x_x [√] Laundry done ─────────────┐
│ [!] Empty the lint filter │
│ (+1) Thanks! │
│ │
│ Tags: fire, hourglass, custom tag │
└───────────────── home · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+2
View File
@@ -0,0 +1,2 @@
{"id":"Md0000000001","time":1764450245,"event":"message","topic":"deploys","title":"Release v2.4.0","content_type":"text/markdown",
"message":"# Deployed\nThe **web** and __api__ services are *live* on ~~staging~~ production.\n\n## Changes\n- Faster `search`\n* New [status page](https://status.example.com)\n+ Fixed _login_ loop in snake_case_name\n\n1. Drain\n2. Migrate\n3. Restart\n\n> Rollback with make rollback\n> if anything breaks.\n\n---\n```\n$ kubectl get pods\nweb-7d9f 1/1 Running\n```\n![chart](https://example.com/chart.png)\nEscaped \\*stars\\* stay.","priority":3}
+27
View File
@@ -0,0 +1,27 @@
┌─ Release v2.4.0 ───────────────────────┐
│ Deployed │
│ The web and api services are live on │
│ staging production. │
│ │
│ Changes │
│ · Faster search │
│ · New status page │
│ · Fixed login loop in snake_case_name │
│ │
│ 1. Drain │
│ 2. Migrate │
│ 3. Restart │
│ │
│ │ Rollback with make rollback │
│ │ if anything breaks. │
│ │
├────────────────────────────────────────┤
│ $ kubectl get pods │
│ web-7d9f 1/1 Running │
│ [image: chart] │
│ Escaped *stars* stay. │
└────────────── deploys · 29 Nov 21:04 ──┘
[qr: https://status.example.com]
status page
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"NoTitle00001","time":1764450245,"event":"message","topic":"alerts","message":"Just a message"}
+4
View File
@@ -0,0 +1,4 @@
┌─ alerts ───────────────────────────────┐
│ Just a message │
└─────────────── alerts · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Kq7vN2pX9aLe","time":1764385920,"event":"message","topic":"backups","title":"Nightly backup",
"message":"restic: 2.1 GB added in 14m 02s, 0 errors.","tags":["white_check_mark","restic"]}
@@ -0,0 +1,7 @@
┌─ [√] Nightly backup ───────────────────┐
│ restic: 2.1 GB added in 14m 02s, 0 │
│ errors. │
│ │
│ Tags: restic │
└────────────── backups · 29 Nov 03:12 ──┘
- - - - - - - partial cut - - - - - - - -
+5
View File
@@ -0,0 +1,5 @@
{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",
"message":"**/var** is at *94%* on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"],
"click":"https://grafana.lan/d/disk",
"actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}],
"attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/file/sPs71M8A2Tq9.png"}}
+13
View File
@@ -0,0 +1,13 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
[image 384 dots: sPs71M8A2Tq9.png]
- - - - - - - partial cut - - - - - - - -
+2
View File
@@ -0,0 +1,2 @@
{"id":"Zp4cW8mR1sYb","time":1764385920,"event":"message","topic":"backups","title":"Prune finished",
"message":"41 snapshots kept, 3 removed.","priority":1}
+4
View File
@@ -0,0 +1,4 @@
── backups · 29 Nov 03:12 ────────────────
Prune finished
41 snapshots kept, 3 removed.
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups","title":"Backup FAILED on nas01",
"message":"Job nightly-offsite exited with code 2 after 3h12m. Last good run: 2 days ago.","priority":5,"tags":["rotating_light"]}
+10
View File
@@ -0,0 +1,10 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ (!) Backup FAILED on nas01 ║
╠════════════════════════════════════════╣
║ Job nightly-offsite exited with code 2 ║
║ after 3h12m. Last good run: 2 days ║
║ ago. ║
╚══════════════ backups · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Upd0Second01","sequence_id":"Upd0First001","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full","message":"/var is at 97% on nas01","priority":4,"tags":["warning"]}
+6
View File
@@ -0,0 +1,6 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 97% on nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"id":"Future000001","time":1764450245,"event":"message","topic":"alerts","message":"From a newer ntfy","priority":3,"icon":"https://example.com/icon.png","poll_id":"x","future_field":{"nested":[1,2,3]},"expires":1764536645}
+4
View File
@@ -0,0 +1,4 @@
┌─ alerts ───────────────────────────────┐
│ From a newer ntfy │
└─────────────── alerts · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Kq7vN2pX9aLe","time":1796063393,"event":"message","topic":"backups","title":"Nightly backup","message":"restic: 2.1 GB added in 14m 02s, 0 errors.","tags":["white_check_mark","restic"]}
+1
View File
@@ -0,0 +1 @@
{"id":"sPs71M8A2Tq9","time":1796063393,"event":"message","topic":"alerts","title":"Disk almost full","message":"**/var** is at *94%* on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"],"click":"https://grafana.lan/d/disk","actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}],"attachment":{"name":"graph.png","type":"image/png","size":884,"expires":1796074193,"url":"http://127.0.0.1:8099/graph.png"}}
+1
View File
@@ -0,0 +1 @@
{"id":"Zp4cW8mR1sYb","time":1796063393,"event":"message","topic":"backups","title":"Prune finished","message":"41 snapshots kept, 3 removed.","priority":1}
+1
View File
@@ -0,0 +1 @@
{"id":"Fb2xQm81kTz0","time":1796063393,"event":"message","topic":"backups","title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. Last good run: 2 days ago.","priority":5,"tags":["rotating_light"]}