publish.go 13 KB

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