Debian Codegraph @

pkg/services/chat/signal/signal.go

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