ntfy/cmd/subscribe.go

273 lines
9.1 KiB
Go
Raw Normal View History

2021-12-17 01:33:01 +00:00
package cmd
import (
"errors"
"fmt"
"github.com/urfave/cli/v2"
"heckel.io/ntfy/client"
"heckel.io/ntfy/util"
2022-05-10 01:25:00 +00:00
"log"
2021-12-17 01:33:01 +00:00
"os"
2022-05-10 01:25:00 +00:00
"os/exec"
"os/user"
"path/filepath"
2021-12-17 01:33:01 +00:00
"strings"
)
2022-05-09 15:03:40 +00:00
func init() {
commands = append(commands, cmdSubscribe)
}
2022-05-10 01:25:00 +00:00
const (
clientRootConfigFileUnixAbsolute = "/etc/ntfy/client.yml"
clientUserConfigFileUnixRelative = "ntfy/client.yml"
clientUserConfigFileWindowsRelative = "ntfy\\client.yml"
)
2021-12-17 01:33:01 +00:00
var cmdSubscribe = &cli.Command{
Name: "subscribe",
Aliases: []string{"sub"},
Usage: "Subscribe to one or more topics on a ntfy server",
2021-12-18 19:43:27 +00:00
UsageText: "ntfy subscribe [OPTIONS..] [TOPIC]",
2021-12-17 01:33:01 +00:00
Action: execSubscribe,
2022-01-23 06:00:38 +00:00
Category: categoryClient,
2021-12-17 01:33:01 +00:00
Flags: []cli.Flag{
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
2021-12-19 03:02:36 +00:00
&cli.StringFlag{Name: "since", Aliases: []string{"s"}, Usage: "return events since `SINCE` (Unix timestamp, or all)"},
2022-02-17 18:12:20 +00:00
&cli.StringFlag{Name: "user", Aliases: []string{"u"}, Usage: "username[:password] used to auth against the server"},
2021-12-18 19:43:27 +00:00
&cli.BoolFlag{Name: "from-config", Aliases: []string{"C"}, Usage: "read subscriptions from config file (service mode)"},
2021-12-17 14:32:59 +00:00
&cli.BoolFlag{Name: "poll", Aliases: []string{"p"}, Usage: "return events and exit, do not listen for new events"},
&cli.BoolFlag{Name: "scheduled", Aliases: []string{"sched", "S"}, Usage: "also return scheduled/delayed events"},
2021-12-18 21:12:36 +00:00
&cli.BoolFlag{Name: "verbose", Aliases: []string{"v"}, Usage: "print verbose output"},
2021-12-17 01:33:01 +00:00
},
2021-12-18 19:43:27 +00:00
Description: `Subscribe to a topic from a ntfy server, and either print or execute a command for
every arriving message. There are 3 modes in which the command can be run:
2021-12-17 01:33:01 +00:00
2021-12-18 19:43:27 +00:00
ntfy subscribe TOPIC
This prints the JSON representation of every incoming message. It is useful when you
have a command that wants to stream-read incoming JSON messages. Unless --poll is passed,
this command stays open forever.
2021-12-17 01:33:01 +00:00
2021-12-18 19:43:27 +00:00
Examples:
ntfy subscribe mytopic # Prints JSON for incoming messages for ntfy.sh/mytopic
ntfy sub home.lan/backups # Subscribe to topic on different server
ntfy sub --poll home.lan/backups # Just query for latest messages and exit
2022-02-17 18:12:20 +00:00
ntfy sub -u phil:mypass secret # Subscribe with username/password
2021-12-18 19:43:27 +00:00
ntfy subscribe TOPIC COMMAND
This executes COMMAND for every incoming messages. The message fields are passed to the
command as environment variables:
2021-12-17 01:33:01 +00:00
2021-12-22 23:16:28 +00:00
Variable Aliases Description
--------------- --------------------- -----------------------------------
$NTFY_ID $id Unique message ID
$NTFY_TIME $time Unix timestamp of the message delivery
$NTFY_TOPIC $topic Topic name
$NTFY_MESSAGE $message, $m Message body
$NTFY_TITLE $title, $t Message title
$NTFY_PRIORITY $priority, $prio, $p Message priority (1=min, 5=max)
$NTFY_TAGS $tags, $tag, $ta Message tags (comma separated list)
$NTFY_RAW $raw Raw JSON message
2021-12-17 01:33:01 +00:00
2021-12-18 19:43:27 +00:00
Examples:
ntfy sub mytopic 'notify-send "$m"' # Execute command for incoming messages
2022-05-09 20:22:52 +00:00
ntfy sub topic1 myscript.sh # Execute script for incoming messages
2021-12-18 19:43:27 +00:00
ntfy subscribe --from-config
2022-05-09 20:22:52 +00:00
Service mode (used in ntfy-client.service). This reads the config file and sets up
subscriptions for every topic in the "subscribe:" block (see config file).
2021-12-18 19:43:27 +00:00
Examples:
ntfy sub --from-config # Read topics from config file
2022-05-09 20:22:52 +00:00
ntfy sub --config=myclient.yml --from-config # Read topics from alternate config file
2022-05-10 01:25:00 +00:00
` + clientCommandDescriptionSuffix,
2021-12-17 01:33:01 +00:00
}
func execSubscribe(c *cli.Context) error {
2021-12-18 21:12:36 +00:00
// Read config and options
2021-12-18 19:43:27 +00:00
conf, err := loadConfig(c)
if err != nil {
return err
}
cl := client.New(conf)
2021-12-17 14:32:59 +00:00
since := c.String("since")
2022-02-17 18:12:20 +00:00
user := c.String("user")
2021-12-17 14:32:59 +00:00
poll := c.Bool("poll")
scheduled := c.Bool("scheduled")
2021-12-18 21:12:36 +00:00
fromConfig := c.Bool("from-config")
2021-12-18 19:43:27 +00:00
topic := c.Args().Get(0)
command := c.Args().Get(1)
2021-12-18 21:12:36 +00:00
if !fromConfig {
conf.Subscribe = nil // wipe if --from-config not passed
}
2021-12-17 14:32:59 +00:00
var options []client.SubscribeOption
if since != "" {
options = append(options, client.WithSince(since))
2021-12-17 01:33:01 +00:00
}
2022-02-17 18:12:20 +00:00
if user != "" {
var pass string
parts := strings.SplitN(user, ":", 2)
if len(parts) == 2 {
user = parts[0]
pass = parts[1]
} else {
fmt.Fprint(c.App.ErrWriter, "Enter Password: ")
p, err := util.ReadPassword(c.App.Reader)
if err != nil {
return err
}
pass = string(p)
fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 20))
}
options = append(options, client.WithBasicAuth(user, pass))
}
2021-12-17 14:32:59 +00:00
if poll {
options = append(options, client.WithPoll())
}
if scheduled {
options = append(options, client.WithScheduled())
}
2021-12-18 21:12:36 +00:00
if topic == "" && len(conf.Subscribe) == 0 {
2021-12-19 03:02:36 +00:00
return errors.New("must specify topic, type 'ntfy subscribe --help' for help")
2021-12-18 21:12:36 +00:00
}
// Execute poll or subscribe
2021-12-17 14:32:59 +00:00
if poll {
2021-12-21 01:46:51 +00:00
return doPoll(c, cl, conf, topic, command, options...)
2021-12-18 21:12:36 +00:00
}
2021-12-21 01:46:51 +00:00
return doSubscribe(c, cl, conf, topic, command, options...)
2021-12-18 21:12:36 +00:00
}
2021-12-21 01:46:51 +00:00
func doPoll(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
2021-12-18 21:12:36 +00:00
for _, s := range conf.Subscribe { // may be nil
2021-12-21 01:46:51 +00:00
if err := doPollSingle(c, cl, s.Topic, s.Command, options...); err != nil {
2021-12-18 19:43:27 +00:00
return err
2021-12-17 14:32:59 +00:00
}
2021-12-18 21:12:36 +00:00
}
if topic != "" {
2021-12-21 01:46:51 +00:00
if err := doPollSingle(c, cl, topic, command, options...); err != nil {
2021-12-18 21:12:36 +00:00
return err
2021-12-17 14:32:59 +00:00
}
2021-12-17 01:33:01 +00:00
}
return nil
}
2021-12-21 01:46:51 +00:00
func doPollSingle(c *cli.Context, cl *client.Client, topic, command string, options ...client.SubscribeOption) error {
2021-12-18 21:12:36 +00:00
messages, err := cl.Poll(topic, options...)
if err != nil {
return err
}
for _, m := range messages {
printMessageOrRunCommand(c, m, command)
2021-12-17 01:33:01 +00:00
}
return nil
}
2021-12-21 01:46:51 +00:00
func doSubscribe(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
2022-05-09 20:22:52 +00:00
cmds := make(map[string]string) // Subscription ID -> command
for _, s := range conf.Subscribe { // May be nil
2021-12-21 20:22:27 +00:00
topicOptions := append(make([]client.SubscribeOption, 0), options...)
for filter, value := range s.If {
topicOptions = append(topicOptions, client.WithFilter(filter, value))
}
2022-02-17 18:16:01 +00:00
if s.User != "" && s.Password != "" {
topicOptions = append(topicOptions, client.WithBasicAuth(s.User, s.Password))
}
2021-12-21 20:22:27 +00:00
subscriptionID := cl.Subscribe(s.Topic, topicOptions...)
2022-05-09 20:22:52 +00:00
cmds[subscriptionID] = s.Command
2021-12-18 21:12:36 +00:00
}
if topic != "" {
2021-12-21 20:22:27 +00:00
subscriptionID := cl.Subscribe(topic, options...)
2022-05-09 20:22:52 +00:00
cmds[subscriptionID] = command
2021-12-18 21:12:36 +00:00
}
for m := range cl.Messages {
2022-05-09 20:22:52 +00:00
cmd, ok := cmds[m.SubscriptionID]
2021-12-18 21:12:36 +00:00
if !ok {
continue
2021-12-17 14:32:59 +00:00
}
2022-05-09 20:22:52 +00:00
printMessageOrRunCommand(c, m, cmd)
2021-12-17 01:33:01 +00:00
}
return nil
}
2021-12-18 21:12:36 +00:00
func printMessageOrRunCommand(c *cli.Context, m *client.Message, command string) {
if command != "" {
runCommand(c, command, m)
} else {
fmt.Fprintln(c.App.Writer, m.Raw)
}
}
func runCommand(c *cli.Context, command string, m *client.Message) {
if err := runCommandInternal(c, command, m); err != nil {
fmt.Fprintf(c.App.ErrWriter, "Command failed: %s\n", err.Error())
}
}
2022-05-10 01:25:00 +00:00
func runCommandInternal(c *cli.Context, script string, m *client.Message) error {
scriptFile := fmt.Sprintf("%s/ntfy-subscribe-%s.%s", os.TempDir(), util.RandomString(10), scriptExt)
if err := os.WriteFile(scriptFile, []byte(scriptHeader+script), 0700); err != nil {
return err
}
defer os.Remove(scriptFile)
verbose := c.Bool("verbose")
if verbose {
log.Printf("[%s] Executing: %s (for message: %s)", util.ShortTopicURL(m.TopicURL), script, m.Raw)
}
cmd := exec.Command(scriptLauncher[0], append(scriptLauncher[1:], scriptFile)...)
cmd.Stdin = c.App.Reader
cmd.Stdout = c.App.Writer
cmd.Stderr = c.App.ErrWriter
cmd.Env = envVars(m)
return cmd.Run()
}
2021-12-17 01:33:01 +00:00
func envVars(m *client.Message) []string {
env := os.Environ()
env = append(env, envVar(m.ID, "NTFY_ID", "id")...)
env = append(env, envVar(m.Topic, "NTFY_TOPIC", "topic")...)
env = append(env, envVar(fmt.Sprintf("%d", m.Time), "NTFY_TIME", "time")...)
env = append(env, envVar(m.Message, "NTFY_MESSAGE", "message", "m")...)
env = append(env, envVar(m.Title, "NTFY_TITLE", "title", "t")...)
env = append(env, envVar(fmt.Sprintf("%d", m.Priority), "NTFY_PRIORITY", "priority", "prio", "p")...)
2021-12-22 09:21:59 +00:00
env = append(env, envVar(strings.Join(m.Tags, ","), "NTFY_TAGS", "tags", "tag", "ta")...)
2021-12-22 23:16:28 +00:00
env = append(env, envVar(m.Raw, "NTFY_RAW", "raw")...)
2021-12-17 01:33:01 +00:00
return env
}
func envVar(value string, vars ...string) []string {
env := make([]string, 0)
for _, v := range vars {
env = append(env, fmt.Sprintf("%s=%s", v, value))
}
return env
}
2021-12-18 19:43:27 +00:00
func loadConfig(c *cli.Context) (*client.Config, error) {
filename := c.String("config")
if filename != "" {
2021-12-22 12:46:17 +00:00
return client.LoadConfig(filename)
2021-12-18 19:43:27 +00:00
}
2022-05-09 20:22:52 +00:00
configFile := defaultConfigFile()
2021-12-18 19:43:27 +00:00
if s, _ := os.Stat(configFile); s != nil {
2021-12-22 12:46:17 +00:00
return client.LoadConfig(configFile)
2021-12-18 19:43:27 +00:00
}
return client.NewConfig(), nil
}
2022-05-10 01:25:00 +00:00
func defaultConfigFileUnix() string {
u, _ := user.Current()
configFile := clientRootConfigFileUnixAbsolute
if u.Uid != "0" {
homeDir, _ := os.UserConfigDir()
return filepath.Join(homeDir, clientUserConfigFileUnixRelative)
}
return configFile
}
func defaultConfigFileWindows() string {
homeDir, _ := os.UserConfigDir()
return filepath.Join(homeDir, clientUserConfigFileWindowsRelative)
}