Debian Codegraph @

pkg/services/chat/teams/teams_service.go

raw
1 package teams
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "net/http"
9 "net/url"
10 "strings"
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 )
17
18 // HTTPClient defines the interface for HTTP operations.
19 type HTTPClient interface {
20 Do(req *http.Request) (*http.Response, error)
21 }
22
23 // defaultHTTPClient implements HTTPClient using http.Client with a timeout.
24 type defaultHTTPClient struct {
25 client *http.Client
26 }
27
28 // Service sends notifications to Microsoft Teams via Power Automate workflow webhooks.
29 type Service struct {
30 standard.Standard
31
32 Config *Config
33 pkr format.PropKeyResolver
34 httpClient HTTPClient
35 }
36
37 // defaultHTTPTimeout is the default timeout for HTTP requests.
38 const defaultHTTPTimeout = 30 * time.Second
39
40 // adaptiveCardVersion is the Adaptive Card schema version used in payloads.
41 const adaptiveCardVersion = "1.2"
42
43 // Do performs the HTTP request.
44 func (c *defaultHTTPClient) Do(req *http.Request) (*http.Response, error) {
45 resp, err := c.client.Do(req)
46 if err != nil {
47 return nil, fmt.Errorf("performing HTTP request: %w", err)
48 }
49
50 return resp, nil
51 }
52
53 // GetHTTPClient returns the service's HTTP client for testing purposes.
54 func (s *Service) GetHTTPClient() HTTPClient {
55 return s.httpClient
56 }
57
58 // GetID returns the service identifier.
59 func (s *Service) GetID() string {
60 return Scheme
61 }
62
63 // Initialize configures the service with a URL and logger.
64 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
65 s.SetLogger(logger)
66
67 s.Config = &Config{}
68 s.pkr = format.NewPropKeyResolver(s.Config)
69 s.httpClient = &defaultHTTPClient{
70 client: &http.Client{Timeout: defaultHTTPTimeout},
71 }
72
73 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
74 return fmt.Errorf("setting default properties: %w", err)
75 }
76
77 return s.Config.SetURL(serviceURL)
78 }
79
80 // Send delivers a notification message to Microsoft Teams.
81 func (s *Service) Send(message string, params *types.Params) error {
82 if s.Config == nil {
83 return ErrMissingHost
84 }
85
86 config := *s.Config
87 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
88 return fmt.Errorf("updating config from params: %w", err)
89 }
90
91 return s.doSend(&config, message)
92 }
93
94 // SetHTTPClient sets the HTTP client for testing purposes.
95 func (s *Service) SetHTTPClient(client HTTPClient) {
96 s.httpClient = client
97 }
98
99 // colorToEnum maps user-provided color values to valid Adaptive Card TextBlock.color enum values.
100 func colorToEnum(color string) string {
101 switch strings.ToLower(color) {
102 case "red", "attention", "danger":
103 return "attention"
104 case "orange", "yellow", "warning", "warn":
105 return "warning"
106 case "green", "good", "success":
107 return "good"
108 case "blue", "accent":
109 return "accent"
110 case "dark":
111 return "dark"
112 case "light":
113 return "light"
114 case "default", "":
115 return "default"
116 default:
117 return "default"
118 }
119 }
120
121 // doSend sends the notification to Teams as an Adaptive Card payload.
122 func (s *Service) doSend(config *Config, message string) error {
123 if config.Host == "" {
124 return ErrMissingHost
125 }
126
127 if err := ValidateWebhookURL(config.Host); err != nil {
128 return err
129 }
130
131 lines := strings.Split(message, "\n")
132 body := make([]adaptiveBlock, 0, len(lines)+1)
133
134 if config.Title != "" {
135 //nolint:exhaustruct // Color, Wrap are optional and set conditionally
136 titleBlock := adaptiveBlock{
137 Type: "TextBlock",
138 Text: config.Title,
139 Weight: "Bolder",
140 Size: "Medium",
141 Color: colorToEnum(config.Color),
142 }
143
144 body = append(body, titleBlock)
145 }
146
147 for _, line := range lines {
148 if strings.TrimSpace(line) == "" {
149 continue
150 }
151
152 //nolint:exhaustruct // Color, Weight, Size are optional and default to zero values
153 body = append(body, adaptiveBlock{
154 Type: "TextBlock",
155 Text: line,
156 Wrap: true,
157 })
158 }
159
160 payload := adaptivePayload{
161 Type: "message",
162 Attachments: []adaptiveAttachment{
163 {
164 ContentType: "application/vnd.microsoft.card.adaptive",
165 ContentURL: nil,
166 Content: adaptiveCardContent{
167 Schema: "http://adaptivecards.io/schemas/adaptive-card.json",
168 Type: "AdaptiveCard",
169 Version: adaptiveCardVersion,
170 Body: body,
171 },
172 },
173 },
174 }
175
176 jsonBytes, err := json.Marshal(payload)
177 if err != nil {
178 return fmt.Errorf("marshaling payload to JSON: %w", err)
179 }
180
181 res, err := s.postJSON(config.Host, jsonBytes)
182 if err != nil {
183 return fmt.Errorf("%w: %s", ErrSendFailed, err.Error())
184 }
185
186 defer func() { _ = res.Body.Close() }()
187
188 if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
189 return fmt.Errorf("%w: %s", ErrSendFailedStatus, res.Status)
190 }
191
192 return nil
193 }
194
195 // postJSON performs an HTTP POST with a JSON payload.
196 func (s *Service) postJSON(serviceURL string, payload []byte) (*http.Response, error) {
197 ctx, cancel := context.WithTimeout(
198 context.Background(),
199 defaultHTTPTimeout,
200 )
201 defer cancel()
202
203 req, err := http.NewRequestWithContext(
204 ctx,
205 http.MethodPost,
206 serviceURL,
207 bytes.NewBuffer(payload),
208 )
209 if err != nil {
210 return nil, fmt.Errorf("creating request: %w", err)
211 }
212
213 req.Header.Set("Content-Type", "application/json")
214
215 res, err := s.httpClient.Do(req)
216 if err != nil {
217 return nil, fmt.Errorf("making HTTP POST request: %w", err)
218 }
219
220 return res, nil
221 }