| 1 |
package homeassistant |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"crypto/tls" |
| 7 |
"encoding/json/v2" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"time" |
| 13 |
|
| 14 |
"github.com/nicholas-fedor/shoutrrr/internal/meta" |
| 15 |
"github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 16 |
"github.com/nicholas-fedor/shoutrrr/pkg/services/standard" |
| 17 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 18 |
) |
| 19 |
|
| 20 |
// Service sends notifications to Home Assistant. |
| 21 |
type Service struct { |
| 22 |
// Standard provides base service functionality including logging. |
| 23 |
standard.Standard |
| 24 |
|
| 25 |
// Config holds Home Assistant credentials and notification options. |
| 26 |
Config *Config |
| 27 |
// pkr resolves property keys for configuration updates from URL parameters. |
| 28 |
pkr format.PropKeyResolver |
| 29 |
// httpClient is the HTTP client used for REST API requests. |
| 30 |
httpClient types.HTTPClient |
| 31 |
} |
| 32 |
|
| 33 |
// requestPayload is the JSON body posted to /api/services/{domain}/{service}. |
| 34 |
type requestPayload struct { |
| 35 |
Message string `json:"message"` |
| 36 |
Title string `json:"title,omitempty"` |
| 37 |
NotificationID string `json:"notification_id,omitempty"` |
| 38 |
Targets []string `json:"target,omitempty"` |
| 39 |
} |
| 40 |
|
| 41 |
const ( |
| 42 |
// contentType is the JSON encoding required by the REST API. |
| 43 |
contentType = "application/json" |
| 44 |
// defaultHTTPTimeout is the timeout applied to REST API requests. |
| 45 |
defaultHTTPTimeout = 10 * time.Second |
| 46 |
) |
| 47 |
|
| 48 |
var ( |
| 49 |
_ types.Service = (*Service)(nil) |
| 50 |
_ types.HTTPClientSetter = (*Service)(nil) |
| 51 |
) |
| 52 |
|
| 53 |
// GetID returns the service identifier. |
| 54 |
// |
| 55 |
// Returns: |
| 56 |
// - The scheme name "homeassistant". |
| 57 |
func (s *Service) GetID() string { |
| 58 |
return Scheme |
| 59 |
} |
| 60 |
|
| 61 |
// Initialize configures the service with a URL and logger. |
| 62 |
// |
| 63 |
// Parameters: |
| 64 |
// - serviceURL: The Home Assistant service URL. |
| 65 |
// - logger: Logger used for service output. |
| 66 |
// |
| 67 |
// Returns: |
| 68 |
// - An error if default properties cannot be applied or the URL is invalid. |
| 69 |
func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error { |
| 70 |
s.SetLogger(logger) |
| 71 |
s.Config = &Config{} |
| 72 |
s.pkr = format.NewPropKeyResolver(s.Config) |
| 73 |
|
| 74 |
if err := s.pkr.SetDefaultProps(s.Config); err != nil { |
| 75 |
return fmt.Errorf("setting default props: %w", err) |
| 76 |
} |
| 77 |
|
| 78 |
if err := s.Config.setURL(&s.pkr, serviceURL); err != nil { |
| 79 |
return err |
| 80 |
} |
| 81 |
|
| 82 |
if s.httpClient == nil { |
| 83 |
s.httpClient = s.newHTTPClient() |
| 84 |
} |
| 85 |
|
| 86 |
return nil |
| 87 |
} |
| 88 |
|
| 89 |
// Send delivers a notification message to Home Assistant. |
| 90 |
// |
| 91 |
// Parameters: |
| 92 |
// - message: The notification body. |
| 93 |
// - params: Optional runtime overrides for title, service, targets, and nid. |
| 94 |
// |
| 95 |
// Returns: |
| 96 |
// - An error if the message is empty, configuration updates fail, or delivery fails. |
| 97 |
func (s *Service) Send(message string, params *types.Params) error { |
| 98 |
if message == "" { |
| 99 |
return ErrMessageEmpty |
| 100 |
} |
| 101 |
|
| 102 |
config := *s.Config |
| 103 |
if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil { |
| 104 |
return fmt.Errorf("updating config from params: %w", err) |
| 105 |
} |
| 106 |
|
| 107 |
if err := s.send(message, &config); err != nil { |
| 108 |
return fmt.Errorf("%w: %w", ErrSendFailed, err) |
| 109 |
} |
| 110 |
|
| 111 |
return nil |
| 112 |
} |
| 113 |
|
| 114 |
// SetHTTPClient sets a custom HTTP client for the service. |
| 115 |
// |
| 116 |
// Parameters: |
| 117 |
// - client: The HTTP client to use for API requests. |
| 118 |
func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 119 |
s.httpClient = client |
| 120 |
} |
| 121 |
|
| 122 |
// newHTTPClient returns the default HTTP client for Home Assistant requests. |
| 123 |
// |
| 124 |
// Returns: |
| 125 |
// - An HTTP client with a 10s timeout, TLS 1.2 minimum, and optional skip-verify. |
| 126 |
func (s *Service) newHTTPClient() types.HTTPClient { |
| 127 |
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} |
| 128 |
if s.Config != nil && s.Config.SkipTLSVerify { |
| 129 |
tlsConfig.InsecureSkipVerify = true |
| 130 |
|
| 131 |
s.Log("Warning: TLS verification is disabled, making connections insecure") |
| 132 |
} |
| 133 |
|
| 134 |
return &http.Client{ |
| 135 |
Timeout: defaultHTTPTimeout, |
| 136 |
Transport: &http.Transport{ |
| 137 |
TLSClientConfig: tlsConfig, |
| 138 |
}, |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
// send posts a notification to the Home Assistant REST API. |
| 143 |
// |
| 144 |
// Parameters: |
| 145 |
// - message: The notification body sent as the JSON field message. |
| 146 |
// - config: The resolved configuration used to build the URL and payload. |
| 147 |
// |
| 148 |
// Returns: |
| 149 |
// - An error if the request cannot be created, sent, or the API returns a non-success status. |
| 150 |
func (s *Service) send(message string, config *Config) error { |
| 151 |
payload, postURL, err := buildRequest(message, config) |
| 152 |
if err != nil { |
| 153 |
return err |
| 154 |
} |
| 155 |
|
| 156 |
body, err := json.Marshal(payload) |
| 157 |
if err != nil { |
| 158 |
return fmt.Errorf("marshaling payload: %w", err) |
| 159 |
} |
| 160 |
|
| 161 |
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) |
| 162 |
defer cancel() |
| 163 |
|
| 164 |
req, err := http.NewRequestWithContext( |
| 165 |
ctx, |
| 166 |
http.MethodPost, |
| 167 |
postURL, |
| 168 |
bytes.NewReader(body), |
| 169 |
) |
| 170 |
if err != nil { |
| 171 |
return fmt.Errorf("creating request: %w", err) |
| 172 |
} |
| 173 |
|
| 174 |
req.Header.Set("Content-Type", contentType) |
| 175 |
req.Header.Set("Authorization", "Bearer "+config.Token) |
| 176 |
req.Header.Set("User-Agent", "shoutrrr/"+meta.Version) |
| 177 |
|
| 178 |
client := s.httpClient |
| 179 |
if client == nil { |
| 180 |
client = &http.Client{Timeout: defaultHTTPTimeout} |
| 181 |
} |
| 182 |
|
| 183 |
res, err := client.Do(req) |
| 184 |
if err != nil { |
| 185 |
return fmt.Errorf("sending request: %w", err) |
| 186 |
} |
| 187 |
|
| 188 |
defer func() { _ = res.Body.Close() }() |
| 189 |
|
| 190 |
responseBody, err := io.ReadAll(res.Body) |
| 191 |
if err != nil { |
| 192 |
return fmt.Errorf("reading response body: %w", err) |
| 193 |
} |
| 194 |
|
| 195 |
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { |
| 196 |
return fmt.Errorf("%w: %s: %s", ErrUnexpectedStatus, res.Status, string(responseBody)) |
| 197 |
} |
| 198 |
|
| 199 |
return nil |
| 200 |
} |
| 201 |
|
| 202 |
// buildRequest constructs the JSON payload and API URL for a notification. |
| 203 |
// |
| 204 |
// Parameters: |
| 205 |
// - message: The notification body. |
| 206 |
// - config: The resolved configuration. |
| 207 |
// |
| 208 |
// Returns: |
| 209 |
// - payload: The JSON body to post. |
| 210 |
// - postURL: The absolute API URL. |
| 211 |
// - err: An error if the service mapping is invalid. |
| 212 |
func buildRequest(message string, config *Config) (requestPayload, string, error) { |
| 213 |
domain, service, err := config.domainService() |
| 214 |
if err != nil { |
| 215 |
return requestPayload{}, "", err |
| 216 |
} |
| 217 |
|
| 218 |
payload := requestPayload{Message: message} |
| 219 |
if config.Title != "" { |
| 220 |
payload.Title = config.Title |
| 221 |
} |
| 222 |
|
| 223 |
if config.isPersistent() { |
| 224 |
if config.Nid != "" { |
| 225 |
payload.NotificationID = config.Nid |
| 226 |
} |
| 227 |
} else if len(config.Targets) > 0 { |
| 228 |
payload.Targets = config.Targets |
| 229 |
} |
| 230 |
|
| 231 |
return payload, config.apiURL(domain, service), nil |
| 232 |
} |