publish.go 11 KB

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