publish.go 11 KB

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