subscribe.go 12 KB

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