Debian Codegraph @

pkg/services/specialized/generic/generic.go

raw
1 package generic
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "maps"
11 "net/http"
12 "net/url"
13 "strings"
14
15 "github.com/nicholas-fedor/shoutrrr/pkg/format"
16 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
17 "github.com/nicholas-fedor/shoutrrr/pkg/types"
18 )
19
20 // Service implements a generic notification service for custom webhooks.
21 type Service struct {
22 standard.Standard
23
24 Config *Config
25 pkr format.PropKeyResolver
26 httpClient types.HTTPClient
27 }
28
29 // JSONTemplate identifies the JSON format for webhook payloads.
30 const (
31 JSONTemplate = "JSON"
32 )
33
34 // ErrSendFailed indicates a failure to send a notification to the generic webhook.
35 var (
36 ErrSendFailed = errors.New("failed to send notification to generic webhook")
37 ErrUnexpectedStatus = errors.New("server returned unexpected response status code")
38 ErrTemplateNotLoaded = errors.New("template has not been loaded")
39 )
40
41 // GetID returns the identifier for this service.
42 func (s *Service) GetID() string {
43 return Scheme
44 }
45
46 // GetPayload prepares the request payload based on the configured template.
47 func (s *Service) GetPayload(config *Config, params types.Params) (io.Reader, error) {
48 switch config.Template {
49 case "":
50 // No template, send message directly
51 return bytes.NewBufferString(params[config.MessageKey]), nil
52 case "json", JSONTemplate:
53 // JSON template, marshal params to JSON
54 // Add extra data to params
55 maps.Copy(params, config.extraData)
56
57 // Marshal to JSON
58 jsonBytes, err := json.Marshal(params)
59 if err != nil {
60 return nil, fmt.Errorf("marshaling params to JSON: %w", err)
61 }
62
63 return bytes.NewBuffer(jsonBytes), nil
64 }
65
66 // Get the template
67 tpl, found := s.GetTemplate(config.Template)
68 if !found {
69 return nil, fmt.Errorf("%w: %q", ErrTemplateNotLoaded, config.Template)
70 }
71
72 // Buffer for template execution
73 bb := &bytes.Buffer{}
74 if err := tpl.Execute(bb, params); err != nil {
75 return nil, fmt.Errorf("executing template %q: %w", config.Template, err)
76 }
77
78 return bb, nil
79 }
80
81 // GetServiceURLFromCustom converts a custom webhook URL into a standard service URL.
82 func (*Service) GetServiceURLFromCustom(customURL *url.URL) (*url.URL, error) {
83 // Copy the URL to modify
84 webhookURL := *customURL
85 if strings.HasPrefix(webhookURL.Scheme, Scheme) {
86 // Remove the scheme prefix if present
87 webhookURL.Scheme = webhookURL.Scheme[len(Scheme)+1:]
88 }
89
90 // Parse config from webhook URL
91 config, pkr, err := ConfigFromWebhookURL(&webhookURL)
92 if err != nil {
93 return nil, err
94 }
95
96 // Generate and return the service URL
97 return config.getURL(&pkr), nil
98 }
99
100 // Initialize configures the service with a URL and logger.
101 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
102 // Set the logger for the service
103 s.SetLogger(logger)
104
105 // Get default config and property key resolver
106 config, pkr := DefaultConfig()
107 // Assign config to service
108 s.Config = config
109 // Assign resolver
110 s.pkr = pkr
111
112 // Set URL and return any error
113 return s.Config.setURL(&s.pkr, serviceURL)
114 }
115
116 // Send delivers a notification message to a generic webhook endpoint.
117 func (s *Service) Send(message string, paramsPtr *types.Params) error {
118 // Create a copy of the config to avoid modifying the original
119 config := *s.Config
120
121 var params types.Params
122 if paramsPtr == nil {
123 // Handle nil params by creating empty map
124 params = types.Params{}
125 } else {
126 params = *paramsPtr
127 }
128
129 if err := s.pkr.UpdateConfigFromParams(&config, &params); err != nil {
130 // Update config with runtime parameters
131 s.Logf("Failed to update params: %v", err)
132 }
133
134 // Prepare parameters for sending
135 sendParams := createSendParams(&config, params, message)
136 if err := s.doSend(&config, sendParams); err != nil {
137 // Execute the HTTP request to send the notification
138 return fmt.Errorf("%w: %s", ErrSendFailed, err.Error())
139 }
140
141 return nil
142 }
143
144 // SetHTTPClient sets a custom HTTP client for the service.
145 func (s *Service) SetHTTPClient(client types.HTTPClient) {
146 if client == nil {
147 s.httpClient = nil
148
149 return
150 }
151
152 if c, ok := client.(*http.Client); ok && c == nil {
153 s.httpClient = nil
154
155 return
156 }
157
158 s.httpClient = client
159 }
160
161 // doSend executes the HTTP request to send a notification to the webhook.
162 func (s *Service) doSend(config *Config, params types.Params) error {
163 // Get the webhook URL as string
164 postURL := config.WebhookURL().String()
165
166 // Prepare the request payload
167 payload, err := s.GetPayload(config, params)
168 if err != nil {
169 return err
170 }
171
172 // Create background context for the request
173 ctx := context.Background()
174
175 // Create HTTP request with context
176 req, err := http.NewRequestWithContext(ctx, config.RequestMethod, postURL, payload)
177 if err != nil {
178 return fmt.Errorf("creating HTTP request: %w", err)
179 }
180
181 // Determine content type based on payload format
182 contentType := config.ContentType
183 if config.Template == "" {
184 // When no template is specified, payload is plain text
185 contentType = "text/plain"
186 }
187
188 // Set content type header
189 req.Header.Set("Content-Type", contentType)
190 // Set accept header
191 req.Header.Set("Accept", contentType)
192
193 for key, value := range config.headers {
194 // Add custom headers
195 req.Header.Set(key, value)
196 }
197
198 client := s.httpClient
199 if client == nil {
200 client = &http.Client{}
201 }
202
203 // Send the HTTP request
204 res, err := client.Do(req)
205 if err != nil {
206 return fmt.Errorf("sending HTTP request: %w", err)
207 }
208
209 if res != nil && res.Body != nil {
210 // Read and log response body if available
211 defer func() {
212 _ = res.Body.Close()
213 }()
214
215 if body, err := io.ReadAll(res.Body); err == nil {
216 s.Log("Server response: ", string(body))
217 }
218 }
219
220 if res.StatusCode >= http.StatusBadRequest {
221 // Check for error status codes (4xx and 5xx)
222 return fmt.Errorf("%w: %s", ErrUnexpectedStatus, res.Status)
223 }
224
225 return nil
226 }
227
228 // createSendParams constructs parameters for sending a notification.
229 func createSendParams(config *Config, params types.Params, message string) types.Params {
230 // Initialize new params map
231 sendParams := types.Params{}
232
233 for key, val := range params {
234 // Copy params, mapping title key if necessary
235 if key == types.TitleKey {
236 key = config.TitleKey
237 }
238
239 sendParams[key] = val
240 }
241
242 // Add the message
243 sendParams[config.MessageKey] = message
244
245 return sendParams
246 }