refactor(im): move adapter factories into per-platform subpackages

registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.

Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:

- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
  unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
  websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
  returns an im.AdapterFactory; container.go now calls each one in a
  single line.

Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.

Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
This commit is contained in:
wizardchen
2026-04-29 18:27:26 +08:00
committed by lyingbug
parent 9af5fb30ac
commit b2975f7d1d
10 changed files with 420 additions and 330 deletions
+10 -330
View File
@@ -6,7 +6,6 @@ package container
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/url"
@@ -77,7 +76,6 @@ import (
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
slackpkg "github.com/slack-go/slack"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
@@ -1162,338 +1160,20 @@ func registerWebSearchProviders(registry *infra_web_search.Registry) {
}
// registerIMAdapterFactories registers adapter factories for each IM platform
// and loads enabled channels from the database.
// and loads enabled channels from the database. Each platform's factory lives
// in its own subpackage to keep this file focused on wiring.
func registerIMAdapterFactories(imService *imPkg.Service) {
ctx := context.Background()
// Register WeCom adapter factory
imService.RegisterAdapterFactory("wecom", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse wecom credentials: %w", err)
}
mode := channel.Mode
if mode == "" {
mode = "websocket"
}
switch mode {
case "webhook":
corpAgentID := 0
if v, ok := creds["corp_agent_id"]; ok {
switch val := v.(type) {
case float64:
corpAgentID = int(val)
case int:
corpAgentID = val
}
}
adapter, err := wecom.NewWebhookAdapter(
getString(creds, "corp_id"),
getString(creds, "agent_secret"),
getString(creds, "token"),
getString(creds, "encoding_aes_key"),
corpAgentID,
getString(creds, "api_base_url"),
)
if err != nil {
return nil, nil, err
}
return adapter, nil, nil
case "websocket":
client, err := wecom.NewLongConnClient(
getString(creds, "bot_id"),
getString(creds, "bot_secret"),
getString(creds, "ws_endpoint"),
getString(creds, "bot_name"),
msgHandler,
)
if err != nil {
return nil, nil, err
}
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] WeCom long connection stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := wecom.NewWSAdapter(client)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unknown WeCom mode: %s", mode)
}
})
// Register Feishu adapter factory
imService.RegisterAdapterFactory("feishu", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse feishu credentials: %w", err)
}
appID := getString(creds, "app_id")
appSecret := getString(creds, "app_secret")
verificationToken := getString(creds, "verification_token")
encryptKey := getString(creds, "encrypt_key")
// Always create the HTTP adapter (needed for SendReply in both modes)
adapter := feishu.NewAdapter(appID, appSecret, verificationToken, encryptKey)
mode := channel.Mode
if mode == "" {
mode = "websocket"
}
switch mode {
case "webhook":
return adapter, nil, nil
case "websocket":
client := feishu.NewLongConnClient(appID, appSecret, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Feishu long connection stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unknown Feishu mode: %s", mode)
}
})
// Register Slack adapter factory
imService.RegisterAdapterFactory("slack", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse slack credentials: %w", err)
}
mode := channel.Mode
if mode == "" {
mode = "websocket"
}
switch mode {
case "webhook":
api := slackpkg.New(getString(creds, "bot_token"))
adapter := slack.NewWebhookAdapter(api, getString(creds, "signing_secret"))
return adapter, func() {}, nil
case "websocket":
client := slack.NewLongConnClient(
getString(creds, "app_token"),
getString(creds, "bot_token"),
msgHandler,
)
adapter := slack.NewAdapter(client, client.GetAPI())
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Slack long connection stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported slack mode: %s", mode)
}
})
// Register Telegram adapter factory
imService.RegisterAdapterFactory("telegram", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse telegram credentials: %w", err)
}
botToken := getString(creds, "bot_token")
mode := channel.Mode
if mode == "" {
mode = "websocket"
}
switch mode {
case "webhook":
secretToken := getString(creds, "secret_token")
adapter := telegram.NewWebhookAdapter(botToken, secretToken)
return adapter, nil, nil
case "websocket":
client := telegram.NewLongConnClient(botToken, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Telegram long polling stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := telegram.NewAdapter(client, botToken)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported telegram mode: %s", mode)
}
})
// Register DingTalk adapter factory
imService.RegisterAdapterFactory("dingtalk", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse dingtalk credentials: %w", err)
}
clientID := getString(creds, "client_id")
clientSecret := getString(creds, "client_secret")
cardTemplateID := getString(creds, "card_template_id")
mode := channel.Mode
if mode == "" {
mode = "websocket"
}
switch mode {
case "webhook":
adapter := dingtalk.NewWebhookAdapter(clientID, clientSecret, cardTemplateID)
return adapter, nil, nil
case "websocket":
client := dingtalk.NewLongConnClient(clientID, clientSecret, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] DingTalk stream stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := dingtalk.NewAdapter(client, clientID, clientSecret, cardTemplateID)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported dingtalk mode: %s", mode)
}
})
// Register Mattermost adapter factory (outgoing webhook + REST API).
imService.RegisterAdapterFactory("mattermost", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)
}
mode := channel.Mode
if mode == "" {
mode = "webhook"
}
if mode != "webhook" {
return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)
}
siteURL := getString(creds, "site_url")
botToken := getString(creds, "bot_token")
outgoingToken := getString(creds, "outgoing_token")
botUserID := getString(creds, "bot_user_id")
if outgoingToken == "" {
return nil, nil, fmt.Errorf("mattermost outgoing_token is required")
}
client, err := mattermost.NewClient(siteURL, botToken)
if err != nil {
return nil, nil, err
}
postReplyToMain := credentialBool(creds, "post_to_main")
adapter := mattermost.NewAdapter(client, outgoingToken, botUserID, postReplyToMain)
return adapter, func() {}, nil
})
// Register WeChat adapter factory
imService.RegisterAdapterFactory("wechat", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
creds, err := parseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse wechat credentials: %w", err)
}
botToken := getString(creds, "bot_token")
ilinkBotID := getString(creds, "ilink_bot_id")
if botToken == "" || ilinkBotID == "" {
return nil, nil, fmt.Errorf("wechat credentials require bot_token and ilink_bot_id")
}
adapter := wechat.NewAdapter(botToken, ilinkBotID)
client := wechat.NewLongPollClient(botToken, ilinkBotID, msgHandler)
pollCtx, pollCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(pollCtx); err != nil && pollCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] WeChat long-poll stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, pollCancel, nil
})
imService.RegisterAdapterFactory("wecom", wecom.NewFactory())
imService.RegisterAdapterFactory("feishu", feishu.NewFactory())
imService.RegisterAdapterFactory("slack", slack.NewFactory())
imService.RegisterAdapterFactory("telegram", telegram.NewFactory())
imService.RegisterAdapterFactory("dingtalk", dingtalk.NewFactory())
imService.RegisterAdapterFactory("mattermost", mattermost.NewFactory())
imService.RegisterAdapterFactory("wechat", wechat.NewFactory())
// Load and start all enabled channels from database
if err := imService.LoadAndStartChannels(); err != nil {
logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err)
}
}
// parseCredentials parses the JSONB credentials field into a map.
func parseCredentials(data []byte) (map[string]interface{}, error) {
if len(data) == 0 {
return map[string]interface{}{}, nil
}
var creds map[string]interface{}
if err := json.Unmarshal(data, &creds); err != nil {
return nil, err
}
return creds, nil
}
// getString safely extracts a string value from a credentials map.
func getString(creds map[string]interface{}, key string) string {
if v, ok := creds[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// credentialBool reads a boolean from JSON credentials (bool, string "true"/"1", or non-zero number).
func credentialBool(creds map[string]interface{}, key string) bool {
v, ok := creds[key]
if !ok {
return false
}
switch x := v.(type) {
case bool:
return x
case string:
s := strings.TrimSpace(strings.ToLower(x))
return s == "true" || s == "1" || s == "yes"
case float64:
return x != 0
case int:
return x != 0
default:
return false
logger.Warnf(context.Background(), "[IM] Failed to load channels from database: %v", err)
}
}
+49
View File
@@ -0,0 +1,49 @@
package im
import (
"encoding/json"
"strings"
)
// ParseCredentials parses the JSONB credentials field into a map.
func ParseCredentials(data []byte) (map[string]any, error) {
if len(data) == 0 {
return map[string]any{}, nil
}
var creds map[string]any
if err := json.Unmarshal(data, &creds); err != nil {
return nil, err
}
return creds, nil
}
// GetString safely extracts a string value from a credentials map.
func GetString(creds map[string]any, key string) string {
if v, ok := creds[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// GetBool reads a boolean from JSON credentials (bool, string "true"/"1", or non-zero number).
func GetBool(creds map[string]any, key string) bool {
v, ok := creds[key]
if !ok {
return false
}
switch x := v.(type) {
case bool:
return x
case string:
s := strings.TrimSpace(strings.ToLower(x))
return s == "true" || s == "1" || s == "yes"
case float64:
return x != 0
case int:
return x != 0
default:
return false
}
}
+48
View File
@@ -0,0 +1,48 @@
package dingtalk
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for DingTalk channels.
// Supports "webhook" and "websocket" (stream mode, default).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse dingtalk credentials: %w", err)
}
clientID := im.GetString(creds, "client_id")
clientSecret := im.GetString(creds, "client_secret")
cardTemplateID := im.GetString(creds, "card_template_id")
mode := im.ResolveMode(channel, "websocket")
switch mode {
case "webhook":
adapter := NewWebhookAdapter(clientID, clientSecret, cardTemplateID)
return adapter, nil, nil
case "websocket":
client := NewLongConnClient(clientID, clientSecret, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] DingTalk stream stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := NewAdapter(client, clientID, clientSecret, cardTemplateID)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported dingtalk mode: %s", mode)
}
}
}
+51
View File
@@ -0,0 +1,51 @@
package feishu
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for Feishu (Lark) channels.
// The HTTP adapter is always created (needed for SendReply in both modes);
// "websocket" mode additionally runs a long-connection event stream.
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse feishu credentials: %w", err)
}
appID := im.GetString(creds, "app_id")
appSecret := im.GetString(creds, "app_secret")
verificationToken := im.GetString(creds, "verification_token")
encryptKey := im.GetString(creds, "encrypt_key")
// Always create the HTTP adapter (needed for SendReply in both modes)
adapter := NewAdapter(appID, appSecret, verificationToken, encryptKey)
mode := im.ResolveMode(channel, "websocket")
switch mode {
case "webhook":
return adapter, nil, nil
case "websocket":
client := NewLongConnClient(appID, appSecret, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Feishu long connection stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unknown Feishu mode: %s", mode)
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package mattermost
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
)
// NewFactory returns an im.AdapterFactory for Mattermost channels.
// Only "webhook" mode is supported (outgoing webhook + REST API);
// the default mode is "webhook" (not "websocket" like other platforms).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)
}
mode := im.ResolveMode(channel, "webhook")
if mode != "webhook" {
return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)
}
siteURL := im.GetString(creds, "site_url")
botToken := im.GetString(creds, "bot_token")
outgoingToken := im.GetString(creds, "outgoing_token")
botUserID := im.GetString(creds, "bot_user_id")
if outgoingToken == "" {
return nil, nil, fmt.Errorf("mattermost outgoing_token is required")
}
client, err := NewClient(siteURL, botToken)
if err != nil {
return nil, nil, err
}
postReplyToMain := im.GetBool(creds, "post_to_main")
adapter := NewAdapter(client, outgoingToken, botUserID, postReplyToMain)
return adapter, func() {}, nil
}
}
+9
View File
@@ -0,0 +1,9 @@
package im
// ResolveMode returns channel.Mode, falling back to def when it is empty.
func ResolveMode(channel *IMChannel, def string) string {
if channel.Mode == "" {
return def
}
return channel.Mode
}
+52
View File
@@ -0,0 +1,52 @@
package slack
import (
"context"
"fmt"
slackpkg "github.com/slack-go/slack"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for Slack channels.
// Supports "webhook" (Events API) and "websocket" (Socket Mode, default).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse slack credentials: %w", err)
}
mode := im.ResolveMode(channel, "websocket")
switch mode {
case "webhook":
api := slackpkg.New(im.GetString(creds, "bot_token"))
adapter := NewWebhookAdapter(api, im.GetString(creds, "signing_secret"))
return adapter, func() {}, nil
case "websocket":
client := NewLongConnClient(
im.GetString(creds, "app_token"),
im.GetString(creds, "bot_token"),
msgHandler,
)
adapter := NewAdapter(client, client.GetAPI())
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Slack long connection stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported slack mode: %s", mode)
}
}
}
+47
View File
@@ -0,0 +1,47 @@
package telegram
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for Telegram bot channels.
// Supports "webhook" and "websocket" (long polling, default).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse telegram credentials: %w", err)
}
botToken := im.GetString(creds, "bot_token")
mode := im.ResolveMode(channel, "websocket")
switch mode {
case "webhook":
secretToken := im.GetString(creds, "secret_token")
adapter := NewWebhookAdapter(botToken, secretToken)
return adapter, nil, nil
case "websocket":
client := NewLongConnClient(botToken, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] Telegram long polling stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := NewAdapter(client, botToken)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unsupported telegram mode: %s", mode)
}
}
}
+39
View File
@@ -0,0 +1,39 @@
package wechat
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for WeChat channels (iLink bot).
// WeChat only supports a long-polling mode, so there is no mode branch.
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse wechat credentials: %w", err)
}
botToken := im.GetString(creds, "bot_token")
ilinkBotID := im.GetString(creds, "ilink_bot_id")
if botToken == "" || ilinkBotID == "" {
return nil, nil, fmt.Errorf("wechat credentials require bot_token and ilink_bot_id")
}
adapter := NewAdapter(botToken, ilinkBotID)
client := NewLongPollClient(botToken, ilinkBotID, msgHandler)
pollCtx, pollCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(pollCtx); err != nil && pollCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] WeChat long-poll stopped for channel %s: %v", channel.ID, err)
}
}()
return adapter, pollCancel, nil
}
}
+72
View File
@@ -0,0 +1,72 @@
package wecom
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for WeCom channels.
// Supports two modes: "webhook" (HTTP callback) and "websocket" (long connection, default).
func NewFactory() im.AdapterFactory {
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
creds, err := im.ParseCredentials(channel.Credentials)
if err != nil {
return nil, nil, fmt.Errorf("parse wecom credentials: %w", err)
}
mode := im.ResolveMode(channel, "websocket")
switch mode {
case "webhook":
corpAgentID := 0
if v, ok := creds["corp_agent_id"]; ok {
switch val := v.(type) {
case float64:
corpAgentID = int(val)
case int:
corpAgentID = val
}
}
adapter, err := NewWebhookAdapter(
im.GetString(creds, "corp_id"),
im.GetString(creds, "agent_secret"),
im.GetString(creds, "token"),
im.GetString(creds, "encoding_aes_key"),
corpAgentID,
im.GetString(creds, "api_base_url"),
)
if err != nil {
return nil, nil, err
}
return adapter, nil, nil
case "websocket":
client, err := NewLongConnClient(
im.GetString(creds, "bot_id"),
im.GetString(creds, "bot_secret"),
im.GetString(creds, "ws_endpoint"),
im.GetString(creds, "bot_name"),
msgHandler,
)
if err != nil {
return nil, nil, err
}
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] WeCom long connection stopped for channel %s: %v", channel.ID, err)
}
}()
adapter := NewWSAdapter(client)
return adapter, wsCancel, nil
default:
return nil, nil, fmt.Errorf("unknown WeCom mode: %s", mode)
}
}
}