426 lines
13 KiB
Go
426 lines
13 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
sdkcard "github.com/open-dingtalk/dingtalk-stream-sdk-go/card"
|
|
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
|
|
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
|
|
)
|
|
|
|
// StreamConfig holds the DingTalk Stream mode credentials plus the tenant
|
|
// this ingress serves. An entirely empty config means the DingTalk channel
|
|
// is disabled; a partially filled config is a fatal misconfiguration.
|
|
type StreamConfig struct {
|
|
ClientID string
|
|
ClientSecret string
|
|
TenantKey string
|
|
}
|
|
|
|
// Enabled reports whether all three values are present. Callers must run
|
|
// Validate first: Enabled on a partially filled config returns false.
|
|
func (c StreamConfig) Enabled() bool {
|
|
return strings.TrimSpace(c.ClientID) != "" &&
|
|
strings.TrimSpace(c.ClientSecret) != "" &&
|
|
strings.TrimSpace(c.TenantKey) != ""
|
|
}
|
|
|
|
// Validate enforces the all-or-nothing rule: either every field is blank
|
|
// (channel disabled, no error) or every field is set (channel enabled).
|
|
// Any mix is an error so misconfigured deployments fail fast at startup.
|
|
func (c StreamConfig) Validate() error {
|
|
id := strings.TrimSpace(c.ClientID) != ""
|
|
secret := strings.TrimSpace(c.ClientSecret) != ""
|
|
tenant := strings.TrimSpace(c.TenantKey) != ""
|
|
if !id && !secret && !tenant {
|
|
return nil
|
|
}
|
|
if id && secret && tenant {
|
|
return nil
|
|
}
|
|
missing := make([]string, 0, 3)
|
|
if !id {
|
|
missing = append(missing, "client id")
|
|
}
|
|
if !secret {
|
|
missing = append(missing, "client secret")
|
|
}
|
|
if !tenant {
|
|
missing = append(missing, "tenant key")
|
|
}
|
|
return fmt.Errorf("dingtalk stream config is partial: missing %s", strings.Join(missing, ", "))
|
|
}
|
|
|
|
// BotCallbackFromSDK converts the official SDK callback model into the
|
|
// channel-internal BotCallback. Msgtype is normalized (trimmed, lowercased).
|
|
// For picture messages the downloadCode is extracted from the SDK Content
|
|
// field (json marshal/unmarshal round-trip); malformed or missing codes
|
|
// produce an empty DownloadCode but never downgrade the Msgtype.
|
|
// For richText messages the Content field is parsed for text+picture items;
|
|
// if a picture item is present Msgtype becomes "picture", otherwise text-only
|
|
// richText is promoted to "text". Malformed/empty richText keeps "richtext".
|
|
func BotCallbackFromSDK(data *chatbot.BotCallbackDataModel) (BotCallback, error) {
|
|
if data == nil {
|
|
return BotCallback{}, errors.New("dingtalk stream: callback data is nil")
|
|
}
|
|
msgtype := strings.ToLower(strings.TrimSpace(data.Msgtype))
|
|
cb := BotCallback{
|
|
ConversationType: data.ConversationType,
|
|
ConversationID: data.ConversationId,
|
|
ConversationTitle: data.ConversationTitle,
|
|
Msgtype: msgtype,
|
|
MsgID: data.MsgId,
|
|
SenderNick: data.SenderNick,
|
|
SenderStaffID: data.SenderStaffId,
|
|
SenderID: data.SenderId,
|
|
IsInAtList: data.IsInAtList,
|
|
SessionWebhook: data.SessionWebhook,
|
|
Text: data.Text.Content,
|
|
}
|
|
if msgtype == "richtext" {
|
|
rtMsgtype, rtText, rtCodes := parseRichText(data.Content)
|
|
cb.Msgtype = rtMsgtype
|
|
cb.Text = rtText
|
|
cb.DownloadCodes = rtCodes
|
|
if len(rtCodes) > 0 {
|
|
cb.DownloadCode = rtCodes[0]
|
|
}
|
|
return cb, nil
|
|
}
|
|
if msgtype == "link" {
|
|
linkURL := extractLinkMessageURL(data.Content)
|
|
if linkURL == "" {
|
|
linkURL = safeHTTPURL(data.Text.Content)
|
|
}
|
|
if linkURL != "" {
|
|
cb.Msgtype = msgTypeText
|
|
cb.Text = linkURL
|
|
}
|
|
return cb, nil
|
|
}
|
|
if msgtype == "picture" {
|
|
cb.DownloadCode = extractDownloadCode(data.Content)
|
|
}
|
|
return cb, nil
|
|
}
|
|
|
|
// extractLinkMessageURL extracts an HTTP(S) target from DingTalk link-card
|
|
// content. Only known URL and envelope keys are traversed so a card image URL
|
|
// (for example picUrl) cannot be mistaken for the message target.
|
|
func extractLinkMessageURL(raw interface{}) string {
|
|
if raw == nil {
|
|
return ""
|
|
}
|
|
b, err := json.Marshal(raw)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
var value interface{}
|
|
if json.Unmarshal(b, &value) != nil {
|
|
return ""
|
|
}
|
|
return findLinkMessageURL(value)
|
|
}
|
|
|
|
func findLinkMessageURL(value interface{}) string {
|
|
object, ok := value.(map[string]interface{})
|
|
if !ok {
|
|
return ""
|
|
}
|
|
for key, candidate := range object {
|
|
switch normalizeLinkField(key) {
|
|
case "messageurl", "linkurl", "singletitleurl", "href", "url":
|
|
if text, ok := candidate.(string); ok {
|
|
if target := safeHTTPURL(text); target != "" {
|
|
return target
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for key, nested := range object {
|
|
switch normalizeLinkField(key) {
|
|
case "content", "link", "data", "card":
|
|
if target := findLinkMessageURL(nested); target != "" {
|
|
return target
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func normalizeLinkField(value string) string {
|
|
value = strings.ToLower(strings.TrimSpace(value))
|
|
value = strings.ReplaceAll(value, "_", "")
|
|
return strings.ReplaceAll(value, "-", "")
|
|
}
|
|
|
|
func safeHTTPURL(raw string) string {
|
|
raw = strings.TrimSpace(raw)
|
|
u, err := url.ParseRequestURI(raw)
|
|
if err != nil || u.Host == "" {
|
|
return ""
|
|
}
|
|
if !strings.EqualFold(u.Scheme, "https") && !strings.EqualFold(u.Scheme, "http") {
|
|
return ""
|
|
}
|
|
return raw
|
|
}
|
|
|
|
// parseRichText parses the SDK Content field for richText messages.
|
|
// It handles three content shapes:
|
|
// 1. Direct object: {"richText": [...]}
|
|
// 2. Bare richText array (compatibility)
|
|
// 3. Nested envelope: {"content":{"richText":[...]}}
|
|
//
|
|
// Picture items are identified by a "type" field (case-insensitive trimmed)
|
|
// equal to "picture". All non-empty download codes are collected in order;
|
|
// text items are joined with newlines.
|
|
//
|
|
// Returns: (msgtype, text, downloadCodes). Msgtype is "picture" if any picture
|
|
// item exists, "text" if only text items, "richtext" if malformed/empty.
|
|
func parseRichText(raw interface{}) (string, string, []string) {
|
|
items := extractRichTextItems(raw)
|
|
if len(items) == 0 {
|
|
return "richtext", "", nil
|
|
}
|
|
|
|
var textParts []string
|
|
var downloadCodes []string
|
|
hasPicture := false
|
|
|
|
for _, item := range items {
|
|
itemType := strings.ToLower(strings.TrimSpace(item.Type))
|
|
|
|
if itemType == "picture" {
|
|
hasPicture = true
|
|
code := strings.TrimSpace(item.DownloadCode)
|
|
if code != "" {
|
|
downloadCodes = append(downloadCodes, code)
|
|
}
|
|
continue
|
|
}
|
|
|
|
txt := strings.TrimSpace(item.Text)
|
|
if txt != "" {
|
|
textParts = append(textParts, txt)
|
|
}
|
|
}
|
|
|
|
text := strings.Join(textParts, "\n")
|
|
|
|
if hasPicture {
|
|
return "picture", text, downloadCodes
|
|
}
|
|
if text != "" {
|
|
return "text", text, nil
|
|
}
|
|
return "richtext", "", nil
|
|
}
|
|
|
|
// richTextItem is a single item in a richText array.
|
|
type richTextItem struct {
|
|
Type string `json:"type"`
|
|
DownloadCode string `json:"downloadCode"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// extractRichTextItems extracts the richText item array from the raw Content
|
|
// field. It handles direct object, bare-array, and nested-envelope shapes.
|
|
func extractRichTextItems(raw interface{}) []richTextItem {
|
|
if raw == nil {
|
|
return nil
|
|
}
|
|
b, err := json.Marshal(raw)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
// Real DingTalk SDK shape: Content is already {"richText": [...]}.
|
|
var object struct {
|
|
RichText []richTextItem `json:"richText"`
|
|
}
|
|
if json.Unmarshal(b, &object) == nil && len(object.RichText) > 0 {
|
|
return object.RichText
|
|
}
|
|
|
|
// Accept a bare array for transport compatibility.
|
|
var direct []richTextItem
|
|
if json.Unmarshal(b, &direct) == nil && len(direct) > 0 {
|
|
return direct
|
|
}
|
|
|
|
// Accept a preserved callback envelope: {"content":{"richText":[...]}}.
|
|
var nested struct {
|
|
Content struct {
|
|
RichText []richTextItem `json:"richText"`
|
|
} `json:"content"`
|
|
}
|
|
if json.Unmarshal(b, &nested) == nil && len(nested.Content.RichText) > 0 {
|
|
return nested.Content.RichText
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// extractDownloadCode attempts to pull content.downloadCode from the SDK
|
|
// Content field (interface{}) via a json marshal/unmarshal round-trip. It
|
|
// never panics on malformed input and returns an empty string for any
|
|
// extraction failure.
|
|
func extractDownloadCode(raw interface{}) string {
|
|
if raw == nil {
|
|
return ""
|
|
}
|
|
b, err := json.Marshal(raw)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
var direct struct {
|
|
DownloadCode string `json:"downloadCode"`
|
|
}
|
|
if json.Unmarshal(b, &direct) == nil && strings.TrimSpace(direct.DownloadCode) != "" {
|
|
return strings.TrimSpace(direct.DownloadCode)
|
|
}
|
|
// Keep compatibility with transports that preserve the callback envelope.
|
|
var nested struct {
|
|
Content struct {
|
|
DownloadCode string `json:"downloadCode"`
|
|
} `json:"content"`
|
|
}
|
|
if err := json.Unmarshal(b, &nested); err != nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(nested.Content.DownloadCode)
|
|
}
|
|
|
|
const callbackDedupTTL = 5 * time.Minute
|
|
|
|
type chatCallbackHandler interface {
|
|
Handle(context.Context, BotCallback) error
|
|
}
|
|
|
|
// newAsyncChatCallbackRouter acknowledges valid DingTalk frames immediately,
|
|
// then processes them outside the SDK callback lifetime. DingTalk retries slow
|
|
// callbacks, so retaining MsgIDs for the platform's five-minute retry window
|
|
// prevents a retry from creating a second streaming card.
|
|
func newAsyncChatCallbackRouter(handler chatCallbackHandler) func(context.Context, *chatbot.BotCallbackDataModel) ([]byte, error) {
|
|
var mu sync.Mutex
|
|
seen := make(map[string]time.Time)
|
|
return func(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {
|
|
cb, err := BotCallbackFromSDK(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sourceType := safeCallbackMessageType(data.Msgtype)
|
|
if sourceType == "link" || sourceType == "richtext" {
|
|
log.Printf("DingTalk callback normalized: source_msgtype=%s normalized_msgtype=%s text_present=%t", sourceType, safeCallbackMessageType(cb.Msgtype), strings.TrimSpace(cb.Text) != "")
|
|
}
|
|
messageID := strings.TrimSpace(cb.MsgID)
|
|
if messageID == "" {
|
|
return nil, errors.New("dingtalk stream: msgId is required")
|
|
}
|
|
|
|
now := time.Now()
|
|
mu.Lock()
|
|
for id, expiresAt := range seen {
|
|
if !expiresAt.After(now) {
|
|
delete(seen, id)
|
|
}
|
|
}
|
|
if expiresAt, exists := seen[messageID]; exists && expiresAt.After(now) {
|
|
mu.Unlock()
|
|
return nil, nil
|
|
}
|
|
seen[messageID] = now.Add(callbackDedupTTL)
|
|
mu.Unlock()
|
|
|
|
workCtx := context.WithoutCancel(ctx)
|
|
go func() {
|
|
if err := handler.Handle(workCtx, cb); err != nil {
|
|
log.Printf("DingTalk async callback failed: stage=handler")
|
|
}
|
|
}()
|
|
return nil, nil
|
|
}
|
|
}
|
|
|
|
func safeCallbackMessageType(raw string) string {
|
|
switch strings.ToLower(strings.TrimSpace(raw)) {
|
|
case "text", "picture", "richtext", "link":
|
|
return strings.ToLower(strings.TrimSpace(raw))
|
|
default:
|
|
return "other"
|
|
}
|
|
}
|
|
|
|
// StreamClient wraps the official DingTalk Stream SDK client. Robot callbacks
|
|
// are acknowledged before the potentially slow QA/card work begins. The SDK
|
|
// default auto-reconnect stays enabled while running; Close disables it so the
|
|
// connection stays closed.
|
|
type StreamClient struct {
|
|
inner *dtsdk.StreamClient
|
|
}
|
|
|
|
// NewStreamClient validates the config, builds the SDK client with the app
|
|
// credential and registers the chatbot callback router. The handler is
|
|
// acknowledged immediately; replies always go through the session webhook.
|
|
func NewStreamClient(config StreamConfig, handler *Handler, feedbackHandlers ...*CardFeedbackHandler) (*StreamClient, error) {
|
|
if err := config.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
if !config.Enabled() {
|
|
return nil, errors.New("dingtalk stream: config is empty, client not created")
|
|
}
|
|
if handler == nil {
|
|
return nil, errors.New("dingtalk stream: handler is required")
|
|
}
|
|
if len(feedbackHandlers) > 1 {
|
|
return nil, errors.New("dingtalk stream: at most one card feedback handler is allowed")
|
|
}
|
|
if len(feedbackHandlers) == 1 && feedbackHandlers[0] == nil {
|
|
return nil, errors.New("dingtalk stream: card feedback handler is nil")
|
|
}
|
|
cred := dtsdk.NewAppCredentialConfig(strings.TrimSpace(config.ClientID), strings.TrimSpace(config.ClientSecret))
|
|
// Keep the SDK default AutoReconnect=true so runtime disconnects
|
|
// reconnect automatically; Close flips it off before closing.
|
|
inner := dtsdk.NewStreamClient(
|
|
dtsdk.WithAppCredential(cred),
|
|
)
|
|
inner.RegisterChatBotCallbackRouter(newAsyncChatCallbackRouter(handler))
|
|
if len(feedbackHandlers) == 1 {
|
|
inner.RegisterCardCallbackRouter(func(ctx context.Context, request *sdkcard.CardRequest) (*sdkcard.CardResponse, error) {
|
|
return feedbackHandlers[0].HandleSDK(ctx, request)
|
|
})
|
|
}
|
|
return &StreamClient{inner: inner}, nil
|
|
}
|
|
|
|
// Start connects to DingTalk Stream and spawns the SDK read loop. Any
|
|
// connection or credential error is propagated to the caller.
|
|
func (c *StreamClient) Start(ctx context.Context) error {
|
|
if c == nil || c.inner == nil {
|
|
return errors.New("dingtalk stream: client is nil")
|
|
}
|
|
if err := c.inner.Start(ctx); err != nil {
|
|
return fmt.Errorf("dingtalk stream start: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Close tears down the websocket. Auto-reconnect is disabled before the
|
|
// underlying Close so the SDK processLoop cannot reconnect afterwards.
|
|
func (c *StreamClient) Close() {
|
|
if c == nil || c.inner == nil {
|
|
return
|
|
}
|
|
c.inner.AutoReconnect = false
|
|
c.inner.Close()
|
|
}
|