subscribe.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package cmd
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "sort"
  8. "strings"
  9. "github.com/urfave/cli/v2"
  10. "heckel.io/ntfy/v2/client"
  11. "heckel.io/ntfy/v2/log"
  12. "heckel.io/ntfy/v2/util"
  13. )
  14. func init() {
  15. commands = append(commands, cmdSubscribe)
  16. }
  17. var flagsSubscribe = append(
  18. append([]cli.Flag{}, flagsDefault...),
  19. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
  20. &cli.StringFlag{Name: "since", Aliases: []string{"s"}, Usage: "return events since `SINCE` (Unix timestamp, or all)"},
  21. &cli.StringFlag{Name: "user", Aliases: []string{"u"}, EnvVars: []string{"NTFY_USER"}, Usage: "username[:password] used to auth against the server"},
  22. &cli.StringFlag{Name: "token", Aliases: []string{"k"}, EnvVars: []string{"NTFY_TOKEN"}, Usage: "access token used to auth against the server"},
  23. &cli.BoolFlag{Name: "from-config", Aliases: []string{"from_config", "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. )
  27. var cmdSubscribe = &cli.Command{
  28. Name: "subscribe",
  29. Aliases: []string{"sub"},
  30. Usage: "Subscribe to one or more topics on a ntfy server",
  31. UsageText: "ntfy subscribe [OPTIONS..] [TOPIC]",
  32. Action: execSubscribe,
  33. Category: categoryClient,
  34. Flags: flagsSubscribe,
  35. Before: initLogFunc,
  36. Description: `Subscribe to a topic from a ntfy server, and either print or execute a command for
  37. every arriving message. There are 3 modes in which the command can be run:
  38. ntfy subscribe TOPIC
  39. This prints the JSON representation of every incoming message. It is useful when you
  40. have a command that wants to stream-read incoming JSON messages. Unless --poll is passed,
  41. this command stays open forever.
  42. Examples:
  43. ntfy subscribe mytopic # Prints JSON for incoming messages for ntfy.sh/mytopic
  44. ntfy sub home.lan/backups # Subscribe to topic on different server
  45. ntfy sub --poll home.lan/backups # Just query for latest messages and exit
  46. ntfy sub -u phil:mypass secret # Subscribe with username/password
  47. ntfy subscribe TOPIC COMMAND
  48. This executes COMMAND for every incoming messages. The message fields are passed to the
  49. command as environment variables:
  50. Variable Aliases Description
  51. --------------- --------------------- -----------------------------------
  52. $NTFY_ID $id Unique message ID
  53. $NTFY_TIME $time Unix timestamp of the message delivery
  54. $NTFY_TOPIC $topic Topic name
  55. $NTFY_MESSAGE $message, $m Message body
  56. $NTFY_TITLE $title, $t Message title
  57. $NTFY_PRIORITY $priority, $prio, $p Message priority (1=min, 5=max)
  58. $NTFY_TAGS $tags, $tag, $ta Message tags (comma separated list)
  59. $NTFY_RAW $raw Raw JSON message
  60. Examples:
  61. ntfy sub mytopic 'notify-send "$m"' # Execute command for incoming messages
  62. ntfy sub topic1 myscript.sh # Execute script for incoming messages
  63. ntfy subscribe --from-config
  64. Service mode (used in ntfy-client.service). This reads the config file and sets up
  65. subscriptions for every topic in the "subscribe:" block (see config file).
  66. Examples:
  67. ntfy sub --from-config # Read topics from config file
  68. ntfy sub --config=myclient.yml --from-config # Read topics from alternate config file
  69. ` + clientCommandDescriptionSuffix,
  70. }
  71. func execSubscribe(c *cli.Context) error {
  72. // Read config and options
  73. conf, err := loadConfig(c)
  74. if err != nil {
  75. return err
  76. }
  77. cl := client.New(conf)
  78. since := c.String("since")
  79. user := c.String("user")
  80. token := c.String("token")
  81. poll := c.Bool("poll")
  82. scheduled := c.Bool("scheduled")
  83. fromConfig := c.Bool("from-config")
  84. topic := c.Args().Get(0)
  85. command := c.Args().Get(1)
  86. // Checks
  87. if user != "" && token != "" {
  88. return errors.New("cannot set both --user and --token")
  89. }
  90. if !fromConfig {
  91. conf.Subscribe = nil // wipe if --from-config not passed
  92. }
  93. var options []client.SubscribeOption
  94. if since != "" {
  95. options = append(options, client.WithSince(since))
  96. }
  97. if token != "" {
  98. options = append(options, client.WithBearerAuth(token))
  99. } else if user != "" {
  100. var pass string
  101. parts := strings.SplitN(user, ":", 2)
  102. if len(parts) == 2 {
  103. user = parts[0]
  104. pass = parts[1]
  105. } else {
  106. fmt.Fprint(c.App.ErrWriter, "Enter Password: ")
  107. p, err := util.ReadPassword(c.App.Reader)
  108. if err != nil {
  109. return err
  110. }
  111. pass = string(p)
  112. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 20))
  113. }
  114. options = append(options, client.WithBasicAuth(user, pass))
  115. } else if conf.DefaultToken != "" {
  116. options = append(options, client.WithBearerAuth(conf.DefaultToken))
  117. } else if conf.DefaultUser != "" && conf.DefaultPassword != nil {
  118. options = append(options, client.WithBasicAuth(conf.DefaultUser, *conf.DefaultPassword))
  119. }
  120. if scheduled {
  121. options = append(options, client.WithScheduled())
  122. }
  123. if topic == "" && len(conf.Subscribe) == 0 {
  124. return errors.New("must specify topic, type 'ntfy subscribe --help' for help")
  125. }
  126. // Execute poll or subscribe
  127. if poll {
  128. return doPoll(c, cl, conf, topic, command, options...)
  129. }
  130. return doSubscribe(c, cl, conf, topic, command, options...)
  131. }
  132. func doPoll(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  133. for _, s := range conf.Subscribe { // may be nil
  134. if auth := maybeAddAuthHeader(s, conf); auth != nil {
  135. options = append(options, auth)
  136. }
  137. if err := doPollSingle(c, cl, s.Topic, s.Command, options...); err != nil {
  138. return err
  139. }
  140. }
  141. if topic != "" {
  142. if err := doPollSingle(c, cl, topic, command, options...); err != nil {
  143. return err
  144. }
  145. }
  146. return nil
  147. }
  148. func doPollSingle(c *cli.Context, cl *client.Client, topic, command string, options ...client.SubscribeOption) error {
  149. messages, err := cl.Poll(topic, options...)
  150. if err != nil {
  151. return err
  152. }
  153. for _, m := range messages {
  154. printMessageOrRunCommand(c, m, command)
  155. }
  156. return nil
  157. }
  158. func doSubscribe(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
  159. cmds := make(map[string]string) // Subscription ID -> command
  160. for _, s := range conf.Subscribe { // May be nil
  161. topicOptions := append(make([]client.SubscribeOption, 0), options...)
  162. for filter, value := range s.If {
  163. topicOptions = append(topicOptions, client.WithFilter(filter, value))
  164. }
  165. if auth := maybeAddAuthHeader(s, conf); auth != nil {
  166. topicOptions = append(topicOptions, auth)
  167. }
  168. subscriptionID, err := cl.Subscribe(s.Topic, topicOptions...)
  169. if err != nil {
  170. return err
  171. }
  172. if s.Command != "" {
  173. cmds[subscriptionID] = s.Command
  174. } else if conf.DefaultCommand != "" {
  175. cmds[subscriptionID] = conf.DefaultCommand
  176. } else {
  177. cmds[subscriptionID] = ""
  178. }
  179. }
  180. if topic != "" {
  181. subscriptionID, err := cl.Subscribe(topic, options...)
  182. if err != nil {
  183. return err
  184. }
  185. cmds[subscriptionID] = command
  186. }
  187. for m := range cl.Messages {
  188. cmd, ok := cmds[m.SubscriptionID]
  189. if !ok {
  190. continue
  191. }
  192. log.Debug("%s Dispatching received message: %s", logMessagePrefix(m), m.Raw)
  193. printMessageOrRunCommand(c, m, cmd)
  194. }
  195. return nil
  196. }
  197. func maybeAddAuthHeader(s client.Subscribe, conf *client.Config) client.SubscribeOption {
  198. // if an explicit empty token or empty user:pass is given, exit without auth
  199. if (s.Token != nil && *s.Token == "") || (s.User != nil && *s.User == "" && s.Password != nil && *s.Password == "") {
  200. return client.WithEmptyAuth()
  201. }
  202. // check for subscription token then subscription user:pass
  203. if s.Token != nil && *s.Token != "" {
  204. return client.WithBearerAuth(*s.Token)
  205. }
  206. if s.User != nil && *s.User != "" && s.Password != nil {
  207. return client.WithBasicAuth(*s.User, *s.Password)
  208. }
  209. // if no subscription token nor subscription user:pass, check for default token then default user:pass
  210. if conf.DefaultToken != "" {
  211. return client.WithBearerAuth(conf.DefaultToken)
  212. }
  213. if conf.DefaultUser != "" && conf.DefaultPassword != nil {
  214. return client.WithBasicAuth(conf.DefaultUser, *conf.DefaultPassword)
  215. }
  216. return nil
  217. }
  218. func printMessageOrRunCommand(c *cli.Context, m *client.Message, command string) {
  219. if command != "" {
  220. runCommand(c, command, m)
  221. } else {
  222. log.Debug("%s Printing raw message", logMessagePrefix(m))
  223. fmt.Fprintln(c.App.Writer, m.Raw)
  224. }
  225. }
  226. func runCommand(c *cli.Context, command string, m *client.Message) {
  227. if err := runCommandInternal(c, command, m); err != nil {
  228. log.Warn("%s Command failed: %s", logMessagePrefix(m), err.Error())
  229. }
  230. }
  231. func runCommandInternal(c *cli.Context, script string, m *client.Message) error {
  232. scriptFile := fmt.Sprintf("%s/ntfy-subscribe-%s.%s", os.TempDir(), util.RandomString(10), scriptExt)
  233. log.Debug("%s Running command '%s' via temporary script %s", logMessagePrefix(m), script, scriptFile)
  234. script = scriptHeader + script
  235. if err := os.WriteFile(scriptFile, []byte(script), 0700); err != nil {
  236. return err
  237. }
  238. defer os.Remove(scriptFile)
  239. log.Debug("%s Executing script %s", logMessagePrefix(m), scriptFile)
  240. cmd := exec.Command(scriptLauncher[0], append(scriptLauncher[1:], scriptFile)...)
  241. cmd.Stdin = c.App.Reader
  242. cmd.Stdout = c.App.Writer
  243. cmd.Stderr = c.App.ErrWriter
  244. cmd.Env = envVars(m)
  245. return cmd.Run()
  246. }
  247. func envVars(m *client.Message) []string {
  248. env := make([]string, 0)
  249. env = append(env, envVar(m.ID, "NTFY_ID", "id")...)
  250. env = append(env, envVar(m.Topic, "NTFY_TOPIC", "topic")...)
  251. env = append(env, envVar(fmt.Sprintf("%d", m.Time), "NTFY_TIME", "time")...)
  252. env = append(env, envVar(m.Message, "NTFY_MESSAGE", "message", "m")...)
  253. env = append(env, envVar(m.Title, "NTFY_TITLE", "title", "t")...)
  254. env = append(env, envVar(fmt.Sprintf("%d", m.Priority), "NTFY_PRIORITY", "priority", "prio", "p")...)
  255. env = append(env, envVar(strings.Join(m.Tags, ","), "NTFY_TAGS", "tags", "tag", "ta")...)
  256. env = append(env, envVar(m.Raw, "NTFY_RAW", "raw")...)
  257. sort.Strings(env)
  258. if log.IsTrace() {
  259. log.Trace("%s With environment:\n%s", logMessagePrefix(m), strings.Join(env, "\n"))
  260. }
  261. return append(os.Environ(), env...)
  262. }
  263. func envVar(value string, vars ...string) []string {
  264. env := make([]string, 0)
  265. for _, v := range vars {
  266. env = append(env, fmt.Sprintf("%s=%s", v, value))
  267. }
  268. return env
  269. }
  270. func loadConfig(c *cli.Context) (*client.Config, error) {
  271. filename := c.String("config")
  272. if filename != "" {
  273. return client.LoadConfig(filename)
  274. }
  275. if client.DefaultConfigFile != "" {
  276. if s, _ := os.Stat(client.DefaultConfigFile); s != nil {
  277. return client.LoadConfig(client.DefaultConfigFile)
  278. }
  279. log.Debug("Config file %s not found", client.DefaultConfigFile)
  280. }
  281. log.Debug("Loading default config")
  282. return client.NewConfig(), nil
  283. }
  284. func logMessagePrefix(m *client.Message) string {
  285. return fmt.Sprintf("%s/%s", util.ShortTopicURL(m.TopicURL), m.ID)
  286. }