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