subscribe.go 8.1 KB

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