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