Files
Enterprise-Knowledge-Base/internal/im/dingtalk/adapter.go
T
2026-07-16 00:17:16 +08:00

927 lines
27 KiB
Go

package dingtalk
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"net"
"net/http"
"net/netip"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// httpClient is a shared HTTP client with a reasonable timeout for DingTalk API calls.
var httpClient = &http.Client{Timeout: 15 * time.Second}
// minCardUpdateInterval is the minimum time between consecutive card streaming updates.
const minCardUpdateInterval = 500 * time.Millisecond
// dingtalkConvTypeGroup is the DingTalk conversation type value for group chats.
const dingtalkConvTypeGroup = "2"
// Compile-time checks.
var (
_ im.Adapter = (*Adapter)(nil)
_ im.StreamSender = (*Adapter)(nil)
_ im.FileDownloader = (*Adapter)(nil)
)
// Adapter implements im.Adapter for DingTalk.
type Adapter struct {
clientID string
clientSecret string
cardTemplateID string // optional: enables AI card streaming when set
messageFileDownloadURL string
allowInsecureDownload bool // tests only; production requires HTTPS
// accessToken cache
tokenMu sync.RWMutex
token string
tokenExpAt time.Time
}
// NewWebhookAdapter creates a DingTalk adapter for HTTP callback mode.
func NewWebhookAdapter(clientID, clientSecret, cardTemplateID string) *Adapter {
startStreamReaper()
return &Adapter{
clientID: clientID,
clientSecret: clientSecret,
cardTemplateID: cardTemplateID,
}
}
// NewAdapter creates a DingTalk adapter for stream (websocket) mode.
// The stream connection itself is managed separately by the supervisor; the
// adapter only sends replies (via sessionWebhook or OpenAPI).
func NewAdapter(clientID, clientSecret, cardTemplateID string) *Adapter {
startStreamReaper()
return &Adapter{
clientID: clientID,
clientSecret: clientSecret,
cardTemplateID: cardTemplateID,
}
}
func (a *Adapter) Platform() im.Platform {
return im.PlatformDingtalk
}
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
return false
}
// VerifyCallback verifies the DingTalk webhook signature (HmacSHA256).
func (a *Adapter) VerifyCallback(c *gin.Context) error {
if a.clientSecret == "" {
return nil
}
timestamp := c.GetHeader("Timestamp")
sign := c.GetHeader("Sign")
if timestamp == "" || sign == "" {
return fmt.Errorf("missing timestamp or sign header")
}
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return fmt.Errorf("invalid timestamp: %w", err)
}
diff := time.Now().UnixMilli() - ts
if diff > 3600*1000 || diff < -3600*1000 {
return fmt.Errorf("timestamp expired")
}
stringToSign := timestamp + "\n" + a.clientSecret
h := hmac.New(sha256.New, []byte(a.clientSecret))
h.Write([]byte(stringToSign))
expectedSign := base64.StdEncoding.EncodeToString(h.Sum(nil))
if !hmac.Equal([]byte(sign), []byte(expectedSign)) {
return fmt.Errorf("invalid signature")
}
return nil
}
// DingTalk callback message structure.
type callbackMessage struct {
ConversationID string `json:"conversationId"`
ConversationType string `json:"conversationType"`
MsgID string `json:"msgId"`
Msgtype string `json:"msgtype"`
Text *textContent `json:"text"`
Content json.RawMessage `json:"content"`
SenderNick string `json:"senderNick"`
SenderStaffId string `json:"senderStaffId"`
SenderID string `json:"senderId"`
SessionWebhook string `json:"sessionWebhook"`
RobotCode string `json:"robotCode"`
AtUsers []atUser `json:"atUsers"`
IsInAtList bool `json:"isInAtList"`
ChatbotCorpId string `json:"chatbotCorpId"`
}
type textContent struct {
Content string `json:"content"`
}
type atUser struct {
DingtalkID string `json:"dingtalkId"`
StaffID string `json:"staffId"`
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
var msg callbackMessage
if err := json.Unmarshal(bodyBytes, &msg); err != nil {
return nil, fmt.Errorf("parse callback: %w", err)
}
return parseCallbackMessage(&msg), nil
}
func parseCallbackMessage(msg *callbackMessage) *im.IncomingMessage {
chatType := im.ChatTypeDirect
chatID := ""
if msg.ConversationType == dingtalkConvTypeGroup {
chatType = im.ChatTypeGroup
chatID = msg.ConversationID
}
userID := msg.SenderStaffId
if userID == "" {
userID = msg.SenderID
}
content := ""
if msg.Text != nil {
content = strings.TrimSpace(msg.Text.Content)
}
messageType := im.MessageTypeText
fileKey := ""
fileName := ""
if strings.EqualFold(msg.Msgtype, "picture") {
messageType = im.MessageTypeImage
fileName = msg.MsgID + ".png"
content = ""
var picture struct {
DownloadCode string `json:"downloadCode"`
}
if json.Unmarshal(msg.Content, &picture) == nil {
fileKey = strings.TrimSpace(picture.DownloadCode)
}
}
return &im.IncomingMessage{
Platform: im.PlatformDingtalk,
UserID: userID,
UserName: msg.SenderNick,
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
MessageType: messageType,
Content: content,
FileKey: fileKey,
FileName: fileName,
Extra: map[string]string{
"session_webhook": msg.SessionWebhook,
},
}
}
const (
dingtalkMessageFileDownloadURL = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"
maxDingTalkAPIResponseBytes = 1 << 20
)
func (a *Adapter) newDingTalkAPIClient(base *http.Client) *http.Client {
client := *base
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
if !a.allowInsecureDownload {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
transport.DialContext = newDingTalkSafeDialContext(net.DefaultResolver.LookupIPAddr, dialer.DialContext)
client.Transport = transport
}
return &client
}
func readBoundedDingTalkAPIResponse(resp *http.Response) ([]byte, error) {
if resp.ContentLength > maxDingTalkAPIResponseBytes {
return nil, fmt.Errorf("dingtalk API response exceeds size limit")
}
payload, err := io.ReadAll(io.LimitReader(resp.Body, maxDingTalkAPIResponseBytes+1))
if err != nil {
return nil, fmt.Errorf("read dingtalk API response: %w", err)
}
if len(payload) > maxDingTalkAPIResponseBytes {
return nil, fmt.Errorf("dingtalk API response exceeds size limit")
}
return payload, nil
}
func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
if msg == nil || strings.TrimSpace(msg.FileKey) == "" {
return nil, "", fmt.Errorf("download code is required")
}
token, err := a.getAccessToken(ctx)
if err != nil {
return nil, "", fmt.Errorf("get access token: %w", err)
}
body, err := json.Marshal(map[string]string{
"downloadCode": msg.FileKey,
"robotCode": a.clientID,
})
if err != nil {
return nil, "", fmt.Errorf("marshal message file request: %w", err)
}
apiURL := a.messageFileDownloadURL
if apiURL == "" {
apiURL = dingtalkMessageFileDownloadURL
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(body))
if err != nil {
return nil, "", fmt.Errorf("create message file request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-acs-dingtalk-access-token", token)
apiClient := a.newDingTalkAPIClient(httpClient)
resp, err := apiClient.Do(req)
if err != nil {
return nil, "", fmt.Errorf("request message file URL: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return nil, "", fmt.Errorf("dingtalk message file API returned %d", resp.StatusCode)
}
payload, err := readBoundedDingTalkAPIResponse(resp)
if err != nil {
return nil, "", err
}
var result struct {
DownloadURL string `json:"downloadUrl"`
}
if err := json.Unmarshal(payload, &result); err != nil {
return nil, "", fmt.Errorf("decode message file response: %w", err)
}
if !a.allowInsecureDownload {
result.DownloadURL, err = normalizeDingTalkInitialDownloadURL(result.DownloadURL)
if err != nil {
return nil, "", err
}
}
if err := validateDingTalkDownloadURL(result.DownloadURL, a.allowInsecureDownload); err != nil {
return nil, "", err
}
downloadReq, err := http.NewRequestWithContext(ctx, http.MethodGet, result.DownloadURL, nil)
if err != nil {
return nil, "", fmt.Errorf("create image download request: %w", err)
}
downloadClient := *httpClient
if !a.allowInsecureDownload {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
transport.DialContext = newDingTalkSafeDialContext(net.DefaultResolver.LookupIPAddr, dialer.DialContext)
downloadClient.Transport = transport
}
downloadClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return validateDingTalkRedirect(req, via, a.allowInsecureDownload)
}
downloadResp, err := downloadClient.Do(downloadReq)
if err != nil {
if ctx.Err() != nil {
return nil, "", ctx.Err()
}
return nil, "", fmt.Errorf("download dingtalk image request failed")
}
if downloadResp.StatusCode < http.StatusOK || downloadResp.StatusCode >= http.StatusMultipleChoices {
downloadResp.Body.Close()
return nil, "", fmt.Errorf("dingtalk image download returned %d", downloadResp.StatusCode)
}
contentType := strings.ToLower(strings.TrimSpace(strings.Split(downloadResp.Header.Get("Content-Type"), ";")[0]))
if msg.MessageType == im.MessageTypeImage && contentType != "" && contentType != "application/octet-stream" && !strings.HasPrefix(contentType, "image/") {
downloadResp.Body.Close()
return nil, "", fmt.Errorf("dingtalk picture response is not an image")
}
return downloadResp.Body, dingtalkDownloadedFileName(downloadResp, msg, contentType), nil
}
var dingtalkBlockedPublicRanges = []netip.Prefix{
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("2001:db8::/32"),
}
func isSafeDingTalkDownloadIP(ip net.IP) bool {
if ip == nil || !secutils.IsPublicIP(ip) {
return false
}
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
}
addr = addr.Unmap()
if !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() || addr.IsUnspecified() || addr.IsMulticast() {
return false
}
for _, prefix := range dingtalkBlockedPublicRanges {
if prefix.Contains(addr) {
return false
}
}
return true
}
func newDingTalkSafeDialContext(
lookup func(context.Context, string) ([]net.IPAddr, error),
dial func(context.Context, string, string) (net.Conn, error),
) func(context.Context, string, string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid dingtalk media address")
}
var ips []net.IPAddr
if literal := net.ParseIP(host); literal != nil {
ips = []net.IPAddr{{IP: literal}}
} else {
ips, err = lookup(ctx, host)
if err != nil {
return nil, fmt.Errorf("resolve dingtalk media host failed")
}
}
if len(ips) == 0 {
return nil, fmt.Errorf("dingtalk media host resolved without addresses")
}
for _, resolved := range ips {
if !isSafeDingTalkDownloadIP(resolved.IP) {
return nil, fmt.Errorf("dingtalk media host resolved to a blocked address")
}
}
var lastErr error
for _, resolved := range ips {
conn, dialErr := dial(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
if dialErr == nil {
return conn, nil
}
lastErr = dialErr
}
return nil, fmt.Errorf("connect to validated dingtalk media address: %w", lastErr)
}
}
func validateDingTalkRedirect(req *http.Request, via []*http.Request, allowInsecure bool) error {
if len(via) >= 10 {
return fmt.Errorf("stopped after 10 dingtalk image redirects")
}
// Go may synthesize Referer from the credential-bearing source URL and copy
// headers across redirects. Media redirects need no inherited headers.
req.Header = make(http.Header)
return validateDingTalkDownloadURL(req.URL.String(), allowInsecure)
}
// normalizeDingTalkInitialDownloadURL upgrades the one-time media URL returned
// directly by DingTalk's authenticated message-file API. Some DingTalk media
// backends still return an http scheme even though the same signed resource is
// available over TLS. Only this initial trusted API response is upgraded;
// redirects remain HTTPS-only and are validated independently.
func normalizeDingTalkInitialDownloadURL(rawURL string) (string, error) {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || u.Hostname() == "" || u.User != nil {
return "", fmt.Errorf("invalid dingtalk download URL")
}
switch u.Scheme {
case "http":
u.Scheme = "https"
case "https":
default:
return "", fmt.Errorf("invalid dingtalk download URL scheme")
}
return u.String(), nil
}
func validateDingTalkDownloadURL(rawURL string, allowInsecure bool) error {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || u.Hostname() == "" || u.User != nil {
return fmt.Errorf("invalid dingtalk download URL")
}
if allowInsecure {
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("invalid dingtalk download URL scheme")
}
return nil
}
if u.Scheme != "https" {
return fmt.Errorf("dingtalk download URL must use HTTPS")
}
if ip := net.ParseIP(u.Hostname()); ip != nil && (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified()) {
return fmt.Errorf("dingtalk download URL points to a private address")
}
if err := secutils.ValidateURLForSSRF(u.String()); err != nil {
return fmt.Errorf("dingtalk download URL failed SSRF validation: %w", err)
}
return nil
}
func dingtalkDownloadedFileName(resp *http.Response, msg *im.IncomingMessage, contentType string) string {
if _, params, err := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); err == nil {
if name := filepath.Base(strings.TrimSpace(params["filename"])); name != "" && name != "." && name != ".." {
return name
}
}
if msg != nil && strings.TrimSpace(msg.FileName) != "" {
return filepath.Base(msg.FileName)
}
ext := ".bin"
if extensions, _ := mime.ExtensionsByType(contentType); len(extensions) > 0 {
ext = extensions[0]
}
if msg != nil && msg.MessageID != "" {
return msg.MessageID + ext
}
return "dingtalk-file" + ext
}
// ── Send reply ──
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
content := im.FormatIMDisplayContent(reply.Content, im.StreamDisplayFinal)
sessionWebhook := ""
if incoming.Extra != nil {
sessionWebhook = incoming.Extra["session_webhook"]
}
if sessionWebhook != "" {
return a.replyViaSessionWebhook(ctx, sessionWebhook, content)
}
return a.replyViaOpenAPI(ctx, incoming, content)
}
func (a *Adapter) replyViaSessionWebhook(ctx context.Context, webhookURL, content string) error {
if err := validateDingTalkDownloadURL(webhookURL, a.allowInsecureDownload); err != nil {
return fmt.Errorf("invalid DingTalk session webhook")
}
body := map[string]interface{}{
"msgtype": "markdown",
"markdown": map[string]string{
"title": "Reply",
"text": content,
},
}
jsonBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal reply: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(jsonBody))
if err != nil {
return fmt.Errorf("create DingTalk session webhook request")
}
req.Header.Set("Content-Type", "application/json")
client := a.newDingTalkAPIClient(httpClient)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("send DingTalk session webhook failed")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("dingtalk session webhook returned %d", resp.StatusCode)
}
if _, err := readBoundedDingTalkAPIResponse(resp); err != nil {
return err
}
return nil
}
func (a *Adapter) replyViaOpenAPI(ctx context.Context, incoming *im.IncomingMessage, content string) error {
token, err := a.getAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
msgParam, err := json.Marshal(map[string]string{"title": "Reply", "text": content})
if err != nil {
return fmt.Errorf("marshal msgParam: %w", err)
}
var apiURL string
body := map[string]interface{}{
"robotCode": a.clientID,
"msgKey": "sampleMarkdown",
"msgParam": string(msgParam),
}
if incoming.ChatType == im.ChatTypeGroup {
apiURL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
body["openConversationId"] = incoming.ChatID
} else {
apiURL = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
body["userIds"] = []string{incoming.UserID}
}
jsonBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal body: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(jsonBody))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-acs-dingtalk-access-token", token)
apiClient := a.newDingTalkAPIClient(httpClient)
resp, err := apiClient.Do(req)
if err != nil {
return fmt.Errorf("send reply failed")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("dingtalk OpenAPI returned %d", resp.StatusCode)
}
if _, err := readBoundedDingTalkAPIResponse(resp); err != nil {
return err
}
return nil
}
// getAccessToken returns a cached or fresh DingTalk access token.
func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
a.tokenMu.RLock()
if a.token != "" && time.Now().Before(a.tokenExpAt) {
token := a.token
a.tokenMu.RUnlock()
return token, nil
}
a.tokenMu.RUnlock()
a.tokenMu.Lock()
defer a.tokenMu.Unlock()
if a.token != "" && time.Now().Before(a.tokenExpAt) {
return a.token, nil
}
body := map[string]string{
"appKey": a.clientID,
"appSecret": a.clientSecret,
}
jsonBody, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://api.dingtalk.com/v1.0/oauth2/accessToken",
bytes.NewReader(jsonBody))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
apiClient := a.newDingTalkAPIClient(httpClient)
resp, err := apiClient.Do(req)
if err != nil {
return "", fmt.Errorf("dingtalk access token request failed")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("dingtalk access token returned %d", resp.StatusCode)
}
payload, err := readBoundedDingTalkAPIResponse(resp)
if err != nil {
return "", err
}
var result struct {
AccessToken string `json:"accessToken"`
ExpireIn int64 `json:"expireIn"`
}
if err := json.Unmarshal(payload, &result); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if result.AccessToken == "" {
return "", fmt.Errorf("empty access token from dingtalk")
}
a.token = result.AccessToken
a.tokenExpAt = time.Now().Add(time.Duration(result.ExpireIn)*time.Second - 5*time.Minute)
return a.token, nil
}
// ── DingTalk OpenAPI helpers for AI Card ──
func (a *Adapter) dingtalkAPI(ctx context.Context, method, path string, body interface{}) (json.RawMessage, error) {
token, err := a.getAccessToken(ctx)
if err != nil {
return nil, fmt.Errorf("get access token: %w", err)
}
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal body: %w", err)
}
url := "https://api.dingtalk.com" + path
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-acs-dingtalk-access-token", token)
apiClient := a.newDingTalkAPIClient(httpClient)
resp, err := apiClient.Do(req)
if err != nil {
return nil, fmt.Errorf("dingtalk API request failed")
}
defer resp.Body.Close()
respBody, readErr := readBoundedDingTalkAPIResponse(resp)
if readErr != nil {
return nil, readErr
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("dingtalk API %s returned %d", path, resp.StatusCode)
}
return respBody, nil
}
// createAndDeliverCard creates an AI card and delivers it to the conversation.
func (a *Adapter) createAndDeliverCard(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
outTrackID := uuid.New().String()
body := map[string]interface{}{
"cardTemplateId": a.cardTemplateID,
"outTrackId": outTrackID,
"callbackType": "STREAM",
"cardData": map[string]interface{}{
"cardParamMap": map[string]string{
"content": "",
},
},
"userIdType": 1,
}
if incoming.ChatType == im.ChatTypeGroup {
// Group chat
convID := incoming.ChatID
body["openSpaceId"] = "dtv1.card//IM_GROUP." + convID
body["imGroupOpenSpaceModel"] = map[string]interface{}{"supportForward": true}
body["imGroupOpenDeliverModel"] = map[string]interface{}{
"robotCode": a.clientID,
"extension": map[string]string{},
}
} else {
// Single chat (1:1 DM)
body["openSpaceId"] = "dtv1.card//IM_ROBOT." + incoming.UserID
body["imRobotOpenSpaceModel"] = map[string]interface{}{"supportForward": true}
body["imRobotOpenDeliverModel"] = map[string]interface{}{
"robotCode": a.clientID,
"spaceType": "IM_ROBOT",
"extension": map[string]string{},
}
}
_, err := a.dingtalkAPI(ctx, http.MethodPost, "/v1.0/card/instances/createAndDeliver", body)
if err != nil {
return "", fmt.Errorf("create card: %w", err)
}
return outTrackID, nil
}
// streamingUpdateCard pushes content to an existing AI card.
func (a *Adapter) streamingUpdateCard(ctx context.Context, outTrackID, content string, isFinalize bool) error {
body := map[string]interface{}{
"outTrackId": outTrackID,
"guid": uuid.New().String(),
"key": "content",
"content": content,
"isFull": true,
"isFinalize": isFinalize,
"isError": false,
}
_, err := a.dingtalkAPI(ctx, http.MethodPut, "/v1.0/card/streaming", body)
return err
}
// ── StreamSender implementation ──
type streamState struct {
mu sync.Mutex
content strings.Builder
sessionWebhook string
outTrackID string // non-empty when using AI card streaming
lastUpdate time.Time // for card update throttling
createdAt time.Time // for orphan stream detection
}
const (
streamOrphanTTL = 5 * time.Minute
streamReaperInterval = 1 * time.Minute
)
var (
streamsMu sync.Mutex
dStreams = map[string]*streamState{}
startReaperOnce sync.Once
reaperStopCh = make(chan struct{})
)
// startStreamReaper starts a background goroutine (once) that periodically
// removes orphaned stream entries. This prevents memory leaks when EndStream
// is never called due to panics or pipeline errors.
func startStreamReaper() {
startReaperOnce.Do(func() {
go func() {
ticker := time.NewTicker(streamReaperInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
cutoff := time.Now().Add(-streamOrphanTTL)
streamsMu.Lock()
for id, state := range dStreams {
if state.createdAt.Before(cutoff) {
delete(dStreams, id)
}
}
streamsMu.Unlock()
case <-reaperStopCh:
return
}
}
}()
})
}
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
sessionWebhook := ""
if incoming.Extra != nil {
sessionWebhook = incoming.Extra["session_webhook"]
}
streamID := fmt.Sprintf("dt:%s:%s", incoming.UserID, incoming.MessageID)
state := &streamState{
sessionWebhook: sessionWebhook,
createdAt: time.Now(),
}
// If card template is configured, create an AI card for streaming
if a.cardTemplateID != "" {
outTrackID, err := a.createAndDeliverCard(ctx, incoming)
if err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to create AI card, falling back to sessionWebhook: %v", err)
} else {
state.outTrackID = outTrackID
}
}
streamsMu.Lock()
dStreams[streamID] = state
streamsMu.Unlock()
logger.Infof(ctx, "[DingTalk] Streaming started: stream_id=%s, card=%v", streamID, state.outTrackID != "")
return streamID, nil
}
func (a *Adapter) UpdateStreamContent(ctx context.Context, incoming *im.IncomingMessage, streamID string, fullContent string) error {
if fullContent == "" {
return nil
}
streamsMu.Lock()
state, ok := dStreams[streamID]
streamsMu.Unlock()
if !ok {
return fmt.Errorf("unknown stream ID: %s", streamID)
}
state.mu.Lock()
state.content.Reset()
state.content.WriteString(fullContent)
if state.outTrackID == "" {
state.mu.Unlock()
return nil
}
if time.Since(state.lastUpdate) < minCardUpdateInterval {
state.mu.Unlock()
return nil
}
state.lastUpdate = time.Now()
outTrackID := state.outTrackID
state.mu.Unlock()
if err := a.streamingUpdateCard(ctx, outTrackID, fullContent, false); err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to update card stream: %v", err)
}
return nil
}
func (a *Adapter) FinalizeStream(ctx context.Context, incoming *im.IncomingMessage, streamID string, finalContent string) error {
streamsMu.Lock()
state, ok := dStreams[streamID]
streamsMu.Unlock()
if !ok {
return fmt.Errorf("unknown stream ID: %s", streamID)
}
state.mu.Lock()
state.content.Reset()
state.content.WriteString(finalContent)
outTrackID := state.outTrackID
state.mu.Unlock()
if outTrackID != "" {
if err := a.streamingUpdateCard(ctx, outTrackID, finalContent, false); err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to finalize card stream: %v", err)
return fmt.Errorf("finalize DingTalk card stream: %w", err)
}
}
return nil
}
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
return a.UpdateStreamContent(ctx, incoming, streamID, content)
}
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
streamsMu.Lock()
state, ok := dStreams[streamID]
delete(dStreams, streamID)
streamsMu.Unlock()
if !ok {
return nil
}
state.mu.Lock()
fullContent := state.content.String()
outTrackID := state.outTrackID
sessionWebhook := state.sessionWebhook
state.mu.Unlock()
if outTrackID != "" {
if err := a.streamingUpdateCard(ctx, outTrackID, fullContent, true); err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to finalize card stream: %v", err)
return fmt.Errorf("end DingTalk card stream: %w", err)
}
} else if sessionWebhook != "" {
if err := a.replyViaSessionWebhook(ctx, sessionWebhook, fullContent); err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to end stream: %v", err)
return fmt.Errorf("end DingTalk session webhook stream: %w", err)
}
} else {
if err := a.replyViaOpenAPI(ctx, incoming, fullContent); err != nil {
logger.Warnf(ctx, "[DingTalk] Failed to end stream via OpenAPI: %v", err)
return fmt.Errorf("end DingTalk OpenAPI stream: %w", err)
}
}
logger.Infof(ctx, "[DingTalk] Streaming ended: stream_id=%s", streamID)
return nil
}