package dingtalk import ( "context" "encoding/json" "errors" "fmt" "strings" "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, 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, rtCode := parseRichText(data.Content) cb.Msgtype = rtMsgtype cb.Text = rtText cb.DownloadCode = rtCode return cb, nil } if msgtype == "picture" { cb.DownloadCode = extractDownloadCode(data.Content) } return cb, nil } // 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". The first non-empty downloadCode is used; subsequent // picture items are ignored. Text items are joined with newlines. // // Returns: (msgtype, text, downloadCode). 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", "", "" } var textParts []string var downloadCode string hasPicture := false for _, item := range items { itemType := strings.ToLower(strings.TrimSpace(item.Type)) if itemType == "picture" { hasPicture = true if downloadCode == "" { code := strings.TrimSpace(item.DownloadCode) if code != "" { downloadCode = code } } continue } txt := strings.TrimSpace(item.Text) if txt != "" { textParts = append(textParts, txt) } } text := strings.Join(textParts, "\n") if hasPicture { return "picture", text, downloadCode } if text != "" { return "text", text, "" } return "richtext", "", "" } // 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) } // StreamClient wraps the official DingTalk Stream SDK client. It wires // robot callbacks into the existing Handler synchronously (no goroutines, // no queue). 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 // invoked synchronously from the SDK callback; its return value only // acknowledges the frame, replies always go through the session webhook. func NewStreamClient(config StreamConfig, handler *Handler) (*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") } 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(func(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) { cb, err := BotCallbackFromSDK(data) if err != nil { return nil, err } if err := handler.Handle(ctx, cb); err != nil { return nil, err } return nil, nil }) 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() }