subscribe.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package cmd
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/urfave/cli/v2"
  6. "heckel.io/ntfy/client"
  7. "heckel.io/ntfy/util"
  8. "log"
  9. "os"
  10. "os/exec"
  11. "os/user"
  12. "strings"
  13. )
  14. var cmdSubscribe = &cli.Command{
  15. Name: "subscribe",
  16. Aliases: []string{"sub"},
  17. Usage: "Subscribe to one or more topics on a ntfy server",
  18. UsageText: "ntfy subscribe [OPTIONS..] [TOPIC]",
  19. Action: execSubscribe,
  20. Category: categoryClient,
  21. Flags: []cli.Flag{
  22. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
  23. &cli.StringFlag{Name: "since", Aliases: []string{"s"}, Usage: "return events since `SINCE` (Unix timestamp, or all)"},
  24. &cli.StringFlag{Name: "user", Aliases: []string{"u"}, Usage: "username[:password] used to auth against the server"},
  25. &cli.BoolFlag{Name: "from-config", Aliases: []string{"C"}, Usage: "read subscriptions from config file (service mode)"},
  26. &cli.BoolFlag{Name: "poll", Aliases: []string{"p"}, Usage: "return events and exit, do not listen for new events"},
  27. &cli.BoolFlag{Name: "scheduled", Aliases: []string{"sched", "S"}, Usage: "also return scheduled/delayed events"},
  28. &cli.BoolFlag{Name: "verbose", Aliases: []string{"v"}, Usage: "print verbose output"},
  29. },
  30. Description: `Subscribe to a topic from a ntfy server, and either print or execute a command for
  31. every arriving message. There are 3 modes in which the command can be run:
  32. ntfy subscribe TOPIC
  33. This prints the JSON representation of every incoming message. It is useful when you
  34. have a command that wants to stream-read incoming JSON messages. Unless --poll is passed,
  35. this command stays open forever.
  36. Examples:
  37. ntfy subscribe mytopic # Prints JSON for incoming messages for ntfy.sh/mytopic
  38. ntfy sub home.lan/backups # Subscribe to topic on different server
  39. ntfy sub --poll home.lan/backups # Just query for latest messages and exit
  40. ntfy sub -u phil:mypass secret # Subscribe with username/password
  41. ntfy subscribe TOPIC COMMAND
  42. This executes COMMAND for every incoming messages. The message fields are passed to the
  43. command as environment variables:
  44. Variable Aliases Description
  45. --------------- --------------------- -----------------------------------
  46. $NTFY_ID $id Unique message ID
  47. $NTFY_TIME $time Unix timestamp of the message delivery
  48. $NTFY_TOPIC $topic Topic name
  49. $NTFY_MESSAGE $message, $m Message body
  50. $NTFY_TITLE $title, $t Message title
  51. $NTFY_PRIORITY $priority, $prio, $p Message priority (1=min, 5=max)
  52. $NTFY_TAGS $tags, $tag, $ta Message tags (comma separated list)
  53. $NTFY_RAW $raw Raw JSON message
  54. Examples:
  55. ntfy sub mytopic 'notify-send "$m"' # Execute command for incoming messages
  56. ntfy sub topic1 /my/script.sh # Execute script for incoming messages
  57. ntfy subscribe --from-config
  58. Service mode (used in ntfy-client.service). This reads the config file (/etc/ntfy/client.yml
  59. or ~/.config/ntfy/client.yml) and sets up subscriptions for every topic in the "subscribe:"
  60. block (see config file).
  61. Examples:
  62. ntfy sub --from-config # Read topics from config file
  63. ntfy sub --config=/my/client.yml --from-config # Read topics from alternate config file
  64. The default config file for all client commands is /etc/ntfy/client.yml (if root user),
  65. or ~/.config/ntfy/client.yml for all other users.`,
  66. }
  67. func execSubscribe(c *cli.Context) error {
  68. // Read config and options
  69. conf, err := loadConfig(c)
  70. if err != nil {
  71. return err
  72. }
  73. cl := client.New(conf)
  74. since := c.String("since")
  75. user := c.String("user")
  76. poll := c.Bool("poll")
  77. scheduled := c.Bool("scheduled")
  78. fromConfig := c.Bool("from-config")
  79. topic := c.Args().Get(0)
  80. command := c.Args().Get(1)
  81. if !fromConfig {
  82. conf.Subscribe = nil // wipe if --from-config not passed
  83. }
  84. var options []client.SubscribeOption
  85. if since != "" {
  86. options = append(options, client.WithSince(since))
  87. }
  88. if user != "" {
  89. var pass string
  90. parts := strings.SplitN(user, ":", 2)
  91. if len(parts) == 2 {
  92. user = parts[0]
  93. pass = parts[1]
  94. } else {
  95. fmt.Fprint(c.App.ErrWriter, "Enter Password: ")
  96. p, err := util.ReadPassword(c.App.Reader)
  97. if err != nil {
  98. return err
  99. }
  100. pass = string(p)
  101. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 20))
  102. }
  103. options = append(options, client.WithBasicAuth(user, pass))
  104. }
  105. if poll {
  106. options = append(options, client.WithPoll())
  107. }
  108. if scheduled {
  109. options = append(options, client.WithScheduled())
  110. }
  111. if topic == "" && len(conf.Subscribe) == 0 {
  112. return errors.New("must specify topic, type 'ntfy subscribe --help' for help")
  113. }
  114. // Execute poll or subscribe
  115. if poll {
  116. return doPoll(c, cl, conf, topic, command, options...)
  117. }
  118. return doSubscribe(c, cl, conf, topic, command, options...)
  119. }
  120. func doPoll(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  121. for _, s := range conf.Subscribe { // may be nil
  122. if err := doPollSingle(c, cl, s.Topic, s.Command, options...); err != nil {
  123. return err
  124. }
  125. }
  126. if topic != "" {
  127. if err := doPollSingle(c, cl, topic, command, options...); err != nil {
  128. return err
  129. }
  130. }
  131. return nil
  132. }
  133. func doPollSingle(c *cli.Context, cl *client.Client, topic, command string, options ...client.SubscribeOption) error {
  134. messages, err := cl.Poll(topic, options...)
  135. if err != nil {
  136. return err
  137. }
  138. for _, m := range messages {
  139. printMessageOrRunCommand(c, m, command)
  140. }
  141. return nil
  142. }
  143. func doSubscribe(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  144. commands := make(map[string]string) // Subscription ID -> command
  145. for _, s := range conf.Subscribe { // May be nil
  146. topicOptions := append(make([]client.SubscribeOption, 0), options...)
  147. for filter, value := range s.If {
  148. topicOptions = append(topicOptions, client.WithFilter(filter, value))
  149. }
  150. if s.User != "" && s.Password != "" {
  151. topicOptions = append(topicOptions, client.WithBasicAuth(s.User, s.Password))
  152. }
  153. subscriptionID := cl.Subscribe(s.Topic, topicOptions...)
  154. commands[subscriptionID] = s.Command
  155. }
  156. if topic != "" {
  157. subscriptionID := cl.Subscribe(topic, options...)
  158. commands[subscriptionID] = command
  159. }
  160. for m := range cl.Messages {
  161. command, ok := commands[m.SubscriptionID]
  162. if !ok {
  163. continue
  164. }
  165. printMessageOrRunCommand(c, m, command)
  166. }
  167. return nil
  168. }
  169. func printMessageOrRunCommand(c *cli.Context, m *client.Message, command string) {
  170. if command != "" {
  171. runCommand(c, command, m)
  172. } else {
  173. fmt.Fprintln(c.App.Writer, m.Raw)
  174. }
  175. }
  176. func runCommand(c *cli.Context, command string, m *client.Message) {
  177. if err := runCommandInternal(c, command, m); err != nil {
  178. fmt.Fprintf(c.App.ErrWriter, "Command failed: %s\n", err.Error())
  179. }
  180. }
  181. func runCommandInternal(c *cli.Context, command string, m *client.Message) error {
  182. scriptFile, err := createTmpScript(command)
  183. if err != nil {
  184. return err
  185. }
  186. defer os.Remove(scriptFile)
  187. verbose := c.Bool("verbose")
  188. if verbose {
  189. log.Printf("[%s] Executing: %s (for message: %s)", util.ShortTopicURL(m.TopicURL), command, m.Raw)
  190. }
  191. cmd := exec.Command("sh", "-c", scriptFile)
  192. cmd.Stdin = c.App.Reader
  193. cmd.Stdout = c.App.Writer
  194. cmd.Stderr = c.App.ErrWriter
  195. cmd.Env = envVars(m)
  196. return cmd.Run()
  197. }
  198. func createTmpScript(command string) (string, error) {
  199. scriptFile := fmt.Sprintf("%s/ntfy-subscribe-%s.sh.tmp", os.TempDir(), util.RandomString(10))
  200. script := fmt.Sprintf("#!/bin/sh\n%s", command)
  201. if err := os.WriteFile(scriptFile, []byte(script), 0700); err != nil {
  202. return "", err
  203. }
  204. return scriptFile, nil
  205. }
  206. func envVars(m *client.Message) []string {
  207. env := os.Environ()
  208. env = append(env, envVar(m.ID, "NTFY_ID", "id")...)
  209. env = append(env, envVar(m.Topic, "NTFY_TOPIC", "topic")...)
  210. env = append(env, envVar(fmt.Sprintf("%d", m.Time), "NTFY_TIME", "time")...)
  211. env = append(env, envVar(m.Message, "NTFY_MESSAGE", "message", "m")...)
  212. env = append(env, envVar(m.Title, "NTFY_TITLE", "title", "t")...)
  213. env = append(env, envVar(fmt.Sprintf("%d", m.Priority), "NTFY_PRIORITY", "priority", "prio", "p")...)
  214. env = append(env, envVar(strings.Join(m.Tags, ","), "NTFY_TAGS", "tags", "tag", "ta")...)
  215. env = append(env, envVar(m.Raw, "NTFY_RAW", "raw")...)
  216. return env
  217. }
  218. func envVar(value string, vars ...string) []string {
  219. env := make([]string, 0)
  220. for _, v := range vars {
  221. env = append(env, fmt.Sprintf("%s=%s", v, value))
  222. }
  223. return env
  224. }
  225. func loadConfig(c *cli.Context) (*client.Config, error) {
  226. filename := c.String("config")
  227. if filename != "" {
  228. return client.LoadConfig(filename)
  229. }
  230. u, _ := user.Current()
  231. configFile := defaultClientRootConfigFile
  232. if u.Uid != "0" {
  233. configFile = util.ExpandHome(defaultClientUserConfigFile)
  234. }
  235. if s, _ := os.Stat(configFile); s != nil {
  236. return client.LoadConfig(configFile)
  237. }
  238. return client.NewConfig(), nil
  239. }