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