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