Debian Codegraph @

pkg/services/chat/discord/discord_service.go

raw symbols SCIP
1 package discord
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net/url"
8 "strings"
9
10 "github.com/nicholas-fedor/shoutrrr/pkg/format"
11 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
12 "github.com/nicholas-fedor/shoutrrr/pkg/types"
13 "github.com/nicholas-fedor/shoutrrr/pkg/util"
14 )
15
16 // Service implements a Discord notification service.
17 type Service struct {
18 standard.Standard
19
20 Config *Config
21 pkr format.PropKeyResolver
22 HTTPClient HTTPClient
23 Sleeper Sleeper
24 }
25
26 const (
27 ChunkSize = 2000 // Maximum size of a single message chunk
28 TotalChunkSize = 6000 // Maximum total size of all chunks
29 ChunkCount = 10 // Maximum number of chunks allowed
30 MaxSearchRunes = 100 // Maximum number of runes to search for split position
31 HooksBaseURL = "https://discord.com/api/webhooks"
32 )
33
34 var limits = types.MessageLimit{
35 ChunkSize: ChunkSize,
36 TotalChunkSize: TotalChunkSize,
37 ChunkCount: ChunkCount,
38 }
39
40 // GetID provides the identifier for this service.
41 func (s *Service) GetID() string {
42 return Scheme
43 }
44
45 // Initialize configures the service with a URL and logger.
46 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
47 s.SetLogger(logger)
48
49 s.Config = &Config{}
50
51 s.pkr = format.NewPropKeyResolver(s.Config)
52 if s.HTTPClient == nil {
53 s.HTTPClient = NewDefaultHTTPClient()
54 }
55
56 s.Sleeper = RealSleeper{} // Default sleeper
57
58 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
59 return fmt.Errorf("setting default properties: %w", err)
60 }
61
62 if err := s.Config.SetURL(serviceURL); err != nil {
63 return fmt.Errorf("setting config URL: %w", err)
64 }
65
66 return nil
67 }
68
69 // Send delivers a notification message to Discord.
70 func (s *Service) Send(message string, params *types.Params) error {
71 if message == "" {
72 return ErrEmptyMessage
73 }
74
75 var firstErr error
76
77 if s.Config.JSON {
78 postURL := CreatePostURLFromConfig(s.Config)
79 if err := s.doSend([]byte(message), postURL); err != nil {
80 return fmt.Errorf("sending JSON message: %w", err)
81 }
82 } else {
83 config := *s.Config
84 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
85 return fmt.Errorf("updating config from params: %w", err)
86 }
87
88 batches := CreateItemsFromPlain(message, config.SplitLines)
89 for _, batch := range batches {
90 if err := s.sendItems(batch, params); err != nil {
91 s.Log(err)
92
93 if firstErr == nil {
94 firstErr = err
95 }
96 }
97 }
98 }
99
100 if firstErr != nil {
101 return fmt.Errorf("failed to send discord notification: %w", firstErr)
102 }
103
104 return nil
105 }
106
107 // SendItems delivers message items with enhanced metadata and formatting to Discord.
108 func (s *Service) SendItems(items []types.MessageItem, params *types.Params) error {
109 return s.sendItems(items, params)
110 }
111
112 // SetHTTPClient sets a custom HTTP client for the service.
113 func (s *Service) SetHTTPClient(client types.HTTPClient) {
114 s.HTTPClient = client
115 }
116
117 // doSend executes an HTTP POST request to deliver the payload to Discord.
118 func (s *Service) doSend(payload []byte, postURL string) error {
119 if err := validateDiscordWebhookURL(postURL); err != nil {
120 return err
121 }
122
123 ctx := context.Background()
124
125 preparer := &JSONRequestPreparer{payload: payload}
126
127 return sendWithRetry(ctx, preparer, postURL, s.HTTPClient, s.Sleeper)
128 }
129
130 // doSendMultipart executes an HTTP POST request with multipart/form-data to deliver payload and files to Discord.
131 func (s *Service) doSendMultipart(
132 payload *WebhookPayload,
133 files []types.File,
134 postURL string,
135 ) error {
136 if err := validateDiscordWebhookURL(postURL); err != nil {
137 return err
138 }
139
140 ctx := context.Background()
141
142 preparer := &MultipartRequestPreparer{
143 payload: payload,
144 files: files,
145 }
146
147 return sendWithRetry(ctx, preparer, postURL, s.HTTPClient, s.Sleeper)
148 }
149
150 func (s *Service) sendItems(items []types.MessageItem, params *types.Params) error {
151 config := *s.Config
152 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
153 return fmt.Errorf("updating config from params: %w", err)
154 }
155
156 payload, err := CreatePayloadFromItems(items, config.Title, config.LevelColors())
157 if err != nil {
158 return fmt.Errorf("creating payload: %w", err)
159 }
160
161 payload.Username = config.Username
162 payload.AvatarURL = config.Avatar
163
164 postURL := CreatePostURLFromConfig(&config)
165
166 // Check if any items have files
167 fileCount := 0
168
169 for _, item := range items {
170 if item.File != nil {
171 fileCount++
172 }
173 }
174
175 files := make([]types.File, 0, fileCount)
176
177 for _, item := range items {
178 if item.File != nil {
179 files = append(files, *item.File)
180 }
181 }
182
183 hasFiles := len(files) > 0
184
185 if hasFiles {
186 return s.doSendMultipart(&payload, files, postURL)
187 }
188
189 payloadBytes, err := json.Marshal(payload)
190 if err != nil {
191 return fmt.Errorf("marshaling payload to JSON: %w", err)
192 }
193
194 return s.doSend(payloadBytes, postURL)
195 }
196
197 // CreateItemsFromPlain converts plain text into MessageItems suitable for Discord's webhook payload.
198 func CreateItemsFromPlain(plain string, splitLines bool) [][]types.MessageItem {
199 var batches [][]types.MessageItem
200
201 if splitLines {
202 return util.MessageItemsFromLines(plain, limits)
203 }
204
205 for {
206 items, omitted := util.PartitionMessage(plain, limits, MaxSearchRunes)
207 batches = append(batches, items)
208
209 if omitted == 0 {
210 break
211 }
212
213 plain = plain[len(plain)-omitted:]
214 }
215
216 return batches
217 }
218
219 // validateDiscordWebhookURL validates the Discord webhook URL for security and correctness.
220 func validateDiscordWebhookURL(postURL string) error {
221 if postURL == "" {
222 return ErrEmptyURL
223 }
224
225 parsedURL, err := url.ParseRequestURI(postURL)
226 if err != nil {
227 return fmt.Errorf("invalid URL: %w", err)
228 }
229
230 if parsedURL.Scheme != "https" {
231 return ErrInvalidScheme
232 }
233
234 if parsedURL.Host != "discord.com" {
235 return ErrInvalidHost
236 }
237
238 if !strings.HasPrefix(parsedURL.Path, "/api/webhooks/") {
239 return ErrInvalidURLPrefix
240 }
241
242 parts := strings.Split(strings.TrimPrefix(postURL, HooksBaseURL+"/"), "/")
243 if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
244 return ErrMalformedURL
245 }
246
247 return nil
248 }