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