Debian Codegraph @

pkg/services/chat/lark/lark_service.go

raw symbols SCIP
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 // SetHTTPClient sets a custom HTTP client for the service.
96 func (s *Service) SetHTTPClient(client types.HTTPClient) {
97 s.httpClient = client
98 }
99
100 // doSend sends the notification to Lark using the configured API URL.
101 func (s *Service) doSend(config *Config, message string, params *types.Params) error {
102 if config.Host == "" {
103 return ErrMissingHost
104 }
105
106 postURL := fmt.Sprintf(apiFormat, config.Host, config.Path)
107
108 payload, err := s.preparePayload(message, config, params)
109 if err != nil {
110 return err
111 }
112
113 return s.sendRequest(postURL, payload)
114 }
115
116 // genSign generates a signature for the request using the secret and timestamp.
117 func (s *Service) genSign(secret string, timestamp int64) (string, error) {
118 stringToSign := fmt.Sprintf("%v\n%s", timestamp, secret)
119
120 h := hmac.New(sha256.New, []byte(stringToSign))
121 if _, err := h.Write([]byte{}); err != nil {
122 return "", fmt.Errorf("%w: computing HMAC: %w", ErrInvalidSignature, err)
123 }
124
125 return base64.StdEncoding.EncodeToString(h.Sum(nil)), nil
126 }
127
128 // getRequestBody constructs the request body for the Lark API, supporting rich content via params.
129 func (s *Service) getRequestBody(
130 message, title, secret string,
131 params *types.Params,
132 ) *RequestBody {
133 body := &RequestBody{}
134
135 if secret != "" {
136 ts := time.Now().Unix()
137 body.Timestamp = strconv.FormatInt(ts, 10)
138
139 sign, err := s.genSign(secret, ts)
140 if err != nil {
141 sign = "" // Fallback to empty string on error
142 }
143
144 body.Sign = sign
145 }
146
147 if title == "" {
148 body.MsgType = MsgTypeText
149 body.Content.Text = message
150 } else {
151 body.MsgType = MsgTypePost
152 //nolint:exhaustruct_v5 // Item fields are populated inline; Link is optional
153 content := [][]Item{{{Tag: TagValueTextContent, Text: message}}}
154
155 if params != nil {
156 if link, ok := (*params)["link"]; ok && link != "" {
157 content = append(
158 content,
159
160 []Item{{Tag: TagValueLink, Text: "More Info", Link: link}},
161 )
162 }
163 }
164
165 //nolint:exhaustruct_v5 // Post fields are populated inline; Zh is optional
166 body.Content.Post = &Post{
167 En: &Message{
168 Title: title,
169 Content: content,
170 },
171 }
172 }
173
174 return body
175 }
176
177 // handleResponse processes the API response and checks for errors.
178 func (s *Service) handleResponse(resp *http.Response) error {
179 if resp.StatusCode != http.StatusOK {
180 return fmt.Errorf("%w: unexpected status %s", ErrSendFailed, resp.Status)
181 }
182
183 data, err := io.ReadAll(resp.Body)
184 if err != nil {
185 return fmt.Errorf("reading response body: %w", err)
186 }
187
188 var response Response
189 if err := json.Unmarshal(data, &response); err != nil {
190 return fmt.Errorf("unmarshaling response: %w", err)
191 }
192
193 if response.Code != 0 {
194 return fmt.Errorf(
195 "%w: server returned code %d: %s",
196 ErrSendFailed,
197 response.Code,
198 response.Msg,
199 )
200 }
201
202 s.Logf(
203 "Notification sent successfully to %s/%s",
204 s.Config.Host,
205 s.Config.Path,
206 )
207
208 return nil
209 }
210
211 // httpClientOrDefault returns the custom client or the package default.
212 func (s *Service) httpClientOrDefault() types.HTTPClient {
213 if s.httpClient != nil {
214 return s.httpClient
215 }
216
217 return httpClient
218 }
219
220 // preparePayload constructs and marshals the request payload for the Lark API.
221 func (s *Service) preparePayload(
222 message string,
223 config *Config,
224 params *types.Params,
225 ) ([]byte, error) {
226 body := s.getRequestBody(message, config.Title, config.Secret, params)
227
228 data, err := json.Marshal(body)
229 if err != nil {
230 return nil, fmt.Errorf("marshaling payload to JSON: %w", err)
231 }
232
233 s.Logf("Lark Request Body: %s", string(data))
234
235 return data, nil
236 }
237
238 // sendRequest performs the HTTP POST request to the Lark API and handles the response.
239 func (s *Service) sendRequest(postURL string, payload []byte) error {
240 req, err := http.NewRequestWithContext(
241 context.Background(),
242 http.MethodPost,
243 postURL,
244 bytes.NewReader(payload),
245 )
246 if err != nil {
247 return fmt.Errorf("creating HTTP request: %w", err)
248 }
249
250 req.Header.Set("Content-Type", "application/json")
251
252 client := s.httpClientOrDefault()
253
254 resp, err := client.Do(req)
255 if err != nil {
256 return fmt.Errorf("%w: making HTTP request: %w", ErrSendFailed, err)
257 }
258
259 defer func() { _ = resp.Body.Close() }()
260
261 return s.handleResponse(resp)
262 }