Debian Codegraph @

pkg/services/push/ifttt/ifttt.go

raw
1 package ifttt
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "net/http"
9 "net/url"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/format"
12 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
13 "github.com/nicholas-fedor/shoutrrr/pkg/types"
14 )
15
16 // Service sends notifications to an IFTTT webhook.
17 type Service struct {
18 standard.Standard
19
20 Config *Config
21 pkr format.PropKeyResolver
22 }
23
24 // apiURLFormat defines the IFTTT webhook URL template.
25 const (
26 apiURLFormat = "https://maker.ifttt.com/trigger/%s/with/key/%s"
27 )
28
29 // ErrSendFailed indicates a failure to send an IFTTT event notification.
30 var (
31 ErrSendFailed = errors.New("failed to send IFTTT event")
32 ErrUnexpectedStatus = errors.New("got unexpected response status code")
33 )
34
35 // GetID returns the identifier for this service.
36 func (s *Service) GetID() string {
37 return Scheme
38 }
39
40 // Initialize configures the service with a URL and logger.
41 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
42 s.SetLogger(logger)
43 s.Config = &Config{
44 UseMessageAsValue: DefaultMessageValue,
45 }
46 s.pkr = format.NewPropKeyResolver(s.Config)
47
48 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
49 return err
50 }
51
52 return nil
53 }
54
55 // Send delivers a notification message to an IFTTT webhook.
56 func (s *Service) Send(message string, params *types.Params) error {
57 config := s.Config
58 if err := s.pkr.UpdateConfigFromParams(config, params); err != nil {
59 return fmt.Errorf("updating config from params: %w", err)
60 }
61
62 payload, err := createJSONToSend(config, message, params)
63 if err != nil {
64 return err
65 }
66
67 for _, event := range config.Events {
68 apiURL := s.createAPIURLForEvent(event)
69 if err := doSend(payload, apiURL); err != nil {
70 return fmt.Errorf("%w: event %q: %w", ErrSendFailed, event, err)
71 }
72 }
73
74 return nil
75 }
76
77 // createAPIURLForEvent builds an IFTTT webhook URL for a specific event.
78 func (s *Service) createAPIURLForEvent(event string) string {
79 return fmt.Sprintf(apiURLFormat, event, s.Config.WebHookID)
80 }
81
82 // doSend executes an HTTP POST request to send the payload to the IFTTT webhook.
83 func doSend(payload []byte, postURL string) error {
84 req, err := http.NewRequestWithContext(
85 context.Background(),
86 http.MethodPost,
87 postURL,
88 bytes.NewBuffer(payload),
89 )
90 if err != nil {
91 return fmt.Errorf("creating HTTP request: %w", err)
92 }
93
94 req.Header.Set("Content-Type", "application/json")
95
96 res, err := http.DefaultClient.Do(req)
97 if err != nil {
98 return fmt.Errorf("sending HTTP request to IFTTT webhook: %w", err)
99 }
100
101 defer func() { _ = res.Body.Close() }()
102
103 if res.StatusCode < 200 || res.StatusCode >= 300 {
104 return fmt.Errorf("%w: %s", ErrUnexpectedStatus, res.Status)
105 }
106
107 return nil
108 }