Debian Codegraph @

pkg/services/chat/lark/lark_service.go

raw
1 package lark
2
3 import (
4 "bytes"
5 "context"
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "net/url"
15 "strconv"
16 "time"
17
18 "github.com/nicholas-fedor/shoutrrr/pkg/format"
19 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
20 "github.com/nicholas-fedor/shoutrrr/pkg/types"
21 )
22
23 // Service sends notifications to Lark.
24 type Service struct {
25 standard.Standard
26
27 Config *Config
28 pkr format.PropKeyResolver
29 httpClient types.HTTPClient
30 }
31
32 // Constants for the Lark service configuration and limits.
33 const (
34 apiFormat = "https://%s/open-apis/bot/v2/hook/%s" // API endpoint format
35 maxLength = 4096 // Maximum message length in bytes
36 defaultTime = 30 * time.Second // Default HTTP client timeout
37 )
38
39 const (
40 larkHost = "open.larksuite.com"
41 feishuHost = "open.feishu.cn"
42 )
43
44 // Error variables for the Lark service.
45 var (
46 ErrInvalidHost = errors.New("invalid host, use 'open.larksuite.com' or 'open.feishu.cn'")
47 ErrNoPath = errors.New(
48 "no path, path like 'xxx' in 'https://open.larksuite.com/open-apis/bot/v2/hook/xxx'",
49 )
50 ErrLargeMessage = errors.New("message exceeds the max length")
51 ErrMissingHost = errors.New("host is required but not specified in the configuration")
52 ErrSendFailed = errors.New("failed to send notification to Lark")
53 ErrInvalidSignature = errors.New("failed to generate valid signature")
54 )
55
56 // httpClient is the fallback default client (used only when no custom client is set).
57 var httpClient = &http.Client{Timeout: defaultTime}
58
59 // GetID returns the service identifier.
60 func (s *Service) GetID() string {
61 return Scheme
62 }
63
64 // Initialize configures the service with a URL and logger.
65 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
66 s.SetLogger(logger)
67 s.Config = &Config{}
68 s.pkr = format.NewPropKeyResolver(s.Config)
69
70 return s.Config.SetURL(serviceURL)
71 }
72
73 // Send delivers a notification message to Lark.
74 func (s *Service) Send(message string, params *types.Params) error {
75 if len(message) > maxLength {
76 return ErrLargeMessage
77 }
78
79 config := *s.Config
80 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
81 return fmt.Errorf("updating params: %w", err)
82 }
83
84 if config.Host != larkHost && config.Host != feishuHost {
85 return ErrInvalidHost
86 }
87
88 if config.Path == "" {
89 return ErrNoPath
90 }
91
92 return s.doSend(&config, message, params)
93 }
94
95 // ServiceTimeout returns the HTTP timeout used for a Lark send.
96 func (*Service) ServiceTimeout(*types.Params) time.Duration {
97 return defaultTime
98 }
99
100 // SetHTTPClient sets a custom HTTP client for the service.
101 func (s *Service) SetHTTPClient(client types.HTTPClient) {
102 s.httpClient = client
103 }
104
105 // doSend sends the notification to Lark using the configured API URL.
106 func (s *Service) doSend(config *Config, message string, params *types.Params) error {
107 if config.Host == "" {
108 return ErrMissingHost
109 }
110
111 postURL := fmt.Sprintf(apiFormat, config.Host, config.Path)
112
113 payload, err := s.preparePayload(message, config, params)
114 if err != nil {
115 return err
116 }
117
118 return s.sendRequest(postURL, payload)
119 }
120
121 // genSign generates a signature for the request using the secret and timestamp.
122 func (s *Service) genSign(secret string, timestamp int64) (string, error) {
123 stringToSign := fmt.Sprintf("%v\n%s", timestamp, secret)
124
125 h := hmac.New(sha256.New, []byte(stringToSign))
126 if _, err := h.Write([]byte{}); err != nil {
127 return "", fmt.Errorf("%w: computing HMAC: %w", ErrInvalidSignature, err)
128 }
129
130 return base64.StdEncoding.EncodeToString(h.Sum(nil)), nil
131 }
132
133 // getRequestBody constructs the request body for the Lark API, supporting rich content via params.
134 func (s *Service) getRequestBody(
135 message, title, secret string,
136 params *types.Params,
137 ) *RequestBody {
138 body := &RequestBody{}
139
140 if secret != "" {
141 ts := time.Now().Unix()
142 body.Timestamp = strconv.FormatInt(ts, 10)
143
144 sign, err := s.genSign(secret, ts)
145 if err != nil {
146 sign = "" // Fallback to empty string on error
147 }
148
149 body.Sign = sign
150 }
151
152 if title == "" {
153 body.MsgType = MsgTypeText
154 body.Content.Text = message
155 } else {
156 body.MsgType = MsgTypePost
157 //nolint:exhaustruct_v5 // Item fields are populated inline; Link is optional
158 content := [][]Item{{{Tag: TagValueTextContent, Text: message}}}
159
160 if params != nil {
161 if link, ok := (*params)["link"]; ok && link != "" {
162 content = append(
163 content,
164
165 []Item{{Tag: TagValueLink, Text: "More Info", Link: link}},
166 )
167 }
168 }
169
170 //nolint:exhaustruct_v5 // Post fields are populated inline; Zh is optional
171 body.Content.Post = &Post{
172 En: &Message{
173 Title: title,
174 Content: content,
175 },
176 }
177 }
178
179 return body
180 }
181
182 // handleResponse processes the API response and checks for errors.
183 func (s *Service) handleResponse(resp *http.Response) error {
184 if resp.StatusCode != http.StatusOK {
185 return fmt.Errorf("%w: unexpected status %s", ErrSendFailed, resp.Status)
186 }
187
188 data, err := io.ReadAll(resp.Body)
189 if err != nil {
190 return fmt.Errorf("reading response body: %w", err)
191 }
192
193 var response Response
194 if err := json.Unmarshal(data, &response); err != nil {
195 return fmt.Errorf("unmarshaling response: %w", err)
196 }
197
198 if response.Code != 0 {
199 return fmt.Errorf(
200 "%w: server returned code %d: %s",
201 ErrSendFailed,
202 response.Code,
203 response.Msg,
204 )
205 }
206
207 s.Logf(
208 "Notification sent successfully to %s/%s",
209 s.Config.Host,
210 s.Config.Path,
211 )
212
213 return nil
214 }
215
216 // httpClientOrDefault returns the custom client or the package default.
217 func (s *Service) httpClientOrDefault() types.HTTPClient {
218 if s.httpClient != nil {
219 return s.httpClient
220 }
221
222 return httpClient
223 }
224
225 // preparePayload constructs and marshals the request payload for the Lark API.
226 func (s *Service) preparePayload(
227 message string,
228 config *Config,
229 params *types.Params,
230 ) ([]byte, error) {
231 body := s.getRequestBody(message, config.Title, config.Secret, params)
232
233 data, err := json.Marshal(body)
234 if err != nil {
235 return nil, fmt.Errorf("marshaling payload to JSON: %w", err)
236 }
237
238 s.Logf("Lark Request Body: %s", string(data))
239
240 return data, nil
241 }
242
243 // sendRequest performs the HTTP POST request to the Lark API and handles the response.
244 func (s *Service) sendRequest(postURL string, payload []byte) error {
245 req, err := http.NewRequestWithContext(
246 context.Background(),
247 http.MethodPost,
248 postURL,
249 bytes.NewReader(payload),
250 )
251 if err != nil {
252 return fmt.Errorf("creating HTTP request: %w", err)
253 }
254
255 req.Header.Set("Content-Type", "application/json")
256
257 client := s.httpClientOrDefault()
258
259 resp, err := client.Do(req)
260 if err != nil {
261 return fmt.Errorf("%w: making HTTP request: %w", ErrSendFailed, err)
262 }
263
264 defer func() { _ = resp.Body.Close() }()
265
266 return s.handleResponse(resp)
267 }