| 1 | // Package send provides the CLI command for sending notifications to various notification services. |
| 2 | package send |
| 3 | |
| 4 | import ( |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "log" |
| 9 | "os" |
| 10 | "strings" |
| 11 | |
| 12 | "github.com/spf13/cobra" |
| 13 | |
| 14 | "github.com/nicholas-fedor/shoutrrr/internal/dedupe" |
| 15 | internalUtil "github.com/nicholas-fedor/shoutrrr/internal/util" |
| 16 | "github.com/nicholas-fedor/shoutrrr/pkg/router" |
| 17 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 18 | "github.com/nicholas-fedor/shoutrrr/pkg/util" |
| 19 | cli "github.com/nicholas-fedor/shoutrrr/shoutrrr/cmd" |
| 20 | ) |
| 21 | |
| 22 | // Command constants define the maximum number of arguments and message length limits. |
| 23 | const ( |
| 24 | MaximumNArgs = 2 |
| 25 | MaxMessageLength = 100 |
| 26 | ) |
| 27 | |
| 28 | // Cmd is the cobra command for sending notifications. |
| 29 | // It sends messages to one or more notification services using configured URLs. |
| 30 | var Cmd = &cobra.Command{ |
| 31 | Use: "send", |
| 32 | Short: "Send a notification using a service url", |
| 33 | Args: cobra.MaximumNArgs(MaximumNArgs), |
| 34 | PreRunE: internalUtil.LoadFlagsFromAltSources, |
| 35 | RunE: Run, |
| 36 | } |
| 37 | |
| 38 | // init initializes the command flags for the send command. |
| 39 | func init() { |
| 40 | Cmd.Flags().BoolP("verbose", "v", false, "Enable verbose output") |
| 41 | Cmd.Flags().StringArrayP("url", "u", []string{}, "The notification URL(s) to send to") |
| 42 | |
| 43 | if err := Cmd.MarkFlagRequired("url"); err != nil { |
| 44 | fmt.Fprintf(os.Stderr, "Error marking URL flag as required: %v\n", err) |
| 45 | } |
| 46 | |
| 47 | Cmd.Flags(). |
| 48 | StringP("message", "m", "", "The message to send to the notification url, or - to read message from stdin") |
| 49 | |
| 50 | if err := Cmd.MarkFlagRequired("message"); err != nil { |
| 51 | fmt.Fprintf(os.Stderr, "Error marking message flag as required: %v\n", err) |
| 52 | } |
| 53 | |
| 54 | Cmd.Flags().StringP("title", "t", "", "The title used for services that support it") |
| 55 | } |
| 56 | |
| 57 | // Run executes the send command and handles its result. |
| 58 | // It processes errors appropriately, exiting with the correct exit code for non-usage errors. |
| 59 | // |
| 60 | // Parameters: |
| 61 | // - cmd: The cobra command containing the parsed flags. |
| 62 | // - _: Unused positional arguments. |
| 63 | // |
| 64 | // Returns: |
| 65 | // - error: An error if the command fails, or nil on success. |
| 66 | func Run(cmd *cobra.Command, _ []string) error { |
| 67 | err := run(cmd) |
| 68 | if err != nil { |
| 69 | var result cli.ExitError |
| 70 | if errors.As(err, &result) && result.ExitCode != cli.ExUsage { |
| 71 | // If the error is not related to CLI usage, report error and exit to avoid cobra error output. |
| 72 | _, _ = fmt.Fprintln(os.Stderr, err.Error()) |
| 73 | |
| 74 | os.Exit(result.ExitCode) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | return err |
| 79 | } |
| 80 | |
| 81 | // logf prints a formatted message to stderr. |
| 82 | // |
| 83 | // Parameters: |
| 84 | // - format: The format string. |
| 85 | // - a: Variadic arguments for the format string. |
| 86 | func logf(format string, a ...any) { |
| 87 | fmt.Fprintf(os.Stderr, format+"\n", a...) |
| 88 | } |
| 89 | |
| 90 | // run executes the core send logic. |
| 91 | // It retrieves flags, reads input, and sends notifications to configured services. |
| 92 | // |
| 93 | // Parameters: |
| 94 | // - cmd: The cobra command containing the parsed flags. |
| 95 | // |
| 96 | // Returns: |
| 97 | // - error: An error if the send operation fails, or nil on success. |
| 98 | func run(cmd *cobra.Command) error { |
| 99 | flags := cmd.Flags() |
| 100 | |
| 101 | // Retrieve verbose flag. |
| 102 | verbose, err := flags.GetBool("verbose") |
| 103 | if err != nil { |
| 104 | return fmt.Errorf("failed to get verbose flag: %w", err) |
| 105 | } |
| 106 | |
| 107 | // Retrieve and deduplicate URLs. |
| 108 | urls, err := flags.GetStringArray("url") |
| 109 | if err != nil { |
| 110 | return fmt.Errorf("failed to get url flag: %w", err) |
| 111 | } |
| 112 | |
| 113 | urls = dedupe.RemoveDuplicates(urls) |
| 114 | |
| 115 | // Retrieve message flag. |
| 116 | message, err := flags.GetString("message") |
| 117 | if err != nil { |
| 118 | return fmt.Errorf("failed to get message flag: %w", err) |
| 119 | } |
| 120 | |
| 121 | // Retrieve title flag. |
| 122 | title, err := flags.GetString("title") |
| 123 | if err != nil { |
| 124 | return fmt.Errorf("failed to get title flag: %w", err) |
| 125 | } |
| 126 | |
| 127 | // Read message from stdin if requested. |
| 128 | if message == "-" { |
| 129 | logf("Reading from STDIN...") |
| 130 | |
| 131 | stringBuilder := strings.Builder{} |
| 132 | |
| 133 | count, err := io.Copy(&stringBuilder, os.Stdin) |
| 134 | if err != nil { |
| 135 | return fmt.Errorf("failed to read message from stdin: %w", err) |
| 136 | } |
| 137 | |
| 138 | logf("Read %d byte(s)", count) |
| 139 | |
| 140 | message = stringBuilder.String() |
| 141 | } |
| 142 | |
| 143 | // Setup logger based on verbose flag. |
| 144 | var logger *log.Logger |
| 145 | |
| 146 | if verbose { |
| 147 | urlsPrefix := "URLs:" |
| 148 | for i, url := range urls { |
| 149 | logf("%s %s", urlsPrefix, url) |
| 150 | |
| 151 | if i == 0 { |
| 152 | // Only display "URLs:" prefix for first line, replace with indentation for subsequent lines. |
| 153 | urlsPrefix = strings.Repeat(" ", len(urlsPrefix)) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | logf("Message: %s", util.Ellipsis(message, MaxMessageLength)) |
| 158 | |
| 159 | if title != "" { |
| 160 | logf("Title: %v", title) |
| 161 | } |
| 162 | |
| 163 | logger = log.New(os.Stderr, "SHOUTRRR ", log.LstdFlags) |
| 164 | } else { |
| 165 | logger = util.DiscardLogger |
| 166 | } |
| 167 | |
| 168 | // Create service router and send notification. |
| 169 | serviceRouter, err := router.NewWithOptions(logger, types.SenderOptions{}, urls...) |
| 170 | if err != nil { |
| 171 | return cli.ConfigurationError(fmt.Sprintf("error invoking send: %s", err)) |
| 172 | } |
| 173 | |
| 174 | params := make(types.Params) |
| 175 | if title != "" { |
| 176 | params["title"] = title |
| 177 | } |
| 178 | |
| 179 | errs := serviceRouter.SendAsync(message, ¶ms) |
| 180 | for err := range errs { |
| 181 | if err != nil { |
| 182 | return cli.TaskUnavailable(err.Error()) |
| 183 | } |
| 184 | |
| 185 | logf("Notification sent") |
| 186 | } |
| 187 | |
| 188 | return nil |
| 189 | } |