| 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 | // SetHTTPClient sets a custom HTTP client for the service. |
| 78 | func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 79 | s.httpClient = client |
| 80 | } |
| 81 | |
| 82 | // doSend sends the notification to WeCom using the configured API URL. |
| 83 | func (s *Service) doSend(config Config, message string, params *types.Params) error { |
| 84 | postURL := fmt.Sprintf(apiURL, config.Key) |
| 85 | |
| 86 | payload, err := s.preparePayload(message, config, params) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | |
| 91 | return s.sendRequest(postURL, payload) |
| 92 | } |
| 93 | |
| 94 | // getRequestBody constructs the request body for the WeCom API. |
| 95 | func (s *Service) getRequestBody( |
| 96 | message string, |
| 97 | config Config, |
| 98 | _ *types.Params, |
| 99 | ) *RequestBody { |
| 100 | body := &RequestBody{ |
| 101 | MsgType: "text", |
| 102 | Text: TextContent{ |
| 103 | Content: message, |
| 104 | }, |
| 105 | } |
| 106 | |
| 107 | // Handle mentions from config |
| 108 | if config.MentionedList != "" { |
| 109 | // Parse comma-separated list |
| 110 | body.Text.MentionedList = []string{config.MentionedList} |
| 111 | } |
| 112 | |
| 113 | if config.MentionedMobileList != "" { |
| 114 | body.Text.MentionedMobileList = []string{config.MentionedMobileList} |
| 115 | } |
| 116 | |
| 117 | return body |
| 118 | } |
| 119 | |
| 120 | // handleResponse processes the API response and checks for errors. |
| 121 | func (s *Service) handleResponse(resp *http.Response) error { |
| 122 | if resp.StatusCode != http.StatusOK { |
| 123 | return fmt.Errorf("%w: unexpected status %s", ErrSendFailed, resp.Status) |
| 124 | } |
| 125 | |
| 126 | data, err := io.ReadAll(resp.Body) |
| 127 | if err != nil { |
| 128 | return fmt.Errorf("reading response body: %w", err) |
| 129 | } |
| 130 | |
| 131 | var response Response |
| 132 | if err := json.Unmarshal(data, &response); err != nil { |
| 133 | return fmt.Errorf("unmarshaling response: %w", err) |
| 134 | } |
| 135 | |
| 136 | if response.ErrCode != 0 { |
| 137 | return fmt.Errorf( |
| 138 | "%w: server returned error code %d: %s", |
| 139 | ErrSendFailed, |
| 140 | response.ErrCode, |
| 141 | response.ErrMsg, |
| 142 | ) |
| 143 | } |
| 144 | |
| 145 | s.Logf("Notification sent successfully to WeCom webhook") |
| 146 | |
| 147 | return nil |
| 148 | } |
| 149 | |
| 150 | // httpClientOrDefault returns the custom client or the package default. |
| 151 | func (s *Service) httpClientOrDefault() types.HTTPClient { |
| 152 | if s.httpClient != nil { |
| 153 | return s.httpClient |
| 154 | } |
| 155 | |
| 156 | return httpClient |
| 157 | } |
| 158 | |
| 159 | // preparePayload constructs and marshals the request payload for the WeCom API. |
| 160 | func (s *Service) preparePayload( |
| 161 | message string, |
| 162 | config Config, |
| 163 | params *types.Params, |
| 164 | ) ([]byte, error) { |
| 165 | body := s.getRequestBody(message, config, params) |
| 166 | |
| 167 | data, err := json.Marshal(body) |
| 168 | if err != nil { |
| 169 | return nil, fmt.Errorf("marshaling payload to JSON: %w", err) |
| 170 | } |
| 171 | |
| 172 | s.Logf("WeCom Request Body: %s", string(data)) |
| 173 | |
| 174 | return data, nil |
| 175 | } |
| 176 | |
| 177 | // sendRequest performs the HTTP POST request to the WeCom API and handles the response. |
| 178 | func (s *Service) sendRequest(postURL string, payload []byte) error { |
| 179 | req, err := http.NewRequestWithContext( |
| 180 | context.Background(), |
| 181 | http.MethodPost, |
| 182 | postURL, |
| 183 | bytes.NewReader(payload), |
| 184 | ) |
| 185 | if err != nil { |
| 186 | return fmt.Errorf("creating HTTP request: %w", err) |
| 187 | } |
| 188 | |
| 189 | req.Header.Set("Content-Type", "application/json") |
| 190 | |
| 191 | client := s.httpClientOrDefault() |
| 192 | |
| 193 | resp, err := client.Do(req) |
| 194 | if err != nil { |
| 195 | return fmt.Errorf("%w: making HTTP request: %w", ErrSendFailed, err) |
| 196 | } |
| 197 | |
| 198 | defer func() { _ = resp.Body.Close() }() |
| 199 | |
| 200 | return s.handleResponse(resp) |
| 201 | } |