Add the notify and ntfy modules and scoped tokens
Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fa15cb27b1
commit
1335ed0687
119 files changed
+5626
-468
No files matched your search
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
@@ -140,20 +142,24 @@ func newSecretCommand() *cobra.Command {
|
||||
}
|
||||
|
||||
func newTokenCommand(configPath *string) *cobra.Command {
|
||||
var (
|
||||
subject string
|
||||
ttl time.Duration
|
||||
)
|
||||
var spec tokenSpec
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
Short: "Prints a bearer token signed with the config's api.secret.",
|
||||
Args: cobra.NoArgs,
|
||||
Long: "Prints a bearer token signed with the config's api.secret. A token may use every\n" +
|
||||
"route except that only one issued with --raw prints jobs with raw ESC/POS elements.\n" +
|
||||
"With --modules, the token may only print and preview through those modules and\n" +
|
||||
"read job status and the module list: give integrations such as ntfy one of these.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if err := spec.check(cmd.Flags().Changed("modules")); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
|
||||
token, err := signToken([]byte(cfg.API.Secret), spec, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -161,11 +167,62 @@ func newTokenCommand(configPath *string) *cobra.Command {
|
||||
return err
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||
cmd.Flags().StringVar(&spec.subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||
cmd.Flags().DurationVar(&spec.ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||
cmd.Flags().StringSliceVar(&spec.modules, "modules", nil,
|
||||
"limit the token to these modules' routes, e.g. ntfy,notify")
|
||||
cmd.Flags().BoolVar(&spec.raw, "raw", false, "let the token print jobs with raw ESC/POS elements")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// tokenSpec is what a token is issued for.
|
||||
type tokenSpec struct {
|
||||
subject string
|
||||
|
||||
// ttl is the token's lifetime; zero means no expiry.
|
||||
ttl time.Duration
|
||||
|
||||
// modules, when not nil, limits the token to these modules' routes.
|
||||
modules []string
|
||||
|
||||
// raw lets the token print raw ESC/POS.
|
||||
raw bool
|
||||
}
|
||||
|
||||
// check refuses a spec the daemon could not honour. limited is set when
|
||||
// --modules was given, even with no names.
|
||||
func (s *tokenSpec) check(limited bool) error {
|
||||
if !limited {
|
||||
return nil
|
||||
}
|
||||
if s.raw {
|
||||
return fmt.Errorf("--raw does nothing with --modules: a token limited to modules cannot reach /api/v1/print")
|
||||
}
|
||||
registry, err := newModules()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var names []string
|
||||
for _, info := range registry.List() {
|
||||
names = append(names, info.Name)
|
||||
}
|
||||
var modules []string
|
||||
for _, name := range s.modules {
|
||||
name = strings.TrimSpace(name)
|
||||
if _, ok := registry.Get(name); !ok {
|
||||
return fmt.Errorf("--modules: unknown module %q; the modules are: %s", name, strings.Join(names, ", "))
|
||||
}
|
||||
if !slices.Contains(modules, name) {
|
||||
modules = append(modules, name)
|
||||
}
|
||||
}
|
||||
if len(modules) == 0 {
|
||||
return fmt.Errorf("--modules needs at least one module: %s", strings.Join(names, ", "))
|
||||
}
|
||||
s.modules = modules
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
|
||||
// on supported platforms; it crashes the program rather than return weak bytes.
|
||||
func newSecret() string {
|
||||
@@ -174,17 +231,21 @@ func newSecret() string {
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
|
||||
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
|
||||
if ttl < 0 {
|
||||
// signToken returns an HS256 JWT issued at now for spec.
|
||||
func signToken(secret []byte, spec tokenSpec, now time.Time) (string, error) {
|
||||
if spec.ttl < 0 {
|
||||
return "", fmt.Errorf("ttl must not be negative")
|
||||
}
|
||||
claims := jwt.RegisteredClaims{
|
||||
Subject: subject,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
claims := server.TokenClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: spec.subject,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
},
|
||||
Modules: spec.modules,
|
||||
Raw: spec.raw,
|
||||
}
|
||||
if ttl > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
|
||||
if spec.ttl > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(spec.ttl))
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
|
||||
if err != nil {
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
)
|
||||
|
||||
func runCommand(t *testing.T, args ...string) (string, error) {
|
||||
@@ -120,8 +122,64 @@ func TestTokenCommand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommandScopes(t *testing.T) {
|
||||
secret := "env-only-secret-env-only-secret-0123"
|
||||
t.Setenv("UBERBRINGER_API_SECRET", secret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
|
||||
parse := func(t *testing.T, out string) server.TokenClaims {
|
||||
t.Helper()
|
||||
var claims server.TokenClaims
|
||||
_, err := jwt.ParseWithClaims(strings.TrimSpace(out), &claims, func(*jwt.Token) (any, error) { return []byte(secret), nil },
|
||||
jwt.WithValidMethods([]string{"HS256"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return claims
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
args []string
|
||||
modules []string
|
||||
raw bool
|
||||
}{
|
||||
{nil, nil, false},
|
||||
{[]string{"--modules", "ntfy,notify"}, []string{"ntfy", "notify"}, false},
|
||||
{[]string{"--modules", "ntfy", "--modules", " ntfy , note"}, []string{"ntfy", "note"}, false},
|
||||
{[]string{"--raw"}, nil, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
|
||||
if err != nil {
|
||||
t.Errorf("%v: %v", tt.args, err)
|
||||
continue
|
||||
}
|
||||
claims := parse(t, out)
|
||||
if strings.Join(claims.Modules, ",") != strings.Join(tt.modules, ",") || (claims.Modules == nil) != (tt.modules == nil) || claims.Raw != tt.raw {
|
||||
t.Errorf("%v: claims mod %q raw %v, want %q and %v", tt.args, claims.Modules, claims.Raw, tt.modules, tt.raw)
|
||||
}
|
||||
}
|
||||
|
||||
refused := []struct {
|
||||
args []string
|
||||
wantErr string
|
||||
}{
|
||||
{[]string{"--modules", "ntfy,pager"}, `--modules: unknown module "pager"; the modules are: note, notify, ntfy`},
|
||||
{[]string{"--modules", ""}, "--modules needs at least one module: note, notify, ntfy"},
|
||||
{[]string{"--modules", "ntfy", "--raw"}, "--raw does nothing with --modules"},
|
||||
}
|
||||
for _, tt := range refused {
|
||||
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("%v: error %v, want it to contain %q", tt.args, err, tt.wantErr)
|
||||
}
|
||||
if strings.Count(out, ".") >= 2 {
|
||||
t.Errorf("%v: printed a token", tt.args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
|
||||
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
|
||||
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), tokenSpec{subject: "x"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -10,18 +10,32 @@ import (
|
||||
|
||||
// newModules returns the registry of every module the daemon offers.
|
||||
func newModules() (*modules.Registry, error) {
|
||||
return modules.NewRegistry(modules.Note())
|
||||
return modules.NewRegistry(modules.Note(), modules.Notify(), modules.Ntfy())
|
||||
}
|
||||
|
||||
// moduleEnv returns a func that gives modules the time now, in the zone and
|
||||
// layout cfg's [format] names.
|
||||
// layout cfg's [format] names, and the card options of its [ntfy] tables.
|
||||
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
|
||||
loc, err := time.LoadLocation(cfg.Format.Timezone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config format.timezone: %w", err)
|
||||
}
|
||||
layout := cfg.Format.TimeLayout
|
||||
card := cardOptions(cfg.Ntfy)
|
||||
return func() modules.Env {
|
||||
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
|
||||
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout, Card: card}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// cardOptions returns the notification layout cfg describes.
|
||||
func cardOptions(cfg config.NtfyConfig) modules.CardOptions {
|
||||
f := cfg.Format
|
||||
return modules.CardOptions{
|
||||
Style: f.Style,
|
||||
MaxLines: f.MaxLines,
|
||||
QR: f.QR,
|
||||
NoImages: !f.Images,
|
||||
NoMarkdown: !f.Markdown,
|
||||
Markers: modules.NewMarkers(cfg.Markers),
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,14 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
|
||||
// With a module name, data is that module's payload.
|
||||
func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
|
||||
job, ok, err := previewJob(ctx, cfg, data, module)
|
||||
if err != nil {
|
||||
var fallbackErr *modules.FallbackError
|
||||
switch {
|
||||
case errors.As(err, &fallbackErr):
|
||||
// The plain receipt is still shown, as it would print.
|
||||
if _, err := fmt.Fprintf(errOut, "warning: module %s: %v\n", module, fallbackErr); err != nil {
|
||||
return err
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
@@ -101,7 +108,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, module string
|
||||
|
||||
// previewJob returns the job to preview: data itself, or with a module name,
|
||||
// the job that module builds from data as its payload, at the time now. ok
|
||||
// is false when the module has nothing to print.
|
||||
// is false when the module has nothing to print. A *FallbackError comes
|
||||
// with the job that prints in its place.
|
||||
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
|
||||
if module == "" {
|
||||
job, err := receipt.DecodeJob(data)
|
||||
@@ -127,12 +135,17 @@ func previewJob(ctx context.Context, cfg *config.Config, data []byte, module str
|
||||
return job, false, err
|
||||
}
|
||||
job, err = m.Build(ctx, data, env())
|
||||
var pe *modules.PayloadError
|
||||
var (
|
||||
pe *modules.PayloadError
|
||||
fe *modules.FallbackError
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, modules.ErrSkip):
|
||||
return job, false, nil
|
||||
case errors.As(err, &pe):
|
||||
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
|
||||
case errors.As(err, &fe):
|
||||
return job, true, err
|
||||
case err != nil:
|
||||
return job, false, fmt.Errorf("module %s: %w", module, err)
|
||||
}
|
||||
|
||||
@@ -135,6 +135,75 @@ func TestPreviewCommandModule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// urgentNtfy is an ntfy message of priority 5, with the time it was sent.
|
||||
const urgentNtfy = `{"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","nas01"]}`
|
||||
|
||||
// The ntfy module previews as the server's /api/v1/preview/ntfy does, with
|
||||
// the [ntfy] tables of the config applied.
|
||||
func TestPreviewCommandNtfy(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, config string
|
||||
want []string
|
||||
}{
|
||||
{"defaults", "[format]\ntimezone = \"UTC\"\n", []string{
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"╔════════════════════════════════════════╗",
|
||||
"║ (!) Backup FAILED on nas01 ║",
|
||||
"╠════════════════════════════════════════╣",
|
||||
"║ Job nightly-offsite exited with code 2 ║",
|
||||
"║ after 3h12m. Last good run: 2 days ║",
|
||||
"║ ago. ║",
|
||||
"║ ║",
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" +
|
||||
"[ntfy.markers]\nrotating_light = \"/!\\\\\"\nnas01 = \"\"\n", []string{
|
||||
"── URGENT · backups · 29 Nov 21:04 ───────",
|
||||
"/!\\ Backup FAILED on nas01",
|
||||
"Job nightly-offsite exited with code 2",
|
||||
"after 3h12m. Last good run: 2 days ago.",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetIn(strings.NewReader(urgentNtfy))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, tt.config), "--module", "ntfy"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Join(tt.want, "\n") + "\n"
|
||||
if out.String() != want || errOut.Len() != 0 {
|
||||
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("keepalive", func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetIn(strings.NewReader(`{"id":"x","time":1764450245,"event":"keepalive","topic":"backups"}`))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "ntfy"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Len() != 0 || errOut.String() != "module ntfy has nothing to print\n" {
|
||||
t.Errorf("output %q, standard error %q", out.String(), errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The note's stamp is the time now in format.timezone and time_layout.
|
||||
func TestPreviewCommandModuleStamp(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
@@ -157,7 +226,7 @@ func TestPreviewCommandModuleErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, module, payload, want string
|
||||
}{
|
||||
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
|
||||
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note, notify, ntfy`},
|
||||
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
|
||||
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
|
||||
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
|
||||
|
||||
@@ -103,7 +103,7 @@ level = "error"
|
||||
return resp.StatusCode == http.StatusOK
|
||||
})
|
||||
|
||||
token, err := signToken([]byte(secret), "test", 0, time.Now())
|
||||
token, err := signToken([]byte(secret), tokenSpec{subject: "test"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// requireBearerToken rejects requests without a valid HS256 bearer token.
|
||||
// Tokens are only read from the Authorization header: query-string tokens
|
||||
// end up in proxy and access logs.
|
||||
// TokenClaims are the claims of a bearer token that Überbringer reads.
|
||||
// Claims other than these, such as user_id, are ignored.
|
||||
type TokenClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
// Modules, when present, limits the token to the routes of these
|
||||
// modules, job status and the module list.
|
||||
Modules []string `json:"mod,omitempty"`
|
||||
|
||||
// Raw lets the token print jobs with raw elements.
|
||||
Raw bool `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
// scopeClaims are the claims that set what a token may do.
|
||||
var scopeClaims = []string{"mod", "raw"}
|
||||
|
||||
// UnmarshalJSON decodes the claims and refuses a scope claim that could be
|
||||
// read as absent: mod given as null, and a scope claim written in another
|
||||
// letter case, which encoding/json would match too.
|
||||
func (c *TokenClaims) UnmarshalJSON(data []byte) error {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
for name := range fields {
|
||||
for _, claim := range scopeClaims {
|
||||
if name != claim && strings.EqualFold(name, claim) {
|
||||
return fmt.Errorf("claim %q: the %q claim is written in lower case", name, claim)
|
||||
}
|
||||
}
|
||||
}
|
||||
if mod, ok := fields["mod"]; ok && string(bytes.TrimSpace(mod)) == "null" {
|
||||
return errors.New(`claim "mod" is null`)
|
||||
}
|
||||
type claims TokenClaims // without this method, so that it decodes as a plain struct
|
||||
return json.Unmarshal(data, (*claims)(c))
|
||||
}
|
||||
|
||||
// tokenScope is what the request's token allows.
|
||||
type tokenScope struct {
|
||||
// limited is set for a token with a mod claim, which may use only the
|
||||
// routes of modules.
|
||||
limited bool
|
||||
modules []string
|
||||
|
||||
// raw is set for a token that may print raw ESC/POS.
|
||||
raw bool
|
||||
}
|
||||
|
||||
// tokenScopeKey stores the request's tokenScope in fiber Locals.
|
||||
type tokenScopeKey struct{}
|
||||
|
||||
// routeScope says which tokens limited to modules may use a route.
|
||||
type routeScope int
|
||||
|
||||
const (
|
||||
// scopeFull routes take only tokens without a mod claim.
|
||||
scopeFull routeScope = iota
|
||||
// scopeAny routes take every valid token.
|
||||
scopeAny
|
||||
// scopeModule routes take a token whose mod claim names the module in
|
||||
// the path, and tokens without one.
|
||||
scopeModule
|
||||
)
|
||||
|
||||
// requireBearerToken rejects requests without a valid HS256 bearer token,
|
||||
// and keeps what the token allows for the routes to check. Tokens are only
|
||||
// read from the Authorization header: query-string tokens end up in proxy
|
||||
// and access logs.
|
||||
func requireBearerToken(secret []byte) fiber.Handler {
|
||||
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
|
||||
@@ -20,14 +93,62 @@ func requireBearerToken(secret []byte) fiber.Handler {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||
return newAPIError(codeUnauthorized.withMessage("missing bearer token"))
|
||||
}
|
||||
if _, err := parser.Parse(token, keyFunc); err != nil {
|
||||
var claims TokenClaims
|
||||
if _, err := parser.ParseWithClaims(token, &claims, keyFunc); err != nil {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
|
||||
return newAPIError(codeUnauthorized.withMessage("invalid or expired token"))
|
||||
}
|
||||
c.Locals(tokenScopeKey{}, tokenScope{limited: claims.Modules != nil, modules: claims.Modules, raw: claims.Raw})
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// scopeFrom returns what the request's token allows. A request that
|
||||
// passed no token check allows nothing.
|
||||
func scopeFrom(c fiber.Ctx) tokenScope {
|
||||
scope, ok := c.Locals(tokenScopeKey{}).(tokenScope)
|
||||
if !ok {
|
||||
return tokenScope{limited: true}
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
// checkScope refuses a token limited to modules on a route its scope does
|
||||
// not include.
|
||||
func checkScope(c fiber.Ctx, route routeScope) error {
|
||||
scope := scopeFrom(c)
|
||||
if !scope.limited || route == scopeAny {
|
||||
return nil
|
||||
}
|
||||
if route == scopeModule && slices.Contains(scope.modules, c.Params("module")) {
|
||||
return nil
|
||||
}
|
||||
msg := "token is limited to job status and the module list"
|
||||
if len(scope.modules) > 0 {
|
||||
msg = "token is limited to modules " + strings.Join(scope.modules, ", ")
|
||||
}
|
||||
return newAPIError(codeTokenScope.withMessage(msg))
|
||||
}
|
||||
|
||||
// checkRaw refuses a job with raw elements unless the token may print raw
|
||||
// ESC/POS. The details name the raw elements.
|
||||
func checkRaw(c fiber.Ctx, job receipt.Job) error {
|
||||
if scopeFrom(c).raw {
|
||||
return nil
|
||||
}
|
||||
var raw []string
|
||||
for i, el := range job.Elements {
|
||||
if el.Type == receipt.TypeRaw {
|
||||
raw = append(raw, fmt.Sprintf("elements[%d] (raw)", i))
|
||||
}
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
msg := "token may not print raw ESC/POS; issue one with uberbringer token --raw"
|
||||
return newAPIError(codeTokenScope.withMessage(msg), raw...)
|
||||
}
|
||||
|
||||
// bearerToken extracts the token from an Authorization header value. The
|
||||
// scheme is case-insensitive (RFC 7235).
|
||||
func bearerToken(header string) (string, bool) {
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
)
|
||||
|
||||
// ntfyMessage is an ntfy message as the ntfy command line client passes it
|
||||
// in $NTFY_RAW.
|
||||
const ntfyMessage = `{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",` +
|
||||
`"message":"/var is at 94% on nas01","priority":4,"tags":["warning","nas01"]}`
|
||||
|
||||
// rawJob is a job with a raw element.
|
||||
const rawJob = `{"elements":[{"type":"text","text":"Hello"},{"type":"raw","hex":"1B 61 01"}]}`
|
||||
|
||||
// tokenWith returns a token with claims.
|
||||
func tokenWith(t *testing.T, claims jwt.MapClaims) string {
|
||||
t.Helper()
|
||||
return token(t, testSecret, jwt.SigningMethodHS256, claims)
|
||||
}
|
||||
|
||||
// request returns a request to target with the token, and with body when
|
||||
// it is not empty.
|
||||
func request(t *testing.T, method, target, body, tok string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, strings.NewReader(body))
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
return req
|
||||
}
|
||||
|
||||
func TestScopedToken(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
ntfyOnly := tokenWith(t, jwt.MapClaims{"sub": "ntfy-cli", "mod": []string{"ntfy", "notify"}})
|
||||
tests := []struct {
|
||||
name, method, target, body string
|
||||
status int
|
||||
code, message string
|
||||
}{
|
||||
{"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, http.StatusAccepted, "", ""},
|
||||
{"print through notify", http.MethodPost, "/api/v1/print/notify", `{"message":"Back at 3"}`, http.StatusAccepted, "", ""},
|
||||
{"preview through ntfy", http.MethodPost, "/api/v1/preview/ntfy", ntfyMessage, http.StatusOK, "", ""},
|
||||
{"keepalive", http.MethodPost, "/api/v1/print/ntfy", `{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`,
|
||||
http.StatusNoContent, "", ""},
|
||||
{"job status", http.MethodGet, "/api/v1/jobs/" + id.String(), "", http.StatusOK, "", ""},
|
||||
{"module list", http.MethodGet, "/api/v1/modules", "", http.StatusOK, "", ""},
|
||||
{"print", http.MethodPost, "/api/v1/print", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
{"preview", http.MethodPost, "/api/v1/preview", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
{"another module", http.MethodPost, "/api/v1/print/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
{"another module's preview", http.MethodPost, "/api/v1/preview/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
{"an unknown module", http.MethodPost, "/api/v1/print/notx", `{}`, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{
|
||||
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy"},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, tt.method, tt.target, tt.body, ntfyOnly))
|
||||
if tt.code != "" {
|
||||
e := expectError(t, resp, body, tt.status, tt.code)
|
||||
if e.Error != tt.message {
|
||||
t.Errorf("error %q, want %q", e.Error, tt.message)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a refused job was queued")
|
||||
}
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("the queued job's source", func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
if resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, ntfyOnly)); resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: "module:ntfy", Ref: "req_test"}) {
|
||||
t.Errorf("meta %+v", jobs.metas)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no modules", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, tokenWith(t, jwt.MapClaims{"mod": []string{}})))
|
||||
if e := expectError(t, resp, body, http.StatusForbidden, "token_scope"); e.Error != "token is limited to job status and the module list" {
|
||||
t.Errorf("error %q", e.Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A token without a mod claim keeps every route, and a module route
|
||||
// records its module as the job's source.
|
||||
func TestUnscopedToken(t *testing.T) {
|
||||
for _, tt := range []struct{ target, body, source string }{
|
||||
{"/api/v1/print", validJob, "print"},
|
||||
{"/api/v1/print/note", shoppingNote, "module:note"},
|
||||
{"/api/v1/print/ntfy", ntfyMessage, "module:ntfy"},
|
||||
} {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, tt.target, tt.body, validToken(t)))
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Errorf("%s: status = %d (%s)", tt.target, resp.StatusCode, body)
|
||||
continue
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: tt.source, Ref: "req_test"}) {
|
||||
t.Errorf("%s: meta %+v", tt.target, jobs.metas)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawNeedsRawToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
claims jwt.MapClaims
|
||||
target string
|
||||
status int
|
||||
}{
|
||||
{"a token without raw", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/print", http.StatusForbidden},
|
||||
{"raw false", jwt.MapClaims{"raw": false}, "/api/v1/print", http.StatusForbidden},
|
||||
{"raw true", jwt.MapClaims{"raw": true}, "/api/v1/print", http.StatusAccepted},
|
||||
{"a preview", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/preview", http.StatusOK},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, tt.target, rawJob, tokenWith(t, tt.claims)))
|
||||
if tt.status != http.StatusForbidden {
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
return
|
||||
}
|
||||
e := expectError(t, resp, body, http.StatusForbidden, "token_scope")
|
||||
if e.Error != "token may not print raw ESC/POS; issue one with uberbringer token --raw" ||
|
||||
strings.Join(e.Details, ";") != "elements[1] (raw)" {
|
||||
t.Errorf("error %+v", e)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("the job was queued")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("an invalid job is refused as invalid first", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", `{"elements":[{"type":"raw"}]}`, validToken(t)))
|
||||
expectError(t, resp, body, http.StatusBadRequest, "invalid_job")
|
||||
})
|
||||
}
|
||||
|
||||
// /api/v1/preview/ntfy shows the card the command line's preview --module
|
||||
// ntfy shows for the same message.
|
||||
func TestPreviewNtfy(t *testing.T) {
|
||||
message := `{"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","nas01"]}`
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/preview/ntfy", message, validToken(t)))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := strings.Join([]string{
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"╔════════════════════════════════════════╗",
|
||||
"║ (!) Backup FAILED on nas01 ║",
|
||||
"╠════════════════════════════════════════╣",
|
||||
"║ Job nightly-offsite exited with code 2 ║",
|
||||
"║ after 3h12m. Last good run: 2 days ║",
|
||||
"║ ago. ║",
|
||||
"║ ║",
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}, "\n") + "\n"
|
||||
if string(body) != want {
|
||||
t.Errorf("preview:\n%s\nwant:\n%s", body, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Claims of the wrong type make the token invalid rather than unscoped.
|
||||
func TestMalformedScopeClaims(t *testing.T) {
|
||||
payloads := []string{
|
||||
`{"mod":"ntfy"}`,
|
||||
`{"mod":[1]}`,
|
||||
`{"raw":"yes"}`,
|
||||
`{"mod":null}`,
|
||||
`{"mod":["ntfy"],"Mod":null}`,
|
||||
`{"MOD":["ntfy"]}`,
|
||||
`{"Raw":true}`,
|
||||
`{"mod":["ntfy"],"mod":null}`,
|
||||
}
|
||||
for _, payload := range payloads {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", validJob, signedPayload(t, payload)))
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("%s: status %d, want 401 (%s)", payload, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// signedPayload returns an HS256 token with payload, as written, for its
|
||||
// claims: unlike a claims value, it can repeat a name.
|
||||
func signedPayload(t *testing.T, payload string) string {
|
||||
t.Helper()
|
||||
enc := base64.RawURLEncoding
|
||||
unsigned := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." + enc.EncodeToString([]byte(payload))
|
||||
mac := hmac.New(sha256.New, testSecret)
|
||||
mac.Write([]byte(unsigned))
|
||||
return unsigned + "." + enc.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// A request ID the client sends stays the job's reference after the
|
||||
// request: fasthttp reuses the buffer it was read from for later requests.
|
||||
func TestClientRequestIDOutlivesTheRequest(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
first := strings.Repeat("A", 40)
|
||||
req := request(t, http.MethodPost, "/api/v1/print", validJob, validToken(t))
|
||||
req.Header.Set("X-Request-ID", first)
|
||||
if resp, body := send(t, s, req); resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
for i := range 20 {
|
||||
req := request(t, http.MethodPost, "/api/v1/preview", validJob, validToken(t))
|
||||
req.Header.Set("X-Request-ID", strings.Repeat(string(rune('B'+i%20)), 40))
|
||||
send(t, s, req)
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0].Ref != first {
|
||||
t.Errorf("the job's reference became %+v, want %q", jobs.metas, first)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ var (
|
||||
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
|
||||
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
|
||||
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
||||
codeTokenScope = errorCode{fiber.StatusForbidden, "token_scope", "the token does not allow this request"}
|
||||
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
|
||||
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
|
||||
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
@@ -66,13 +67,21 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.submit(c, job)
|
||||
if err := checkRaw(c, job); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.submit(c, job, "print")
|
||||
}
|
||||
|
||||
// submit queues a validated job and answers 202 with its status and a
|
||||
// Location header, or refuses it when the queue is full or closed.
|
||||
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
|
||||
status, err := s.jobs.Submit(job)
|
||||
// submit queues a validated job, from source, and answers 202 with its
|
||||
// status and a Location header, or refuses it when the queue is full or
|
||||
// closed. The request ID is the job's reference at its source. It is
|
||||
// cloned, as is source, because the queue keeps them after the request:
|
||||
// an ID the client sent points into a buffer fasthttp reuses for the next
|
||||
// request.
|
||||
func (s *Server) submit(c fiber.Ctx, job receipt.Job, source string) error {
|
||||
meta := printqueue.Meta{Source: strings.Clone(source), Ref: strings.Clone(requestid.FromContext(c))}
|
||||
status, err := s.jobs.Submit(job, meta)
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
c.Set(fiber.HeaderRetryAfter, "10")
|
||||
|
||||
@@ -54,7 +54,7 @@ func (s *Server) handlePrintModule(c fiber.Ctx) error {
|
||||
case skip:
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
return s.submit(c, job)
|
||||
return s.submit(c, job, "module:"+c.Params("module"))
|
||||
}
|
||||
|
||||
// handlePreviewModule builds a job as handlePrintModule does and answers
|
||||
@@ -88,13 +88,19 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
||||
}
|
||||
|
||||
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
|
||||
var payloadErr *modules.PayloadError
|
||||
var (
|
||||
payloadErr *modules.PayloadError
|
||||
fallbackErr *modules.FallbackError
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, modules.ErrSkip):
|
||||
return receipt.Job{}, true, nil
|
||||
case errors.As(err, &payloadErr):
|
||||
msg := fmt.Sprintf("invalid payload for module %q", name)
|
||||
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
|
||||
case errors.As(err, &fallbackErr):
|
||||
// The plain receipt still prints; the fault is reported once.
|
||||
s.reportModuleFallback(c, name, fallbackErr)
|
||||
case err != nil:
|
||||
return job, false, fmt.Errorf("module %s: %w", name, err)
|
||||
}
|
||||
@@ -159,3 +165,20 @@ func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
|
||||
)
|
||||
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
|
||||
}
|
||||
|
||||
// reportModuleFallback logs and reports a module that could not lay out
|
||||
// its receipt and built the plain fallback instead, which still prints.
|
||||
// The error never quotes the payload.
|
||||
func (s *Server) reportModuleFallback(c fiber.Ctx, name string, fallbackErr *modules.FallbackError) {
|
||||
attrs := []slog.Attr{
|
||||
slog.String("module", name),
|
||||
slog.String("err", fallbackErr.Error()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
}
|
||||
if fallbackErr.Stack != "" {
|
||||
attrs = append(attrs, slog.String("stack", fallbackErr.Stack))
|
||||
}
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "module printed its fallback receipt", attrs...)
|
||||
hubFrom(c).CaptureException(fmt.Errorf("module %s: %w", name, fallbackErr))
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -15,9 +16,9 @@ import (
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// fakeModule answers according to its body: "skip", "payload", "invalid"
|
||||
// and "fail" give those outcomes, and any other body prints as one line of
|
||||
// text with the build time.
|
||||
// fakeModule answers according to its body: "skip", "payload", "invalid",
|
||||
// "fail" and "fallback" give those outcomes, and any other body prints as
|
||||
// one line of text with the build time.
|
||||
type fakeModule struct{}
|
||||
|
||||
func (fakeModule) Name() string { return "fake" }
|
||||
@@ -33,6 +34,9 @@ func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receip
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
|
||||
case "fail":
|
||||
return receipt.Job{}, errors.New("module broke")
|
||||
case "fallback":
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "plain"}}},
|
||||
&modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"}
|
||||
}
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
|
||||
}
|
||||
@@ -149,6 +153,37 @@ func TestModuleRefusals(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A module that falls back to its plain receipt still prints it, and the
|
||||
// fault is logged once at ERROR, with its stack, and reported once.
|
||||
func TestModuleFallback(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
target string
|
||||
status int
|
||||
}{{"/api/v1/print/fake", http.StatusAccepted}, {"/api/v1/preview/fake", http.StatusOK}} {
|
||||
t.Run(tt.target, func(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||
resp, raw := send(t, s, moduleRequest(t, tt.target, "fallback"))
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw)
|
||||
}
|
||||
if tt.status == http.StatusAccepted && (len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "plain") {
|
||||
t.Errorf("queued %+v, want the plain receipt", jobs.submitted)
|
||||
}
|
||||
failures := errorLines(logs.lines(t))
|
||||
if len(failures) != 1 || failures[0]["msg"] != "module printed its fallback receipt" ||
|
||||
failures[0]["module"] != "fake" || failures[0]["stack"] != "goroutine 1" ||
|
||||
!strings.Contains(fmt.Sprint(failures[0]["err"]), "panic: layout bug") {
|
||||
t.Errorf("error lines = %v, want one for the fallback", failures)
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A module that builds a job validation refuses has a bug: the client gets
|
||||
// 422 with the problems, and the bug is logged and reported once, without
|
||||
// the problems, which can quote the payload.
|
||||
@@ -231,7 +266,9 @@ func TestModuleList(t *testing.T) {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
|
||||
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"},` +
|
||||
`{"name":"notify","description":"Notification card from title, message, priority and tags"},` +
|
||||
`{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}]`
|
||||
if string(body) != want {
|
||||
t.Errorf("body = %s, want %s", body, want)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,8 @@ type Route struct {
|
||||
// errors are the codes the handler answers with itself;
|
||||
// DocumentedErrors adds those of the middleware.
|
||||
errors []errorCode
|
||||
// scope says which tokens limited to modules may use the route.
|
||||
scope routeScope
|
||||
handle func(*Server, fiber.Ctx) error
|
||||
}
|
||||
|
||||
@@ -99,6 +101,9 @@ func (r Route) DocumentedErrors() []ErrorDoc {
|
||||
if r.Request != nil {
|
||||
codes = append(codes, codeBodyTooLarge)
|
||||
}
|
||||
if r.Auth && r.scope != scopeAny {
|
||||
codes = append(codes, codeTokenScope)
|
||||
}
|
||||
if r.Auth {
|
||||
codes = append(codes, codeUnauthorized, codeRateLimited)
|
||||
}
|
||||
@@ -183,7 +188,8 @@ func Routes() []Route {
|
||||
Summary: "Queue a print job",
|
||||
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
|
||||
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
|
||||
"failed job.",
|
||||
"failed job. A job with raw elements needs a token issued with uberbringer token --raw, " +
|
||||
"and a token limited to modules cannot use this route.",
|
||||
Tag: "print",
|
||||
Auth: true,
|
||||
Request: receipt.Job{},
|
||||
@@ -192,6 +198,7 @@ func Routes() []Route {
|
||||
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
|
||||
"its status."}}}},
|
||||
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
|
||||
scope: scopeFull,
|
||||
handle: (*Server).handlePrint,
|
||||
},
|
||||
{
|
||||
@@ -212,6 +219,7 @@ func Routes() []Route {
|
||||
{MediaType: mediaJSON, Body: previewResponse{}},
|
||||
}}},
|
||||
errors: []errorCode{codeInvalidJob, codeTooManyLines},
|
||||
scope: scopeFull,
|
||||
handle: (*Server).handlePreview,
|
||||
},
|
||||
{
|
||||
@@ -227,6 +235,7 @@ func Routes() []Route {
|
||||
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
|
||||
errors: []errorCode{codeJobNotFound},
|
||||
scope: scopeAny,
|
||||
handle: (*Server).handleJob,
|
||||
},
|
||||
{
|
||||
@@ -234,10 +243,11 @@ func Routes() []Route {
|
||||
Path: BasePath + "/print/{module}",
|
||||
OperationID: "printModule",
|
||||
Summary: "Queue the receipt a module builds from its payload",
|
||||
Description: "The module named in the path builds a receipt from the body, its own payload, " +
|
||||
"which is decoded strictly: an unknown field or one of the wrong type is refused, with " +
|
||||
"every problem listed. The receipt is then validated and queued as on /api/v1/print. A " +
|
||||
"module with nothing to print answers 204.",
|
||||
Description: "The module named in the path builds a receipt from the body, its own payload. " +
|
||||
"note and notify decode it strictly: an unknown field or one of the wrong type is refused, " +
|
||||
"with every problem listed; ntfy ignores the fields it does not know. The receipt is then " +
|
||||
"validated and queued as on /api/v1/print. A module with nothing to print answers 204. A " +
|
||||
"token limited to modules (uberbringer token --modules) may use only the modules it names.",
|
||||
Tag: "modules",
|
||||
Auth: true,
|
||||
Request: modulePayload{},
|
||||
@@ -251,6 +261,7 @@ func Routes() []Route {
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeQueueFull, codeShuttingDown},
|
||||
scope: scopeModule,
|
||||
handle: (*Server).handlePrintModule,
|
||||
},
|
||||
{
|
||||
@@ -275,6 +286,7 @@ func Routes() []Route {
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeTooManyLines},
|
||||
scope: scopeModule,
|
||||
handle: (*Server).handlePreviewModule,
|
||||
},
|
||||
{
|
||||
@@ -287,6 +299,7 @@ func Routes() []Route {
|
||||
Auth: true,
|
||||
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
|
||||
scope: scopeAny,
|
||||
handle: (*Server).handleModules,
|
||||
},
|
||||
}
|
||||
@@ -313,14 +326,20 @@ func fiberPath(path string) string {
|
||||
|
||||
// registerRoutes adds every route of the table to the app. api is the group
|
||||
// at BasePath that holds the bearer token, rate limit and no-store
|
||||
// middleware.
|
||||
// middleware; its routes refuse the tokens their scope leaves out.
|
||||
func (s *Server) registerRoutes(api fiber.Router) {
|
||||
for _, r := range Routes() {
|
||||
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
|
||||
path := fiberPath(r.Path)
|
||||
switch {
|
||||
case r.Auth:
|
||||
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), handler)
|
||||
scoped := func(c fiber.Ctx) error {
|
||||
if err := checkScope(c, r.scope); err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(c)
|
||||
}
|
||||
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), scoped)
|
||||
case r.NoStore:
|
||||
s.app.Add([]string{r.Method}, path, noStore, handler)
|
||||
default:
|
||||
|
||||
@@ -27,7 +27,7 @@ const shutdownTimeout = 10 * time.Second
|
||||
|
||||
// Jobs is the print queue as seen by the HTTP handlers.
|
||||
type Jobs interface {
|
||||
Submit(job receipt.Job) (printqueue.Status, error)
|
||||
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
|
||||
Status(id printqueue.JobID) (printqueue.Status, error)
|
||||
Pending() int
|
||||
}
|
||||
|
||||
@@ -33,20 +33,22 @@ var testSecret = []byte("0123456789abcdef0123456789abcdef")
|
||||
type fakeJobs struct {
|
||||
mu sync.Mutex
|
||||
submitted []receipt.Job
|
||||
metas []printqueue.Meta
|
||||
submitErr error
|
||||
statusErr error
|
||||
statuses map[printqueue.JobID]printqueue.Status
|
||||
nextID printqueue.JobID
|
||||
}
|
||||
|
||||
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
|
||||
func (f *fakeJobs) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.submitErr != nil {
|
||||
return printqueue.Status{}, f.submitErr
|
||||
}
|
||||
f.submitted = append(f.submitted, job)
|
||||
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
|
||||
f.metas = append(f.metas, meta)
|
||||
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, Source: meta.Source, CreatedAt: time.Now()}
|
||||
f.statuses[f.nextID] = st
|
||||
return st, nil
|
||||
}
|
||||
@@ -136,7 +138,7 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
|
||||
registry, err := modules.NewRegistry(fakeModule{}, modules.Note(), modules.Notify(), modules.Ntfy())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -583,7 +585,7 @@ func TestPrintQueueRefusals(t *testing.T) {
|
||||
func TestJobStatus(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
||||
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy", Attempts: 1},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
get := func(path, auth string) *http.Request {
|
||||
@@ -596,7 +598,7 @@ func TestJobStatus(t *testing.T) {
|
||||
auth := "Bearer " + validToken(t)
|
||||
|
||||
resp, body := do(t, s, get("/api/v1/jobs/"+id.String(), auth))
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" {
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" || body["source"] != "module:ntfy" {
|
||||
t.Errorf("GET known job = %d %v", resp.StatusCode, body)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
@@ -45,6 +46,7 @@ type Config struct {
|
||||
API APIConfig `mapstructure:"api"`
|
||||
Printer PrinterConfig `mapstructure:"printer"`
|
||||
Format FormatConfig `mapstructure:"format"`
|
||||
Ntfy NtfyConfig `mapstructure:"ntfy"`
|
||||
Queue QueueConfig `mapstructure:"queue"`
|
||||
Images ImagesConfig `mapstructure:"images"`
|
||||
Sentry SentryConfig `mapstructure:"sentry"`
|
||||
@@ -127,6 +129,48 @@ type FormatConfig struct {
|
||||
TimeLayout string `mapstructure:"time_layout"`
|
||||
}
|
||||
|
||||
// Values of NtfyFormatConfig's settings.
|
||||
var (
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
)
|
||||
|
||||
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the
|
||||
// most characters in a marker.
|
||||
const (
|
||||
MaxNtfyLines = 400
|
||||
MaxMarker = 16
|
||||
)
|
||||
|
||||
// NtfyConfig configures how notifications print, from the notify and ntfy
|
||||
// modules.
|
||||
type NtfyConfig struct {
|
||||
Format NtfyFormatConfig `mapstructure:"format"`
|
||||
|
||||
// Markers override the markers printed for tags, by tag: an empty
|
||||
// marker hides the tag.
|
||||
Markers map[string]string `mapstructure:"markers"`
|
||||
}
|
||||
|
||||
// NtfyFormatConfig configures the layout of a notification.
|
||||
type NtfyFormatConfig struct {
|
||||
// Style is auto, which picks the form from the priority, box or
|
||||
// compact.
|
||||
Style string `mapstructure:"style"`
|
||||
|
||||
// MaxLines is how many lines of a message print, as written.
|
||||
MaxLines int `mapstructure:"max_lines"`
|
||||
|
||||
// QR is all, first or none: which links print as QR codes.
|
||||
QR string `mapstructure:"qr"`
|
||||
|
||||
// Images prints attached images.
|
||||
Images bool `mapstructure:"images"`
|
||||
|
||||
// Markdown lays out markdown messages.
|
||||
Markdown bool `mapstructure:"markdown"`
|
||||
}
|
||||
|
||||
// QueueConfig configures the print queue.
|
||||
type QueueConfig struct {
|
||||
// Size is the number of jobs that may wait to be printed.
|
||||
@@ -203,6 +247,15 @@ func Default() Config {
|
||||
Timezone: "Local",
|
||||
TimeLayout: "02 Jan 15:04",
|
||||
},
|
||||
Ntfy: NtfyConfig{
|
||||
Format: NtfyFormatConfig{
|
||||
Style: "auto",
|
||||
MaxLines: 40,
|
||||
QR: "all",
|
||||
Images: true,
|
||||
Markdown: true,
|
||||
},
|
||||
},
|
||||
Queue: QueueConfig{
|
||||
Size: 100,
|
||||
History: 1000,
|
||||
@@ -240,7 +293,7 @@ func Load(path string) (*Config, error) {
|
||||
var envSet []string
|
||||
bound := map[string]bool{PathEnvVar: true}
|
||||
for _, key := range slices.Sorted(maps.Keys(keys)) {
|
||||
if keys[key] != setting {
|
||||
if keys[key] == section {
|
||||
continue
|
||||
}
|
||||
name := envVar(key)
|
||||
@@ -290,6 +343,7 @@ func Load(path string) (*Config, error) {
|
||||
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
)),
|
||||
@@ -363,12 +417,14 @@ func readFile(path string) (map[string]any, error) {
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// keyKind tells a setting from a section that holds settings.
|
||||
// keyKind tells a setting from a section that holds settings, and from a
|
||||
// table setting, whose keys are the user's own.
|
||||
type keyKind int
|
||||
|
||||
const (
|
||||
setting keyKind = iota + 1
|
||||
section
|
||||
tableSetting
|
||||
)
|
||||
|
||||
// registerDefaults sets every field of the config struct rv as a Viper
|
||||
@@ -385,13 +441,18 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
|
||||
key = prefix + "." + tag
|
||||
}
|
||||
field := rv.Field(i)
|
||||
if field.Kind() == reflect.Struct {
|
||||
switch field.Kind() {
|
||||
case reflect.Struct:
|
||||
keys[key] = section
|
||||
registerDefaults(v, key, field, keys)
|
||||
continue
|
||||
case reflect.Map:
|
||||
// A default table would merge with the file's instead of
|
||||
// giving way to it; the table settings default to empty.
|
||||
keys[key] = tableSetting
|
||||
default:
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
}
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,6 +489,10 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
u, c := checkKeys(sub, path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case isTable && kind == tableSetting:
|
||||
u, c := checkTable(sub, path)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case !isTable && kind == setting:
|
||||
default:
|
||||
unknown = append(unknown, path)
|
||||
@@ -436,6 +501,26 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
return unknown, clashes
|
||||
}
|
||||
|
||||
// checkTable checks the entries of a table setting at path, whose names are
|
||||
// the user's own. Like checkKeys, it returns as unknown a name with a dot
|
||||
// and an entry that is itself a table, and the names that differ only in
|
||||
// case.
|
||||
func checkTable(entries map[string]any, path string) (unknown, clashes []string) {
|
||||
seen := make(map[string]string, len(entries))
|
||||
for _, name := range slices.Sorted(maps.Keys(entries)) {
|
||||
entry := path + "." + displayKey(name)
|
||||
if other, ok := seen[strings.ToLower(name)]; ok {
|
||||
clashes = append(clashes, other+" and "+entry)
|
||||
continue
|
||||
}
|
||||
seen[strings.ToLower(name)] = entry
|
||||
if _, isTable := entries[name].(map[string]any); isTable || strings.Contains(name, ".") {
|
||||
unknown = append(unknown, entry)
|
||||
}
|
||||
}
|
||||
return unknown, clashes
|
||||
}
|
||||
|
||||
// displayKey quotes a key name that TOML would need quoted, so that spaces,
|
||||
// dots and empty names show in messages.
|
||||
func displayKey(name string) string {
|
||||
@@ -546,6 +631,35 @@ func stringToList() mapstructure.DecodeHookFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// stringToTable reads a table setting from a string, such as an
|
||||
// environment variable: entries name=value, separated by commas, with the
|
||||
// spaces around each trimmed, so "a=[A], b=" sets a to "[A]" and b to "". A
|
||||
// value cannot hold a comma.
|
||||
func stringToTable() mapstructure.DecodeHookFunc {
|
||||
return func(from, to reflect.Type, data any) (any, error) {
|
||||
if from.Kind() != reflect.String || to.Kind() != reflect.Map {
|
||||
return data, nil
|
||||
}
|
||||
entries := make(map[string]string)
|
||||
raw := strings.TrimSpace(data.(string))
|
||||
if raw == "" {
|
||||
return entries, nil
|
||||
}
|
||||
for item := range strings.SplitSeq(raw, ",") {
|
||||
name, value, ok := strings.Cut(item, "=")
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
if !ok || name == "" {
|
||||
return nil, errors.New("expected entries name=value separated by commas, e.g. backup=[B],skull=")
|
||||
}
|
||||
if _, dup := entries[name]; dup {
|
||||
return nil, fmt.Errorf("%q is given twice", name)
|
||||
}
|
||||
entries[name] = strings.TrimSpace(value)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Validate reports every problem with the configuration.
|
||||
func (c *Config) Validate() error {
|
||||
var errs []error
|
||||
@@ -591,6 +705,16 @@ func (c *Config) Validate() error {
|
||||
check(showsTime(c.Format.TimeLayout),
|
||||
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
|
||||
|
||||
nf := c.Ntfy.Format
|
||||
check(slices.Contains(NtfyStyles, nf.Style), "ntfy.format.style: %q must be one of %s", nf.Style, strings.Join(NtfyStyles, ", "))
|
||||
check(nf.MaxLines >= 1 && nf.MaxLines <= MaxNtfyLines, "ntfy.format.max_lines must be 1-%d", MaxNtfyLines)
|
||||
check(slices.Contains(NtfyQRModes, nf.QR), "ntfy.format.qr: %q must be one of %s", nf.QR, strings.Join(NtfyQRModes, ", "))
|
||||
for _, tag := range slices.Sorted(maps.Keys(c.Ntfy.Markers)) {
|
||||
check(strings.TrimSpace(tag) != "", "ntfy.markers: a tag name is empty")
|
||||
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
|
||||
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
|
||||
}
|
||||
|
||||
check(c.Queue.Size > 0, "queue.size must be positive")
|
||||
check(c.Queue.History >= 0, "queue.history must not be negative")
|
||||
|
||||
|
||||
@@ -300,6 +300,66 @@ func TestLoadErrors(t *testing.T) {
|
||||
body: "\xff\xfe[\x00a\x00p\x00i\x00]\x00",
|
||||
wantErr: "the file is UTF-16; save it as UTF-8",
|
||||
},
|
||||
{
|
||||
name: "ntfy style",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nstyle = \"fancy\"\n",
|
||||
wantErr: `ntfy.format.style: "fancy" must be one of auto, box, compact`,
|
||||
},
|
||||
{
|
||||
name: "ntfy max lines zero",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 0\n",
|
||||
wantErr: "ntfy.format.max_lines must be 1-400",
|
||||
},
|
||||
{
|
||||
name: "ntfy max lines too many",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 401\n",
|
||||
wantErr: "ntfy.format.max_lines must be 1-400",
|
||||
},
|
||||
{
|
||||
name: "ntfy qr",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nqr = \"some\"\n",
|
||||
wantErr: `ntfy.format.qr: "some" must be one of all, first, none`,
|
||||
},
|
||||
{
|
||||
name: "ntfy images not a flag",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nimages = \"yes\"\n",
|
||||
wantErr: "'ntfy.format.images' expected true or false",
|
||||
},
|
||||
{
|
||||
name: "unknown ntfy key",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nserver = \"https://ntfy.sh\"\n",
|
||||
wantErr: "unknown keys: ntfy.server",
|
||||
},
|
||||
{
|
||||
name: "marker too long",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[a very long marker]\"\n",
|
||||
wantErr: `ntfy.markers.backup: "[a very long marker]" is longer than 16 characters`,
|
||||
},
|
||||
{
|
||||
name: "marker that is not a string",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = 1\n",
|
||||
wantErr: "ntfy.markers",
|
||||
},
|
||||
{
|
||||
name: "marker table",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers.backup]\nmarker = \"[B]\"\n",
|
||||
wantErr: "unknown keys: ntfy.markers.backup",
|
||||
},
|
||||
{
|
||||
name: "marker name with a dot",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\n\"a.b\" = \"[B]\"\n",
|
||||
wantErr: `unknown keys: ntfy.markers."a.b"`,
|
||||
},
|
||||
{
|
||||
name: "markers that differ only in case",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[b]\"\nBackup = \"[B]\"\n",
|
||||
wantErr: "keys that differ only in case: ntfy.markers.Backup and ntfy.markers.backup",
|
||||
},
|
||||
{
|
||||
name: "markers as a value",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nmarkers = \"backup=[B]\"\n",
|
||||
wantErr: "unknown keys: ntfy.markers",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -326,11 +386,74 @@ func TestExampleConfigLoads(t *testing.T) {
|
||||
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
|
||||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
|
||||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
|
||||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
|
||||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
|
||||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 {
|
||||
t.Error("example config values drifted from the defaults it documents")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNtfy(t *testing.T) {
|
||||
def := config.Default().Ntfy.Format
|
||||
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true}) {
|
||||
t.Errorf("defaults %+v", def)
|
||||
}
|
||||
|
||||
cfg, err := config.Load(writeConfig(t, `
|
||||
[api]
|
||||
secret = "`+validSecret+`"
|
||||
[printer]
|
||||
address = "p"
|
||||
[ntfy.format]
|
||||
style = "compact"
|
||||
max_lines = 400
|
||||
qr = "first"
|
||||
images = false
|
||||
markdown = false
|
||||
[ntfy.markers]
|
||||
backup = "[B]"
|
||||
skull = ""
|
||||
"+1" = "+1"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false}
|
||||
if cfg.Ntfy.Format != want {
|
||||
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
|
||||
}
|
||||
if m := cfg.Ntfy.Markers; len(m) != 3 || m["backup"] != "[B]" || m["skull"] != "" || m["+1"] != "+1" {
|
||||
t.Errorf("markers %q", m)
|
||||
}
|
||||
|
||||
t.Run("environment", func(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
|
||||
t.Setenv("UBERBRINGER_NTFY_FORMAT_STYLE", "box")
|
||||
t.Setenv("UBERBRINGER_NTFY_MARKERS", " Backup = [B] , skull= ")
|
||||
cfg, err := config.Load("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Ntfy.Format.Style != "box" {
|
||||
t.Errorf("style %q", cfg.Ntfy.Format.Style)
|
||||
}
|
||||
if m := cfg.Ntfy.Markers; len(m) != 2 || m["backup"] != "[B]" || m["skull"] != "" {
|
||||
t.Errorf("markers %q", m)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("environment wins over the file", func(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_NTFY_MARKERS", "tada=\\o/")
|
||||
cfg, err := config.Load(writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[B]\"\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := cfg.Ntfy.Markers; len(m) != 1 || m["tada"] != `\o/` {
|
||||
t.Errorf("markers %q", m)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestLoadEnvironmentOverridesFile(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
[api]
|
||||
@@ -485,6 +608,10 @@ func TestLoadEnvironmentErrors(t *testing.T) {
|
||||
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
|
||||
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
|
||||
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
|
||||
{"marker without a value", "UBERBRINGER_NTFY_MARKERS", "backup", "expected entries name=value separated by commas"},
|
||||
{"marker without a name", "UBERBRINGER_NTFY_MARKERS", "=[B]", "expected entries name=value separated by commas"},
|
||||
{"marker given twice", "UBERBRINGER_NTFY_MARKERS", "backup=[B],Backup=[b]", `"backup" is given twice`},
|
||||
{"ntfy style", "UBERBRINGER_NTFY_FORMAT_QR", "every", "ntfy.format.qr"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -509,6 +636,7 @@ func TestLoadMissingFile(t *testing.T) {
|
||||
func TestValue(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.Images.AllowedHosts = []string{"a.lan", "b.lan"}
|
||||
cfg.Ntfy.Markers = map[string]string{"skull": "", "backup": "[B]"}
|
||||
tests := []struct {
|
||||
key, want, wantErr string
|
||||
}{
|
||||
@@ -520,6 +648,10 @@ func TestValue(t *testing.T) {
|
||||
{key: "images.allow_private_networks", want: "false"},
|
||||
{key: "format.timezone", want: "Local"},
|
||||
{key: "format.time_layout", want: "02 Jan 15:04"},
|
||||
{key: "ntfy.format.style", want: "auto"},
|
||||
{key: "ntfy.format.images", want: "true"},
|
||||
{key: "ntfy.markers", want: "backup=[B],skull="},
|
||||
{key: "ntfy.format", wantErr: `"ntfy.format" is a section`},
|
||||
{key: "printer", wantErr: `"printer" is a section`},
|
||||
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
|
||||
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
|
||||
|
||||
@@ -2,14 +2,17 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Value returns the setting at the dotted key, such as "webserver.port", in
|
||||
// the form a config file or an environment variable gives it: durations such
|
||||
// as "15s", lists comma-separated. Key names match case-insensitively.
|
||||
// as "15s", lists comma-separated, and tables as name=value entries, sorted
|
||||
// and comma-separated. Key names match case-insensitively.
|
||||
func (c *Config) Value(key string) (string, error) {
|
||||
v := reflect.ValueOf(*c)
|
||||
for part := range strings.SplitSeq(key, ".") {
|
||||
@@ -27,6 +30,12 @@ func (c *Config) Value(key string) (string, error) {
|
||||
return value.String(), nil
|
||||
case []string:
|
||||
return strings.Join(value, ","), nil
|
||||
case map[string]string:
|
||||
entries := make([]string, 0, len(value))
|
||||
for _, name := range slices.Sorted(maps.Keys(value)) {
|
||||
entries = append(entries, name+"="+value[name])
|
||||
}
|
||||
return strings.Join(entries, ","), nil
|
||||
default:
|
||||
return fmt.Sprint(value), nil
|
||||
}
|
||||
|
||||
@@ -471,3 +471,32 @@ func TestLookupProfile(t *testing.T) {
|
||||
t.Errorf("unknown model err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQRModules(t *testing.T) {
|
||||
tests := []struct {
|
||||
n int
|
||||
level escpos.QRCorrection
|
||||
want int
|
||||
}{
|
||||
{1, escpos.QRCorrectionM, 21},
|
||||
{14, escpos.QRCorrectionM, 21},
|
||||
{15, escpos.QRCorrectionM, 25},
|
||||
{213, escpos.QRCorrectionM, 57},
|
||||
{504, escpos.QRCorrectionM, 85},
|
||||
{505, escpos.QRCorrectionM, 89},
|
||||
{17, escpos.QRCorrectionL, 21},
|
||||
{7, escpos.QRCorrectionH, 21},
|
||||
{2953, escpos.QRCorrectionL, 177},
|
||||
{2954, escpos.QRCorrectionL, 177},
|
||||
{2331, escpos.QRCorrectionM, 177},
|
||||
{1663, escpos.QRCorrectionQ, 177},
|
||||
{1273, escpos.QRCorrectionH, 177},
|
||||
{1274, escpos.QRCorrectionH, 177},
|
||||
{10, escpos.QRCorrection(0), 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := escpos.QRModules(tt.n, tt.level); got != tt.want {
|
||||
t.Errorf("QRModules(%d, %d) = %d, want %d", tt.n, tt.level, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,40 @@ const (
|
||||
MaxQRModuleSize = 16
|
||||
)
|
||||
|
||||
// qrByteCapacity holds, for each QR version from 1 to 40, how many bytes a
|
||||
// code of that version holds in byte mode at correction levels L, M, Q and
|
||||
// H (ISO/IEC 18004).
|
||||
var qrByteCapacity = [40][4]int{
|
||||
{17, 14, 11, 7}, {32, 26, 20, 14}, {53, 42, 32, 24}, {78, 62, 46, 34},
|
||||
{106, 84, 60, 44}, {134, 106, 74, 58}, {154, 122, 86, 64}, {192, 152, 108, 84},
|
||||
{230, 180, 130, 98}, {271, 213, 151, 119}, {321, 251, 177, 137}, {367, 287, 203, 155},
|
||||
{425, 331, 241, 177}, {458, 362, 258, 194}, {520, 412, 292, 220}, {586, 450, 322, 250},
|
||||
{644, 504, 364, 280}, {718, 560, 394, 310}, {792, 624, 442, 338}, {858, 666, 482, 382},
|
||||
{929, 711, 509, 403}, {1003, 779, 565, 439}, {1091, 857, 611, 461}, {1171, 911, 661, 511},
|
||||
{1273, 997, 715, 535}, {1367, 1059, 751, 593}, {1465, 1125, 805, 625}, {1528, 1190, 868, 658},
|
||||
{1628, 1264, 908, 698}, {1732, 1370, 982, 742}, {1840, 1452, 1030, 790}, {1952, 1538, 1112, 842},
|
||||
{2068, 1628, 1168, 898}, {2188, 1722, 1228, 958}, {2303, 1809, 1283, 983}, {2431, 1911, 1351, 1051},
|
||||
{2563, 1989, 1423, 1093}, {2699, 2099, 1499, 1139}, {2809, 2213, 1579, 1219}, {2953, 2331, 1663, 1273},
|
||||
}
|
||||
|
||||
// QRModules returns how many modules wide a QR code holding n bytes at
|
||||
// level is at most, or 0 for a level that is not one. It assumes byte mode,
|
||||
// the least dense, so the printer's own code is never wider; data that
|
||||
// only a denser mode holds, such as thousands of digits, counts as the
|
||||
// largest version, 177 modules.
|
||||
func QRModules(n int, level QRCorrection) int {
|
||||
if level < QRCorrectionL || level > QRCorrectionH {
|
||||
return 0
|
||||
}
|
||||
column := int(level - QRCorrectionL)
|
||||
for v, capacity := range qrByteCapacity {
|
||||
if n <= capacity[column] {
|
||||
return 17 + 4*(v+1)
|
||||
}
|
||||
}
|
||||
return 17 + 4*len(qrByteCapacity)
|
||||
}
|
||||
|
||||
// ParseQRCorrection returns the correction level named by name: L, M, Q or H.
|
||||
func ParseQRCorrection(name string) (QRCorrection, error) {
|
||||
switch strings.ToUpper(strings.TrimSpace(name)) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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;
|
||||
// -  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 }
|
||||
@@ -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"},
|
||||
{" and ", "[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/) ",
|
||||
"```\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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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
@@ -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
@@ -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 - - - - - - - -
|
||||
@@ -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
@@ -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
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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
|
||||
```
|
||||

|
||||
Escaped \*stars\* stay.
|
||||
@@ -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
|
||||
@@ -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
@@ -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 - - - - - - - -
|
||||
@@ -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
@@ -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 - - - - - - - -
|
||||
@@ -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}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -0,0 +1 @@
|
||||
{"message":"Back at 3"}
|
||||
@@ -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}]}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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"]}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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\nEscaped \\*stars\\* stay.","priority":3}
|
||||
+27
@@ -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 - - - - - - - -
|
||||
@@ -0,0 +1 @@
|
||||
{"id":"NoTitle00001","time":1764450245,"event":"message","topic":"alerts","message":"Just a message"}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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"}}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -0,0 +1,2 @@
|
||||
{"id":"Zp4cW8mR1sYb","time":1764385920,"event":"message","topic":"backups","title":"Prune finished",
|
||||
"message":"41 snapshots kept, 3 removed.","priority":1}
|
||||
@@ -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"]}
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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"]}
|
||||
@@ -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}
|
||||
@@ -0,0 +1,4 @@
|
||||
┌─ alerts ───────────────────────────────┐
|
||||
│ From a newer ntfy │
|
||||
└─────────────── alerts · 29 Nov 21:04 ──┘
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
@@ -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"]}
|
||||
@@ -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"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"id":"Zp4cW8mR1sYb","time":1796063393,"event":"message","topic":"backups","title":"Prune finished","message":"41 snapshots kept, 3 removed.","priority":1}
|
||||
@@ -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"]}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Package ntfy holds the wire types of ntfy (https://ntfy.sh), the
|
||||
// notification service: the message objects its subscribe API streams, one
|
||||
// JSON object per line.
|
||||
package ntfy
|
||||
|
||||
// Event types of a Message.
|
||||
const (
|
||||
EventOpen = "open"
|
||||
EventKeepalive = "keepalive"
|
||||
EventMessage = "message"
|
||||
EventPollRequest = "poll_request"
|
||||
EventMessageDelete = "message_delete"
|
||||
EventMessageClear = "message_clear"
|
||||
)
|
||||
|
||||
// Priorities. A message without one has the default priority.
|
||||
const (
|
||||
PriorityMin = 1
|
||||
PriorityLow = 2
|
||||
PriorityDefault = 3
|
||||
PriorityHigh = 4
|
||||
PriorityMax = 5
|
||||
)
|
||||
|
||||
// Content types and encodings of a message body.
|
||||
const (
|
||||
ContentTypeMarkdown = "text/markdown"
|
||||
EncodingBase64 = "base64"
|
||||
)
|
||||
|
||||
// Message is one object of the subscribe API, such as the ntfy command
|
||||
// line client passes to a command in $NTFY_RAW. Only event "message"
|
||||
// carries a notification.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
// SequenceID groups the messages that update one notification, which a
|
||||
// later message of the sequence replaces. ntfy leaves it out when it
|
||||
// equals ID. A publisher may choose it, so the first message of a
|
||||
// sequence can have a SequenceID that differs from its ID.
|
||||
SequenceID string `json:"sequence_id,omitempty"`
|
||||
|
||||
// Time is when the message was published, in Unix seconds.
|
||||
Time int64 `json:"time"`
|
||||
Expires int64 `json:"expires,omitempty"`
|
||||
Event string `json:"event"`
|
||||
Topic string `json:"topic"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
|
||||
// RawPriority is 1-5, or 0 when the message has none.
|
||||
RawPriority int `json:"priority,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Click string `json:"click,omitempty"`
|
||||
Icon string `json:"icon,omitempty"`
|
||||
Actions []Action `json:"actions,omitempty"`
|
||||
|
||||
Attachment *Attachment `json:"attachment,omitempty"`
|
||||
PollID string `json:"poll_id,omitempty"`
|
||||
|
||||
// ContentType is empty for plain text, or text/markdown.
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
|
||||
// Encoding is empty for UTF-8 text, or base64 for a binary body.
|
||||
Encoding string `json:"encoding,omitempty"`
|
||||
}
|
||||
|
||||
// Priority returns the message's priority, 1-5. A missing or out-of-range
|
||||
// priority is the default, 3.
|
||||
func (m Message) Priority() int {
|
||||
if m.RawPriority < PriorityMin || m.RawPriority > PriorityMax {
|
||||
return PriorityDefault
|
||||
}
|
||||
return m.RawPriority
|
||||
}
|
||||
|
||||
// Action is a button on a notification. View actions open URL; http
|
||||
// actions send a request with Method, Headers and Body; broadcast actions
|
||||
// send an Android intent with Extras; copy actions copy Value to the
|
||||
// clipboard.
|
||||
type Action struct {
|
||||
ID string `json:"id"`
|
||||
Action string `json:"action"`
|
||||
Label string `json:"label"`
|
||||
Clear bool `json:"clear"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Body string `json:"body,omitempty"`
|
||||
Intent string `json:"intent,omitempty"`
|
||||
Extras map[string]string `json:"extras,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// Action types.
|
||||
const (
|
||||
ActionView = "view"
|
||||
ActionHTTP = "http"
|
||||
ActionBroadcast = "broadcast"
|
||||
ActionCopy = "copy"
|
||||
)
|
||||
|
||||
// Attachment is a file attached to a message.
|
||||
type Attachment struct {
|
||||
Name string `json:"name"`
|
||||
|
||||
// Type is the file's media type, e.g. image/png. It may be empty.
|
||||
Type string `json:"type,omitempty"`
|
||||
|
||||
// Size is in bytes.
|
||||
Size int64 `json:"size,omitempty"`
|
||||
|
||||
// Expires is when the file is deleted from the server, in Unix
|
||||
// seconds; 0 for a file hosted elsewhere.
|
||||
Expires int64 `json:"expires,omitempty"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// AttachmentMessage is the message ntfy gives a message published with an
|
||||
// attachment and no text, with the file's name in place of %s.
|
||||
const AttachmentMessage = "You received a file: %s"
|
||||
@@ -0,0 +1,49 @@
|
||||
package ntfy_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"uberbringer/internal/pkg/ntfy"
|
||||
)
|
||||
|
||||
func TestPriority(t *testing.T) {
|
||||
for raw, want := range map[int]int{0: 3, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 3, -1: 3} {
|
||||
if got := (ntfy.Message{RawPriority: raw}).Priority(); got != want {
|
||||
t.Errorf("priority %d: Priority() = %d, want %d", raw, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A message as ntfy sends it decodes into every field, and unknown fields
|
||||
// are ignored.
|
||||
func TestDecodeMessage(t *testing.T) {
|
||||
raw := `{"id":"sPs71M8A2Tq9","sequence_id":"seq1","time":1764450245,"expires":1764493445,"event":"message",
|
||||
"topic":"alerts","title":"Disk almost full","message":"**/var** is at *94%*","priority":4,"tags":["warning","nas01"],
|
||||
"click":"https://grafana.lan/d/disk","icon":"https://example.com/i.png","content_type":"text/markdown","encoding":"",
|
||||
"poll_id":"p1","future":true,
|
||||
"actions":[{"id":"a1","action":"view","label":"Open","url":"https://grafana.lan/d/disk","clear":true},
|
||||
{"id":"a2","action":"http","label":"Close","url":"https://h/","method":"PUT","headers":{"X":"1"},"body":"b"},
|
||||
{"id":"a3","action":"broadcast","label":"B","intent":"i","extras":{"k":"v"}},
|
||||
{"id":"a4","action":"copy","label":"C","value":"123456"}],
|
||||
"attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/f.png"}}`
|
||||
var m ntfy.Message
|
||||
if err := json.Unmarshal([]byte(raw), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.ID != "sPs71M8A2Tq9" || m.SequenceID != "seq1" || m.Time != 1764450245 || m.Expires != 1764493445 ||
|
||||
m.Event != ntfy.EventMessage || m.Topic != "alerts" || m.Title != "Disk almost full" ||
|
||||
m.Message != "**/var** is at *94%*" || m.Priority() != ntfy.PriorityHigh || len(m.Tags) != 2 ||
|
||||
m.Click != "https://grafana.lan/d/disk" || m.Icon == "" || m.ContentType != ntfy.ContentTypeMarkdown || m.PollID != "p1" {
|
||||
t.Errorf("message %+v", m)
|
||||
}
|
||||
if len(m.Actions) != 4 || !m.Actions[0].Clear || m.Actions[1].Method != "PUT" || m.Actions[1].Headers["X"] != "1" ||
|
||||
m.Actions[1].Body != "b" || m.Actions[2].Intent != "i" || m.Actions[2].Extras["k"] != "v" ||
|
||||
m.Actions[3].Action != ntfy.ActionCopy || m.Actions[3].Value != "123456" {
|
||||
t.Errorf("actions %+v", m.Actions)
|
||||
}
|
||||
if a := m.Attachment; a == nil || a.Name != "graph.png" || a.Type != "image/png" || a.Size != 33848 ||
|
||||
a.Expires != 1764461045 || a.URL != "https://ntfy.example.com/f.png" {
|
||||
t.Errorf("attachment %+v", m.Attachment)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,9 @@ type Status struct {
|
||||
ID JobID `json:"id"`
|
||||
// State is where the job is in its lifecycle.
|
||||
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
|
||||
// Source says where the job came from: print for POST /api/v1/print,
|
||||
// or module:<name> for a module route, e.g. module:ntfy.
|
||||
Source string `json:"source,omitempty"`
|
||||
// Error says why a failed job failed.
|
||||
Error string `json:"error,omitempty"`
|
||||
// Attempts is how many times the job was sent to the printer.
|
||||
@@ -105,9 +108,22 @@ type Options struct {
|
||||
OnFailure func(id JobID, err error)
|
||||
}
|
||||
|
||||
// Meta says where a job came from. It is kept with the job's status and
|
||||
// logged with it; it never holds what the job prints.
|
||||
type Meta struct {
|
||||
// Source is the kind of client that sent the job, e.g. print or
|
||||
// module:ntfy.
|
||||
Source string
|
||||
|
||||
// Ref identifies the job at its source, e.g. the ID of the request
|
||||
// that sent it.
|
||||
Ref string
|
||||
}
|
||||
|
||||
type queuedJob struct {
|
||||
id JobID
|
||||
job receipt.Job
|
||||
id JobID
|
||||
job receipt.Job
|
||||
meta Meta
|
||||
}
|
||||
|
||||
// Queue runs print jobs on a single worker. It is safe for concurrent use.
|
||||
@@ -146,9 +162,10 @@ func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options)
|
||||
}
|
||||
}
|
||||
|
||||
// Submit queues job. The job should already be validated so callers can
|
||||
// report problems synchronously; it is validated again when rendered.
|
||||
func (q *Queue) Submit(job receipt.Job) (Status, error) {
|
||||
// Submit queues job, sent from where meta says. The job should already be
|
||||
// validated so callers can report problems synchronously; it is validated
|
||||
// again when rendered.
|
||||
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
|
||||
id, err := typeid.New[JobID]()
|
||||
if err != nil {
|
||||
return Status{}, fmt.Errorf("generating job ID: %w", err)
|
||||
@@ -160,11 +177,11 @@ func (q *Queue) Submit(job receipt.Job) (Status, error) {
|
||||
return Status{}, ErrClosed
|
||||
}
|
||||
select {
|
||||
case q.jobs <- queuedJob{id: id, job: job}:
|
||||
case q.jobs <- queuedJob{id: id, job: job, meta: meta}:
|
||||
default:
|
||||
return Status{}, ErrQueueFull
|
||||
}
|
||||
status := &Status{ID: id, State: StateQueued, CreatedAt: time.Now().UTC()}
|
||||
status := &Status{ID: id, State: StateQueued, Source: meta.Source, CreatedAt: time.Now().UTC()}
|
||||
q.statuses[id] = status
|
||||
return *status, nil
|
||||
}
|
||||
@@ -216,10 +233,10 @@ func (q *Queue) process(ctx context.Context, qj queuedJob) {
|
||||
now := time.Now().UTC()
|
||||
s.State, s.StartedAt = StatePrinting, &now
|
||||
})
|
||||
logger := q.logger.With("job_id", qj.id.String())
|
||||
logger := q.logger.With("job_id", qj.id.String(), "source", qj.meta.Source, "ref", qj.meta.Ref)
|
||||
logger.Info("printing job", "elements", len(qj.job.Elements), "copies", max(qj.job.Copies, 1))
|
||||
|
||||
attempts, err := q.print(ctx, jobCtx, qj.job)
|
||||
attempts, err := q.print(ctx, jobCtx, qj.job, logger)
|
||||
q.finish(qj.id, attempts, err)
|
||||
if err != nil {
|
||||
logger.Error("job failed", "attempts", attempts, "err", err)
|
||||
@@ -232,8 +249,9 @@ func (q *Queue) process(ctx context.Context, qj queuedJob) {
|
||||
}
|
||||
|
||||
// print renders job once and sends it, retrying failed sends with backoff.
|
||||
// Retries stop early when runCtx is cancelled.
|
||||
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, error) {
|
||||
// Retries stop early when runCtx is cancelled. logger carries the job's
|
||||
// fields.
|
||||
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job, logger *slog.Logger) (int, error) {
|
||||
data, err := q.renderer.Render(jobCtx, job)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("rendering: %w", err)
|
||||
@@ -247,7 +265,7 @@ func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, err
|
||||
if attempt > q.options.Retries {
|
||||
return attempt, err
|
||||
}
|
||||
q.logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
|
||||
logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
|
||||
select {
|
||||
case <-time.After(delay):
|
||||
case <-runCtx.Done():
|
||||
|
||||
@@ -114,7 +114,7 @@ func TestSubmitAndPrintInOrder(t *testing.T) {
|
||||
|
||||
var last printqueue.Status
|
||||
for _, text := range []string{"one", "two", "three"} {
|
||||
st, err := q.Submit(job(text))
|
||||
st, err := q.Submit(job(text), printqueue.Meta{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -132,11 +132,63 @@ func TestSubmitAndPrintInOrder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// lockedBuffer is a log destination safe for the worker and the test.
|
||||
type lockedBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf strings.Builder
|
||||
}
|
||||
|
||||
func (b *lockedBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *lockedBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
func TestMetaInStatusAndLogs(t *testing.T) {
|
||||
var logs lockedBuffer
|
||||
// One failed send, so that the retry is logged too.
|
||||
q := printqueue.New(fakeRenderer{}, &fakeSender{failures: 1}, slog.New(slog.NewTextHandler(&logs, nil)),
|
||||
printqueue.Options{Size: 1, History: 1, Retries: 1, RetryDelay: time.Millisecond})
|
||||
startQueue(t, q)
|
||||
|
||||
st, err := q.Submit(job("private text"), printqueue.Meta{Source: "module:ntfy", Ref: "req_01kbx4n6m3ex8tq0wq3r5vrzq1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Source != "module:ntfy" {
|
||||
t.Errorf("submit status source = %q", st.Source)
|
||||
}
|
||||
done := waitForState(t, q, st.ID, printqueue.StateDone)
|
||||
if done.Source != "module:ntfy" {
|
||||
t.Errorf("done status source = %q", done.Source)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
|
||||
if len(lines) != 3 || !strings.Contains(lines[1], "send failed, retrying") {
|
||||
t.Fatalf("want the printing, retry and printed lines, got:\n%s", logs.String())
|
||||
}
|
||||
for _, line := range lines {
|
||||
for _, want := range []string{"source=module:ntfy", "ref=req_01kbx4n6m3ex8tq0wq3r5vrzq1", "job_id=" + st.ID.String()} {
|
||||
if !strings.Contains(line, want) {
|
||||
t.Errorf("log line lacks %s: %s", want, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.Contains(logs.String(), "private text") {
|
||||
t.Error("the job's text reached the logs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetriesThenSucceeds(t *testing.T) {
|
||||
sender := &fakeSender{failures: 2}
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{Retries: 3})
|
||||
startQueue(t, q)
|
||||
st, _ := q.Submit(job("x"))
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
done := waitForState(t, q, st.ID, printqueue.StateDone)
|
||||
if done.Attempts != 3 {
|
||||
t.Errorf("attempts = %d, want 3", done.Attempts)
|
||||
@@ -151,7 +203,7 @@ func TestFailsAfterRetries(t *testing.T) {
|
||||
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
|
||||
})
|
||||
cancel, wait := startQueue(t, q)
|
||||
st, _ := q.Submit(job("x"))
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
|
||||
t.Errorf("failed status = %+v", failed)
|
||||
@@ -176,7 +228,7 @@ func TestRenderFailureIsNotRetried(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3})
|
||||
startQueue(t, q)
|
||||
st, _ := q.Submit(job("x"))
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if !strings.Contains(failed.Error, "image blocked") || len(sender.Sent()) != 0 {
|
||||
t.Errorf("failed status = %+v, sent %v", failed, sender.Sent())
|
||||
@@ -187,11 +239,11 @@ func TestQueueFull(t *testing.T) {
|
||||
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{Size: 2})
|
||||
// Not running, so nothing drains the queue.
|
||||
for range 2 {
|
||||
if _, err := q.Submit(job("x")); err != nil {
|
||||
if _, err := q.Submit(job("x"), printqueue.Meta{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := q.Submit(job("x")); !errors.Is(err, printqueue.ErrQueueFull) {
|
||||
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrQueueFull) {
|
||||
t.Errorf("err = %v, want ErrQueueFull", err)
|
||||
}
|
||||
if q.Pending() != 2 {
|
||||
@@ -204,9 +256,9 @@ func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
|
||||
cancel, wait := startQueue(t, q)
|
||||
|
||||
first, _ := q.Submit(job("first"))
|
||||
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||
waitForState(t, q, first.ID, printqueue.StatePrinting)
|
||||
second, _ := q.Submit(job("second"))
|
||||
second, _ := q.Submit(job("second"), printqueue.Meta{})
|
||||
|
||||
// Cancel while the first send is still blocked, so Run is shutting down
|
||||
// by the time that send completes.
|
||||
@@ -220,7 +272,7 @@ func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
|
||||
if st, _ := q.Status(second.ID); st.State != printqueue.StateFailed || !strings.Contains(st.Error, "shutting down") {
|
||||
t.Errorf("waiting job = %+v, want failed with shutting down", st)
|
||||
}
|
||||
if _, err := q.Submit(job("late")); !errors.Is(err, printqueue.ErrClosed) {
|
||||
if _, err := q.Submit(job("late"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrClosed) {
|
||||
t.Errorf("submit after shutdown err = %v, want ErrClosed", err)
|
||||
}
|
||||
}
|
||||
@@ -231,7 +283,7 @@ func TestHistoryEviction(t *testing.T) {
|
||||
startQueue(t, q)
|
||||
var ids []printqueue.JobID
|
||||
for range 3 {
|
||||
st, _ := q.Submit(job("x"))
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
ids = append(ids, st.ID)
|
||||
waitForState(t, q, st.ID, printqueue.StateDone)
|
||||
}
|
||||
@@ -245,7 +297,7 @@ func TestHistoryEviction(t *testing.T) {
|
||||
|
||||
func TestParseJobID(t *testing.T) {
|
||||
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{})
|
||||
st, _ := q.Submit(job("x"))
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
parsed, err := printqueue.ParseJobID(st.ID.String())
|
||||
if err != nil || parsed != st.ID {
|
||||
t.Errorf("ParseJobID(%s) = %v, %v", st.ID, parsed, err)
|
||||
|
||||
@@ -68,11 +68,13 @@ var fields = []field{
|
||||
{"hri", func(e Element) bool { return e.HRI != "" }},
|
||||
{"url", func(e Element) bool { return e.URL != "" }},
|
||||
{"base64", func(e Element) bool { return e.Base64 != "" }},
|
||||
{"optional", func(e Element) bool { return e.Optional }},
|
||||
{"hex", func(e Element) bool { return e.Hex != "" }},
|
||||
{"mode", func(e Element) bool { return e.Mode != "" }},
|
||||
{"children", func(e Element) bool { return e.Children != nil }},
|
||||
{"title", func(e Element) bool { return e.Title != "" }},
|
||||
{"title_style", func(e Element) bool { return e.TitleStyle != "" }},
|
||||
{"title_bold", func(e Element) bool { return e.TitleBold }},
|
||||
{"footer", func(e Element) bool { return e.Footer != "" }},
|
||||
{"style", func(e Element) bool { return e.Style != "" }},
|
||||
{"padding", func(e Element) bool { return e.Padding != nil }},
|
||||
@@ -86,11 +88,16 @@ var fields = []field{
|
||||
}
|
||||
|
||||
// blockOnly are the fields no other type takes.
|
||||
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader items bullet done")
|
||||
var blockOnly = fieldSet("children title title_style title_bold footer style padding fit columns pairs leader items bullet done")
|
||||
|
||||
// ownFields maps each field that only one of the other types takes to that
|
||||
// type. The rest of the other types refuse it, as they refuse the block
|
||||
// fields.
|
||||
var ownFields = map[string]string{"optional": TypeImage}
|
||||
|
||||
// blockFields are the fields each block takes at the top level.
|
||||
var blockFields = map[string]map[string]bool{
|
||||
TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"),
|
||||
TypeBox: fieldSet("text bold underline invert align size font children title title_style title_bold footer style padding fit columns"),
|
||||
TypeRule: fieldSet("text bold align size font style columns"),
|
||||
TypeKV: fieldSet("pairs leader size font columns"),
|
||||
TypeList: fieldSet("items bullet done size font columns"),
|
||||
@@ -118,7 +125,8 @@ func fieldSet(names string) map[string]bool {
|
||||
|
||||
// checkFields reports fields set on el that its type does not take. The
|
||||
// blocks and the children of a box take only their own fields; the other
|
||||
// types ignore unrelated fields, except the block fields.
|
||||
// types ignore unrelated fields, except the block fields and the fields
|
||||
// another type owns.
|
||||
func (el Element) checkFields(inBox bool) []string {
|
||||
allowed, strict := blockFields[el.Type]
|
||||
if inBox {
|
||||
@@ -138,7 +146,8 @@ func (el Element) checkFields(inBox bool) []string {
|
||||
problems = append(problems, fmt.Sprintf("%s is inherited from the box", f.name))
|
||||
case inBox && !allowed[f.name]:
|
||||
problems = append(problems, fmt.Sprintf("field %q does not apply to %s inside a box", f.name, el.Type))
|
||||
case strict && !allowed[f.name], !strict && blockOnly[f.name]:
|
||||
case strict && !allowed[f.name], !strict && blockOnly[f.name],
|
||||
!strict && ownFields[f.name] != "" && ownFields[f.name] != el.Type:
|
||||
problems = append(problems, fmt.Sprintf("field %q does not apply to %s", f.name, el.Type))
|
||||
}
|
||||
}
|
||||
@@ -166,6 +175,7 @@ func checkColumns(columns int) error {
|
||||
type boxSpec struct {
|
||||
style boxStyle
|
||||
capped bool
|
||||
title textStyle
|
||||
text textStyle
|
||||
align escpos.Justification
|
||||
padding int
|
||||
@@ -177,6 +187,7 @@ type boxSpec struct {
|
||||
|
||||
func (el Element) boxSpec() (boxSpec, error) {
|
||||
s := boxSpec{
|
||||
title: textStyle{bold: el.TitleBold},
|
||||
text: textStyle{bold: el.Bold, invert: el.Invert},
|
||||
padding: defaultPadding,
|
||||
fit: el.Fit,
|
||||
|
||||
@@ -140,7 +140,7 @@ func (lo *layout) box(el Element, spec boxSpec, cols int) []blockLine {
|
||||
padding = min(padding, (width-minBoxWidth)/2)
|
||||
content := width - 2 - 2*padding
|
||||
|
||||
lines := []blockLine{set.top(title, spec.capped, width)}
|
||||
lines := []blockLine{set.top(title, spec.title, spec.capped, width)}
|
||||
for _, it := range items {
|
||||
if it.kind == itemDivider {
|
||||
lines = append(lines, lo.divider(set, it, width))
|
||||
@@ -285,8 +285,8 @@ func (it boxItem) contentLines(width int) []blockLine {
|
||||
return lines
|
||||
}
|
||||
|
||||
// top draws the top border, with the title set into it.
|
||||
func (b borders) top(title string, capped bool, width int) blockLine {
|
||||
// top draws the top border, with the title set into it in style.
|
||||
func (b borders) top(title string, style textStyle, capped bool, width int) blockLine {
|
||||
h := string(b.horizontal)
|
||||
inner := width - 2
|
||||
room := inlineTitleRoom
|
||||
@@ -306,7 +306,7 @@ func (b borders) top(title string, capped bool, width int) blockLine {
|
||||
rest := width - runeLen(head) - runeLen(title) - runeLen(tail) - 1
|
||||
return blockLine{
|
||||
plain(head),
|
||||
plain(title),
|
||||
{text: title, style: style},
|
||||
plain(tail + fill(h, rest) + string(b.topRight)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,32 @@ func TestBlockStyleRuns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBoxTitleBold(t *testing.T) {
|
||||
p, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "box", Title: "Title", TitleBold: true, Text: "x"},
|
||||
{Type: "box", Title: "Capped", TitleStyle: "capped", TitleBold: true, Style: "double", Text: "x"},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bold := escpos.Run{Bold: true, Font: escpos.FontA, W: 1, H: 1}
|
||||
tests := []struct {
|
||||
line int
|
||||
text string
|
||||
want []escpos.Run
|
||||
}{
|
||||
{0, "┌─ Title ", []escpos.Run{withSpan(bold, 3, 8)}},
|
||||
{1, "│ x ", nil},
|
||||
{3, "╔═╡ Capped ╞", []escpos.Run{withSpan(bold, 4, 10)}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
line := p.Lines[tt.line]
|
||||
if !strings.HasPrefix(line.Text, tt.text) || fmt.Sprint(line.Runs) != fmt.Sprint(tt.want) {
|
||||
t.Errorf("line %d %q runs = %+v, want %q... with %+v", tt.line, line.Text, line.Runs, tt.text, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withSpan(r escpos.Run, from, to int) escpos.Run {
|
||||
r.From, r.To = from, to
|
||||
return r
|
||||
@@ -287,6 +313,7 @@ func TestPreview(t *testing.T) {
|
||||
{Type: "raw", Hex: "1B 61 01 07"},
|
||||
{Type: "image", URL: "https://images.example/logo.png?size=2", Width: 384},
|
||||
{Type: "image", Base64: "iVBORw0KGgo=", Width: 600},
|
||||
{Type: "image", URL: "https://images.example/wide.png", Width: 600, Optional: true},
|
||||
{Type: "qr", Data: "https://example.com"},
|
||||
{Type: "barcode", Symbology: "ean8", Data: "9638507"},
|
||||
{Type: "cut", Mode: "full"},
|
||||
@@ -303,6 +330,7 @@ func TestPreview(t *testing.T) {
|
||||
"[raw 4 bytes]",
|
||||
"[image 384 dots: logo.png]",
|
||||
"[image 600 dots: base64]",
|
||||
"[image 512 dots: wide.png]",
|
||||
"[qr: https://example.com]",
|
||||
"[barcode ean8: 9638507]",
|
||||
" - - - - - - - - full cut - - - - - - - -",
|
||||
@@ -315,8 +343,8 @@ func TestPreview(t *testing.T) {
|
||||
if p.Lines[2].Data != "https://images.example/logo.png?size=2" || p.Lines[3].Data != "base64" {
|
||||
t.Errorf("image data = %q, %q", p.Lines[2].Data, p.Lines[3].Data)
|
||||
}
|
||||
if p.Columns != 42 || p.CodePage != escpos.CodePage437 || p.LineCount != 10 {
|
||||
t.Errorf("columns %d, code page %s, %d lines; want 42, cp437 and 10", p.Columns, p.CodePage, p.LineCount)
|
||||
if p.Columns != 42 || p.CodePage != escpos.CodePage437 || p.LineCount != 12 {
|
||||
t.Errorf("columns %d, code page %s, %d lines; want 42, cp437 and 12", p.Columns, p.CodePage, p.LineCount)
|
||||
}
|
||||
wantWarnings := []string{
|
||||
"elements[0]: 1 character not in cp437 printed as ?",
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -74,11 +75,17 @@ func TestRenderCompat(t *testing.T) {
|
||||
var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex from the current renderer")
|
||||
|
||||
// paperReceipts are jobs whose printed result was checked on the TM-T88IV,
|
||||
// with the file their bytes are pinned in. The bytes are rendered for a
|
||||
// TM-T88 in CP437 with the default options.
|
||||
var paperReceipts = []struct{ job, hex string }{
|
||||
{filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")},
|
||||
{filepath.Join("testdata", "paper", "note.json"), filepath.Join("testdata", "paper", "note.hex")},
|
||||
// with the file their bytes are pinned in and, for a job with an image
|
||||
// URL, the image it was printed with. The bytes are rendered for a TM-T88
|
||||
// in CP437 with the default options.
|
||||
var paperReceipts = []struct{ job, hex, image string }{
|
||||
{job: filepath.Join("..", "..", "..", "examples", "blocks.json"), hex: filepath.Join("testdata", "paper", "blocks.hex")},
|
||||
{job: filepath.Join("testdata", "paper", "note.json"), hex: filepath.Join("testdata", "paper", "note.hex")},
|
||||
{job: filepath.Join("testdata", "paper", "ntfy-high.json"), hex: filepath.Join("testdata", "paper", "ntfy-high.hex"),
|
||||
image: filepath.Join("testdata", "paper", "graph.png")},
|
||||
{job: filepath.Join("testdata", "paper", "ntfy-urgent.json"), hex: filepath.Join("testdata", "paper", "ntfy-urgent.hex")},
|
||||
{job: filepath.Join("testdata", "paper", "ntfy-default.json"), hex: filepath.Join("testdata", "paper", "ntfy-default.hex")},
|
||||
{job: filepath.Join("testdata", "paper", "ntfy-min.json"), hex: filepath.Join("testdata", "paper", "ntfy-min.hex")},
|
||||
}
|
||||
|
||||
// TestPaperReceipts fails when the bytes of a receipt checked on paper
|
||||
@@ -90,17 +97,27 @@ func TestPaperReceipts(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fetcher := &fakeFetcher{err: errors.New("the job has no image")}
|
||||
if receiptFile.image != "" {
|
||||
if fetcher.data, err = os.ReadFile(receiptFile.image); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fetcher.err = nil
|
||||
}
|
||||
r := receipt.NewRenderer(receipt.Options{
|
||||
Profile: profile,
|
||||
CodePage: escpos.CodePage437,
|
||||
MaxPixels: 25_000_000,
|
||||
MaxHeight: 4000,
|
||||
MaxLines: 2000,
|
||||
}, &fakeFetcher{})
|
||||
}, fetcher)
|
||||
got, err := r.Render(context.Background(), readJob(t, receiptFile.job))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(got, []byte("[image unavailable]")) {
|
||||
t.Fatal("an image of the receipt did not load")
|
||||
}
|
||||
if *updatePaper {
|
||||
if err := os.MkdirAll(filepath.Dir(receiptFile.hex), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -87,7 +87,9 @@ type Element struct {
|
||||
Bold bool `json:"bold,omitempty"`
|
||||
// Size sets width and height together: 1-8 for text, 1-3 for a block,
|
||||
// whose borders scale with its text. For a QR code it is the module size
|
||||
// in dots, 1-16, default 6. 0 means the default.
|
||||
// in dots, 1-16, default 6, made smaller for a code that could be wider
|
||||
// than the paper, its width worked out as if its data were bytes. 0
|
||||
// means the default.
|
||||
Size int `json:"size,omitempty" jsonschema:"minimum=0,maximum=16"`
|
||||
// Width is the character width for text (1-8), the module width of a
|
||||
// barcode (2-6, default 3), or the target width of an image in dots. 0
|
||||
@@ -132,6 +134,10 @@ type Element struct {
|
||||
// Base64 is an image's data in base64, or a data:image/...;base64, URI:
|
||||
// PNG, JPEG, GIF or WebP.
|
||||
Base64 string `json:"base64,omitempty"`
|
||||
// Optional prints the line [image unavailable] in place of an image
|
||||
// that cannot be fetched or decoded, instead of failing the whole job,
|
||||
// and shrinks an image whose width is wider than the paper to it.
|
||||
Optional bool `json:"optional,omitempty"`
|
||||
|
||||
// Hex is a raw element's ESC/POS bytes in hex, spaces allowed, e.g.
|
||||
// "1B 61 01". It is sent as given.
|
||||
@@ -147,6 +153,8 @@ type Element struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
// TitleStyle is inline, the default, or capped.
|
||||
TitleStyle string `json:"title_style,omitempty" jsonschema:"enum=inline,enum=capped"`
|
||||
// TitleBold prints a box's title bold.
|
||||
TitleBold bool `json:"title_bold,omitempty"`
|
||||
// Footer is text set into a box's bottom border, on the right.
|
||||
Footer string `json:"footer,omitempty"`
|
||||
// Style is a box's border style (single, double, double-h, double-v or
|
||||
|
||||
@@ -104,6 +104,61 @@ func foldFor(r rune, cp escpos.CodePage) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// codePages are the code pages a printer may be set to.
|
||||
var codePages = []escpos.CodePage{escpos.CodePage437, escpos.CodePage850, escpos.CodePage858, escpos.CodePage1252}
|
||||
|
||||
// StripEmoji removes the emoji from s, which normalize would print as '?':
|
||||
// each emoji sequence, with its selectors, skin tones and the emoji joined
|
||||
// to it, and each flag. Symbols among the emoji that a code page prints or
|
||||
// folds to a look-alike, such as ■, → and ✓, stay. So that a removed emoji
|
||||
// leaves no gap, the spaces after it go when the text before it is empty or
|
||||
// ends in a space, and spaces before it go when it ends a line.
|
||||
func StripEmoji(s string) string {
|
||||
runes := []rune(s)
|
||||
out := make([]rune, 0, len(runes))
|
||||
removed := false
|
||||
trim := func() {
|
||||
for len(out) > 0 && out[len(out)-1] == ' ' {
|
||||
out = out[:len(out)-1]
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(runes); i++ {
|
||||
r := runes[i]
|
||||
switch {
|
||||
case invisible(r):
|
||||
continue
|
||||
case pictographic(r) && !keptSymbol(r):
|
||||
i = emojiSequenceEnd(runes, i)
|
||||
removed = true
|
||||
continue
|
||||
case r == ' ' && removed && (len(out) == 0 || out[len(out)-1] == ' ' || out[len(out)-1] == '\n'):
|
||||
continue
|
||||
case r == '\n' && removed:
|
||||
trim()
|
||||
}
|
||||
removed = false
|
||||
out = append(out, r)
|
||||
}
|
||||
if removed {
|
||||
trim()
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// keptSymbol reports whether StripEmoji keeps r: a code page prints it, or
|
||||
// it folds to a look-alike.
|
||||
func keptSymbol(r rune) bool {
|
||||
if _, ok := folds[r]; ok {
|
||||
return true
|
||||
}
|
||||
for _, cp := range codePages {
|
||||
if cp.CanEncode(r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// invisible reports whether r only changes how the characters around it
|
||||
// look: variation selectors, zero-width spaces and joiners, emoji skin
|
||||
// tones, tag characters and the keycap mark.
|
||||
|
||||
@@ -74,6 +74,36 @@ func TestNormalizeLeavesPrintableTextAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripEmoji(t *testing.T) {
|
||||
tests := []struct{ in, want string }{
|
||||
{"plain text", "plain text"},
|
||||
{"Party 🎉", "Party"},
|
||||
{"🎉 Party", "Party"},
|
||||
{"Backup 🎉 done", "Backup done"},
|
||||
{"Backup 🎉 done", "Backup done"},
|
||||
{"a🎉b", "ab"},
|
||||
{"Done 🎉\nNext 🎉 line", "Done\nNext line"},
|
||||
{"👍🏽 skin tone", "skin tone"},
|
||||
{"👨\u200D👩\u200D👧 family", "family"},
|
||||
{"🇬🇧 flag", "flag"},
|
||||
{"🏴\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F tag sequence", "tag sequence"},
|
||||
{"⚠\uFE0F careful ❤\uFE0F", "careful"},
|
||||
{"1\uFE0F\u20E3 keycap", "1 keycap"},
|
||||
{"zero\u200Bwidth", "zerowidth"},
|
||||
// Symbols a code page prints or folds stay.
|
||||
{"■ → ← ✓ ✔ ⌐ √ ° ·", "■ → ← ✓ ✔ ⌐ √ ° ·"},
|
||||
{"box ┌─┐ ░▒▓█", "box ┌─┐ ░▒▓█"},
|
||||
{"✔\uFE0F checked", "✔ checked"},
|
||||
{"", ""},
|
||||
{"🎉", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := StripEmoji(tt.in); got != tt.want {
|
||||
t.Errorf("StripEmoji(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRunsBeforeWrap(t *testing.T) {
|
||||
// The ellipsis takes three columns, so "word…" no longer fits in 6.
|
||||
text, _ := normalize("ab word…", escpos.CodePage437)
|
||||
|
||||
@@ -53,7 +53,7 @@ func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error) {
|
||||
if err != nil {
|
||||
return Preview{}, fmt.Errorf("reading back the rendered receipt: %w", err)
|
||||
}
|
||||
labelImages(lines, job)
|
||||
labelImages(lines, job, r.options.Profile.DotsPerLine)
|
||||
|
||||
var warnings []string
|
||||
for i := range job.Elements {
|
||||
@@ -79,7 +79,8 @@ func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error) {
|
||||
|
||||
// placeholderImages returns a blank one-row raster across the paper for
|
||||
// every image element, and a warning for each image that would fail to
|
||||
// print because it is wider than the paper.
|
||||
// print because it is wider than the paper. An optional image that is
|
||||
// wider shrinks to the paper instead.
|
||||
func (r *Renderer) placeholderImages(job Job) (map[int]*image.Paletted, map[int]string) {
|
||||
paper := r.options.Profile.DotsPerLine
|
||||
images := make(map[int]*image.Paletted)
|
||||
@@ -88,7 +89,7 @@ func (r *Renderer) placeholderImages(job Job) (map[int]*image.Paletted, map[int]
|
||||
if el.Type != TypeImage {
|
||||
continue
|
||||
}
|
||||
if el.Width > paper {
|
||||
if el.Width > paper && !el.Optional {
|
||||
warnings[i] = fmt.Sprintf("elements[%d] (image): width %d is wider than the %d-dot paper, so the job would fail", i, el.Width, paper)
|
||||
}
|
||||
images[i] = image.NewPaletted(image.Rect(0, 0, paper, 1), color.Palette{color.White, color.Black})
|
||||
@@ -97,8 +98,9 @@ func (r *Renderer) placeholderImages(job Job) (map[int]*image.Paletted, map[int]
|
||||
}
|
||||
|
||||
// labelImages replaces the size of each image placeholder with the source
|
||||
// of its element, in order, copy after copy.
|
||||
func labelImages(lines []escpos.PreviewLine, job Job) {
|
||||
// of its element, in order, copy after copy. An optional image wider than
|
||||
// the paper, paper dots, is labelled with the width it prints at.
|
||||
func labelImages(lines []escpos.PreviewLine, job Job, paper int) {
|
||||
var sources []Element
|
||||
for _, el := range job.Elements {
|
||||
if el.Type == TypeImage {
|
||||
@@ -117,8 +119,11 @@ func labelImages(lines []escpos.PreviewLine, job Job) {
|
||||
name, data = imageName(el.URL), el.URL
|
||||
}
|
||||
lines[i].Text = fmt.Sprintf("[image: %s]", name)
|
||||
if el.Width > 0 {
|
||||
lines[i].Text = fmt.Sprintf("[image %d dots: %s]", el.Width, name)
|
||||
if width := el.Width; width > 0 {
|
||||
if el.Optional {
|
||||
width = min(width, paper)
|
||||
}
|
||||
lines[i].Text = fmt.Sprintf("[image %d dots: %s]", width, name)
|
||||
}
|
||||
lines[i].Data = data
|
||||
}
|
||||
|
||||
@@ -285,6 +285,119 @@ func TestRenderFetchFailureProducesNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderOptionalImage(t *testing.T) {
|
||||
fetchErr := errors.New("blocked")
|
||||
job := receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: "before"},
|
||||
{Type: "image", URL: "https://images.example/x.png", Optional: true, Align: "center"},
|
||||
{Type: "text", Text: "after"},
|
||||
}}
|
||||
for name, fetcher := range map[string]*fakeFetcher{
|
||||
"fetch fails": {err: fetchErr},
|
||||
"decode fails": {data: []byte("not an image")},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
out, err := newRenderer(t, fetcher).Render(context.Background(), job)
|
||||
if err != nil {
|
||||
t.Fatalf("Render: %v", err)
|
||||
}
|
||||
// Centred, as the image would have been.
|
||||
at := bytes.Index(out, []byte("[image unavailable]\n"))
|
||||
if at < 0 {
|
||||
t.Fatalf("no placeholder line in % X", out)
|
||||
}
|
||||
if centre := bytes.LastIndex(out[:at], []byte{0x1B, 0x61}); centre < 0 || out[centre+2] != 1 {
|
||||
t.Errorf("the placeholder is not centred: % X", out)
|
||||
}
|
||||
if bytes.Contains(out, []byte{0x1D, 0x76, 0x30}) {
|
||||
t.Error("an image that failed to load was printed")
|
||||
}
|
||||
if !bytes.Contains(out, []byte("after")) {
|
||||
t.Error("the rest of the receipt is missing")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("not optional", func(t *testing.T) {
|
||||
job := job
|
||||
job.Elements = append([]receipt.Element(nil), job.Elements...)
|
||||
job.Elements[1].Optional = false
|
||||
out, err := newRenderer(t, &fakeFetcher{err: fetchErr}).Render(context.Background(), job)
|
||||
if !errors.Is(err, fetchErr) || out != nil {
|
||||
t.Errorf("Render = %d bytes, %v; want nil and the fetch error", len(out), err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("loads", func(t *testing.T) {
|
||||
out, err := newRenderer(t, &fakeFetcher{data: pngData(t, 100, 10)}).Render(context.Background(), job)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(out, []byte("[image unavailable]")) || !bytes.Contains(out, []byte{0x1D, 0x76, 0x30}) {
|
||||
t.Error("an optional image that loads did not print as an image")
|
||||
}
|
||||
})
|
||||
|
||||
// The renderer is a 576-dot TM-T20: a width of 600 shrinks to 576 dots,
|
||||
// 72 bytes a raster row, while a required image of that width fails.
|
||||
t.Run("wider than the paper", func(t *testing.T) {
|
||||
wide := job
|
||||
wide.Elements = append([]receipt.Element(nil), job.Elements...)
|
||||
wide.Elements[1].Width = 600
|
||||
out, err := newRenderer(t, &fakeFetcher{data: pngData(t, 600, 10)}).Render(context.Background(), wide)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(out, []byte("[image unavailable]")) || !bytes.Contains(out, []byte{0x1D, 0x76, 0x30, 0, 72, 0}) {
|
||||
t.Errorf("the image did not print 576 dots wide: % X", out)
|
||||
}
|
||||
wide.Elements[1].Optional = false
|
||||
if _, err := newRenderer(t, &fakeFetcher{data: pngData(t, 600, 10)}).Render(context.Background(), wide); err == nil {
|
||||
t.Error("a required image wider than the paper printed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A QR code that would be wider than the paper prints with smaller
|
||||
// modules; one that fits keeps its size.
|
||||
func TestRenderQRFitsThePaper(t *testing.T) {
|
||||
profile, err := escpos.LookupProfile("generic-58mm")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := receipt.NewRenderer(receipt.Options{Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000}, &fakeFetcher{})
|
||||
moduleSize := func(data string, size int) byte {
|
||||
t.Helper()
|
||||
out, err := r.Render(context.Background(), receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: data, Size: size}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := bytes.Index(out, []byte{0x1D, '(', 'k', 3, 0, '1', 'C'})
|
||||
if at < 0 {
|
||||
t.Fatalf("no module size in % X", out)
|
||||
}
|
||||
return out[at+7]
|
||||
}
|
||||
// 26 bytes at M is version 2, 25 modules: 125 dots at size 5.
|
||||
if got := moduleSize("https://grafana.lan/d/disk", 5); got != 5 {
|
||||
t.Errorf("a code that fits: size %d, want 5", got)
|
||||
}
|
||||
// 500 bytes at M is version 17, 85 modules: 425 dots at size 5, wider
|
||||
// than 384; size 4 makes 340.
|
||||
if got := moduleSize(strings.Repeat("x", 500), 5); got != 4 {
|
||||
t.Errorf("a code too wide: size %d, want 4", got)
|
||||
}
|
||||
// 2331 bytes at M is version 40, 177 modules: only size 2 fits.
|
||||
if got := moduleSize(strings.Repeat("x", 2331), 16); got != 2 {
|
||||
t.Errorf("the largest code: size %d, want 2", got)
|
||||
}
|
||||
// 2400 digits fit only a denser mode than bytes, so they count as version
|
||||
// 40 too.
|
||||
if got := moduleSize(strings.Repeat("7", 2400), 6); got != 2 {
|
||||
t.Errorf("2400 digits: size %d, want 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user