| 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 |
s.pkr = format.NewPropKeyResolver(s.Config) |
| 51 |
s.HTTPClient = NewDefaultHTTPClient() // Default client for backward compatibility |
| 52 |
s.Sleeper = RealSleeper{} // Default sleeper |
| 53 |
|
| 54 |
if err := s.pkr.SetDefaultProps(s.Config); err != nil { |
| 55 |
return fmt.Errorf("setting default properties: %w", err) |
| 56 |
} |
| 57 |
|
| 58 |
if err := s.Config.SetURL(serviceURL); err != nil { |
| 59 |
return fmt.Errorf("setting config URL: %w", err) |
| 60 |
} |
| 61 |
|
| 62 |
return nil |
| 63 |
} |
| 64 |
|
| 65 |
// Send delivers a notification message to Discord. |
| 66 |
func (s *Service) Send(message string, params *types.Params) error { |
| 67 |
if message == "" { |
| 68 |
return ErrEmptyMessage |
| 69 |
} |
| 70 |
|
| 71 |
var firstErr error |
| 72 |
|
| 73 |
if s.Config.JSON { |
| 74 |
postURL := CreatePostURLFromConfig(s.Config) |
| 75 |
if err := s.doSend([]byte(message), postURL); err != nil { |
| 76 |
return fmt.Errorf("sending JSON message: %w", err) |
| 77 |
} |
| 78 |
} else { |
| 79 |
config := *s.Config |
| 80 |
if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil { |
| 81 |
return fmt.Errorf("updating config from params: %w", err) |
| 82 |
} |
| 83 |
|
| 84 |
batches := CreateItemsFromPlain(message, config.SplitLines) |
| 85 |
for _, batch := range batches { |
| 86 |
if err := s.sendItems(batch, params); err != nil { |
| 87 |
s.Log(err) |
| 88 |
|
| 89 |
if firstErr == nil { |
| 90 |
firstErr = err |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
if firstErr != nil { |
| 97 |
return fmt.Errorf("failed to send discord notification: %w", firstErr) |
| 98 |
} |
| 99 |
|
| 100 |
return nil |
| 101 |
} |
| 102 |
|
| 103 |
// SendItems delivers message items with enhanced metadata and formatting to Discord. |
| 104 |
func (s *Service) SendItems(items []types.MessageItem, params *types.Params) error { |
| 105 |
return s.sendItems(items, params) |
| 106 |
} |
| 107 |
|
| 108 |
// doSend executes an HTTP POST request to deliver the payload to Discord. |
| 109 |
func (s *Service) doSend(payload []byte, postURL string) error { |
| 110 |
if err := validateDiscordWebhookURL(postURL); err != nil { |
| 111 |
return err |
| 112 |
} |
| 113 |
|
| 114 |
ctx := context.Background() |
| 115 |
|
| 116 |
preparer := &JSONRequestPreparer{payload: payload} |
| 117 |
|
| 118 |
return sendWithRetry(ctx, preparer, postURL, s.HTTPClient, s.Sleeper) |
| 119 |
} |
| 120 |
|
| 121 |
// doSendMultipart executes an HTTP POST request with multipart/form-data to deliver payload and files to Discord. |
| 122 |
func (s *Service) doSendMultipart( |
| 123 |
payload *WebhookPayload, |
| 124 |
files []types.File, |
| 125 |
postURL string, |
| 126 |
) error { |
| 127 |
if err := validateDiscordWebhookURL(postURL); err != nil { |
| 128 |
return err |
| 129 |
} |
| 130 |
|
| 131 |
ctx := context.Background() |
| 132 |
|
| 133 |
preparer := &MultipartRequestPreparer{ |
| 134 |
payload: payload, |
| 135 |
files: files, |
| 136 |
} |
| 137 |
|
| 138 |
return sendWithRetry(ctx, preparer, postURL, s.HTTPClient, s.Sleeper) |
| 139 |
} |
| 140 |
|
| 141 |
func (s *Service) sendItems(items []types.MessageItem, params *types.Params) error { |
| 142 |
config := *s.Config |
| 143 |
if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil { |
| 144 |
return fmt.Errorf("updating config from params: %w", err) |
| 145 |
} |
| 146 |
|
| 147 |
payload, err := CreatePayloadFromItems(items, config.Title, config.LevelColors()) |
| 148 |
if err != nil { |
| 149 |
return fmt.Errorf("creating payload: %w", err) |
| 150 |
} |
| 151 |
|
| 152 |
payload.Username = config.Username |
| 153 |
payload.AvatarURL = config.Avatar |
| 154 |
|
| 155 |
postURL := CreatePostURLFromConfig(&config) |
| 156 |
|
| 157 |
// Check if any items have files |
| 158 |
fileCount := 0 |
| 159 |
|
| 160 |
for _, item := range items { |
| 161 |
if item.File != nil { |
| 162 |
fileCount++ |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
files := make([]types.File, 0, fileCount) |
| 167 |
|
| 168 |
for _, item := range items { |
| 169 |
if item.File != nil { |
| 170 |
files = append(files, *item.File) |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
hasFiles := len(files) > 0 |
| 175 |
|
| 176 |
if hasFiles { |
| 177 |
return s.doSendMultipart(&payload, files, postURL) |
| 178 |
} |
| 179 |
|
| 180 |
payloadBytes, err := json.Marshal(payload) |
| 181 |
if err != nil { |
| 182 |
return fmt.Errorf("marshaling payload to JSON: %w", err) |
| 183 |
} |
| 184 |
|
| 185 |
return s.doSend(payloadBytes, postURL) |
| 186 |
} |
| 187 |
|
| 188 |
// CreateItemsFromPlain converts plain text into MessageItems suitable for Discord's webhook payload. |
| 189 |
func CreateItemsFromPlain(plain string, splitLines bool) [][]types.MessageItem { |
| 190 |
var batches [][]types.MessageItem |
| 191 |
|
| 192 |
if splitLines { |
| 193 |
return util.MessageItemsFromLines(plain, limits) |
| 194 |
} |
| 195 |
|
| 196 |
for { |
| 197 |
items, omitted := util.PartitionMessage(plain, limits, MaxSearchRunes) |
| 198 |
batches = append(batches, items) |
| 199 |
|
| 200 |
if omitted == 0 { |
| 201 |
break |
| 202 |
} |
| 203 |
|
| 204 |
plain = plain[len(plain)-omitted:] |
| 205 |
} |
| 206 |
|
| 207 |
return batches |
| 208 |
} |
| 209 |
|
| 210 |
// validateDiscordWebhookURL validates the Discord webhook URL for security and correctness. |
| 211 |
func validateDiscordWebhookURL(postURL string) error { |
| 212 |
if postURL == "" { |
| 213 |
return ErrEmptyURL |
| 214 |
} |
| 215 |
|
| 216 |
parsedURL, err := url.ParseRequestURI(postURL) |
| 217 |
if err != nil { |
| 218 |
return fmt.Errorf("invalid URL: %w", err) |
| 219 |
} |
| 220 |
|
| 221 |
if parsedURL.Scheme != "https" { |
| 222 |
return ErrInvalidScheme |
| 223 |
} |
| 224 |
|
| 225 |
if parsedURL.Host != "discord.com" { |
| 226 |
return ErrInvalidHost |
| 227 |
} |
| 228 |
|
| 229 |
if !strings.HasPrefix(parsedURL.Path, "/api/webhooks/") { |
| 230 |
return ErrInvalidURLPrefix |
| 231 |
} |
| 232 |
|
| 233 |
parts := strings.Split(strings.TrimPrefix(postURL, HooksBaseURL+"/"), "/") |
| 234 |
if len(parts) != 2 || parts[0] == "" || parts[1] == "" { |
| 235 |
return ErrMalformedURL |
| 236 |
} |
| 237 |
|
| 238 |
return nil |
| 239 |
} |