Debian Codegraph @

mail/format.go

raw
1 package mail
2
3 import (
4 _ "embed" // required by go:embed
5 "encoding/json"
6 "fmt"
7 "mime"
8 "strings"
9 "time"
10
11 "heckel.io/ntfy/v2/model"
12 "heckel.io/ntfy/v2/util"
13 )
14
15 var (
16 //go:embed "mailer_emoji_map.json"
17 emojisJSON string
18
19 // emojiMap maps ntfy tag names to emoji, parsed once from the embedded JSON in init
20 emojiMap map[string]string
21 )
22
23 func init() {
24 if err := json.Unmarshal([]byte(emojisJSON), &emojiMap); err != nil {
25 panic("mail: invalid embedded emoji map: " + err.Error())
26 }
27 }
28
29 func formatMail(baseURL, senderIP, from, to string, m *model.Message) (string, error) {
30 topicURL := baseURL + "/" + m.Topic
31 subject := m.Title
32 if subject == "" {
33 subject = m.Message
34 }
35 subject = strings.ReplaceAll(strings.ReplaceAll(subject, "\r", ""), "\n", " ")
36 message := m.Message
37 trailer := ""
38 if len(m.Tags) > 0 {
39 emojis, tags := toEmojis(m.Tags)
40 if len(emojis) > 0 {
41 subject = strings.Join(emojis, " ") + " " + subject
42 }
43 if len(tags) > 0 {
44 trailer = "Tags: " + strings.Join(tags, ", ")
45 }
46 }
47 if m.Priority != 0 && m.Priority != 3 {
48 priority, err := util.PriorityString(m.Priority)
49 if err != nil {
50 return "", err
51 }
52 if trailer != "" {
53 trailer += "\n"
54 }
55 trailer += fmt.Sprintf("Priority: %s", priority)
56 }
57 if trailer != "" {
58 message += "\n\n" + trailer
59 }
60 date := time.Unix(m.Time, 0).UTC().Format(time.RFC1123Z)
61 subject = mime.BEncoding.Encode("utf-8", subject)
62 body := `From: "{shortTopicURL}" <{from}>
63 To: {to}
64 Date: {date}
65 Subject: {subject}
66 Content-Type: text/plain; charset="utf-8"
67
68 {message}
69
70 --
71 This message was sent by {ip} at {time} via {topicURL}`
72 body = strings.ReplaceAll(body, "{from}", from)
73 body = strings.ReplaceAll(body, "{to}", to)
74 body = strings.ReplaceAll(body, "{date}", date)
75 body = strings.ReplaceAll(body, "{subject}", subject)
76 body = strings.ReplaceAll(body, "{message}", message)
77 body = strings.ReplaceAll(body, "{topicURL}", topicURL)
78 body = strings.ReplaceAll(body, "{shortTopicURL}", util.ShortTopicURL(topicURL))
79 body = strings.ReplaceAll(body, "{time}", time.Unix(m.Time, 0).UTC().Format(time.RFC1123))
80 body = strings.ReplaceAll(body, "{ip}", senderIP)
81 return body, nil
82 }
83
84 func toEmojis(tags []string) (emojisOut []string, tagsOut []string) {
85 tagsOut = make([]string, 0)
86 emojisOut = make([]string, 0)
87 for _, t := range tags {
88 if emoji, ok := emojiMap[t]; ok {
89 emojisOut = append(emojisOut, emoji)
90 } else {
91 tagsOut = append(tagsOut, t)
92 }
93 }
94 return
95 }