Debian Codegraph @

pkg/services/specialized/notifiarr/notifiarr.go

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