Debian Codegraph @

pkg/services/chat/wecom/wecom_service.go

raw
1 package wecom
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "time"
13
14 "github.com/nicholas-fedor/shoutrrr/pkg/format"
15 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
16 "github.com/nicholas-fedor/shoutrrr/pkg/types"
17 )
18
19 // Service sends notifications to WeCom.
20 type Service struct {
21 standard.Standard
22
23 Config *Config
24 pkr format.PropKeyResolver
25 httpClient types.HTTPClient
26 }
27
28 // Constants for the WeCom service configuration and limits.
29 const (
30 apiURL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s"
31 maxLength = 4096 // Maximum message length in bytes
32 defaultTime = 30 * time.Second
33 )
34
35 // Error variables for the WeCom service.
36 var (
37 ErrLargeMessage = fmt.Errorf("message exceeds the max length of %d bytes", maxLength)
38 ErrSendFailed = errors.New("failed to send notification to WeCom")
39 ErrKeyRequired = errors.New("webhook key is required")
40 )
41
42 // httpClient is the fallback default client (used only when no custom client is set).
43 var httpClient = &http.Client{Timeout: defaultTime}
44
45 // GetID returns the service identifier.
46 func (s *Service) GetID() string {
47 return Scheme
48 }
49
50 // Initialize configures the service with a URL and logger.
51 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
52 s.SetLogger(logger)
53 s.Config = &Config{}
54 s.pkr = format.NewPropKeyResolver(s.Config)
55
56 return s.Config.SetURL(serviceURL)
57 }
58
59 // Send delivers a notification message to WeCom.
60 func (s *Service) Send(message string, params *types.Params) error {
61 if len(message) > maxLength {
62 return ErrLargeMessage
63 }
64
65 config := *s.Config
66 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
67 return fmt.Errorf("updating params: %w", err)
68 }
69
70 if config.Key == "" {
71 return ErrKeyRequired
72 }
73
74 return s.doSend(config, message, params)
75 }
76
77 // ServiceTimeout returns the HTTP timeout used for a WeCom send.
78 func (*Service) ServiceTimeout(*types.Params) time.Duration {
79 return defaultTime
80 }
81
82 // SetHTTPClient sets a custom HTTP client for the service.
83 func (s *Service) SetHTTPClient(client types.HTTPClient) {
84 s.httpClient = client
85 }
86
87 // doSend sends the notification to WeCom using the configured API URL.
88 func (s *Service) doSend(config Config, message string, params *types.Params) error {
89 postURL := fmt.Sprintf(apiURL, config.Key)
90
91 payload, err := s.preparePayload(message, config, params)
92 if err != nil {
93 return err
94 }
95
96 return s.sendRequest(postURL, payload)
97 }
98
99 // getRequestBody constructs the request body for the WeCom API.
100 func (s *Service) getRequestBody(
101 message string,
102 config Config,
103 _ *types.Params,
104 ) *RequestBody {
105 body := &RequestBody{
106 MsgType: "text",
107 Text: TextContent{
108 Content: message,
109 },
110 }
111
112 // Handle mentions from config
113 if config.MentionedList != "" {
114 // Parse comma-separated list
115 body.Text.MentionedList = []string{config.MentionedList}
116 }
117
118 if config.MentionedMobileList != "" {
119 body.Text.MentionedMobileList = []string{config.MentionedMobileList}
120 }
121
122 return body
123 }
124
125 // handleResponse processes the API response and checks for errors.
126 func (s *Service) handleResponse(resp *http.Response) error {
127 if resp.StatusCode != http.StatusOK {
128 return fmt.Errorf("%w: unexpected status %s", ErrSendFailed, resp.Status)
129 }
130
131 data, err := io.ReadAll(resp.Body)
132 if err != nil {
133 return fmt.Errorf("reading response body: %w", err)
134 }
135
136 var response Response
137 if err := json.Unmarshal(data, &response); err != nil {
138 return fmt.Errorf("unmarshaling response: %w", err)
139 }
140
141 if response.ErrCode != 0 {
142 return fmt.Errorf(
143 "%w: server returned error code %d: %s",
144 ErrSendFailed,
145 response.ErrCode,
146 response.ErrMsg,
147 )
148 }
149
150 s.Logf("Notification sent successfully to WeCom webhook")
151
152 return nil
153 }
154
155 // httpClientOrDefault returns the custom client or the package default.
156 func (s *Service) httpClientOrDefault() types.HTTPClient {
157 if s.httpClient != nil {
158 return s.httpClient
159 }
160
161 return httpClient
162 }
163
164 // preparePayload constructs and marshals the request payload for the WeCom API.
165 func (s *Service) preparePayload(
166 message string,
167 config Config,
168 params *types.Params,
169 ) ([]byte, error) {
170 body := s.getRequestBody(message, config, params)
171
172 data, err := json.Marshal(body)
173 if err != nil {
174 return nil, fmt.Errorf("marshaling payload to JSON: %w", err)
175 }
176
177 s.Logf("WeCom Request Body: %s", string(data))
178
179 return data, nil
180 }
181
182 // sendRequest performs the HTTP POST request to the WeCom API and handles the response.
183 func (s *Service) sendRequest(postURL string, payload []byte) error {
184 req, err := http.NewRequestWithContext(
185 context.Background(),
186 http.MethodPost,
187 postURL,
188 bytes.NewReader(payload),
189 )
190 if err != nil {
191 return fmt.Errorf("creating HTTP request: %w", err)
192 }
193
194 req.Header.Set("Content-Type", "application/json")
195
196 client := s.httpClientOrDefault()
197
198 resp, err := client.Do(req)
199 if err != nil {
200 return fmt.Errorf("%w: making HTTP request: %w", ErrSendFailed, err)
201 }
202
203 defer func() { _ = resp.Body.Close() }()
204
205 return s.handleResponse(resp)
206 }