| 1 | package signal |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 14 | "github.com/nicholas-fedor/shoutrrr/pkg/services/standard" |
| 15 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 16 | ) |
| 17 | |
| 18 | // Service sends notifications to Signal recipients via signal-cli-rest-api. |
| 19 | type Service struct { |
| 20 | standard.Standard |
| 21 | |
| 22 | Config *Config |
| 23 | pkr format.PropKeyResolver |
| 24 | httpClient types.HTTPClient |
| 25 | } |
| 26 | |
| 27 | // HTTP request timeout duration. |
| 28 | const ( |
| 29 | defaultHTTPTimeout = 30 * time.Second |
| 30 | ) |
| 31 | |
| 32 | // GetID returns the identifier for this service. |
| 33 | // |
| 34 | // Returns: |
| 35 | // - string: the service identifier. |
| 36 | func (s *Service) GetID() string { |
| 37 | return Scheme |
| 38 | } |
| 39 | |
| 40 | // Initialize configures the service with a URL and logger. |
| 41 | // |
| 42 | // Parameters: |
| 43 | // - serviceURL: the configuration URL for the Signal service |
| 44 | // - logger: the logger to use for logging |
| 45 | // |
| 46 | // Returns: |
| 47 | // - error: if configuration fails, nil otherwise |
| 48 | func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error { |
| 49 | s.SetLogger(logger) |
| 50 | s.Config = &Config{} |
| 51 | s.pkr = format.NewPropKeyResolver(s.Config) |
| 52 | |
| 53 | if err := s.Config.setURL(&s.pkr, serviceURL); err != nil { |
| 54 | return err |
| 55 | } |
| 56 | |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | // Send delivers a notification message to Signal recipients. |
| 61 | // |
| 62 | // Parameters: |
| 63 | // - message: the text message to send |
| 64 | // - params: optional parameters (e.g., attachments) |
| 65 | // |
| 66 | // Returns: |
| 67 | // - error: if the send operation fails, nil otherwise |
| 68 | func (s *Service) Send(message string, params *types.Params) error { |
| 69 | config := *s.Config |
| 70 | |
| 71 | // Separate config params from message params (like attachments) |
| 72 | var ( |
| 73 | configParams *types.Params |
| 74 | messageParams *types.Params |
| 75 | ) |
| 76 | |
| 77 | if params != nil { |
| 78 | configParams = &types.Params{} |
| 79 | messageParams = &types.Params{} |
| 80 | |
| 81 | for key, value := range *params { |
| 82 | // Check if this is a config parameter |
| 83 | if _, err := s.pkr.Get(key); err == nil { |
| 84 | // It's a valid config key |
| 85 | (*configParams)[key] = value |
| 86 | } else { |
| 87 | // It's a message parameter (like attachments) |
| 88 | (*messageParams)[key] = value |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | if err := s.pkr.UpdateConfigFromParams(&config, configParams); err != nil { |
| 93 | return fmt.Errorf("updating config from params: %w", err) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | return s.sendMessage(message, &config, messageParams) |
| 98 | } |
| 99 | |
| 100 | // SetHTTPClient sets a custom HTTP client for the service. |
| 101 | func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 102 | s.httpClient = client |
| 103 | } |
| 104 | |
| 105 | // buildAPIURL constructs the Signal API endpoint URL from the configuration. |
| 106 | // |
| 107 | // Parameters: |
| 108 | // - config: the service configuration |
| 109 | // |
| 110 | // Returns: |
| 111 | // - string: the full API endpoint URL |
| 112 | func (s *Service) buildAPIURL(config *Config) string { |
| 113 | scheme := "https" |
| 114 | if config.DisableTLS { |
| 115 | scheme = "http" |
| 116 | } |
| 117 | |
| 118 | return fmt.Sprintf("%s://%s:%d/v2/send", scheme, config.Host, config.Port) |
| 119 | } |
| 120 | |
| 121 | // createPayload builds the JSON payload for the Signal API request. |
| 122 | // |
| 123 | // Parameters: |
| 124 | // - message: the message text |
| 125 | // - config: the service configuration |
| 126 | // - params: optional parameters (may include attachments) |
| 127 | // |
| 128 | // Returns: |
| 129 | // - sendMessagePayload: the payload struct to be sent |
| 130 | func (s *Service) createPayload( |
| 131 | message string, |
| 132 | config *Config, |
| 133 | params *types.Params, |
| 134 | ) sendMessagePayload { |
| 135 | payload := sendMessagePayload{ |
| 136 | Message: message, |
| 137 | Number: config.Source, |
| 138 | Recipients: config.Recipients, |
| 139 | Base64Attachments: nil, // will be set if attachments provided |
| 140 | } |
| 141 | |
| 142 | // Check for attachments in params (passed during Send call) |
| 143 | // Note: Shoutrrr doesn't have a standard attachment interface, |
| 144 | // so we check for "attachments" parameter with base64 data |
| 145 | if params != nil { |
| 146 | if attachments, ok := (*params)["attachments"]; ok && attachments != "" { |
| 147 | // Parse comma-separated base64 attachments |
| 148 | attachmentList := strings.Split(attachments, ",") |
| 149 | for i, attachment := range attachmentList { |
| 150 | attachmentList[i] = strings.TrimSpace(attachment) |
| 151 | } |
| 152 | |
| 153 | payload.Base64Attachments = attachmentList |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | return payload |
| 158 | } |
| 159 | |
| 160 | // createRequest builds the HTTP request for the Signal API. |
| 161 | // |
| 162 | // Parameters: |
| 163 | // - config: the service configuration |
| 164 | // - payload: the payload to send (passed as pointer for efficiency) |
| 165 | // |
| 166 | // Returns: |
| 167 | // - *http.Request: the constructed HTTP request |
| 168 | // - context.CancelFunc: a function to cancel the request context |
| 169 | // - error: if request creation fails, nil otherwise |
| 170 | func (s *Service) createRequest( |
| 171 | config *Config, |
| 172 | payload *sendMessagePayload, |
| 173 | ) (*http.Request, context.CancelFunc, error) { |
| 174 | apiURL := s.buildAPIURL(config) |
| 175 | |
| 176 | jsonData, err := json.Marshal(payload) |
| 177 | if err != nil { |
| 178 | return nil, nil, fmt.Errorf("marshaling payload to JSON: %w", err) |
| 179 | } |
| 180 | |
| 181 | ctx, cancel := context.WithTimeout( |
| 182 | context.Background(), |
| 183 | defaultHTTPTimeout, |
| 184 | ) |
| 185 | |
| 186 | req, err := http.NewRequestWithContext( |
| 187 | ctx, |
| 188 | http.MethodPost, |
| 189 | apiURL, |
| 190 | bytes.NewBuffer(jsonData), |
| 191 | ) |
| 192 | if err != nil { |
| 193 | cancel() |
| 194 | |
| 195 | return nil, nil, fmt.Errorf("creating HTTP request: %w", err) |
| 196 | } |
| 197 | |
| 198 | req.Header.Set("Content-Type", "application/json") |
| 199 | s.setAuthentication(req, config) |
| 200 | |
| 201 | return req, cancel, nil |
| 202 | } |
| 203 | |
| 204 | // httpClientOrDefault returns the injected client or a default client. |
| 205 | func (s *Service) httpClientOrDefault() types.HTTPClient { |
| 206 | if s.httpClient != nil { |
| 207 | return s.httpClient |
| 208 | } |
| 209 | |
| 210 | return &http.Client{Timeout: defaultHTTPTimeout} |
| 211 | } |
| 212 | |
| 213 | // parseResponse reads and logs the response from the Signal API. |
| 214 | // |
| 215 | // Parameters: |
| 216 | // - resp: the HTTP response to parse |
| 217 | func (s *Service) parseResponse(resp *http.Response) { |
| 218 | var response sendMessageResponse |
| 219 | if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { |
| 220 | s.Logf("Warning: failed to parse response: %v", err) |
| 221 | } else { |
| 222 | s.Logf("Message sent successfully at timestamp %d", response.Timestamp) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // sendMessage sends a message to all configured recipients. |
| 227 | // |
| 228 | // Parameters: |
| 229 | // - message: the message text to send |
| 230 | // - config: the service configuration |
| 231 | // - params: optional parameters (e.g., attachments) |
| 232 | // |
| 233 | // Returns: |
| 234 | // - error: if sending fails, nil otherwise |
| 235 | func (s *Service) sendMessage(message string, config *Config, params *types.Params) error { |
| 236 | if len(config.Recipients) == 0 { |
| 237 | return ErrNoRecipients |
| 238 | } |
| 239 | |
| 240 | payload := s.createPayload(message, config, params) |
| 241 | |
| 242 | req, cancel, err := s.createRequest(config, &payload) |
| 243 | if err != nil { |
| 244 | return err |
| 245 | } |
| 246 | defer cancel() |
| 247 | |
| 248 | return s.sendRequest(req) |
| 249 | } |
| 250 | |
| 251 | // sendRequest executes the HTTP request and processes the response. |
| 252 | // |
| 253 | // Parameters: |
| 254 | // - req: the HTTP request to execute |
| 255 | // |
| 256 | // Returns: |
| 257 | // - error: if the request fails or returns a non-success status, nil otherwise |
| 258 | func (s *Service) sendRequest(req *http.Request) error { |
| 259 | client := s.httpClientOrDefault() |
| 260 | |
| 261 | resp, err := client.Do(req) |
| 262 | if err != nil { |
| 263 | return fmt.Errorf("sending HTTP request: %w", err) |
| 264 | } |
| 265 | |
| 266 | defer func() { _ = resp.Body.Close() }() |
| 267 | |
| 268 | // Check response status |
| 269 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 270 | return fmt.Errorf("%w: server returned status %d", ErrSendFailed, resp.StatusCode) |
| 271 | } |
| 272 | |
| 273 | // Parse response (optional, for logging) |
| 274 | s.parseResponse(resp) |
| 275 | |
| 276 | return nil |
| 277 | } |
| 278 | |
| 279 | // setAuthentication configures HTTP authentication headers on the request. |
| 280 | // |
| 281 | // Parameters: |
| 282 | // - req: the HTTP request to modify |
| 283 | // - config: the service configuration containing credentials |
| 284 | func (s *Service) setAuthentication(req *http.Request, config *Config) { |
| 285 | // Add authentication - prefer Bearer token over Basic Auth |
| 286 | if config.Token != "" { |
| 287 | req.Header.Set("Authorization", "Bearer "+config.Token) |
| 288 | } else if config.User != "" { |
| 289 | req.SetBasicAuth(config.User, config.Password) |
| 290 | } |
| 291 | } |