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 }