package dingtalk import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "sync" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" ) const ( groupSendURL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" // maxGroupPayloadBytes caps the serialized JSON body sent to the group // message endpoint. maxGroupPayloadBytes = 64 << 10 // 64 KiB // questionRuneLimit caps the displayed question in the markdown body. questionRuneLimit = 500 // answerRuneLimit caps the displayed answer in the markdown body. answerRuneLimit = 1000 ) // SupportGroupSender sends DingTalk group Markdown notifications via the // official groupMessages/send OpenAPI. It is safe by construction: all // config fields are trimmed, nil client installs hardened defaults, and // all error paths are sanitised. type SupportGroupSender struct { clientID string clientSecret string openConversation string tokenURL string groupURL string apiClient *http.Client mu sync.Mutex token string tokenTill time.Time } var _ coverage.Notifier = (*SupportGroupSender)(nil) // NewSupportGroupSender creates a SupportGroupSender. All three config values // are required after trimming. A nil http.Client installs a hardened default // (no redirects, Proxy=nil, 15s timeout). func NewSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client) (*SupportGroupSender, error) { return newSupportGroupSender(clientID, clientSecret, openConversationID, client, oauthTokenURL, groupSendURL, false) } // newSupportGroupSenderForTest is used by tests to inject httptest URLs. func newSupportGroupSenderForTest(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string) (*SupportGroupSender, error) { return newSupportGroupSender(clientID, clientSecret, openConversationID, client, tokenURL, groupURL, true) } func newSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string, allowTest bool) (*SupportGroupSender, error) { clientID = strings.TrimSpace(clientID) clientSecret = strings.TrimSpace(clientSecret) openConversationID = strings.TrimSpace(openConversationID) if clientID == "" { return nil, errors.New("dingtalk group sender: clientID is required") } if clientSecret == "" { return nil, errors.New("dingtalk group sender: clientSecret is required") } if openConversationID == "" { return nil, errors.New("dingtalk group sender: openConversationId is required") } base := &http.Client{Timeout: 15 * time.Second} if client != nil { copyClient := *client base = ©Client if base.Timeout <= 0 { base.Timeout = 15 * time.Second } } apiClient := *base apiClient.CheckRedirect = func(*http.Request, []*http.Request) error { return errors.New("dingtalk API redirect refused") } if !allowTest { transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil apiClient.Transport = transport } return &SupportGroupSender{ clientID: clientID, clientSecret: clientSecret, openConversation: openConversationID, tokenURL: tokenURL, groupURL: groupURL, apiClient: &apiClient, }, nil } // Send sends a support-case notification to the DingTalk group. func (s *SupportGroupSender) Send(ctx context.Context, notif coverage.SupportNotification) error { if notif.CaseID == "" { return errors.New("dingtalk group sender: CaseID is required") } // Build the markdown notification body title, text := s.renderMarkdown(notif) msgParam := map[string]string{ "title": title, "text": text, } msgParamJSON, err := json.Marshal(msgParam) if err != nil { return errors.New("dingtalk group sender: encode msgParam failed") } body := map[string]any{ "msgKey": "sampleMarkdown", "msgParam": string(msgParamJSON), "openConversationId": s.openConversation, "robotCode": s.clientID, } bodyJSON, err := json.Marshal(body) if err != nil { return errors.New("dingtalk group sender: encode request body failed") } if len(bodyJSON) > maxGroupPayloadBytes { return fmt.Errorf("dingtalk group sender: payload exceeds %d bytes", maxGroupPayloadBytes) } // Get access token token, err := s.accessToken(ctx) if err != nil { return err } // POST to groupMessages/send respPayload, err := s.doJSON(ctx, http.MethodPost, s.groupURL, body, token) if err != nil { return err } // Check business response var bizResp struct { ProcessQueryKey string `json:"processQueryKey"` ErrCode int `json:"errcode"` } if err := json.Unmarshal(respPayload, &bizResp); err != nil { return errors.New("dingtalk group sender: invalid API response") } if bizResp.ErrCode != 0 { return errors.New("dingtalk group sender: API returned business error") } if strings.TrimSpace(bizResp.ProcessQueryKey) == "" { return errors.New("dingtalk group sender: incomplete API response") } return nil } // renderMarkdown produces a title and text for the group notification. func (s *SupportGroupSender) renderMarkdown(notif coverage.SupportNotification) (title, text string) { title = fmt.Sprintf("📋 知识缺失通知 #%s", notif.CaseID) convType := "群聊" if notif.ConversationType == core.ConversationDirect { convType = "单聊" } question := truncateRunes(notif.Question, questionRuneLimit) answer := truncateRunes(notif.Answer, answerRuneLimit) var b strings.Builder b.WriteString("## 📋 知识缺失通知\n\n") b.WriteString(fmt.Sprintf("**Case ID:** %s\n\n", notif.CaseID)) b.WriteString(fmt.Sprintf("**提问人:** %s\n\n", notif.SenderName)) b.WriteString(fmt.Sprintf("**渠道/会话类型:** %s / %s\n\n", notif.Channel, convType)) b.WriteString(fmt.Sprintf("**问题摘要:**\n> %s\n\n", question)) b.WriteString(fmt.Sprintf("**回答摘要:**\n> %s\n\n", answer)) b.WriteString(fmt.Sprintf("**相关结果数:** %d\n\n", notif.ReferenceCount)) b.WriteString(fmt.Sprintf("**最高Score:** %.4f\n", notif.TopScore)) return title, b.String() } func truncateRunes(s string, limit int) string { if limit <= 0 { return s } runes := []rune(s) if len(runes) <= limit { return s } return string(runes[:limit]) + "..." } func (s *SupportGroupSender) accessToken(ctx context.Context) (string, error) { s.mu.Lock() defer s.mu.Unlock() if s.token != "" && time.Now().Before(s.tokenTill) { return s.token, nil } payload, err := s.doJSON(ctx, http.MethodPost, s.tokenURL, map[string]string{ "appKey": s.clientID, "appSecret": s.clientSecret, }, "") if err != nil { return "", err } var response struct { AccessToken string `json:"accessToken"` ExpireIn int64 `json:"expireIn"` } if json.Unmarshal(payload, &response) != nil || strings.TrimSpace(response.AccessToken) == "" { return "", errors.New("dingtalk group sender: invalid OAuth response") } ttl := time.Duration(response.ExpireIn) * time.Second refreshAfter := ttl - 5*time.Minute if refreshAfter <= 0 { refreshAfter = ttl / 2 } if refreshAfter <= 0 { refreshAfter = time.Minute } s.token = response.AccessToken s.tokenTill = time.Now().Add(refreshAfter) return s.token, nil } func (s *SupportGroupSender) doJSON(ctx context.Context, method, endpoint string, value any, token string) ([]byte, error) { body, err := json.Marshal(value) if err != nil { return nil, errors.New("dingtalk group sender: encode API request failed") } req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body)) if err != nil { return nil, errors.New("dingtalk group sender: create API request failed") } req.Header.Set("Content-Type", "application/json") if token != "" { req.Header.Set("x-acs-dingtalk-access-token", token) } resp, err := s.apiClient.Do(req) if err != nil { if ctx.Err() != nil { return nil, ctx.Err() } // Propagate redirect errors so callers can detect them. if strings.Contains(err.Error(), "redirect") { return nil, err } return nil, errors.New("dingtalk group sender: API request failed") } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { // Discard body without reading it — sanitised error _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxAPIResponseBytes)) return nil, fmt.Errorf("dingtalk group sender: API HTTP %d", resp.StatusCode) } return readBoundedAPIResponse(resp) }