1
0

subscribe.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "os"
  9. "strings"
  10. )
  11. func init() {
  12. commands = append(commands, cmdSubscribe)
  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 myscript.sh # Execute script for incoming messages
  57. ntfy subscribe --from-config
  58. Service mode (used in ntfy-client.service). This reads the config file and sets up
  59. subscriptions for every topic in the "subscribe:" block (see config file).
  60. Examples:
  61. ntfy sub --from-config # Read topics from config file
  62. ntfy sub --config=myclient.yml --from-config # Read topics from alternate config file
  63. ` + defaultClientConfigFileDescriptionSuffix,
  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. user := c.String("user")
  74. poll := c.Bool("poll")
  75. scheduled := c.Bool("scheduled")
  76. fromConfig := c.Bool("from-config")
  77. topic := c.Args().Get(0)
  78. command := c.Args().Get(1)
  79. if !fromConfig {
  80. conf.Subscribe = nil // wipe if --from-config not passed
  81. }
  82. var options []client.SubscribeOption
  83. if since != "" {
  84. options = append(options, client.WithSince(since))
  85. }
  86. if user != "" {
  87. var pass string
  88. parts := strings.SplitN(user, ":", 2)
  89. if len(parts) == 2 {
  90. user = parts[0]
  91. pass = parts[1]
  92. } else {
  93. fmt.Fprint(c.App.ErrWriter, "Enter Password: ")
  94. p, err := util.ReadPassword(c.App.Reader)
  95. if err != nil {
  96. return err
  97. }
  98. pass = string(p)
  99. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 20))
  100. }
  101. options = append(options, client.WithBasicAuth(user, pass))
  102. }
  103. if poll {
  104. options = append(options, client.WithPoll())
  105. }
  106. if scheduled {
  107. options = append(options, client.WithScheduled())
  108. }
  109. if topic == "" && len(conf.Subscribe) == 0 {
  110. return errors.New("must specify topic, type 'ntfy subscribe --help' for help")
  111. }
  112. // Execute poll or subscribe
  113. if poll {
  114. return doPoll(c, cl, conf, topic, command, options...)
  115. }
  116. return doSubscribe(c, cl, conf, topic, command, options...)
  117. }
  118. func doPoll(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  119. for _, s := range conf.Subscribe { // may be nil
  120. if err := doPollSingle(c, cl, s.Topic, s.Command, options...); err != nil {
  121. return err
  122. }
  123. }
  124. if topic != "" {
  125. if err := doPollSingle(c, cl, topic, command, options...); err != nil {
  126. return err
  127. }
  128. }
  129. return nil
  130. }
  131. func doPollSingle(c *cli.Context, cl *client.Client, topic, command string, options ...client.SubscribeOption) error {
  132. messages, err := cl.Poll(topic, options...)
  133. if err != nil {
  134. return err
  135. }
  136. for _, m := range messages {
  137. printMessageOrRunCommand(c, m, command)
  138. }
  139. return nil
  140. }
  141. func doSubscribe(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  142. cmds := make(map[string]string) // Subscription ID -> command
  143. for _, s := range conf.Subscribe { // May be nil
  144. topicOptions := append(make([]client.SubscribeOption, 0), options...)
  145. for filter, value := range s.If {
  146. topicOptions = append(topicOptions, client.WithFilter(filter, value))
  147. }
  148. if s.User != "" && s.Password != "" {
  149. topicOptions = append(topicOptions, client.WithBasicAuth(s.User, s.Password))
  150. }
  151. subscriptionID := cl.Subscribe(s.Topic, topicOptions...)
  152. cmds[subscriptionID] = s.Command
  153. }
  154. if topic != "" {
  155. subscriptionID := cl.Subscribe(topic, options...)
  156. cmds[subscriptionID] = command
  157. }
  158. for m := range cl.Messages {
  159. cmd, ok := cmds[m.SubscriptionID]
  160. if !ok {
  161. continue
  162. }
  163. printMessageOrRunCommand(c, m, cmd)
  164. }
  165. return nil
  166. }
  167. func printMessageOrRunCommand(c *cli.Context, m *client.Message, command string) {
  168. if command != "" {
  169. runCommand(c, command, m)
  170. } else {
  171. fmt.Fprintln(c.App.Writer, m.Raw)
  172. }
  173. }
  174. func runCommand(c *cli.Context, command string, m *client.Message) {
  175. if err := runCommandInternal(c, command, m); err != nil {
  176. fmt.Fprintf(c.App.ErrWriter, "Command failed: %s\n", err.Error())
  177. }
  178. }
  179. func envVars(m *client.Message) []string {
  180. env := os.Environ()
  181. env = append(env, envVar(m.ID, "NTFY_ID", "id")...)
  182. env = append(env, envVar(m.Topic, "NTFY_TOPIC", "topic")...)
  183. env = append(env, envVar(fmt.Sprintf("%d", m.Time), "NTFY_TIME", "time")...)
  184. env = append(env, envVar(m.Message, "NTFY_MESSAGE", "message", "m")...)
  185. env = append(env, envVar(m.Title, "NTFY_TITLE", "title", "t")...)
  186. env = append(env, envVar(fmt.Sprintf("%d", m.Priority), "NTFY_PRIORITY", "priority", "prio", "p")...)
  187. env = append(env, envVar(strings.Join(m.Tags, ","), "NTFY_TAGS", "tags", "tag", "ta")...)
  188. env = append(env, envVar(m.Raw, "NTFY_RAW", "raw")...)
  189. return env
  190. }
  191. func envVar(value string, vars ...string) []string {
  192. env := make([]string, 0)
  193. for _, v := range vars {
  194. env = append(env, fmt.Sprintf("%s=%s", v, value))
  195. }
  196. return env
  197. }
  198. func loadConfig(c *cli.Context) (*client.Config, error) {
  199. filename := c.String("config")
  200. if filename != "" {
  201. return client.LoadConfig(filename)
  202. }
  203. configFile := defaultConfigFile()
  204. if s, _ := os.Stat(configFile); s != nil {
  205. return client.LoadConfig(configFile)
  206. }
  207. return client.NewConfig(), nil
  208. }