Debian Codegraph @

pkg/services/push/gotify/gotify.go

raw
1 package gotify
2
3 import (
4 "fmt"
5 "net/http"
6 "net/url"
7 "sync"
8
9 "github.com/nicholas-fedor/shoutrrr/pkg/format"
10 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
11 "github.com/nicholas-fedor/shoutrrr/pkg/types"
12 "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
13 )
14
15 // Service implements a Gotify notification service that handles sending push notifications
16 // to Gotify servers. It manages HTTP client configuration, TLS settings, authentication,
17 // and payload construction for reliable message delivery.
18 type Service struct {
19 standard.Standard // Embeds the standard service functionality including logging
20
21 Config *Config // Holds the configuration settings for the Gotify service, including host, token, and other parameters
22 pkr format.PropKeyResolver // Property key resolver used to update configuration from URL parameters dynamically
23 mu sync.Mutex // Protects HTTP client initialization for thread safety
24 httpClient *http.Client // HTTP client instance configured with appropriate timeout and transport settings for API calls
25 client jsonclient.Client // JSON client wrapper that handles JSON request/response marshaling and HTTP communication
26
27 // Interface dependencies (injected during initialization)
28 httpClientManager HTTPClientManager
29 urlBuilder URLBuilder
30 payloadBuilder PayloadBuilder
31 validator Validator
32 sender Sender
33 }
34
35 // GetHTTPClient returns the HTTP client used by this service.
36 // This method implements the MockClientService interface for testing.
37 func (s *Service) GetHTTPClient() *http.Client {
38 return s.httpClient
39 }
40
41 // GetID returns the identifier for this service.
42 func (s *Service) GetID() string {
43 return Scheme
44 }
45
46 // Initialize configures the service with a URL and logger.
47 // This method sets up the entire service infrastructure including configuration parsing,
48 // HTTP client creation with appropriate TLS settings, and logging capabilities.
49 // Parameters:
50 // - serviceURL: The URL containing Gotify server configuration (host, token, path, etc.)
51 // - logger: Logger instance for recording service operations and warnings
52 //
53 // Returns: error if configuration parsing or setup fails, nil on success.
54 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
55 // Set the logger for this service instance to enable logging throughout the service lifecycle
56 s.SetLogger(logger)
57
58 // Initialize the configuration with default values
59 s.Config = &Config{
60 Title: "Shoutrrr notification", // Default notification title used when none specified
61 }
62
63 // Create a property key resolver to handle dynamic configuration updates from parameters
64 s.pkr = format.NewPropKeyResolver(s.Config)
65
66 // Parse the configuration URL to extract host, token, path, and other settings
67 err := s.Config.SetURL(serviceURL)
68 if err != nil {
69 return fmt.Errorf("failed to set URL: %w", err)
70 }
71
72 // Inject default implementations for interfaces
73 s.httpClientManager = &DefaultHTTPClientManager{}
74 s.urlBuilder = &DefaultURLBuilder{}
75 s.payloadBuilder = &DefaultPayloadBuilder{}
76 s.validator = &DefaultValidator{}
77 s.sender = &DefaultSender{}
78
79 // Initialize HTTP client and related components in a thread-safe manner
80 s.initClient()
81
82 return nil // Return success
83 }
84
85 // Send delivers a notification message to Gotify.
86 // This is the main entry point for sending notifications. It handles message validation,
87 // parameter processing, configuration updates, URL construction, authentication setup,
88 // and HTTP request execution.
89 // Parameters:
90 // - message: The notification message content to send (cannot be empty)
91 // - params: Optional parameters that can override configuration settings or provide extras
92 //
93 // Returns: error if sending fails or validation fails, nil on successful delivery.
94 func (s *Service) Send(message string, params *types.Params) error {
95 if err := s.validateInputs(message, params); err != nil {
96 return fmt.Errorf("input validation failed: %w", err)
97 }
98
99 s.initClient()
100
101 config, extras, err := s.processConfig(params)
102 if err != nil {
103 return fmt.Errorf("failed to process config: %w", err)
104 }
105
106 postURL, request, headers, err := s.buildRequest(message, &config, extras)
107 if err != nil {
108 return fmt.Errorf("failed to build request: %w", err)
109 }
110
111 return s.sendRequest(postURL, request, headers)
112 }
113
114 // buildRequest constructs the URL, payload, and headers for the HTTP request.
115 func (s *Service) buildRequest(
116 message string,
117 config *Config,
118 extras map[string]any,
119 ) (string, *MessageRequest, http.Header, error) {
120 // Validate token format before constructing URL
121 if !s.validator.ValidateToken(config.Token) {
122 return "", nil, nil, fmt.Errorf("%w: %q", ErrInvalidToken, config.Token)
123 }
124
125 // Construct the complete API endpoint URL
126 postURL, err := s.urlBuilder.BuildURL(config)
127 if err != nil {
128 return "", nil, nil, fmt.Errorf("failed to build URL: %w", err)
129 }
130
131 // Prepare the JSON request payload
132 request := s.payloadBuilder.PrepareRequest(message, config, extras, config.Date)
133
134 // Prepare headers for header-based authentication
135 var headers http.Header
136 if config.UseHeader {
137 headers = make(http.Header)
138 headers.Set("X-Gotify-Key", config.Token)
139 }
140
141 return postURL, request, headers, nil
142 }
143
144 // initClient initializes the HTTP client and related components.
145 // This method ensures that the transport, HTTP client, JSON client,
146 // and TLS warning logging are performed when needed, allowing re-initialization if the client becomes nil.
147 func (s *Service) initClient() {
148 initClient(s, s.httpClientManager)
149 }
150
151 // processConfig handles configuration processing including parameter updates, validation, and extras parsing.
152 func (s *Service) processConfig(params *types.Params) (Config, map[string]any, error) {
153 // Get reference to current configuration
154 config := *s.Config
155
156 // Filter out 'extras' parameter as it's handled separately from other config updates
157 filteredParams := filterParams(params)
158
159 // Update configuration with filtered parameters (title, priority, etc.)
160 if err := s.pkr.UpdateConfigFromParams(&config, &filteredParams); err != nil {
161 return config, nil, fmt.Errorf("failed to update config from params: %w", err)
162 }
163
164 // Validate priority is within valid range (-2 to 10)
165 if err := s.validator.ValidatePriority(config.Priority); err != nil {
166 return config, nil, fmt.Errorf("priority validation failed: %w", err)
167 }
168
169 // Validate and convert date format
170 validatedDate, err := s.validator.ValidateDate(config.Date)
171 if err != nil {
172 s.Logf("Invalid date format: %v", err)
173
174 config.Date = ""
175 } else {
176 config.Date = validatedDate
177 }
178
179 // Parse extras from parameters or fall back to config extras
180 extras, err := s.payloadBuilder.ParseExtras(params, &config)
181 if err != nil {
182 s.Logf("Failed to parse extras from params: %v", err)
183
184 extras = config.Extras
185 }
186
187 return config, extras, nil
188 }
189
190 // sendRequest handles the HTTP request.
191 // This function executes the actual HTTP POST request to the Gotify API endpoint,
192 // handling both successful responses and error conditions with appropriate error wrapping.
193 // Parameters:
194 // - postURL: The complete API endpoint URL to send the request to
195 // - request: The JSON payload to send in the request body
196 // - headers: Optional headers to set on the request
197 //
198 // Returns: error if the request fails or server returns an error, nil on success.
199 func (s *Service) sendRequest(
200 postURL string,
201 request *MessageRequest,
202 headers http.Header,
203 ) error {
204 if err := s.sender.SendRequest(
205 s.httpClient,
206 postURL,
207 request,
208 headers,
209 ); err != nil {
210 return fmt.Errorf("%s: %w", ErrSendFailed.Error(), err)
211 }
212
213 return nil
214 }
215
216 // validateInputs performs initial validation checks for the Send method.
217 func (s *Service) validateInputs(message string, _ *types.Params) error {
218 if err := s.validator.ValidateMessage(message); err != nil {
219 return fmt.Errorf("message validation failed: %w", err)
220 }
221
222 if err := s.validator.ValidateServiceInitialized(s.Config); err != nil {
223 return fmt.Errorf("service initialization validation failed: %w", err)
224 }
225
226 return nil
227 }
228
229 // filterParams filters out 'extras' parameters from the given params.
230 func filterParams(params *types.Params) types.Params {
231 if params == nil {
232 return types.Params{}
233 }
234
235 filtered := make(types.Params)
236
237 for k, v := range *params {
238 if k != "extras" {
239 filtered[k] = v
240 }
241 }
242
243 return filtered
244 }