406 lines
12 KiB
Go
406 lines
12 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
|
)
|
|
|
|
const (
|
|
cardCreateURL = "https://api.dingtalk.com/v1.0/card/instances/createAndDeliver"
|
|
cardStreamingURL = "https://api.dingtalk.com/v1.0/card/streaming"
|
|
cardDebugPrivateKey = "_CARD_DEBUG_TOOL_ENTRY"
|
|
)
|
|
|
|
// CardRequest is the input for sending a final AI card.
|
|
type CardRequest struct {
|
|
ConversationType core.ConversationType
|
|
ExternalUserID string
|
|
ExternalChatID string
|
|
Content string
|
|
}
|
|
|
|
// CardSender sends DingTalk AI cards via the OpenAPI.
|
|
type CardSender struct {
|
|
clientID string
|
|
clientSecret string
|
|
cardTemplateID string
|
|
tokenURL string
|
|
createURL string
|
|
streamURL string
|
|
apiClient *http.Client
|
|
allowTestURL bool
|
|
debugUserID string
|
|
|
|
mu sync.Mutex
|
|
token string
|
|
tokenTill time.Time
|
|
}
|
|
|
|
// CardSenderOption configures optional CardSender behavior.
|
|
type CardSenderOption func(*CardSender)
|
|
|
|
// WithCardDebugUserID enables DingTalk's official card debug entry only for
|
|
// the matching user through per-user privateData. A blank value keeps it off.
|
|
func WithCardDebugUserID(userID string) CardSenderOption {
|
|
return func(sender *CardSender) {
|
|
sender.debugUserID = strings.TrimSpace(userID)
|
|
}
|
|
}
|
|
|
|
// NewCardSender creates a CardSender. All three config values are required
|
|
// after trimming whitespace. A nil http.Client installs a hardened default
|
|
// (no redirects, Proxy=nil, 15s timeout).
|
|
func NewCardSender(clientID, clientSecret, cardTemplateID string, client *http.Client, options ...CardSenderOption) (*CardSender, error) {
|
|
return newCardSender(clientID, clientSecret, cardTemplateID, client, oauthTokenURL, cardCreateURL, cardStreamingURL, false, options...)
|
|
}
|
|
|
|
// newCardSenderForTest is used by tests to inject httptest URLs.
|
|
func newCardSenderForTest(clientID, clientSecret, cardTemplateID string, client *http.Client, tokenURL, createURL string, options ...CardSenderOption) (*CardSender, error) {
|
|
streamURL := strings.TrimSuffix(createURL, "/create") + "/stream"
|
|
return newCardSender(clientID, clientSecret, cardTemplateID, client, tokenURL, createURL, streamURL, true, options...)
|
|
}
|
|
|
|
func newCardSender(clientID, clientSecret, cardTemplateID string, client *http.Client, tokenURL, createURL, streamURL string, allowTest bool, options ...CardSenderOption) (*CardSender, error) {
|
|
clientID = strings.TrimSpace(clientID)
|
|
clientSecret = strings.TrimSpace(clientSecret)
|
|
cardTemplateID = strings.TrimSpace(cardTemplateID)
|
|
if clientID == "" {
|
|
return nil, errors.New("dingtalk card sender: clientID is required")
|
|
}
|
|
if clientSecret == "" {
|
|
return nil, errors.New("dingtalk card sender: clientSecret is required")
|
|
}
|
|
if cardTemplateID == "" {
|
|
return nil, errors.New("dingtalk card sender: cardTemplateID 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
|
|
}
|
|
|
|
sender := &CardSender{
|
|
clientID: clientID,
|
|
clientSecret: clientSecret,
|
|
cardTemplateID: cardTemplateID,
|
|
tokenURL: tokenURL,
|
|
createURL: createURL,
|
|
streamURL: streamURL,
|
|
apiClient: &apiClient,
|
|
allowTestURL: allowTest,
|
|
}
|
|
for _, option := range options {
|
|
if option != nil {
|
|
option(sender)
|
|
}
|
|
}
|
|
return sender, nil
|
|
}
|
|
|
|
// SendFinalCard sends the AI card to DingTalk and returns the generated outTrackID.
|
|
// It is a thin wrapper: StartCard → UpdateCard(finalize=true).
|
|
func (s *CardSender) SendFinalCard(ctx context.Context, req CardRequest) (string, error) {
|
|
outTrackID, err := s.StartCard(ctx, req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := s.UpdateCard(ctx, outTrackID, req.Content, true, false); err != nil {
|
|
return "", err
|
|
}
|
|
return outTrackID, nil
|
|
}
|
|
|
|
// StartCard creates a card instance via createAndDeliver and returns the
|
|
// generated outTrackID. It does NOT call the streaming finalize endpoint;
|
|
// callers must use UpdateCard to stream content.
|
|
func (s *CardSender) StartCard(ctx context.Context, req CardRequest) (string, error) {
|
|
// Validate conversation type before any API call
|
|
if req.ConversationType != core.ConversationDirect && req.ConversationType != core.ConversationGroup {
|
|
return "", fmt.Errorf("dingtalk card: unsupported conversation type %q", req.ConversationType)
|
|
}
|
|
|
|
// Validate content
|
|
req.Content = strings.TrimSpace(req.Content)
|
|
if req.Content == "" {
|
|
return "", errors.New("dingtalk card: content is required")
|
|
}
|
|
if len(req.Content) > 64*1024 {
|
|
return "", errors.New("dingtalk card: content exceeds 64 KiB")
|
|
}
|
|
|
|
// Validate identity fields. ExternalUserID is also available for group
|
|
// askers and is used only for per-user card private data.
|
|
req.ExternalUserID = strings.TrimSpace(req.ExternalUserID)
|
|
if req.ConversationType == core.ConversationDirect {
|
|
if req.ExternalUserID == "" {
|
|
return "", errors.New("dingtalk card: ExternalUserID is required for direct conversations")
|
|
}
|
|
} else {
|
|
req.ExternalChatID = strings.TrimSpace(req.ExternalChatID)
|
|
if req.ExternalChatID == "" {
|
|
return "", errors.New("dingtalk card: ExternalChatID is required for group conversations")
|
|
}
|
|
}
|
|
|
|
// Generate outTrackID
|
|
outTrackID, err := generateUUID()
|
|
if err != nil {
|
|
return "", fmt.Errorf("dingtalk card: generate outTrackId: %w", err)
|
|
}
|
|
|
|
// Build card body
|
|
body := s.buildCardBody(req, outTrackID)
|
|
|
|
// Get access token
|
|
token, err := s.accessToken(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Send card (create only, no finalize)
|
|
if err := s.postCard(ctx, body, token); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return outTrackID, nil
|
|
}
|
|
|
|
// UpdateCard sends a streaming update to an existing card. outTrackID and
|
|
// content must be non-empty after trimming; content must not exceed 64 KiB.
|
|
// Set isFinalize=true to close the card; set isError=true to mark the card
|
|
// as an error state.
|
|
func (s *CardSender) UpdateCard(ctx context.Context, outTrackID, content string, isFinalize, isError bool) error {
|
|
outTrackID = strings.TrimSpace(outTrackID)
|
|
if outTrackID == "" {
|
|
return errors.New("dingtalk card: outTrackID is required")
|
|
}
|
|
content = strings.TrimSpace(content)
|
|
if content == "" {
|
|
return errors.New("dingtalk card: content is required")
|
|
}
|
|
if len(content) > 64*1024 {
|
|
return errors.New("dingtalk card: content exceeds 64 KiB")
|
|
}
|
|
log.Print(formatCardUpdateDiagnostic(content, isFinalize, isError))
|
|
|
|
token, err := s.accessToken(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return s.finalizeCard(ctx, outTrackID, content, token, isFinalize, isError)
|
|
}
|
|
|
|
func (s *CardSender) buildCardBody(req CardRequest, outTrackID string) map[string]any {
|
|
body := map[string]any{
|
|
"cardTemplateId": s.cardTemplateID,
|
|
"outTrackId": outTrackID,
|
|
"callbackType": "STREAM",
|
|
"cardData": map[string]any{
|
|
"cardParamMap": map[string]any{
|
|
"content": req.Content,
|
|
"feedbackSelected": "",
|
|
"feedbackReasonSelected": "",
|
|
"showFeedbackReasons": "false",
|
|
"feedbackMessage": "",
|
|
},
|
|
},
|
|
"userIdType": 1,
|
|
}
|
|
|
|
if req.ConversationType == core.ConversationDirect {
|
|
body["openSpaceId"] = "dtv1.card//IM_ROBOT." + req.ExternalUserID
|
|
body["imRobotOpenSpaceModel"] = map[string]any{
|
|
"supportForward": true,
|
|
}
|
|
body["imRobotOpenDeliverModel"] = map[string]any{
|
|
"robotCode": s.clientID,
|
|
"spaceType": "IM_ROBOT",
|
|
"extension": map[string]any{},
|
|
}
|
|
} else {
|
|
body["openSpaceId"] = "dtv1.card//IM_GROUP." + req.ExternalChatID
|
|
body["imGroupOpenSpaceModel"] = map[string]any{
|
|
"supportForward": true,
|
|
}
|
|
body["imGroupOpenDeliverModel"] = map[string]any{
|
|
"robotCode": s.clientID,
|
|
"extension": map[string]any{},
|
|
}
|
|
}
|
|
if s.debugUserID != "" && req.ExternalUserID == s.debugUserID {
|
|
body["privateData"] = map[string]any{
|
|
req.ExternalUserID: map[string]any{
|
|
"cardParamMap": map[string]any{
|
|
cardDebugPrivateKey: "show",
|
|
},
|
|
},
|
|
}
|
|
}
|
|
return body
|
|
}
|
|
|
|
func (s *CardSender) 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.postJSON(ctx, 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 card: 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 *CardSender) postCard(ctx context.Context, body map[string]any, token string) error {
|
|
payload, err := s.postJSON(ctx, s.createURL, body, token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return validateDingTalkBusinessResponse(payload)
|
|
}
|
|
|
|
func validateDingTalkBusinessResponse(payload []byte) error {
|
|
if len(bytes.TrimSpace(payload)) == 0 {
|
|
return nil
|
|
}
|
|
var response struct {
|
|
Success *bool `json:"success"`
|
|
ErrCode any `json:"errcode"`
|
|
}
|
|
if json.Unmarshal(payload, &response) != nil {
|
|
return nil
|
|
}
|
|
if response.Success != nil && !*response.Success {
|
|
return errors.New("dingtalk card: API business failure")
|
|
}
|
|
if response.ErrCode != nil && fmt.Sprint(response.ErrCode) != "0" {
|
|
return errors.New("dingtalk card: API business failure")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *CardSender) finalizeCard(ctx context.Context, outTrackID, content, token string, isFinalize, isError bool) error {
|
|
guid, err := generateUUID()
|
|
if err != nil {
|
|
return errors.New("dingtalk card: generate stream guid failed")
|
|
}
|
|
body := map[string]any{
|
|
"outTrackId": outTrackID,
|
|
"guid": guid,
|
|
"key": "content",
|
|
"content": content,
|
|
"isFull": true,
|
|
"isFinalize": isFinalize,
|
|
"isError": isError,
|
|
}
|
|
payload, err := s.doJSON(ctx, http.MethodPut, s.streamURL, body, token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return validateDingTalkBusinessResponse(payload)
|
|
}
|
|
|
|
func (s *CardSender) postJSON(ctx context.Context, endpoint string, value any, token string) ([]byte, error) {
|
|
return s.doJSON(ctx, http.MethodPost, endpoint, value, token)
|
|
}
|
|
|
|
func (s *CardSender) 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 card: encode API request failed")
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, errors.New("dingtalk card: 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()
|
|
}
|
|
return nil, errors.New("dingtalk card: API request failed")
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
// Discard body without reading it
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxAPIResponseBytes))
|
|
return nil, fmt.Errorf("dingtalk card: API HTTP %d", resp.StatusCode)
|
|
}
|
|
|
|
return readBoundedAPIResponse(resp)
|
|
}
|
|
|
|
// generateUUID creates a UUID v4 (random) using crypto/rand, formatted as
|
|
// lowercase hex with dashes: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
|
|
func generateUUID() (string, error) {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return "", err
|
|
}
|
|
// Set version 4
|
|
b[6] = (b[6] & 0x0f) | 0x40
|
|
// Set variant bits (10xx)
|
|
b[8] = (b[8] & 0x3f) | 0x80
|
|
|
|
return fmt.Sprintf("%x-%x-%x-%x-%x",
|
|
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
|
}
|