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