Debian Codegraph @

pkg/services/push/bark/bark.go

raw
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 // ServiceTimeout returns the HTTP timeout used for a Bark send.
143 //
144 // Parameters:
145 // - params: Unused. The budget does not depend on send parameters.
146 //
147 // Returns:
148 // - [defaultHTTPTimeout].
149 func (*Service) ServiceTimeout(*types.Params) time.Duration {
150 return defaultHTTPTimeout
151 }
152
153 // SetHTTPClient sets a custom HTTP client for the service.
154 func (s *Service) SetHTTPClient(client types.HTTPClient) {
155 if client == nil {
156 s.HTTPClient = NewDefaultHTTPClient()
157
158 return
159 }
160
161 s.HTTPClient = client
162 }
163
164 // sendAPI sends a notification to the Bark server using the configured endpoint.
165 // This method handles JSON serialization, HTTP request creation, and response parsing.
166 //
167 // Parameters:
168 // - config: The Bark service configuration containing API settings.
169 // - message: The notification body text to send.
170 //
171 // Returns:
172 // - An error if the API request fails.
173 func (s *Service) sendAPI(config *Config, message string) error {
174 // Use background context for the request - services can add context support
175 // by wrapping this method or using a custom HTTP client
176 ctx := context.Background()
177
178 response := APIResponse{}
179 request := PushPayload{
180 Body: message,
181 DeviceKey: config.DeviceKey,
182 Title: config.Title,
183 Category: config.Category,
184 Copy: config.Copy,
185 Sound: config.Sound,
186 Group: config.Group,
187 Badge: &config.Badge,
188 Icon: config.Icon,
189 URL: config.URL,
190 }
191
192 requestBody, err := json.Marshal(request)
193 if err != nil {
194 return fmt.Errorf("marshaling request to JSON: %w", err)
195 }
196
197 apiURL := config.GetAPIURL("push")
198
199 httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(requestBody))
200 if err != nil {
201 return fmt.Errorf("creating request: %w", err)
202 }
203
204 httpReq.Header.Set("Content-Type", "application/json")
205
206 httpResp, err := s.HTTPClient.Do(httpReq)
207 if err != nil {
208 if jsonErr, ok := errors.AsType[jsonclient.Error](err); ok {
209 if json.Unmarshal([]byte(jsonErr.Body), &response) == nil {
210 return &response
211 }
212 }
213
214 return fmt.Errorf("%w: %w", ErrFailedAPIRequest, err)
215 }
216
217 defer func() { _ = httpResp.Body.Close() }()
218
219 if err := json.NewDecoder(httpResp.Body).Decode(&response); err != nil {
220 return fmt.Errorf("decoding response: %w", err)
221 }
222
223 if response.Code != http.StatusOK {
224 if response.Message != "" {
225 return &response
226 }
227
228 return fmt.Errorf("%w: %d", ErrUnexpectedStatus, response.Code)
229 }
230
231 return nil
232 }