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) }