|
| 1 | +package signal |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 15 | + "github.com/nicholas-fedor/shoutrrr/pkg/services/standard" |
| 16 | + "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 17 | +) |
| 18 | + |
| 19 | +// HTTP request timeout duration. |
| 20 | +const ( |
| 21 | + defaultHTTPTimeout = 30 * time.Second |
| 22 | +) |
| 23 | + |
| 24 | +// ErrSendFailed indicates a failure to send a Signal message. |
| 25 | +var ( |
| 26 | + ErrSendFailed = errors.New("failed to send Signal message") |
| 27 | +) |
| 28 | + |
| 29 | +// Service sends notifications to Signal recipients via signal-cli-rest-api. |
| 30 | +type Service struct { |
| 31 | + standard.Standard |
| 32 | + Config *Config |
| 33 | + pkr format.PropKeyResolver |
| 34 | +} |
| 35 | + |
| 36 | +// Send delivers a notification message to Signal recipients. |
| 37 | +func (service *Service) Send(message string, params *types.Params) error { |
| 38 | + config := *service.Config |
| 39 | + |
| 40 | + // Separate config params from message params (like attachments) |
| 41 | + var ( |
| 42 | + configParams *types.Params |
| 43 | + messageParams *types.Params |
| 44 | + ) |
| 45 | + |
| 46 | + if params != nil { |
| 47 | + configParams = &types.Params{} |
| 48 | + messageParams = &types.Params{} |
| 49 | + |
| 50 | + for key, value := range *params { |
| 51 | + // Check if this is a config parameter |
| 52 | + if _, err := service.pkr.Get(key); err == nil { |
| 53 | + // It's a valid config key |
| 54 | + (*configParams)[key] = value |
| 55 | + } else { |
| 56 | + // It's a message parameter (like attachments) |
| 57 | + (*messageParams)[key] = value |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if err := service.pkr.UpdateConfigFromParams(&config, configParams); err != nil { |
| 62 | + return fmt.Errorf("updating config from params: %w", err) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return service.sendMessage(message, &config, messageParams) |
| 67 | +} |
| 68 | + |
| 69 | +// Initialize configures the service with a URL and logger. |
| 70 | +func (service *Service) Initialize(configURL *url.URL, logger types.StdLogger) error { |
| 71 | + service.SetLogger(logger) |
| 72 | + service.Config = &Config{} |
| 73 | + service.pkr = format.NewPropKeyResolver(service.Config) |
| 74 | + |
| 75 | + if err := service.Config.setURL(&service.pkr, configURL); err != nil { |
| 76 | + return err |
| 77 | + } |
| 78 | + |
| 79 | + return nil |
| 80 | +} |
| 81 | + |
| 82 | +// GetID returns the identifier for this service. |
| 83 | +func (service *Service) GetID() string { |
| 84 | + return Scheme |
| 85 | +} |
| 86 | + |
| 87 | +// sendMessage sends a message to all configured recipients. |
| 88 | +func (service *Service) sendMessage(message string, config *Config, params *types.Params) error { |
| 89 | + if len(config.Recipients) == 0 { |
| 90 | + return ErrNoRecipients |
| 91 | + } |
| 92 | + |
| 93 | + payload := service.createPayload(message, config, params) |
| 94 | + |
| 95 | + req, cancel, err := service.createRequest(config, payload) |
| 96 | + if err != nil { |
| 97 | + return err |
| 98 | + } |
| 99 | + defer cancel() |
| 100 | + |
| 101 | + return service.sendRequest(req) |
| 102 | +} |
| 103 | + |
| 104 | +// createPayload builds the JSON payload for the Signal API request. |
| 105 | +func (service *Service) createPayload( |
| 106 | + message string, |
| 107 | + config *Config, |
| 108 | + params *types.Params, |
| 109 | +) sendMessagePayload { |
| 110 | + payload := sendMessagePayload{ |
| 111 | + Message: message, |
| 112 | + Number: config.Source, |
| 113 | + Recipients: config.Recipients, |
| 114 | + } |
| 115 | + |
| 116 | + // Check for attachments in params (passed during Send call) |
| 117 | + // Note: Shoutrrr doesn't have a standard attachment interface, |
| 118 | + // so we check for "attachments" parameter with base64 data |
| 119 | + if params != nil { |
| 120 | + if attachments, ok := (*params)["attachments"]; ok && attachments != "" { |
| 121 | + // Parse comma-separated base64 attachments |
| 122 | + attachmentList := strings.Split(attachments, ",") |
| 123 | + for i, attachment := range attachmentList { |
| 124 | + attachmentList[i] = strings.TrimSpace(attachment) |
| 125 | + } |
| 126 | + |
| 127 | + payload.Base64Attachments = attachmentList |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return payload |
| 132 | +} |
| 133 | + |
| 134 | +// createRequest builds the HTTP request for the Signal API. |
| 135 | +func (service *Service) createRequest( |
| 136 | + config *Config, |
| 137 | + payload sendMessagePayload, |
| 138 | +) (*http.Request, context.CancelFunc, error) { |
| 139 | + apiURL := service.buildAPIURL(config) |
| 140 | + |
| 141 | + jsonData, err := json.Marshal(payload) |
| 142 | + if err != nil { |
| 143 | + return nil, nil, fmt.Errorf("marshaling payload to JSON: %w", err) |
| 144 | + } |
| 145 | + |
| 146 | + ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) |
| 147 | + |
| 148 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewBuffer(jsonData)) |
| 149 | + if err != nil { |
| 150 | + cancel() |
| 151 | + |
| 152 | + return nil, nil, fmt.Errorf("creating HTTP request: %w", err) |
| 153 | + } |
| 154 | + |
| 155 | + req.Header.Set("Content-Type", "application/json") |
| 156 | + service.setAuthentication(req, config) |
| 157 | + |
| 158 | + return req, cancel, nil |
| 159 | +} |
| 160 | + |
| 161 | +// buildAPIURL constructs the Signal API endpoint URL. |
| 162 | +func (service *Service) buildAPIURL(config *Config) string { |
| 163 | + scheme := "https" |
| 164 | + if config.DisableTLS { |
| 165 | + scheme = "http" |
| 166 | + } |
| 167 | + |
| 168 | + return fmt.Sprintf("%s://%s:%d/v2/send", scheme, config.Host, config.Port) |
| 169 | +} |
| 170 | + |
| 171 | +// setAuthentication configures HTTP authentication headers. |
| 172 | +func (service *Service) setAuthentication(req *http.Request, config *Config) { |
| 173 | + // Add authentication - prefer Bearer token over Basic Auth |
| 174 | + if config.Token != "" { |
| 175 | + req.Header.Set("Authorization", "Bearer "+config.Token) |
| 176 | + } else if config.User != "" { |
| 177 | + req.SetBasicAuth(config.User, config.Password) |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +// sendRequest executes the HTTP request and handles the response. |
| 182 | +func (service *Service) sendRequest(req *http.Request) error { |
| 183 | + client := &http.Client{} |
| 184 | + |
| 185 | + resp, err := client.Do(req) |
| 186 | + if err != nil { |
| 187 | + return fmt.Errorf("sending HTTP request: %w", err) |
| 188 | + } |
| 189 | + defer resp.Body.Close() |
| 190 | + |
| 191 | + // Check response status |
| 192 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 193 | + return fmt.Errorf("%w: server returned status %d", ErrSendFailed, resp.StatusCode) |
| 194 | + } |
| 195 | + |
| 196 | + // Parse response (optional, for logging) |
| 197 | + service.parseResponse(resp) |
| 198 | + |
| 199 | + return nil |
| 200 | +} |
| 201 | + |
| 202 | +// parseResponse extracts and logs response information. |
| 203 | +func (service *Service) parseResponse(resp *http.Response) { |
| 204 | + var response sendMessageResponse |
| 205 | + if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { |
| 206 | + service.Logf("Warning: failed to parse response: %v", err) |
| 207 | + } else { |
| 208 | + service.Logf("Message sent successfully at timestamp %d", response.Timestamp) |
| 209 | + } |
| 210 | +} |
0 commit comments