subscribe.go 7.9 KB

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