Files
Enterprise-Knowledge-Base/internal/im/dingtalk/longconn.go
T
2026-07-16 00:49:26 +08:00

168 lines
4.5 KiB
Go

package dingtalk
import (
"context"
"encoding/json"
"strings"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// MessageHandler is called when an IM message is received via stream connection.
type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error
// LongConnClient manages a DingTalk Stream mode connection.
type LongConnClient struct {
clientID string
clientSecret string
handler MessageHandler
streamClient *dtsdk.StreamClient
}
// NewLongConnClient creates a DingTalk stream client.
func NewLongConnClient(clientID, clientSecret string, handler MessageHandler) *LongConnClient {
cli := dtsdk.NewStreamClient(
dtsdk.WithAppCredential(&dtsdk.AppCredentialConfig{
ClientId: clientID,
ClientSecret: clientSecret,
}),
)
c := &LongConnClient{
clientID: clientID,
clientSecret: clientSecret,
handler: handler,
streamClient: cli,
}
cli.RegisterChatBotCallbackRouter(c.onChatBotMessage)
return c
}
// Start establishes the stream connection. The underlying SDK's Start is
// non-blocking: it dials the websocket, spawns its internal read/reconnect
// loops, and returns once the connection is established (or the attempt fails).
func (c *LongConnClient) Start(ctx context.Context) error {
logger.Infof(ctx, "[IM] DingTalk Stream connecting...")
return c.streamClient.Start(ctx)
}
// Close tears down the stream connection. AutoReconnect is disabled first so
// that closing the connection does not trigger the SDK's internal reconnect.
func (c *LongConnClient) Close() {
c.streamClient.AutoReconnect = false
c.streamClient.Close()
}
func (c *LongConnClient) onChatBotMessage(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {
chatType := im.ChatTypeDirect
chatID := ""
if data.ConversationType == dingtalkConvTypeGroup {
chatType = im.ChatTypeGroup
chatID = data.ConversationId
}
userID := data.SenderStaffId
if userID == "" {
userID = data.SenderId
}
messageType, content, fileKey := parseDingTalkStreamPayload(data.Msgtype, data.Content, data.Text.Content)
fileName := ""
if messageType == im.MessageTypeImage {
fileName = data.MsgId + ".png"
}
incoming := &im.IncomingMessage{
Platform: im.PlatformDingtalk,
UserID: userID,
UserName: data.SenderNick,
ChatID: chatID,
ChatType: chatType,
MessageID: data.MsgId,
MessageType: messageType,
Content: content,
FileKey: fileKey,
FileName: fileName,
Extra: map[string]string{
"session_webhook": data.SessionWebhook,
},
}
if err := c.handler(ctx, incoming); err != nil {
logger.Errorf(ctx, "[DingTalk] Handle message error: %v", err)
}
return nil, nil
}
func parseDingTalkStreamPayload(msgType string, rawContent interface{}, text string) (im.MessageType, string, string) {
normalizedType := strings.ToLower(strings.TrimSpace(msgType))
if normalizedType != "picture" && normalizedType != "richtext" {
return im.MessageTypeText, strings.TrimSpace(text), ""
}
var payload []byte
switch value := rawContent.(type) {
case string:
payload = []byte(value)
case []byte:
payload = value
case json.RawMessage:
payload = value
default:
var err error
payload, err = json.Marshal(rawContent)
if err != nil {
return im.MessageTypeImage, "", ""
}
}
if normalizedType == "richtext" {
var rich struct {
Items []struct {
Text string `json:"text"`
Type string `json:"type"`
DownloadCode string `json:"downloadCode"`
} `json:"richText"`
}
if json.Unmarshal(payload, &rich) != nil {
return im.MessageTypeText, strings.TrimSpace(text), ""
}
var textParts []string
fileKey := ""
hasPicture := false
for _, item := range rich.Items {
if itemText := strings.TrimSpace(item.Text); itemText != "" {
textParts = append(textParts, itemText)
}
if strings.EqualFold(strings.TrimSpace(item.Type), "picture") {
hasPicture = true
if fileKey == "" {
fileKey = strings.TrimSpace(item.DownloadCode)
}
}
}
content := strings.Join(textParts, "\n")
if hasPicture {
return im.MessageTypeImage, content, fileKey
}
return im.MessageTypeText, content, ""
}
var picture struct {
DownloadCode string `json:"downloadCode"`
}
if json.Unmarshal(payload, &picture) != nil {
return im.MessageTypeImage, "", ""
}
return im.MessageTypeImage, "", strings.TrimSpace(picture.DownloadCode)
}