Debian Codegraph @

pkg/services/chat/signal/signal_config.go

raw
1 package signal
2
3 import (
4 "fmt"
5 "net"
6 "net/url"
7 "regexp"
8 "strconv"
9 "strings"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/format"
12 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
13 "github.com/nicholas-fedor/shoutrrr/pkg/types"
14 )
15
16 // Config holds settings for the Signal notification service.
17 type Config struct {
18 standard.EnumlessConfig
19
20 Host string `default:"localhost" desc:"Signal REST API server hostname or IP" key:"host"`
21 Port int `default:"8080" desc:"Signal REST API server port" key:"port"`
22 User string ` desc:"Username for HTTP Basic Auth" key:"user"`
23 Password string ` desc:"Password for HTTP Basic Auth" key:"password" sensitive:"true"`
24 Token string ` desc:"API token for Bearer authentication" key:"token,apikey"`
25 Source string ` desc:"Source phone number (with country code)" key:"source"`
26 Recipients []string ` desc:"Recipient phone numbers or group IDs" key:"recipients,to"`
27 DisableTLS bool `default:"No" desc:"Disable TLS for Signal REST API connection" key:"disabletls"`
28 }
29
30 // Scheme identifies this service in configuration URLs.
31 const (
32 Scheme = "signal"
33 // minPathParts is the minimum number of path parts required (source + at least one recipient).
34 minPathParts = 2
35 )
36
37 // phoneRegex validates phone number format (with or without + prefix).
38 var phoneRegex = regexp.MustCompile(`^\+?[0-9\s)(+-]+$`)
39
40 // groupRegex validates group ID format.
41 var groupRegex = regexp.MustCompile(`^group\.[a-zA-Z0-9_+/=-]+$`)
42
43 // GetURL generates a URL from the current configuration values.
44 //
45 // Returns:
46 // - *url.URL: the generated URL representing the configuration.
47 func (c *Config) GetURL() *url.URL {
48 resolver := format.NewPropKeyResolver(c)
49
50 return c.getURL(&resolver)
51 }
52
53 // SetURL updates the configuration from a URL representation.
54 //
55 // Parameters:
56 // - serviceURL: the URL to parse configuration from
57 //
58 // Returns:
59 // - error: if parsing fails, nil otherwise
60 func (c *Config) SetURL(serviceURL *url.URL) error {
61 resolver := format.NewPropKeyResolver(c)
62
63 return c.setURL(&resolver, serviceURL)
64 }
65
66 // getURL constructs a URL from the Config's fields using the provided resolver.
67 //
68 // Parameters:
69 // - resolver: the configuration query resolver for property resolution
70 //
71 // Returns:
72 // - *url.URL: the constructed URL
73 func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
74 recipients := strings.Join(c.Recipients, "/")
75
76 result := &url.URL{
77 Scheme: Scheme,
78 Host: fmt.Sprintf("%s:%d", c.Host, c.Port),
79 Path: fmt.Sprintf("/%s/%s", c.Source, recipients),
80 RawQuery: format.BuildQuery(resolver),
81 }
82
83 // Add user:password if authentication is configured
84 if c.User != "" {
85 if c.Password != "" {
86 result.User = url.UserPassword(c.User, c.Password)
87 } else {
88 result.User = url.User(c.User)
89 }
90 }
91
92 return result
93 }
94
95 // parseAuth extracts user and password from the URL.
96 //
97 // Parameters:
98 // - serviceURL: the URL to extract authentication from
99 //
100 // Returns:
101 // - error: if extraction fails, nil otherwise
102 func (c *Config) parseAuth(serviceURL *url.URL) error {
103 if serviceURL.User != nil {
104 c.User = serviceURL.User.Username()
105 if password, ok := serviceURL.User.Password(); ok {
106 c.Password = password
107 }
108 }
109
110 return nil
111 }
112
113 // parseHostPort extracts host and port from the URL.
114 //
115 // Parameters:
116 // - serviceURL: the URL to extract host and port from
117 //
118 // Returns:
119 // - error: if parsing fails, nil otherwise
120 func (c *Config) parseHostPort(serviceURL *url.URL) error {
121 host, portStr, err := net.SplitHostPort(serviceURL.Host)
122 if err != nil {
123 // If no port specified, use default
124 host = serviceURL.Host
125 portStr = "8080"
126 }
127
128 c.Host = host
129
130 if portStr != "" {
131 if port, err := strconv.Atoi(portStr); err == nil {
132 c.Port = port
133 }
134 }
135
136 return nil
137 }
138
139 // parsePath extracts source phone number and recipients from the URL path.
140 //
141 // Parameters:
142 // - serviceURL: the URL to extract path from
143 //
144 // Returns:
145 // - error: if parsing fails, nil otherwise
146 func (c *Config) parsePath(serviceURL *url.URL) error {
147 pathParts := strings.Split(strings.Trim(serviceURL.Path, "/"), "/")
148 if len(pathParts) < minPathParts {
149 return ErrNoRecipients
150 }
151
152 // First part is source phone number
153 source := pathParts[0]
154 if !isValidPhoneNumber(source) {
155 return fmt.Errorf("%w: %s", ErrInvalidPhoneNumber, source)
156 }
157
158 c.Source = source
159
160 // Parse recipients from remaining path parts
161 recipients, err := parseRecipients(pathParts[1:])
162 if err != nil {
163 return err
164 }
165
166 c.Recipients = recipients
167
168 return nil
169 }
170
171 // parseRecipients parses recipient phone numbers and group IDs from URL path segments.
172 // It handles group IDs that may contain "/" characters by accumulating consecutive segments.
173 //
174 // Parameters:
175 // - pathParts: the URL path segments to parse
176 //
177 // Returns:
178 // - []string: the parsed recipients
179 // - error: if parsing fails, nil otherwise
180 func parseRecipients(pathParts []string) ([]string, error) {
181 if len(pathParts) == 0 {
182 return nil, ErrNoRecipients
183 }
184
185 var (
186 recipients []string
187 currentGroupID strings.Builder
188 )
189
190 inGroupID := false
191
192 for _, part := range pathParts {
193 switch {
194 case strings.HasPrefix(part, "group."):
195 // Finalize any previous group ID
196 if inGroupID {
197 recipients = append(recipients, currentGroupID.String())
198 }
199 // Start new group ID
200 currentGroupID.Reset()
201 currentGroupID.WriteString(part)
202
203 inGroupID = true
204
205 case inGroupID && !strings.HasPrefix(part, "+"):
206 // Continue building group ID (not a phone number)
207 currentGroupID.WriteString("/" + part)
208
209 default:
210 // Finalize any group ID in progress
211 if inGroupID {
212 recipients = append(recipients, currentGroupID.String())
213 inGroupID = false
214 }
215 // Add phone number or other recipient
216 recipients = append(recipients, part)
217 }
218 }
219
220 // Finalize any remaining group ID
221 if inGroupID {
222 recipients = append(recipients, currentGroupID.String())
223 }
224
225 // Validate all recipients
226 for _, recipient := range recipients {
227 if !isValidPhoneNumber(recipient) && !isValidGroupID(recipient) {
228 return nil, fmt.Errorf("%w: %s", ErrInvalidRecipient, recipient)
229 }
230 }
231
232 return recipients, nil
233 }
234
235 // parseQuery processes query parameters using the resolver.
236 //
237 // Parameters:
238 // - resolver: the configuration query resolver
239 // - serviceURL: the URL containing query parameters
240 //
241 // Returns:
242 // - error: if parsing fails, nil otherwise
243 func (c *Config) parseQuery(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
244 for key, vals := range serviceURL.Query() {
245 if err := resolver.Set(key, vals[0]); err != nil {
246 return fmt.Errorf("setting config property %q from URL query: %w", key, err)
247 }
248 }
249
250 return nil
251 }
252
253 // setURL updates the Config from a URL using the provided resolver.
254 //
255 // Parameters:
256 // - resolver: the configuration query resolver
257 // - serviceURL: the URL to parse
258 //
259 // Returns:
260 // - error: if parsing fails, nil otherwise
261 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
262 // Handle dummy URL used for documentation generation
263 if serviceURL.String() == "signal://[email protected]" {
264 c.Host = "localhost"
265 c.Port = 8080
266 c.Source = "+1234567890"
267 c.Recipients = []string{"+0987654321"}
268 c.DisableTLS = false
269
270 return nil
271 }
272
273 if err := c.parseAuth(serviceURL); err != nil {
274 return err
275 }
276
277 if err := c.parseHostPort(serviceURL); err != nil {
278 return err
279 }
280
281 if err := c.parsePath(serviceURL); err != nil {
282 return err
283 }
284
285 if err := c.parseQuery(resolver, serviceURL); err != nil {
286 return err
287 }
288
289 return nil
290 }
291
292 // isValidPhoneNumber checks if the string is a valid phone number.
293 //
294 // Parameters:
295 // - phone: the phone number string to validate
296 //
297 // Returns:
298 // - bool: true if valid, false otherwise
299 func isValidPhoneNumber(phone string) bool {
300 return phoneRegex.MatchString(phone)
301 }
302
303 // isValidGroupID checks if the string is a valid group ID.
304 //
305 // Parameters:
306 // - groupID: the group ID string to validate
307 //
308 // Returns:
309 // - bool: true if valid, false otherwise
310 func isValidGroupID(groupID string) bool {
311 return groupRegex.MatchString(groupID)
312 }