| 1 |
package googlechat |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"net/http" |
| 10 |
"net/url" |
| 11 |
|
| 12 |
"github.com/nicholas-fedor/shoutrrr/pkg/services/standard" |
| 13 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 14 |
) |
| 15 |
|
| 16 |
// Service implements a Google Chat notification service. |
| 17 |
type Service struct { |
| 18 |
standard.Standard |
| 19 |
|
| 20 |
Config *Config |
| 21 |
} |
| 22 |
|
| 23 |
// ErrUnexpectedStatus indicates an unexpected HTTP status code from the Google Chat API. |
| 24 |
var ErrUnexpectedStatus = errors.New("google chat api returned unexpected http status code") |
| 25 |
|
| 26 |
// GetID returns the identifier for this service. |
| 27 |
func (s *Service) GetID() string { |
| 28 |
return Scheme |
| 29 |
} |
| 30 |
|
| 31 |
// Initialize configures the service with a URL and logger. |
| 32 |
func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error { |
| 33 |
s.SetLogger(logger) |
| 34 |
|
| 35 |
s.Config = &Config{} |
| 36 |
|
| 37 |
return s.Config.SetURL(serviceURL) |
| 38 |
} |
| 39 |
|
| 40 |
// Send delivers a notification message to Google Chat. |
| 41 |
func (s *Service) Send(message string, _ *types.Params) error { |
| 42 |
config := s.Config |
| 43 |
|
| 44 |
jsonBody, err := json.Marshal(JSON{Text: message}) |
| 45 |
if err != nil { |
| 46 |
return fmt.Errorf("marshaling message to JSON: %w", err) |
| 47 |
} |
| 48 |
|
| 49 |
postURL := getAPIURL(config) |
| 50 |
jsonBuffer := bytes.NewBuffer(jsonBody) |
| 51 |
|
| 52 |
req, err := http.NewRequestWithContext( |
| 53 |
context.Background(), |
| 54 |
http.MethodPost, |
| 55 |
postURL.String(), |
| 56 |
jsonBuffer, |
| 57 |
) |
| 58 |
if err != nil { |
| 59 |
return fmt.Errorf("creating HTTP request: %w", err) |
| 60 |
} |
| 61 |
|
| 62 |
req.Header.Set("Content-Type", "application/json") |
| 63 |
|
| 64 |
resp, err := http.DefaultClient.Do(req) |
| 65 |
if err != nil { |
| 66 |
return fmt.Errorf("sending notification to Google Chat: %w", err) |
| 67 |
} |
| 68 |
|
| 69 |
defer func() { _ = resp.Body.Close() }() |
| 70 |
|
| 71 |
if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 72 |
return fmt.Errorf("%w: %d", ErrUnexpectedStatus, resp.StatusCode) |
| 73 |
} |
| 74 |
|
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
// getAPIURL constructs the service URL for Google Chat notifications. |
| 79 |
func getAPIURL(config *Config) *url.URL { |
| 80 |
query := url.Values{} |
| 81 |
query.Set("key", config.Key) |
| 82 |
query.Set("token", config.Token) |
| 83 |
|
| 84 |
return &url.URL{ |
| 85 |
Path: config.Path, |
| 86 |
Host: config.Host, |
| 87 |
Scheme: "https", |
| 88 |
RawQuery: query.Encode(), |
| 89 |
} |
| 90 |
} |