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