Debian Codegraph @

action/action.go

raw
1 // Package action parses the "action buttons" that can be attached to a notification, in both the
2 // JSON and the human-readable "simple" format described at https://ntfy.sh/docs/publish/#action-buttons.
3 package action
4
5 import (
6 "encoding/json"
7 "errors"
8 "fmt"
9 "regexp"
10 "strings"
11 "unicode/utf8"
12
13 "heckel.io/ntfy/v2/model"
14 "heckel.io/ntfy/v2/util"
15 )
16
17 const (
18 actionIDLength = 10
19 actionEOF = rune(0)
20 actionsMax = 3
21 )
22
23 const (
24 actionView = "view"
25 actionBroadcast = "broadcast"
26 actionHTTP = "http"
27 actionCopy = "copy"
28 )
29
30 var (
31 actionsAll = []string{actionView, actionBroadcast, actionHTTP, actionCopy}
32 actionsWithURL = []string{actionView, actionHTTP} // Must be distinct from actionsWithValue, see populateAction()
33 actionsWithValue = []string{actionCopy} // Must be distinct from actionsWithURL, see populateAction()
34 actionsKeyRegex = regexp.MustCompile(`^([-.\w]+)\s*=\s*`)
35 )
36
37 type actionParser struct {
38 input string
39 pos int
40 }
41
42 // Parse parses the actions string as described in https://ntfy.sh/docs/publish/#action-buttons.
43 // It supports both a JSON representation (if the string begins with "[", see parseActionsFromJSON),
44 // and the "simple" format, which is more human-readable, but harder to parse (see parseActionsFromSimple).
45 func Parse(s string) (actions []*model.Action, err error) {
46 // Parse JSON or simple format
47 s = strings.TrimSpace(s)
48 if strings.HasPrefix(s, "[") {
49 actions, err = parseActionsFromJSON(s)
50 } else {
51 actions, err = parseActionsFromSimple(s)
52 }
53 if err != nil {
54 return nil, err
55 }
56
57 // Add ID field, ensure correct uppercase/lowercase
58 for i := range actions {
59 actions[i].ID = util.RandomString(actionIDLength)
60 actions[i].Action = strings.ToLower(actions[i].Action)
61 actions[i].Method = strings.ToUpper(actions[i].Method)
62 }
63
64 // Validate
65 if len(actions) > actionsMax {
66 return nil, fmt.Errorf("only %d actions allowed", actionsMax)
67 }
68 for _, action := range actions {
69 if !util.Contains(actionsAll, action.Action) {
70 return nil, fmt.Errorf("parameter 'action' cannot be '%s', valid values are 'view', 'broadcast', 'http' and 'copy'", action.Action)
71 } else if action.Label == "" {
72 return nil, fmt.Errorf("parameter 'label' is required")
73 } else if util.Contains(actionsWithURL, action.Action) && action.URL == "" {
74 return nil, fmt.Errorf("parameter 'url' is required for action '%s'", action.Action)
75 } else if util.Contains(actionsWithValue, action.Action) && action.Value == "" {
76 return nil, fmt.Errorf("parameter 'value' is required for action '%s'", action.Action)
77 } else if action.Action == actionHTTP && util.Contains([]string{"GET", "HEAD"}, action.Method) && action.Body != "" {
78 return nil, fmt.Errorf("parameter 'body' cannot be set if method is %s", action.Method)
79 }
80 }
81
82 return actions, nil
83 }
84
85 // parseActionsFromJSON converts a JSON array into an array of actions
86 func parseActionsFromJSON(s string) ([]*model.Action, error) {
87 actions := make([]*model.Action, 0)
88 if err := json.Unmarshal([]byte(s), &actions); err != nil {
89 return nil, fmt.Errorf("JSON error: %w", err)
90 }
91 return actions, nil
92 }
93
94 // parseActionsFromSimple parses the "simple" actions string (as described in
95 // https://ntfy.sh/docs/publish/#action-buttons), into an array of actions.
96 //
97 // It can parse an actions string like this:
98 //
99 // view, "Look ma, commas and \"quotes\" too", url=https://..; action=broadcast, ...
100 //
101 // It works by advancing the position ("pos") through the input string ("input").
102 //
103 // The parser is heavily inspired by https://go.dev/src/text/template/parse/lex.go (which
104 // is described by Rob Pike in this video: https://www.youtube.com/watch?v=HxaD_trXwRE),
105 // though it does not use state functions at all.
106 //
107 // Other resources:
108 //
109 // https://adampresley.github.io/2015/04/12/writing-a-lexer-and-parser-in-go-part-1.html
110 // https://github.com/adampresley/sample-ini-parser/blob/master/services/lexer/lexer/Lexer.go
111 // https://github.com/benbjohnson/sql-parser/blob/master/scanner.go
112 // https://blog.gopheracademy.com/advent-2014/parsers-lexers/
113 func parseActionsFromSimple(s string) ([]*model.Action, error) {
114 if !utf8.ValidString(s) {
115 return nil, errors.New("invalid utf-8 string")
116 }
117 parser := &actionParser{
118 pos: 0,
119 input: s,
120 }
121 return parser.Parse()
122 }
123
124 // Parse loops trough parseAction() until the end of the string is reached
125 func (p *actionParser) Parse() ([]*model.Action, error) {
126 actions := make([]*model.Action, 0)
127 for !p.eof() {
128 a, err := p.parseAction()
129 if err != nil {
130 return nil, err
131 }
132 actions = append(actions, a)
133 }
134 return actions, nil
135 }
136
137 // parseAction parses the individual sections of an action using parseSection into key/value pairs,
138 // and then uses populateAction to interpret the keys/values. The function terminates
139 // when EOF or ";" is reached.
140 func (p *actionParser) parseAction() (*model.Action, error) {
141 a := model.NewAction()
142 section := 0
143 for {
144 key, value, last, err := p.parseSection()
145 if err != nil {
146 return nil, err
147 }
148 if err := populateAction(a, section, key, value); err != nil {
149 return nil, err
150 }
151 p.slurpSpaces()
152 if last {
153 return a, nil
154 }
155 section++
156 }
157 }
158
159 // populateAction is the "business logic" of the parser. It applies the key/value
160 // pair to the action instance.
161 func populateAction(newAction *model.Action, section int, key, value string) error {
162 // Auto-expand keys based on their index
163 if key == "" && section == 0 {
164 key = "action"
165 } else if key == "" && section == 1 {
166 key = "label"
167 } else if key == "" && section == 2 && util.Contains(actionsWithURL, newAction.Action) {
168 key = "url"
169 } else if key == "" && section == 2 && util.Contains(actionsWithValue, newAction.Action) {
170 key = "value"
171 }
172
173 // Validate
174 if key == "" {
175 return fmt.Errorf("term '%s' unknown", value)
176 }
177
178 // Populate
179 if strings.HasPrefix(key, "headers.") {
180 newAction.Headers[strings.TrimPrefix(key, "headers.")] = value
181 } else if strings.HasPrefix(key, "extras.") {
182 newAction.Extras[strings.TrimPrefix(key, "extras.")] = value
183 } else {
184 switch strings.ToLower(key) {
185 case "action":
186 newAction.Action = value
187 case "label":
188 newAction.Label = value
189 case "clear":
190 lvalue := strings.ToLower(value)
191 if !util.Contains([]string{"true", "yes", "1", "false", "no", "0"}, lvalue) {
192 return fmt.Errorf("parameter 'clear' cannot be '%s', only boolean values are allowed (true/yes/1/false/no/0)", value)
193 }
194 newAction.Clear = lvalue == "true" || lvalue == "yes" || lvalue == "1"
195 case "url":
196 newAction.URL = value
197 case "method":
198 newAction.Method = value
199 case "body":
200 newAction.Body = value
201 case "value":
202 newAction.Value = value
203 case "intent":
204 newAction.Intent = value
205 default:
206 return fmt.Errorf("key '%s' unknown", key)
207 }
208 }
209 return nil
210 }
211
212 // parseSection parses a section ("key=value") and returns a key/value pair. It terminates
213 // when EOF or "," is reached.
214 func (p *actionParser) parseSection() (key string, value string, last bool, err error) {
215 p.slurpSpaces()
216 key = p.parseKey()
217 r, w := p.peek()
218 if isSectionEnd(r) {
219 p.pos += w
220 last = isLastSection(r)
221 return
222 } else if r == '"' || r == '\'' {
223 value, last, err = p.parseQuotedValue(r)
224 return
225 }
226 value, last = p.parseValue()
227 return
228 }
229
230 // parseKey uses a regex to determine whether the current position is a key definition ("key =")
231 // and returns the key if it is, or an empty string otherwise.
232 func (p *actionParser) parseKey() string {
233 matches := actionsKeyRegex.FindStringSubmatch(p.input[p.pos:])
234 if len(matches) == 2 {
235 p.pos += len(matches[0])
236 return matches[1]
237 }
238 return ""
239 }
240
241 // parseValue reads the input until EOF, "," or ";" and returns the value string. Unlike parseQuotedValue,
242 // this function does not support "," or ";" in the value itself, and spaces in the beginning and end of the
243 // string are trimmed.
244 func (p *actionParser) parseValue() (value string, last bool) {
245 start := p.pos
246 for {
247 r, w := p.peek()
248 if isSectionEnd(r) {
249 last = isLastSection(r)
250 value = strings.TrimSpace(p.input[start:p.pos])
251 p.pos += w
252 return
253 }
254 p.pos += w
255 }
256 }
257
258 // parseQuotedValue reads the input until it finds an unescaped end quote character ("), and then
259 // advances the position beyond the section end. It supports quoting strings using backslash (\).
260 func (p *actionParser) parseQuotedValue(quote rune) (value string, last bool, err error) {
261 p.pos++
262 start := p.pos
263 var prev rune
264 for {
265 r, w := p.peek()
266 if r == actionEOF {
267 err = fmt.Errorf("unexpected end of input, quote started at position %d", start)
268 return
269 } else if r == quote && prev != '\\' {
270 value = strings.ReplaceAll(p.input[start:p.pos], "\\"+string(quote), string(quote)) // \" -> "
271 p.pos += w
272
273 // Advance until section end (after "," or ";")
274 p.slurpSpaces()
275 r, w := p.peek()
276 last = isLastSection(r)
277 if !isSectionEnd(r) {
278 err = fmt.Errorf("unexpected character '%c' at position %d", r, p.pos)
279 return
280 }
281 p.pos += w
282 return
283 }
284 prev = r
285 p.pos += w
286 }
287 }
288
289 // slurpSpaces reads all space characters and advances the position
290 func (p *actionParser) slurpSpaces() {
291 for {
292 r, w := p.peek()
293 if r == actionEOF || !isSpace(r) {
294 return
295 }
296 p.pos += w
297 }
298 }
299
300 // peek returns the next run and its width
301 func (p *actionParser) peek() (rune, int) {
302 if p.eof() {
303 return actionEOF, 0
304 }
305 return utf8.DecodeRuneInString(p.input[p.pos:])
306 }
307
308 // eof returns true if the end of the input has been reached
309 func (p *actionParser) eof() bool {
310 return p.pos >= len(p.input)
311 }
312
313 func isSpace(r rune) bool {
314 return r == ' ' || r == '\t' || r == '\r' || r == '\n'
315 }
316
317 func isSectionEnd(r rune) bool {
318 return r == actionEOF || r == ';' || r == ','
319 }
320
321 func isLastSection(r rune) bool {
322 return r == actionEOF || r == ';'
323 }