Files

178 lines
5.3 KiB
Go

// ProactiveClient pushes messages to WeCom (企业微信) users without a prior
// incoming message, via the self-built application message API
// (/cgi-bin/message/send). Unlike WebhookAdapter — whose SendReply answers an
// incoming message — this client is driven by the training scheduler to
// deliver scheduled reminders (outbox pattern in tr_notifications).
//
// Reference: https://developer.work.weixin.qq.com/document/path/90236
package wecom
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"unicode/utf8"
)
// maxMarkdownBytes is the WeCom markdown content limit; longer content is
// rejected by the API with errcode 40058-style errors.
const maxMarkdownBytes = 2048
// ProactiveClient sends application messages to WeCom users by userid.
// Credentials mirror the webhook-mode IM channel (corp_id / agent_secret /
// corp_agent_id), so operators maintain one set of credentials per tenant.
type ProactiveClient struct {
corpID string
agentSecret string
corpAgentID int
apiBaseURL string
// Token cache — WeCom tokens expire in 7200 seconds (2 hours); cached
// with a safety margin, same as WebhookAdapter.
tokenMu sync.Mutex
tokenCache string
tokenExpAt time.Time
}
// NewProactiveClient creates a proactive push client. apiBaseURL may be empty
// for the public cloud endpoint; a custom value must pass the same SSRF
// checks as the webhook adapter (private deployments add the host to
// SSRF_WHITELIST).
func NewProactiveClient(corpID, agentSecret string, corpAgentID int, apiBaseURL string) (*ProactiveClient, error) {
if corpID == "" || agentSecret == "" {
return nil, fmt.Errorf("wecom proactive client requires corp_id and agent_secret")
}
if apiBaseURL == "" {
apiBaseURL = defaultAPIBaseURL
}
apiBaseURL = strings.TrimRight(apiBaseURL, "/")
if err := validateEndpointURL(apiBaseURL, defaultAPIBaseURL, "https"); err != nil {
return nil, fmt.Errorf("invalid api_base_url: %w", err)
}
return &ProactiveClient{
corpID: corpID,
agentSecret: agentSecret,
corpAgentID: corpAgentID,
apiBaseURL: apiBaseURL,
}, nil
}
// SendMarkdown sends one markdown message to the listed WeCom userids in a
// single message/send call (touser joined with "|"). An empty list is a no-op.
func (c *ProactiveClient) SendMarkdown(ctx context.Context, userIDs []string, content string) error {
if len(userIDs) == 0 {
return nil
}
accessToken, err := c.getAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
content = truncateUTF8Bytes(content, maxMarkdownBytes)
payload := map[string]interface{}{
"touser": strings.Join(userIDs, "|"),
"msgtype": "markdown",
"agentid": c.corpAgentID,
"markdown": map[string]string{"content": content},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal payload: %w", err)
}
sendURL := fmt.Sprintf("%s/cgi-bin/message/send?access_token=%s", c.apiBaseURL, accessToken)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, sendURL, bytes.NewReader(payloadBytes))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("send message: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode response: %w", err)
}
if result.ErrCode != 0 {
return fmt.Errorf("wecom api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
return nil
}
// getAccessToken retrieves the WeCom access token with caching.
func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) {
c.tokenMu.Lock()
defer c.tokenMu.Unlock()
if c.tokenCache != "" && time.Now().Before(c.tokenExpAt) {
return c.tokenCache, nil
}
tokenURL := fmt.Sprintf("%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
c.apiBaseURL, c.corpID, c.agentSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request access token: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"` // seconds
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if result.ErrCode != 0 {
return "", fmt.Errorf("get token error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
c.tokenCache = result.AccessToken
// Cache with 5-minute safety margin
ttl := time.Duration(result.ExpiresIn) * time.Second
if ttl > 5*time.Minute {
ttl -= 5 * time.Minute
}
c.tokenExpAt = time.Now().Add(ttl)
return c.tokenCache, nil
}
// truncateUTF8Bytes clips s to at most limit bytes without splitting a rune.
func truncateUTF8Bytes(s string, limit int) string {
if len(s) <= limit {
return s
}
var b strings.Builder
n := 0
for _, r := range s {
size := utf8.RuneLen(r)
if size <= 0 || n+size > limit {
break
}
b.WriteString(string(r))
n += size
}
return b.String()
}