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