| 1 | package bark |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 14 | "github.com/nicholas-fedor/shoutrrr/pkg/services/standard" |
| 15 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 16 | "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient" |
| 17 | ) |
| 18 | |
| 19 | // HTTPClient defines the interface for HTTP operations required by the Bark service. |
| 20 | // This interface allows for dependency injection of HTTP clients for testing purposes. |
| 21 | type HTTPClient interface { |
| 22 | Do(req *http.Request) (*http.Response, error) |
| 23 | } |
| 24 | |
| 25 | // DefaultHTTPClient is the default HTTP client implementation used when no |
| 26 | // custom client is provided. It uses a reasonable timeout to prevent hanging requests. |
| 27 | type DefaultHTTPClient struct { |
| 28 | client *http.Client |
| 29 | } |
| 30 | |
| 31 | // Service sends push notifications to Bark-enabled iOS devices. |
| 32 | type Service struct { |
| 33 | standard.Standard |
| 34 | |
| 35 | Config *Config |
| 36 | pkr format.PropKeyResolver |
| 37 | HTTPClient HTTPClient |
| 38 | } |
| 39 | |
| 40 | // defaultHTTPTimeout is the default timeout for HTTP requests. |
| 41 | const defaultHTTPTimeout = 30 * time.Second |
| 42 | |
| 43 | // NewDefaultHTTPClient creates a new HTTP client with default timeout settings. |
| 44 | // |
| 45 | // Returns: |
| 46 | // - A configured DefaultHTTPClient instance ready for use. |
| 47 | func NewDefaultHTTPClient() *DefaultHTTPClient { |
| 48 | return &DefaultHTTPClient{ |
| 49 | client: &http.Client{ |
| 50 | Timeout: defaultHTTPTimeout, |
| 51 | }, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Do executes the HTTP request and returns the response. |
| 56 | // |
| 57 | // Parameters: |
| 58 | // - req: The HTTP request to execute. |
| 59 | // |
| 60 | // Returns: |
| 61 | // - The HTTP response from the server. |
| 62 | // - An error if the request fails. |
| 63 | func (c *DefaultHTTPClient) Do(req *http.Request) (*http.Response, error) { |
| 64 | resp, err := c.client.Do(req) |
| 65 | if err != nil { |
| 66 | return resp, fmt.Errorf("executing HTTP request: %w", err) |
| 67 | } |
| 68 | |
| 69 | return resp, nil |
| 70 | } |
| 71 | |
| 72 | // GetID returns the scheme identifier for the Bark service. |
| 73 | // |
| 74 | // Returns: |
| 75 | // - The string "bark" representing this notification service. |
| 76 | func (s *Service) GetID() string { |
| 77 | return Scheme |
| 78 | } |
| 79 | |
| 80 | // Initialize sets up the Bark service with configuration from the provided URL. |
| 81 | // |
| 82 | // Parameters: |
| 83 | // - serviceURL: URL containing configuration for the Bark service. |
| 84 | // - logger: Standard logger for output messages. |
| 85 | // |
| 86 | // Returns: |
| 87 | // - An error if initialization fails. |
| 88 | func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error { |
| 89 | s.SetLogger(logger) |
| 90 | s.Config = &Config{} |
| 91 | |
| 92 | s.pkr = format.NewPropKeyResolver(s.Config) |
| 93 | if s.HTTPClient == nil { |
| 94 | s.HTTPClient = NewDefaultHTTPClient() |
| 95 | } |
| 96 | |
| 97 | if err := s.pkr.SetDefaultProps(s.Config); err != nil { |
| 98 | return fmt.Errorf("setting default properties: %w", err) |
| 99 | } |
| 100 | |
| 101 | return s.Config.setURL(&s.pkr, serviceURL) |
| 102 | } |
| 103 | |
| 104 | // Send transmits a notification message to the Bark server. |
| 105 | // |
| 106 | // Parameters: |
| 107 | // - message: The notification body text to send. |
| 108 | // - params: Additional parameters for notification customization. |
| 109 | // |
| 110 | // Returns: |
| 111 | // - An error if the notification fails to send. |
| 112 | func (s *Service) Send(message string, params *types.Params) error { |
| 113 | config := s.Config |
| 114 | |
| 115 | if err := s.pkr.UpdateConfigFromParams(config, params); err != nil { |
| 116 | return fmt.Errorf("%w: %w", ErrUpdateParamsFailed, err) |
| 117 | } |
| 118 | |
| 119 | if err := s.sendAPI(config, message); err != nil { |
| 120 | return fmt.Errorf("failed to send bark notification: %w", err) |
| 121 | } |
| 122 | |
| 123 | return nil |
| 124 | } |
| 125 | |
| 126 | // SendItems converts message items to plain text and sends as a notification. |
| 127 | // This method handles rich message items by extracting plain text content. |
| 128 | // |
| 129 | // Parameters: |
| 130 | // - items: Slice of message items to send. |
| 131 | // - params: Additional parameters for notification customization. |
| 132 | // |
| 133 | // Returns: |
| 134 | // - An error if the notification fails to send. |
| 135 | func (s *Service) SendItems(items []types.MessageItem, params *types.Params) error { |
| 136 | // Convert message items to plain text |
| 137 | message := types.ItemsToPlain(items) |
| 138 | |
| 139 | return s.Send(message, params) |
| 140 | } |
| 141 | |
| 142 | // SetHTTPClient sets a custom HTTP client for the service. |
| 143 | func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 144 | if client == nil { |
| 145 | s.HTTPClient = NewDefaultHTTPClient() |
| 146 | |
| 147 | return |
| 148 | } |
| 149 | |
| 150 | s.HTTPClient = client |
| 151 | } |
| 152 | |
| 153 | // sendAPI sends a notification to the Bark server using the configured endpoint. |
| 154 | // This method handles JSON serialization, HTTP request creation, and response parsing. |
| 155 | // |
| 156 | // Parameters: |
| 157 | // - config: The Bark service configuration containing API settings. |
| 158 | // - message: The notification body text to send. |
| 159 | // |
| 160 | // Returns: |
| 161 | // - An error if the API request fails. |
| 162 | func (s *Service) sendAPI(config *Config, message string) error { |
| 163 | // Use background context for the request - services can add context support |
| 164 | // by wrapping this method or using a custom HTTP client |
| 165 | ctx := context.Background() |
| 166 | |
| 167 | response := APIResponse{} |
| 168 | request := PushPayload{ |
| 169 | Body: message, |
| 170 | DeviceKey: config.DeviceKey, |
| 171 | Title: config.Title, |
| 172 | Category: config.Category, |
| 173 | Copy: config.Copy, |
| 174 | Sound: config.Sound, |
| 175 | Group: config.Group, |
| 176 | Badge: &config.Badge, |
| 177 | Icon: config.Icon, |
| 178 | URL: config.URL, |
| 179 | } |
| 180 | |
| 181 | requestBody, err := json.Marshal(request) |
| 182 | if err != nil { |
| 183 | return fmt.Errorf("marshaling request to JSON: %w", err) |
| 184 | } |
| 185 | |
| 186 | apiURL := config.GetAPIURL("push") |
| 187 | |
| 188 | httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(requestBody)) |
| 189 | if err != nil { |
| 190 | return fmt.Errorf("creating request: %w", err) |
| 191 | } |
| 192 | |
| 193 | httpReq.Header.Set("Content-Type", "application/json") |
| 194 | |
| 195 | httpResp, err := s.HTTPClient.Do(httpReq) |
| 196 | if err != nil { |
| 197 | var jsonErr jsonclient.Error |
| 198 | if errors.As(err, &jsonErr) { |
| 199 | if json.Unmarshal([]byte(jsonErr.Body), &response) == nil { |
| 200 | return &response |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | return fmt.Errorf("%w: %w", ErrFailedAPIRequest, err) |
| 205 | } |
| 206 | |
| 207 | defer func() { _ = httpResp.Body.Close() }() |
| 208 | |
| 209 | if err := json.NewDecoder(httpResp.Body).Decode(&response); err != nil { |
| 210 | return fmt.Errorf("decoding response: %w", err) |
| 211 | } |
| 212 | |
| 213 | if response.Code != http.StatusOK { |
| 214 | if response.Message != "" { |
| 215 | return &response |
| 216 | } |
| 217 | |
| 218 | return fmt.Errorf("%w: %d", ErrUnexpectedStatus, response.Code) |
| 219 | } |
| 220 | |
| 221 | return nil |
| 222 | } |