package dingtalk import ( "context" "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. It is a pure one-to-one field mapping; no // trimming, validation or business logic happens here (Handler owns that). func BotCallbackFromSDK(data *chatbot.BotCallbackDataModel) (BotCallback, error) { if data == nil { return BotCallback{}, errors.New("dingtalk stream: callback data is nil") } return BotCallback{ ConversationType: data.ConversationType, ConversationID: data.ConversationId, Msgtype: data.Msgtype, MsgID: data.MsgId, SenderNick: data.SenderNick, SenderStaffID: data.SenderStaffId, SenderID: data.SenderId, IsInAtList: data.IsInAtList, SessionWebhook: data.SessionWebhook, Text: data.Text.Content, }, nil } // 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() }