Debian Codegraph @

pkg/services/chat/teams/teams_service.go

raw symbols SCIP
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 // SetHTTPClient sets the HTTP client for testing purposes.
88 func (s *Service) SetHTTPClient(client types.HTTPClient) {
89 if client == nil {
90 s.httpClient = &defaultHTTPClient{
91 client: &http.Client{Timeout: defaultHTTPTimeout},
92 }
93
94 return
95 }
96
97 switch c := client.(type) {
98 case *http.Client:
99 s.httpClient = &defaultHTTPClient{client: c}
100 case HTTPClient:
101 s.httpClient = c
102 }
103 }
104
105 // colorToEnum maps user-provided color values to valid Adaptive Card TextBlock.color enum values.
106 func colorToEnum(color string) string {
107 switch strings.ToLower(color) {
108 case "red", "attention", "danger":
109 return "attention"
110 case "orange", "yellow", "warning", "warn":
111 return "warning"
112 case "green", "good", "success":
113 return "good"
114 case "blue", "accent":
115 return "accent"
116 case "dark":
117 return "dark"
118 case "light":
119 return "light"
120 case "default", "":
121 return "default"
122 default:
123 return "default"
124 }
125 }
126
127 // doSend sends the notification to Teams as an Adaptive Card payload.
128 func (s *Service) doSend(config *Config, message string) error {
129 if config.Host == "" {
130 return ErrMissingHost
131 }
132
133 if err := ValidateWebhookURL(config.Host); err != nil {
134 return err
135 }
136
137 lines := strings.Split(message, "\n")
138 body := make([]adaptiveBlock, 0, len(lines)+1)
139
140 if config.Title != "" {
141 //nolint:exhaustruct_v5 // Color, Wrap are optional and set conditionally
142 titleBlock := adaptiveBlock{
143 Type: "TextBlock",
144 Text: config.Title,
145 Weight: "Bolder",
146 Size: "Medium",
147 Color: colorToEnum(config.Color),
148 }
149
150 body = append(body, titleBlock)
151 }
152
153 for _, line := range lines {
154 if strings.TrimSpace(line) == "" {
155 continue
156 }
157
158 //nolint:exhaustruct_v5 // Color, Weight, Size are optional and default to zero values
159 body = append(body, adaptiveBlock{
160 Type: "TextBlock",
161 Text: line,
162 Wrap: true,
163 })
164 }
165
166 payload := adaptivePayload{
167 Type: "message",
168 Attachments: []adaptiveAttachment{
169 {
170 ContentType: "application/vnd.microsoft.card.adaptive",
171 ContentURL: nil,
172 Content: adaptiveCardContent{
173 Schema: "http://adaptivecards.io/schemas/adaptive-card.json",
174 Type: "AdaptiveCard",
175 Version: adaptiveCardVersion,
176 Body: body,
177 },
178 },
179 },
180 }
181
182 jsonBytes, err := json.Marshal(payload)
183 if err != nil {
184 return fmt.Errorf("marshaling payload to JSON: %w", err)
185 }
186
187 res, err := s.postJSON(config.Host, jsonBytes)
188 if err != nil {
189 return fmt.Errorf("%w: %s", ErrSendFailed, err.Error())
190 }
191
192 defer func() { _ = res.Body.Close() }()
193
194 if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
195 return fmt.Errorf("%w: %s", ErrSendFailedStatus, res.Status)
196 }
197
198 return nil
199 }
200
201 // postJSON performs an HTTP POST with a JSON payload.
202 func (s *Service) postJSON(serviceURL string, payload []byte) (*http.Response, error) {
203 ctx, cancel := context.WithTimeout(
204 context.Background(),
205 defaultHTTPTimeout,
206 )
207 defer cancel()
208
209 req, err := http.NewRequestWithContext(
210 ctx,
211 http.MethodPost,
212 serviceURL,
213 bytes.NewBuffer(payload),
214 )
215 if err != nil {
216 return nil, fmt.Errorf("creating request: %w", err)
217 }
218
219 req.Header.Set("Content-Type", "application/json")
220
221 res, err := s.httpClient.Do(req)
222 if err != nil {
223 return nil, fmt.Errorf("making HTTP POST request: %w", err)
224 }
225
226 return res, nil
227 }