Debian Codegraph @

pkg/services/specialized/notifiarr/notifiarr.go

raw
1 package notifiarr
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "regexp"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/nicholas-fedor/shoutrrr/pkg/format"
18 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
19 "github.com/nicholas-fedor/shoutrrr/pkg/types"
20 )
21
22 // Service implements a Notifiarr notification service.
23 type Service struct {
24 standard.Standard
25
26 Config *Config
27 pkr format.PropKeyResolver
28 httpClient types.HTTPClient
29 }
30
31 // presenceFlags holds boolean flags indicating presence of Discord fields.
32 type presenceFlags struct {
33 channel, color, thumbnail, image, title, icon, content, description, footer, fields, mentions bool
34 }
35
36 const (
37 // APIBaseURL is the base URL for Notifiarr API.
38 APIBaseURL = "https://notifiarr.com/api/v1/notification/passthrough"
39 // MentionTypeNone represents no mention type.
40 MentionTypeNone = 0
41 // MentionTypeUser represents a user mention type.
42 MentionTypeUser = 1
43 // MentionTypeRole represents a role mention type.
44 MentionTypeRole = 2
45 )
46
47 // requestTimeout is the timeout for one Notifiarr request.
48 const requestTimeout = 30 * time.Second
49
50 // ErrSendFailed indicates a failure to send a notification to Notifiarr.
51 var (
52 ErrSendFailed = errors.New("failed to send notification to Notifiarr")
53 // ErrUnexpectedStatus indicates the server returned an unexpected response status code.
54 ErrUnexpectedStatus = errors.New("server returned unexpected response status code")
55 // ErrInvalidAPIKey indicates an invalid API key was provided.
56 ErrInvalidAPIKey = errors.New("invalid API key")
57 // ErrAuthenticationFailed indicates authentication failure (e.g., 401 response).
58 ErrAuthenticationFailed = errors.New("authentication failed")
59 // ErrEmptyMessage indicates the message is empty.
60 ErrEmptyMessage = errors.New("message is empty")
61 // ErrInvalidURL indicates an invalid URL format.
62 ErrInvalidURL = errors.New("invalid URL format")
63 // ErrInvalidChannelID indicates an invalid channel ID.
64 ErrInvalidChannelID = errors.New("invalid channel ID")
65 // ErrNoDiscordFields indicates no Discord fields present.
66 ErrNoDiscordFields = errors.New("no Discord fields present")
67 )
68
69 // mentionRegex is a compiled regular expression for parsing Discord user/role mentions.
70 var mentionRegex = regexp.MustCompile(`<@!?(\d+)>|<@&(\d+)>`)
71
72 // HasAny returns true if any of the boolean fields are true, false otherwise.
73 func (pf presenceFlags) HasAny() bool {
74 return pf.channel || pf.color || pf.thumbnail || pf.image || pf.title || pf.icon ||
75 pf.content ||
76 pf.description ||
77 pf.footer ||
78 pf.fields ||
79 pf.mentions
80 }
81
82 // ExtractPingIDs extracts user and role IDs from mention strings.
83 func (s *Service) ExtractPingIDs(mentions []string) ([]int, []int) {
84 var pingUsers, pingRoles []int
85
86 for _, mention := range mentions {
87 mentionType, id := ParseMention(mention)
88 switch mentionType {
89 case MentionTypeUser:
90 pingUsers = append(pingUsers, id)
91 case MentionTypeRole:
92 pingRoles = append(pingRoles, id)
93 }
94 }
95
96 return pingUsers, pingRoles
97 }
98
99 // GetID returns the identifier for this service.
100 func (s *Service) GetID() string {
101 return Scheme
102 }
103
104 // GetServiceURLFromCustom converts a custom webhook URL into a standard service URL.
105 func (*Service) GetServiceURLFromCustom(serviceURL *url.URL) (*url.URL, error) {
106 // Copy the URL to modify
107 webhookURL := *serviceURL
108 if strings.HasPrefix(webhookURL.Scheme, Scheme) && len(webhookURL.Scheme) > len(Scheme) &&
109 webhookURL.Scheme[len(Scheme)] == '+' {
110 // Remove the scheme prefix if present
111 webhookURL.Scheme = webhookURL.Scheme[len(Scheme)+1:]
112 }
113
114 // Parse config from webhook URL
115 config, pkr, err := ConfigFromWebhookURL(&webhookURL)
116 if err != nil {
117 return nil, err
118 }
119
120 // Generate and return the service URL
121 return config.getURL(&pkr), nil
122 }
123
124 // Initialize configures the service with a URL and logger.
125 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
126 // Set the logger for the service
127 s.SetLogger(logger)
128 // Initialize service config
129 s.Config = &Config{}
130 // Initialize property key resolver
131 s.pkr = format.NewPropKeyResolver(s.Config)
132
133 // Set default properties
134 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
135 return fmt.Errorf("setting default properties: %w", err)
136 }
137
138 // Set URL and return any error
139 if err := s.Config.SetURL(serviceURL); err != nil {
140 return fmt.Errorf("setting config URL: %w", err)
141 }
142
143 return nil
144 }
145
146 // ParseChannelID parses the channel string to an integer.
147 func (s *Service) ParseChannelID(channelStr string) (int, error) {
148 var channelID int
149
150 _, err := fmt.Sscanf(channelStr, "%d", &channelID)
151 if err != nil {
152 return 0, fmt.Errorf("invalid channel ID format '%s': %w", channelStr, ErrInvalidChannelID)
153 }
154
155 return channelID, nil
156 }
157
158 // ParseFields parses a JSON string into a slice of Field structs.
159 func (s *Service) ParseFields(fieldsStr string) ([]Field, error) {
160 var fields []Field
161 if err := json.Unmarshal([]byte(fieldsStr), &fields); err != nil {
162 return nil, fmt.Errorf("unmarshaling fields JSON: %w", err)
163 }
164
165 return fields, nil
166 }
167
168 // ParseMentions extracts Discord user and role mentions from the message content.
169 func (s *Service) ParseMentions(message string) []string {
170 var mentions []string
171
172 matches := mentionRegex.FindAllStringSubmatch(message, -1)
173 for _, match := range matches {
174 if match[1] != "" {
175 mentions = append(mentions, fmt.Sprintf("<@%s>", match[1]))
176 } else if match[2] != "" {
177 mentions = append(mentions, fmt.Sprintf("<@&%s>", match[2]))
178 }
179 }
180
181 return mentions
182 }
183
184 // Send delivers a notification message to Notifiarr.
185 func (s *Service) Send(message string, paramsPtr *types.Params) error {
186 // Check for empty message
187 if message == "" {
188 return ErrEmptyMessage
189 }
190
191 // Create a copy of the config to avoid modifying the original
192 config := *s.Config
193
194 var params types.Params
195 // Handle nil params by creating empty map
196 if paramsPtr == nil {
197 params = types.Params{}
198 } else {
199 params = *paramsPtr
200 }
201
202 // Filter params to only include valid config keys for config updates
203 validConfigKeys := map[string]bool{
204 "name": true,
205 "channel": true,
206 "color": true,
207 "thumbnail": true,
208 "image": true,
209 }
210 filteredParams := types.Params{}
211
212 for k, v := range params {
213 if validConfigKeys[k] {
214 filteredParams[k] = v
215 }
216 }
217
218 // Update config with filtered parameters
219 if err := s.pkr.UpdateConfigFromParams(&config, &filteredParams); err != nil {
220 s.Logf("Failed to update params: %v", err)
221 }
222
223 // Create the payload
224 payload, err := s.createPayload(message, params, &config)
225 if err != nil {
226 return fmt.Errorf("creating payload: %w", err)
227 }
228
229 // Send the notification
230 if err := s.doSend(payload); err != nil {
231 return fmt.Errorf("%w: %s", ErrSendFailed, err.Error())
232 }
233
234 return nil
235 }
236
237 // ServiceTimeout returns the HTTP timeout used for a Notifiarr send.
238 func (*Service) ServiceTimeout(*types.Params) time.Duration {
239 return requestTimeout
240 }
241
242 // SetHTTPClient sets a custom HTTP client for the service.
243 func (s *Service) SetHTTPClient(client types.HTTPClient) {
244 if client == nil {
245 s.httpClient = nil
246
247 return
248 }
249
250 if c, ok := client.(*http.Client); ok && c == nil {
251 s.httpClient = nil
252
253 return
254 }
255
256 s.httpClient = client
257 }
258
259 // buildDiscordPayload constructs the Discord payload if any fields are present.
260 func (s *Service) buildDiscordPayload(
261 flags presenceFlags,
262 message string,
263 params types.Params,
264 config *Config,
265 ) (*DiscordPayload, error) {
266 if !flags.HasAny() {
267 return nil, ErrNoDiscordFields
268 }
269
270 discord := &DiscordPayload{}
271
272 if flags.channel {
273 // Parse channel ID from config string to integer
274 channelID, err := s.ParseChannelID(config.Channel)
275 if err != nil {
276 return nil, fmt.Errorf("parsing channel ID: %w", err)
277 }
278
279 discord.IDs = &IDPayload{Channel: channelID}
280 }
281
282 if flags.color {
283 // Assign color from config
284 discord.Color = config.Color
285 }
286
287 if flags.thumbnail || flags.image {
288 // Set thumbnail and image URLs from config
289 discord.Images = &ImagePayload{
290 Thumbnail: config.Thumbnail,
291 Image: config.Image,
292 }
293 }
294
295 // Construct text payload with title, icon, content, description, and footer from params
296 textPayload := &TextPayload{
297 Title: params[types.TitleKey],
298 Icon: params["icon"],
299 Content: params["content"],
300 Description: message,
301 Footer: params["footer"],
302 }
303
304 if flags.fields {
305 // Parse JSON fields string into Field structs
306 fields, err := s.ParseFields(params["fields"])
307 if err != nil {
308 return nil, fmt.Errorf("parsing fields: %w", err)
309 }
310
311 textPayload.Fields = fields
312 }
313
314 discord.Text = textPayload
315
316 if flags.mentions {
317 // Extract Discord mentions from message content
318 mentions := s.ParseMentions(message)
319
320 // Extract user and role IDs for ping setup (collects all mentions)
321 pingUsers, pingRoles := s.ExtractPingIDs(mentions)
322 if len(pingUsers) > 0 || len(pingRoles) > 0 {
323 pingPayload := &PingPayload{}
324 if len(pingUsers) > 0 {
325 pingPayload.PingUser = &pingUsers[0] // Use first user mention
326 }
327
328 if len(pingRoles) > 0 {
329 pingPayload.PingRole = &pingRoles[0] // Use first role mention
330 }
331
332 discord.Ping = pingPayload
333 }
334 }
335
336 return discord, nil
337 }
338
339 // createPayload creates the JSON payload for Notifiarr API.
340 func (s *Service) createPayload(
341 message string,
342 params types.Params,
343 config *Config,
344 ) ([]byte, error) {
345 // Parse the update parameter from params
346 updatePtr := ParseUpdateFlag(params)
347 // Build the notification data structure
348 notificationData := buildNotificationData(updatePtr, config, params)
349 // Check presence flags for Discord fields
350 flags := checkPresenceFlags(message, params, config, s)
351
352 // Build the Discord payload if fields are present
353 discord, err := s.buildDiscordPayload(flags, message, params, config)
354 if err != nil {
355 return nil, err
356 }
357
358 notification := NotificationPayload{
359 Notification: notificationData,
360 Discord: discord,
361 }
362
363 // Marshal the notification to JSON
364 payloadBytes, err := json.Marshal(notification)
365 if err != nil {
366 return nil, fmt.Errorf("marshaling payload to JSON: %w", err)
367 }
368
369 return payloadBytes, nil
370 }
371
372 // doSend executes the HTTP request to send a notification to Notifiarr.
373 // It includes a timeout to prevent hangs and differentiates between authentication failures and other errors.
374 func (s *Service) doSend(payload []byte) error {
375 // Build the API URL with API key
376 apiURL := fmt.Sprintf("%s/%s", APIBaseURL, s.Config.APIKey)
377
378 // Create context with timeout to prevent request hangs
379 ctx, cancel := context.WithTimeout(
380 context.Background(),
381 requestTimeout,
382 )
383 defer cancel()
384
385 // Create HTTP request with context and timeout
386 req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewBuffer(payload))
387 if err != nil {
388 return fmt.Errorf("creating HTTP request: %w", err)
389 }
390
391 // Set headers
392 req.Header.Set("Content-Type", "application/json")
393 req.Header.Set("Accept", "application/json")
394
395 client := s.httpClient
396 if client == nil {
397 client = &http.Client{}
398 }
399
400 res, err := client.Do(req)
401 if err != nil {
402 return fmt.Errorf("sending HTTP request: %w", err)
403 }
404
405 if res != nil && res.Body != nil {
406 defer func() {
407 _ = res.Body.Close()
408 }()
409
410 if body, err := io.ReadAll(res.Body); err == nil {
411 s.Log("Server response: ", string(body))
412 }
413 }
414
415 // Check for authentication failure (401 Unauthorized)
416 if res.StatusCode == http.StatusUnauthorized {
417 return ErrAuthenticationFailed
418 }
419
420 // Check for other unexpected status codes
421 if res.StatusCode < 200 || res.StatusCode >= 300 {
422 return fmt.Errorf("%w: %s", ErrUnexpectedStatus, res.Status)
423 }
424
425 return nil
426 }
427
428 // ParseMention parses a single mention string and returns the type (0=none, 1=user, 2=role) and ID if valid.
429 func ParseMention(mention string) (int, int) {
430 if !strings.HasPrefix(mention, "<@") || !strings.HasSuffix(mention, ">") {
431 return MentionTypeNone, 0
432 }
433
434 idStr := mention[2 : len(mention)-1]
435 if strings.HasPrefix(idStr, "&") {
436 roleIDStr := idStr[1:]
437 if roleID, err := strconv.Atoi(roleIDStr); err == nil {
438 return MentionTypeRole, roleID
439 }
440 } else {
441 // Handle user mentions, which may have a "!" prefix for nicknames
442 userIDStr := strings.TrimPrefix(idStr, "!")
443
444 if userID, err := strconv.Atoi(userIDStr); err == nil {
445 return MentionTypeUser, userID
446 }
447 }
448
449 return MentionTypeNone, 0
450 }
451
452 // ParseUpdateFlag parses the update parameter from params.
453 func ParseUpdateFlag(params types.Params) *bool {
454 if updateStr, exists := params["update"]; exists && updateStr != "" {
455 switch updateStr {
456 case "true":
457 return &[]bool{true}[0]
458 case "false":
459 return &[]bool{false}[0]
460 }
461 }
462
463 return nil
464 }
465
466 // buildNotificationData creates the notification data structure.
467 func buildNotificationData(updatePtr *bool, config *Config, params types.Params) NotificationData {
468 return NotificationData{
469 Update: updatePtr,
470 Name: config.Name,
471 Event: params["id"],
472 }
473 }
474
475 // checkPresenceFlags determines which Discord fields are present.
476 func checkPresenceFlags(
477 message string,
478 params types.Params,
479 config *Config,
480 service *Service,
481 ) presenceFlags {
482 return presenceFlags{
483 channel: config.Channel != "",
484 color: config.Color != "",
485 thumbnail: config.Thumbnail != "",
486 image: config.Image != "",
487 title: params[types.TitleKey] != "",
488 icon: params["icon"] != "",
489 content: params["content"] != "",
490 description: message != "",
491 footer: params["footer"] != "",
492 fields: params["fields"] != "",
493 mentions: len(service.ParseMentions(message)) > 0,
494 }
495 }