Debian Codegraph @

cmd/subscribe.go

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