Debian Codegraph @

cmd/publish.go

raw
1 package cmd
2
3 import (
4 "errors"
5 "fmt"
6 "github.com/urfave/cli/v2"
7 "heckel.io/ntfy/v2/client"
8 "heckel.io/ntfy/v2/log"
9 "heckel.io/ntfy/v2/util"
10 "io"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "strings"
15 "time"
16 )
17
18 func init() {
19 commands = append(commands, cmdPublish)
20 }
21
22 var flagsPublish = append(
23 append([]cli.Flag{}, flagsDefault...),
24 &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG"}, Usage: "client config file"},
25 &cli.StringFlag{Name: "title", Aliases: []string{"t"}, EnvVars: []string{"NTFY_TITLE"}, Usage: "message title"},
26 &cli.StringFlag{Name: "message", Aliases: []string{"m"}, EnvVars: []string{"NTFY_MESSAGE"}, Usage: "message body"},
27 &cli.StringFlag{Name: "priority", Aliases: []string{"p"}, EnvVars: []string{"NTFY_PRIORITY"}, Usage: "priority of the message (1=min, 2=low, 3=default, 4=high, 5=max)"},
28 &cli.StringFlag{Name: "tags", Aliases: []string{"tag", "T"}, EnvVars: []string{"NTFY_TAGS"}, Usage: "comma separated list of tags and emojis"},
29 &cli.StringFlag{Name: "delay", Aliases: []string{"at", "in", "D"}, EnvVars: []string{"NTFY_DELAY"}, Usage: "delay/schedule message"},
30 &cli.StringFlag{Name: "click", Aliases: []string{"U"}, EnvVars: []string{"NTFY_CLICK"}, Usage: "URL to open when notification is clicked"},
31 &cli.StringFlag{Name: "icon", Aliases: []string{"i"}, EnvVars: []string{"NTFY_ICON"}, Usage: "URL to use as notification icon"},
32 &cli.StringFlag{Name: "actions", Aliases: []string{"A"}, EnvVars: []string{"NTFY_ACTIONS"}, Usage: "actions JSON array or simple definition"},
33 &cli.StringFlag{Name: "attach", Aliases: []string{"a"}, EnvVars: []string{"NTFY_ATTACH"}, Usage: "URL to send as an external attachment"},
34 &cli.BoolFlag{Name: "markdown", Aliases: []string{"md"}, EnvVars: []string{"NTFY_MARKDOWN"}, Usage: "Message is formatted as Markdown"},
35 &cli.StringFlag{Name: "template", Aliases: []string{"tpl"}, EnvVars: []string{"NTFY_TEMPLATE"}, Usage: "use templates to transform JSON message body"},
36 &cli.StringFlag{Name: "filename", Aliases: []string{"name", "n"}, EnvVars: []string{"NTFY_FILENAME"}, Usage: "filename for the attachment"},
37 &cli.StringFlag{Name: "sequence-id", Aliases: []string{"sequence_id", "sid", "S"}, EnvVars: []string{"NTFY_SEQUENCE_ID"}, Usage: "sequence ID for updating notifications"},
38 &cli.StringFlag{Name: "file", Aliases: []string{"f"}, EnvVars: []string{"NTFY_FILE"}, Usage: "file to upload as an attachment"},
39 &cli.StringFlag{Name: "email", Aliases: []string{"mail", "e"}, EnvVars: []string{"NTFY_EMAIL"}, Usage: "also send to e-mail address"},
40 &cli.StringFlag{Name: "user", Aliases: []string{"u"}, EnvVars: []string{"NTFY_USER"}, Usage: "username[:password] used to auth against the server"},
41 &cli.StringFlag{Name: "token", Aliases: []string{"k"}, EnvVars: []string{"NTFY_TOKEN"}, Usage: "access token used to auth against the server"},
42 &cli.IntFlag{Name: "wait-pid", Aliases: []string{"wait_pid", "pid"}, EnvVars: []string{"NTFY_WAIT_PID"}, Usage: "wait until PID exits before publishing"},
43 &cli.BoolFlag{Name: "wait-cmd", Aliases: []string{"wait_cmd", "cmd", "done"}, EnvVars: []string{"NTFY_WAIT_CMD"}, Usage: "run command and wait until it finishes before publishing"},
44 &cli.BoolFlag{Name: "no-cache", Aliases: []string{"no_cache", "C"}, EnvVars: []string{"NTFY_NO_CACHE"}, Usage: "do not cache message server-side"},
45 &cli.BoolFlag{Name: "no-firebase", Aliases: []string{"no_firebase", "F"}, EnvVars: []string{"NTFY_NO_FIREBASE"}, Usage: "do not forward message to Firebase"},
46 &cli.BoolFlag{Name: "quiet", Aliases: []string{"q"}, EnvVars: []string{"NTFY_QUIET"}, Usage: "do not print message"},
47 )
48
49 var cmdPublish = &cli.Command{
50 Name: "publish",
51 Aliases: []string{"pub", "send", "trigger"},
52 Usage: "Send message via a ntfy server",
53 UsageText: `ntfy publish [OPTIONS..] TOPIC [MESSAGE...]
54 ntfy publish [OPTIONS..] --wait-cmd COMMAND...
55 NTFY_TOPIC=.. ntfy publish [OPTIONS..] [MESSAGE...]`,
56 Action: execPublish,
57 Category: categoryClient,
58 Flags: flagsPublish,
59 Before: initLogFunc,
60 Description: `Publish a message to a ntfy server.
61
62 Examples:
63 ntfy publish mytopic This is my message # Send simple message
64 ntfy send myserver.com/mytopic "This is my message" # Send message to different default host
65 ntfy pub -p high backups "Backups failed" # Send high priority message
66 ntfy pub --tags=warning,skull backups "Backups failed" # Add tags/emojis to message
67 ntfy pub --delay=10s delayed_topic Laterzz # Delay message by 10s
68 ntfy pub --at=8:30am delayed_topic Laterzz # Send message at 8:30am
69 ntfy pub -e [email protected] alerts 'App is down!' # Also send email to [email protected]
70 ntfy pub --click="https://reddit.com" redd 'New msg' # Opens Reddit when notification is clicked
71 ntfy pub --icon="http://some.tld/icon.png" 'Icon!' # Send notification with custom icon
72 ntfy pub --attach="http://some.tld/file.zip" files # Send ZIP archive from URL as attachment
73 ntfy pub --file=flower.jpg flowers 'Nice!' # Send image.jpg as attachment
74 ntfy pub -S my-id mytopic 'Update me' # Send with sequence ID for updates
75 echo 'message' | ntfy publish mytopic # Send message from stdin
76 ntfy pub -u phil:mypass secret Psst # Publish with username/password
77 ntfy pub --wait-pid 1234 mytopic # Wait for process 1234 to exit before publishing
78 ntfy pub --wait-cmd mytopic rsync -av ./ /tmp/a # Run command and publish after it completes
79 NTFY_USER=phil:mypass ntfy pub secret Psst # Use env variables to set username/password
80 NTFY_TOPIC=mytopic ntfy pub "some message" # Use NTFY_TOPIC variable as topic
81 cat flower.jpg | ntfy pub --file=- flowers 'Nice!' # Same as above, send image.jpg as attachment
82 ntfy trigger mywebhook # Sending without message, useful for webhooks
83
84 Please also check out the docs on publishing messages. Especially for the --tags and --delay options,
85 it has incredibly useful information: https://ntfy.sh/docs/publish/.
86
87 ` + clientCommandDescriptionSuffix,
88 }
89
90 func execPublish(c *cli.Context) error {
91 conf, err := loadConfig(c)
92 if err != nil {
93 return err
94 }
95 title := c.String("title")
96 priority := c.String("priority")
97 tags := c.String("tags")
98 delay := c.String("delay")
99 click := c.String("click")
100 icon := c.String("icon")
101 actions := c.String("actions")
102 attach := c.String("attach")
103 markdown := c.Bool("markdown")
104 template := c.String("template")
105 filename := c.String("filename")
106 sequenceID := c.String("sequence-id")
107 file := c.String("file")
108 email := c.String("email")
109 user := c.String("user")
110 token := c.String("token")
111 noCache := c.Bool("no-cache")
112 noFirebase := c.Bool("no-firebase")
113 quiet := c.Bool("quiet")
114 pid := c.Int("wait-pid")
115
116 // Checks
117 if user != "" && token != "" {
118 return errors.New("cannot set both --user and --token")
119 }
120
121 // Do the things
122 topic, message, command, err := parseTopicMessageCommand(c)
123 if err != nil {
124 return err
125 }
126 var options []client.PublishOption
127 if title != "" {
128 options = append(options, client.WithTitle(title))
129 }
130 if priority != "" {
131 options = append(options, client.WithPriority(priority))
132 }
133 if tags != "" {
134 options = append(options, client.WithTagsList(tags))
135 }
136 if delay != "" {
137 options = append(options, client.WithDelay(delay))
138 }
139 if click != "" {
140 options = append(options, client.WithClick(click))
141 }
142 if icon != "" {
143 options = append(options, client.WithIcon(icon))
144 }
145 if actions != "" {
146 options = append(options, client.WithActions(strings.ReplaceAll(actions, "\n", " ")))
147 }
148 if attach != "" {
149 options = append(options, client.WithAttach(attach))
150 }
151 if markdown {
152 options = append(options, client.WithMarkdown())
153 }
154 if template != "" {
155 options = append(options, client.WithTemplate(template))
156 }
157 if filename != "" {
158 options = append(options, client.WithFilename(filename))
159 }
160 if sequenceID != "" {
161 options = append(options, client.WithSequenceID(sequenceID))
162 }
163 if email != "" {
164 options = append(options, client.WithEmail(email))
165 }
166 if noCache {
167 options = append(options, client.WithNoCache())
168 }
169 if noFirebase {
170 options = append(options, client.WithNoFirebase())
171 }
172 if token != "" {
173 options = append(options, client.WithBearerAuth(token))
174 } else if user != "" {
175 var pass string
176 parts := strings.SplitN(user, ":", 2)
177 if len(parts) == 2 {
178 user = parts[0]
179 pass = parts[1]
180 } else {
181 fmt.Fprint(c.App.ErrWriter, "Enter Password: ")
182 p, err := util.ReadPassword(c.App.Reader)
183 if err != nil {
184 return err
185 }
186 pass = string(p)
187 fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 20))
188 }
189 options = append(options, client.WithBasicAuth(user, pass))
190 } else if conf.DefaultToken != "" {
191 options = append(options, client.WithBearerAuth(conf.DefaultToken))
192 } else if conf.DefaultUser != "" && conf.DefaultPassword != nil {
193 options = append(options, client.WithBasicAuth(conf.DefaultUser, *conf.DefaultPassword))
194 }
195 if pid > 0 {
196 newMessage, err := waitForProcess(pid)
197 if err != nil {
198 return err
199 } else if message == "" {
200 message = newMessage
201 }
202 } else if len(command) > 0 {
203 newMessage, err := runAndWaitForCommand(command)
204 if err != nil {
205 return err
206 } else if message == "" {
207 message = newMessage
208 }
209 }
210 var body io.Reader
211 if file == "" {
212 body = strings.NewReader(message)
213 } else {
214 if message != "" {
215 options = append(options, client.WithMessage(message))
216 }
217 if file == "-" {
218 if filename == "" {
219 options = append(options, client.WithFilename("stdin"))
220 }
221 body = c.App.Reader
222 } else {
223 if filename == "" {
224 options = append(options, client.WithFilename(filepath.Base(file)))
225 }
226 body, err = os.Open(file)
227 if err != nil {
228 return err
229 }
230 }
231 }
232 cl := client.New(conf)
233 m, err := cl.PublishReader(topic, body, options...)
234 if err != nil {
235 return err
236 }
237 if !quiet {
238 fmt.Fprintln(c.App.Writer, strings.TrimSpace(m.Raw))
239 }
240 return nil
241 }
242
243 // parseTopicMessageCommand reads the topic and the remaining arguments from the context.
244
245 // There are a few cases to consider:
246 //
247 // ntfy publish <topic> [<message>]
248 // ntfy publish --wait-cmd <topic> <command>
249 // NTFY_TOPIC=.. ntfy publish [<message>]
250 // NTFY_TOPIC=.. ntfy publish --wait-cmd <command>
251 func parseTopicMessageCommand(c *cli.Context) (topic string, message string, command []string, err error) {
252 var args []string
253 topic, args, err = parseTopicAndArgs(c)
254 if err != nil {
255 return
256 }
257 if c.Bool("wait-cmd") {
258 if len(args) == 0 {
259 err = errors.New("must specify command when --wait-cmd is passed, type 'ntfy publish --help' for help")
260 return
261 }
262 command = args
263 } else {
264 message = strings.Join(args, " ")
265 }
266 if c.String("message") != "" {
267 message = c.String("message")
268 }
269 if message == "" && isStdinRedirected() {
270 var data []byte
271 data, err = io.ReadAll(io.LimitReader(c.App.Reader, 1024*1024))
272 if err != nil {
273 log.Debug("Failed to read from stdin: %s", err.Error())
274 return
275 }
276 message = strings.TrimSpace(string(data))
277 }
278 return
279 }
280
281 func parseTopicAndArgs(c *cli.Context) (topic string, args []string, err error) {
282 envTopic := os.Getenv("NTFY_TOPIC")
283 if envTopic != "" {
284 topic = envTopic
285 return topic, remainingArgs(c, 0), nil
286 }
287 if c.NArg() < 1 {
288 return "", nil, errors.New("must specify topic, type 'ntfy publish --help' for help")
289 }
290 return c.Args().Get(0), remainingArgs(c, 1), nil
291 }
292
293 func remainingArgs(c *cli.Context, fromIndex int) []string {
294 if c.NArg() > fromIndex {
295 return c.Args().Slice()[fromIndex:]
296 }
297 return []string{}
298 }
299
300 func waitForProcess(pid int) (message string, err error) {
301 if !processExists(pid) {
302 return "", fmt.Errorf("process with PID %d not running", pid)
303 }
304 start := time.Now()
305 log.Debug("Waiting for process with PID %d to exit", pid)
306 for processExists(pid) {
307 time.Sleep(500 * time.Millisecond)
308 }
309 runtime := time.Since(start).Round(time.Millisecond)
310 log.Debug("Process with PID %d exited after %s", pid, runtime)
311 return fmt.Sprintf("Process with PID %d exited after %s", pid, runtime), nil
312 }
313
314 func runAndWaitForCommand(command []string) (message string, err error) {
315 prettyCmd := util.QuoteCommand(command)
316 log.Debug("Running command: %s", prettyCmd)
317 start := time.Now()
318 cmd := exec.Command(command[0], command[1:]...)
319 if log.IsTrace() {
320 cmd.Stdout = os.Stdout
321 cmd.Stderr = os.Stderr
322 }
323 err = cmd.Run()
324 runtime := time.Since(start).Round(time.Millisecond)
325 if err != nil {
326 if exitError, ok := err.(*exec.ExitError); ok {
327 log.Debug("Command failed after %s (exit code %d): %s", runtime, exitError.ExitCode(), prettyCmd)
328 return fmt.Sprintf("Command failed after %s (exit code %d): %s", runtime, exitError.ExitCode(), prettyCmd), nil
329 }
330 // Hard fail when command does not exist or could not be properly launched
331 return "", fmt.Errorf("command failed: %s, error: %s", prettyCmd, err.Error())
332 }
333 log.Debug("Command succeeded after %s: %s", runtime, prettyCmd)
334 return fmt.Sprintf("Command succeeded after %s: %s", runtime, prettyCmd), nil
335 }
336
337 func isStdinRedirected() bool {
338 stat, err := os.Stdin.Stat()
339 if err != nil {
340 log.Debug("Failed to stat stdin: %s", err.Error())
341 return false
342 }
343 return (stat.Mode() & os.ModeCharDevice) == 0
344 }