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>
264 lines
8.1 KiB
Go
264 lines
8.1 KiB
Go
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;
|
|
// -  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 }
|