feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds (open.larksuite.com and open.feishu.cn). WeKnora touches both from two places — the IM bot and the Wiki data-source connector — and this brings Lark to parity across both. Neither API surface differs, so rather than duplicate either implementation, each is parametrized by a Region and registered twice. IM (internal/im/feishu): Every API call routes through a.api(), which prefixes the region's host, and the WebSocket client passes larkws.WithDomain — the SDK defaults to open.feishu.cn, so Lark long connections would otherwise fail to authenticate. Data source (internal/datasource/connector/feishu): Lark was half-supported: the client honoured a base_url override and a LarkBaseURL constant existed, but the connector registered only as "feishu" and the UI never exposed base_url, so Lark wikis could not be configured at all. Lark is now its own connector type. base_url is kept as an explicit override so data sources that pointed a "feishu" connector at open.larksuite.com keep working. Bugs found and fixed along the way: - Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in four places, so a Lark wiki linked into the wrong cloud entirely. - Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x). BotIdentity carries a unique index, so without this a Lark channel would be rejected as a duplicate of an unrelated Feishu bot sharing an app_id. - The card image cache is now keyed by app_id. image_keys are issued per app on one cloud; a Feishu key handed to a Lark app fails the card update with code=200570. - The datasource doc claimed Lark "adapts automatically" — it could not, since the UI had no way to reach base_url. Permissions are where the clouds genuinely diverge. Identical APIs do not mean identical permission catalogues: aily:file:read, aily:file:write and corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's scope JSON into Lark fails to import. That JSON is also over-broad (it covers products WeKnora never calls) and simultaneously incomplete (it omits the drive:*/docx:* scopes the connector needs). Lark therefore gets its own list, derived from the 17 endpoints the code actually calls and checked identifier-by-identifier against Lark's own API reference, plus a full Feishu→Lark mapping table marking each scope verified, unverified, or absent. Both features use tenant_access_token only — no user_access_ token exists anywhere in the repo — so the user dimension stays empty. Known limitation: Region.ThinkingText makes Lark's initial card placeholder English, but once streaming starts the think-block headers come from the shared MarkdownThinkStyle and are Chinese on every platform (Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a locale through FormatIMDisplayContent, which has no platform context — a cross-platform change, not a Lark one. Documented as such. The channel-creation 400 message is now derived from validIMPlatforms so the list cannot drift as platforms are added. Tests: region invariants and per-region URL construction on both sides, the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url override precedence, an end-to-end SendReply against a fake Open Platform (token fetch, reply, thread-unsupported fallback, hard-error surfacing), and a ListResources drive asserting wiki links never leak the other cloud's host. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
// Package feishu implements the Feishu (飞书/Lark) IM adapter for WeKnora.
|
||||
// Package feishu implements the Feishu (飞书) IM adapter for WeKnora, and with
|
||||
// it the Lark adapter: Feishu and Lark are the same product on two isolated
|
||||
// clouds (open.feishu.cn and open.larksuite.com) sharing one API surface, so a
|
||||
// single implementation serves both. A Region picks the cloud — see region.go.
|
||||
//
|
||||
// Feishu bot flow:
|
||||
// Bot flow:
|
||||
// 1. User sends a message to the bot (direct or @mention in group)
|
||||
// 2. Feishu calls our event subscription URL with the message event
|
||||
// 3. We parse the event, run QA, then call Feishu API to send reply
|
||||
// 2. Feishu/Lark calls our event subscription URL with the message event
|
||||
// 3. We parse the event, run QA, then call the Open Platform API to send a reply
|
||||
// 4. For streaming: create a card, then use CardKit streaming update API
|
||||
//
|
||||
// Reference: https://open.feishu.cn/document/server-docs/im-v1/message/create
|
||||
@@ -40,6 +43,7 @@ var httpClient = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// Adapter implements im.Adapter for Feishu/Lark.
|
||||
type Adapter struct {
|
||||
region Region
|
||||
appID string
|
||||
appSecret string
|
||||
verificationToken string
|
||||
@@ -51,10 +55,11 @@ type Adapter struct {
|
||||
tokenExpAt time.Time
|
||||
}
|
||||
|
||||
// NewAdapter creates a new Feishu adapter.
|
||||
func NewAdapter(appID, appSecret, verificationToken, encryptKey string) *Adapter {
|
||||
// NewAdapter creates a new adapter for the given region (RegionFeishu or RegionLark).
|
||||
func NewAdapter(region Region, appID, appSecret, verificationToken, encryptKey string) *Adapter {
|
||||
startStreamReaper()
|
||||
return &Adapter{
|
||||
region: region,
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
verificationToken: verificationToken,
|
||||
@@ -62,6 +67,12 @@ func NewAdapter(appID, appSecret, verificationToken, encryptKey string) *Adapter
|
||||
}
|
||||
}
|
||||
|
||||
// api builds an Open Platform API URL on this adapter's cloud. path is a format
|
||||
// string beginning with "/open-apis/"; args fill its verbs.
|
||||
func (a *Adapter) api(path string, args ...any) string {
|
||||
return a.region.OpenBaseURL + fmt.Sprintf(path, args...)
|
||||
}
|
||||
|
||||
// startStreamReaper starts a background goroutine (once) that periodically
|
||||
// removes orphaned stream entries from feishuStreams. This prevents memory
|
||||
// leaks when EndStream is never called due to panics or pipeline errors.
|
||||
@@ -102,7 +113,7 @@ func StopStreamReaper() {
|
||||
|
||||
// Platform returns the platform identifier.
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
return im.PlatformFeishu
|
||||
return a.region.Platform
|
||||
}
|
||||
|
||||
// VerifyCallback verifies the Feishu event callback by checking the verification token.
|
||||
@@ -167,7 +178,7 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
if err := json.Unmarshal(bodyBytes, &encryptedBody); err == nil && encryptedBody.Encrypt != "" {
|
||||
decrypted, err := a.decrypt(encryptedBody.Encrypt)
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "[Feishu] Failed to decrypt: %v", err)
|
||||
logger.Errorf(c.Request.Context(), "[%s] Failed to decrypt: %v", a.region.Label, err)
|
||||
return false
|
||||
}
|
||||
if err := json.Unmarshal(decrypted, &body); err != nil {
|
||||
@@ -257,7 +268,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
// Check event type
|
||||
if eventBody.Header == nil || eventBody.Header.EventType != "im.message.receive_v1" {
|
||||
if eventBody.Header != nil {
|
||||
logger.Infof(c.Request.Context(), "[Feishu] Ignoring event type: %s", eventBody.Header.EventType)
|
||||
logger.Infof(c.Request.Context(), "[%s] Ignoring event type: %s", a.region.Label, eventBody.Header.EventType)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
@@ -312,7 +323,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: a.region.Platform,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -334,7 +345,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
return nil, nil
|
||||
}
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: a.region.Platform,
|
||||
MessageType: im.MessageTypeFile,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -356,7 +367,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
return nil, nil
|
||||
}
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: a.region.Platform,
|
||||
MessageType: im.MessageTypeImage,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -418,7 +429,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: a.region.Platform,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -429,7 +440,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
}, nil
|
||||
|
||||
default:
|
||||
logger.Infof(c.Request.Context(), "[Feishu] Ignoring unsupported message type: %s", msg.MessageType)
|
||||
logger.Infof(c.Request.Context(), "[%s] Ignoring unsupported message type: %s", a.region.Label, msg.MessageType)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
@@ -514,20 +525,21 @@ func (a *Adapter) sendWithFallback(
|
||||
// some event payloads omit it), skip straight to the fallback send API —
|
||||
// the reply API needs a message_id in the path and can't work without one.
|
||||
if incoming.MessageID != "" && feishuSafePathParam(incoming.MessageID) {
|
||||
replyURL := fmt.Sprintf("https://open.feishu.cn/open-apis/im/v1/messages/%s/reply", incoming.MessageID)
|
||||
replyURL := a.api("/open-apis/im/v1/messages/%s/reply", incoming.MessageID)
|
||||
code, msg, err := a.postFeishuMessage(ctx, accessToken, replyURL, replyPayload)
|
||||
switch {
|
||||
case err != nil:
|
||||
// Network/transport error — try the fallback since send-message is
|
||||
// a different endpoint that might succeed.
|
||||
logger.Warnf(ctx, "[Feishu] reply API transport error (will try fallback): %v", err)
|
||||
logger.Warnf(ctx, "[%s] reply API transport error (will try fallback): %v", a.region.Label, err)
|
||||
case code == 0:
|
||||
return nil
|
||||
case !fallbackEligibleErrorCodes[code]:
|
||||
return fmt.Errorf("feishu reply api error: code=%d msg=%s", code, msg)
|
||||
return fmt.Errorf("%s reply api error: code=%d msg=%s", a.region.Label, code, msg)
|
||||
default:
|
||||
// Fallback-eligible: retry via plain send-message API.
|
||||
logger.Warnf(ctx, "[Feishu] reply API returned code=%d msg=%s, falling back to send-message API", code, msg)
|
||||
logger.Warnf(ctx, "[%s] reply API returned code=%d msg=%s, falling back to send-message API",
|
||||
a.region.Label, code, msg)
|
||||
}
|
||||
} else if incoming.MessageID != "" {
|
||||
// message_id present but contains unsafe characters — refuse rather
|
||||
@@ -535,17 +547,19 @@ func (a *Adapter) sendWithFallback(
|
||||
// id suggests a tampered payload.
|
||||
return fmt.Errorf("invalid message_id for reply API: %q", incoming.MessageID)
|
||||
} else {
|
||||
logger.Warnf(ctx, "[Feishu] incoming message has no message_id; replying via send-message API (will not attach to thread)")
|
||||
logger.Warnf(ctx,
|
||||
"[%s] incoming message has no message_id; replying via send-message API (will not attach to thread)",
|
||||
a.region.Label)
|
||||
}
|
||||
|
||||
// Fallback: plain send-message API.
|
||||
fallbackURL := fmt.Sprintf("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=%s", receiveIDType)
|
||||
fallbackURL := a.api("/open-apis/im/v1/messages?receive_id_type=%s", receiveIDType)
|
||||
code, msg, err := a.postFeishuMessage(ctx, accessToken, fallbackURL, fallbackPayload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send message (fallback): %w", err)
|
||||
}
|
||||
if code != 0 {
|
||||
return fmt.Errorf("feishu send api error: code=%d msg=%s", code, msg)
|
||||
return fmt.Errorf("%s send api error: code=%d msg=%s", a.region.Label, code, msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -616,7 +630,7 @@ func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io
|
||||
resourceType = "image"
|
||||
}
|
||||
|
||||
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/im/v1/messages/%s/resources/%s?type=%s",
|
||||
apiURL := a.api("/open-apis/im/v1/messages/%s/resources/%s?type=%s",
|
||||
msg.MessageID, msg.FileKey, resourceType)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil)
|
||||
@@ -700,12 +714,14 @@ func (s *feishuStreamState) nextSeq() int {
|
||||
}
|
||||
|
||||
// buildStreamingCardJSON builds a Card JSON 2.0 with streaming_mode enabled.
|
||||
func buildStreamingCardJSON() string {
|
||||
// The placeholder text follows the region so Lark users see English rather than
|
||||
// the Chinese wording Feishu users expect.
|
||||
func buildStreamingCardJSON(region Region) string {
|
||||
card := map[string]interface{}{
|
||||
"schema": "2.0",
|
||||
"config": map[string]interface{}{
|
||||
"streaming_mode": true,
|
||||
"summary": map[string]string{"content": "正在思考..."},
|
||||
"summary": map[string]string{"content": region.ThinkingText},
|
||||
},
|
||||
"header": map[string]interface{}{
|
||||
"template": "blue",
|
||||
@@ -715,7 +731,7 @@ func buildStreamingCardJSON() string {
|
||||
"elements": []map[string]interface{}{
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": "💭 正在思考...",
|
||||
"content": "💭 " + region.ThinkingText,
|
||||
"text_size": "normal",
|
||||
"element_id": streamingElementID,
|
||||
},
|
||||
@@ -734,7 +750,7 @@ func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage)
|
||||
}
|
||||
|
||||
// 1. Create card entity via CardKit API
|
||||
cardJSON := buildStreamingCardJSON()
|
||||
cardJSON := buildStreamingCardJSON(a.region)
|
||||
cardID, err := a.cardkitCreate(ctx, accessToken, cardJSON)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create card: %w", err)
|
||||
@@ -750,7 +766,7 @@ func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage)
|
||||
feishuStreams[cardID] = &feishuStreamState{createdAt: time.Now()}
|
||||
feishuStreamsMu.Unlock()
|
||||
|
||||
logger.Infof(ctx, "[Feishu] Streaming started: card_id=%s", cardID)
|
||||
logger.Infof(ctx, "[%s] Streaming started: card_id=%s", a.region.Label, cardID)
|
||||
return cardID, nil
|
||||
}
|
||||
|
||||
@@ -820,10 +836,10 @@ func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, s
|
||||
|
||||
// Turn off streaming_mode to remove loading indicator
|
||||
if err := a.cardkitSetStreaming(ctx, accessToken, streamID, false, seq); err != nil {
|
||||
logger.Warnf(ctx, "[Feishu] Failed to disable streaming_mode: %v", err)
|
||||
logger.Warnf(ctx, "[%s] Failed to disable streaming_mode: %v", a.region.Label, err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Feishu] Streaming ended: card_id=%s", streamID)
|
||||
logger.Infof(ctx, "[%s] Streaming ended: card_id=%s", a.region.Label, streamID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -838,7 +854,7 @@ func (a *Adapter) cardkitCreate(ctx context.Context, accessToken, cardJSON strin
|
||||
})
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://open.feishu.cn/open-apis/cardkit/v1/cards", bytes.NewReader(payload))
|
||||
a.api("/open-apis/cardkit/v1/cards"), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -915,8 +931,7 @@ func (a *Adapter) cardkitUpdateElement(ctx context.Context, accessToken, cardID,
|
||||
"sequence": sequence,
|
||||
})
|
||||
|
||||
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/cardkit/v1/cards/%s/elements/%s/content",
|
||||
cardID, elementID)
|
||||
apiURL := a.api("/open-apis/cardkit/v1/cards/%s/elements/%s/content", cardID, elementID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, apiURL, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -991,10 +1006,10 @@ func (a *Adapter) resolveMarkdownImages(ctx context.Context, accessToken, conten
|
||||
alt, rawURL := sub[1], sub[2]
|
||||
imgKey, err := a.imageKeyForURL(ctx, accessToken, rawURL)
|
||||
if err != nil || imgKey == "" {
|
||||
logger.Warnf(ctx, "[Feishu] image upload failed, degrading to link: url=%s err=%v", rawURL, err)
|
||||
logger.Warnf(ctx, "[%s] image upload failed, degrading to link: url=%s err=%v", a.region.Label, rawURL, err)
|
||||
label := alt
|
||||
if label == "" {
|
||||
label = "图片"
|
||||
label = a.region.ImageFallbackLabel
|
||||
}
|
||||
return fmt.Sprintf("[%s](%s)", label, rawURL)
|
||||
}
|
||||
@@ -1005,7 +1020,10 @@ func (a *Adapter) resolveMarkdownImages(ctx context.Context, accessToken, conten
|
||||
// imageKeyForURL returns a Feishu image_key for the given URL, uploading it if
|
||||
// not already cached.
|
||||
func (a *Adapter) imageKeyForURL(ctx context.Context, accessToken, rawURL string) (string, error) {
|
||||
key := imageCacheKey(rawURL)
|
||||
// image_keys are issued per app on a single cloud. Scope the cache by app so
|
||||
// a key uploaded by a Feishu app is never handed to a Lark app (or to another
|
||||
// tenant's app), which would fail the card update with code=200570.
|
||||
key := a.appID + "\x00" + imageCacheKey(rawURL)
|
||||
|
||||
feishuImageKeyMu.Lock()
|
||||
if v, ok := feishuImageKeyCache[key]; ok {
|
||||
@@ -1074,7 +1092,7 @@ func (a *Adapter) uploadImageFromURL(ctx context.Context, accessToken, rawURL st
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://open.feishu.cn/open-apis/im/v1/images", &body)
|
||||
a.api("/open-apis/im/v1/images"), &body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -1117,7 +1135,7 @@ func (a *Adapter) cardkitSetStreaming(ctx context.Context, accessToken, cardID s
|
||||
"sequence": sequence,
|
||||
})
|
||||
|
||||
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/cardkit/v1/cards/%s/settings", cardID)
|
||||
apiURL := a.api("/open-apis/cardkit/v1/cards/%s/settings", cardID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, apiURL, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1160,7 +1178,7 @@ func (a *Adapter) getTenantAccessToken(ctx context.Context) (string, error) {
|
||||
})
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
|
||||
a.api("/open-apis/auth/v3/tenant_access_token/internal"),
|
||||
bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create request: %w", err)
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestImageCacheKey_StripsQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestResolveMarkdownImages_NoImageUnchanged(t *testing.T) {
|
||||
a := &Adapter{}
|
||||
a := &Adapter{region: RegionFeishu}
|
||||
in := "hello **world** [link](https://example.com)"
|
||||
if got := a.resolveMarkdownImages(context.Background(), "tok", in); got != in {
|
||||
t.Errorf("content without image was modified: %q", got)
|
||||
@@ -77,7 +77,7 @@ func TestResolveMarkdownImages_NoImageUnchanged(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestResolveMarkdownImages_FallbackToLinkOnFailure(t *testing.T) {
|
||||
a := &Adapter{}
|
||||
a := &Adapter{region: RegionFeishu}
|
||||
// A direct-IP loopback URL fails SSRF validation before any network call,
|
||||
// so the image must degrade to a plain markdown link (never left as ![]()).
|
||||
in := "see  here"
|
||||
@@ -89,3 +89,16 @@ func TestResolveMarkdownImages_FallbackToLinkOnFailure(t *testing.T) {
|
||||
t.Errorf("expected link fallback with alt text, got: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An image with no alt text falls back to the region's own label, so Lark users
|
||||
// do not get a Chinese link label.
|
||||
func TestResolveMarkdownImages_FallbackLabelFollowsRegion(t *testing.T) {
|
||||
for _, region := range []Region{RegionFeishu, RegionLark} {
|
||||
a := &Adapter{region: region}
|
||||
got := a.resolveMarkdownImages(context.Background(), "tok", "")
|
||||
want := "[" + region.ImageFallbackLabel + "](http://127.0.0.1/x.png)"
|
||||
if got != want {
|
||||
t.Errorf("%s fallback = %q, want %q", region.Label, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,14 +8,17 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// NewFactory returns an im.AdapterFactory for Feishu (Lark) channels.
|
||||
// NewFactory returns an im.AdapterFactory for channels on the given region's
|
||||
// cloud — RegionFeishu for 飞书, RegionLark for Lark. Both use the same
|
||||
// credentials and modes; only the API host and tenant differ.
|
||||
//
|
||||
// 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 {
|
||||
func NewFactory(region Region) 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)
|
||||
return nil, nil, fmt.Errorf("parse %s credentials: %w", region.Platform, err)
|
||||
}
|
||||
|
||||
appID := im.GetString(creds, "app_id")
|
||||
@@ -24,7 +27,7 @@ func NewFactory() im.AdapterFactory {
|
||||
encryptKey := im.GetString(creds, "encrypt_key")
|
||||
|
||||
// Always create the HTTP adapter (needed for SendReply in both modes)
|
||||
adapter := NewAdapter(appID, appSecret, verificationToken, encryptKey)
|
||||
adapter := NewAdapter(region, appID, appSecret, verificationToken, encryptKey)
|
||||
|
||||
mode := im.ResolveMode(channel, "websocket")
|
||||
|
||||
@@ -33,12 +36,13 @@ func NewFactory() im.AdapterFactory {
|
||||
return adapter, nil, nil
|
||||
|
||||
case "websocket":
|
||||
client := NewLongConnClient(appID, appSecret, msgHandler)
|
||||
client := NewLongConnClient(region, 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)
|
||||
logger.Errorf(context.Background(), "[IM] %s long connection stopped for channel %s: %v",
|
||||
region.Label, channel.ID, err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -54,7 +58,7 @@ func NewFactory() im.AdapterFactory {
|
||||
return adapter, stop, nil
|
||||
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unknown Feishu mode: %s", mode)
|
||||
return nil, nil, fmt.Errorf("unknown %s mode: %s", region.Platform, mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,46 +16,50 @@ import (
|
||||
// MessageHandler is called when an IM message is received via long connection.
|
||||
type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error
|
||||
|
||||
// LongConnClient manages a Feishu WebSocket long connection.
|
||||
// LongConnClient manages a Feishu/Lark WebSocket long connection.
|
||||
type LongConnClient struct {
|
||||
region Region
|
||||
appID string
|
||||
wsClient *larkws.Client
|
||||
}
|
||||
|
||||
// NewLongConnClient creates a Feishu long connection client.
|
||||
// When a text message arrives, it converts it to IncomingMessage and calls handler.
|
||||
func NewLongConnClient(appID, appSecret string, handler MessageHandler) *LongConnClient {
|
||||
// NewLongConnClient creates a long connection client on the given region's cloud.
|
||||
// When a message arrives, it converts it to IncomingMessage and calls handler.
|
||||
func NewLongConnClient(region Region, appID, appSecret string, handler MessageHandler) *LongConnClient {
|
||||
// Long connection mode does not require verificationToken or encryptKey;
|
||||
// those are only used for webhook signature verification and decryption.
|
||||
eventHandler := dispatcher.NewEventDispatcher("", "").
|
||||
OnP2MessageReceiveV1(func(ctx context.Context, event *larkim.P2MessageReceiveV1) error {
|
||||
msg := convertEvent(event)
|
||||
msg := convertEvent(region, event)
|
||||
if msg == nil {
|
||||
return nil
|
||||
}
|
||||
return handler(ctx, msg)
|
||||
})
|
||||
|
||||
sdkLogger := &feishuLoggerAdapter{appID: appID}
|
||||
sdkLogger := &feishuLoggerAdapter{region: region, appID: appID}
|
||||
|
||||
// WithDomain points the SDK at the region's cloud. It defaults to
|
||||
// open.feishu.cn, so Lark apps would otherwise fail to authenticate.
|
||||
wsClient := larkws.NewClient(appID, appSecret,
|
||||
larkws.WithEventHandler(eventHandler),
|
||||
larkws.WithAutoReconnect(true),
|
||||
larkws.WithLogger(sdkLogger),
|
||||
larkws.WithDomain(region.OpenBaseURL),
|
||||
)
|
||||
|
||||
return &LongConnClient{appID: appID, wsClient: wsClient}
|
||||
return &LongConnClient{region: region, appID: appID, wsClient: wsClient}
|
||||
}
|
||||
|
||||
// Start begins the WebSocket long connection. It blocks until ctx is cancelled.
|
||||
func (c *LongConnClient) Start(ctx context.Context) error {
|
||||
logger.Infof(ctx, "[IM] Feishu WebSocket connecting (app_id=%s)...", c.appID)
|
||||
logger.Infof(ctx, "[IM] %s WebSocket connecting (app_id=%s)...", c.region.Label, c.appID)
|
||||
return c.wsClient.Start(ctx)
|
||||
}
|
||||
|
||||
// Close tears down the WebSocket long connection.
|
||||
//
|
||||
// This is the only reliable way to stop a Feishu long connection: the SDK's
|
||||
// This is the only reliable way to stop a long connection: the SDK's
|
||||
// Start blocks on a bare select{} and neither Start, pingLoop, nor
|
||||
// receiveMessageLoop observe the passed context, so cancelling ctx alone leaves
|
||||
// the underlying socket alive and the SDK auto-reconnecting. Client.Close()
|
||||
@@ -66,48 +70,50 @@ func (c *LongConnClient) Close() {
|
||||
c.wsClient.Close()
|
||||
}
|
||||
|
||||
// feishuLoggerAdapter bridges the Feishu SDK logger to our unified logger,
|
||||
// feishuLoggerAdapter bridges the Feishu/Lark SDK logger to our unified logger,
|
||||
// replacing raw SDK connection messages with a consistent format.
|
||||
type feishuLoggerAdapter struct {
|
||||
appID string
|
||||
region Region
|
||||
appID string
|
||||
}
|
||||
|
||||
func (l *feishuLoggerAdapter) Debug(ctx context.Context, args ...interface{}) {
|
||||
logger.Debugf(ctx, "[Feishu] %s", fmt.Sprint(args...))
|
||||
logger.Debugf(ctx, "[%s] %s", l.region.Label, fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
func (l *feishuLoggerAdapter) Info(ctx context.Context, args ...interface{}) {
|
||||
msg := fmt.Sprint(args...)
|
||||
if strings.HasPrefix(msg, "connected to ") {
|
||||
logger.Infof(ctx, "[IM] Feishu WebSocket connected successfully (app_id=%s)", l.appID)
|
||||
logger.Infof(ctx, "[IM] %s WebSocket connected successfully (app_id=%s)", l.region.Label, l.appID)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "[Feishu] %s", msg)
|
||||
logger.Infof(ctx, "[%s] %s", l.region.Label, msg)
|
||||
}
|
||||
|
||||
func (l *feishuLoggerAdapter) Warn(ctx context.Context, args ...interface{}) {
|
||||
logger.Warnf(ctx, "[Feishu] %s", fmt.Sprint(args...))
|
||||
logger.Warnf(ctx, "[%s] %s", l.region.Label, fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
func (l *feishuLoggerAdapter) Error(ctx context.Context, args ...interface{}) {
|
||||
logger.Errorf(ctx, "[Feishu] %s", fmt.Sprint(args...))
|
||||
logger.Errorf(ctx, "[%s] %s", l.region.Label, fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// convertEvent converts a Feishu SDK event to a unified IncomingMessage.
|
||||
// Supports text and file messages. Returns nil for unsupported types.
|
||||
func convertEvent(event *larkim.P2MessageReceiveV1) *im.IncomingMessage {
|
||||
// convertEvent converts a Feishu/Lark SDK event to a unified IncomingMessage.
|
||||
// Supports text, file, image and post messages. Returns nil for other types.
|
||||
func convertEvent(region Region, event *larkim.P2MessageReceiveV1) *im.IncomingMessage {
|
||||
if event == nil || event.Event == nil || event.Event.Message == nil {
|
||||
logger.Warnf(context.Background(), "[Feishu][RX] event dropped: nil event/event/message")
|
||||
logger.Warnf(context.Background(), "[%s][RX] event dropped: nil event/event/message", region.Label)
|
||||
return nil
|
||||
}
|
||||
|
||||
msg := event.Event.Message
|
||||
|
||||
// Debug: log every raw receive event so we can see exactly what Feishu
|
||||
// Debug: log every raw receive event so we can see exactly what the platform
|
||||
// delivers (or doesn't). This is the single chokepoint for all message
|
||||
// types — adding it here catches text/file/image/post uniformly.
|
||||
logger.Infof(context.Background(),
|
||||
"[Feishu][RX] msg_type=%q chat_type=%q chat_id=%q msg_id=%q root_id=%q parent_id=%q thread_id=%q content=%q",
|
||||
"[%s][RX] msg_type=%q chat_type=%q chat_id=%q msg_id=%q root_id=%q parent_id=%q thread_id=%q content=%q",
|
||||
region.Label,
|
||||
ptrStr(msg.MessageType), ptrStr(msg.ChatType), ptrStr(msg.ChatId),
|
||||
ptrStr(msg.MessageId), ptrStr(msg.RootId), ptrStr(msg.ParentId),
|
||||
ptrStr(msg.ThreadId), ptrStr(msg.Content),
|
||||
@@ -143,20 +149,23 @@ func convertEvent(event *larkim.P2MessageReceiveV1) *im.IncomingMessage {
|
||||
|
||||
switch msgType {
|
||||
case "text":
|
||||
return convertTextEvent(msg, openID, chatID, chatType, messageID)
|
||||
return convertTextEvent(region, msg, openID, chatID, chatType, messageID)
|
||||
case "file":
|
||||
return convertFileEvent(msg, openID, chatID, chatType, messageID)
|
||||
return convertFileEvent(region, msg, openID, chatID, chatType, messageID)
|
||||
case "image":
|
||||
return convertImageEvent(msg, openID, chatID, chatType, messageID)
|
||||
return convertImageEvent(region, msg, openID, chatID, chatType, messageID)
|
||||
case "post":
|
||||
return convertPostEvent(msg, openID, chatID, chatType, messageID)
|
||||
return convertPostEvent(region, msg, openID, chatID, chatType, messageID)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// convertTextEvent handles text message type.
|
||||
func convertTextEvent(msg *larkim.EventMessage, openID, chatID string, chatType im.ChatType, messageID string) *im.IncomingMessage {
|
||||
func convertTextEvent(
|
||||
region Region, msg *larkim.EventMessage,
|
||||
openID, chatID string, chatType im.ChatType, messageID string,
|
||||
) *im.IncomingMessage {
|
||||
var textContent struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
@@ -180,7 +189,7 @@ func convertTextEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: region.Platform,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -191,7 +200,10 @@ func convertTextEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
}
|
||||
|
||||
// convertFileEvent handles file message type.
|
||||
func convertFileEvent(msg *larkim.EventMessage, openID, chatID string, chatType im.ChatType, messageID string) *im.IncomingMessage {
|
||||
func convertFileEvent(
|
||||
region Region, msg *larkim.EventMessage,
|
||||
openID, chatID string, chatType im.ChatType, messageID string,
|
||||
) *im.IncomingMessage {
|
||||
if msg.Content == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -207,7 +219,7 @@ func convertFileEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: region.Platform,
|
||||
MessageType: im.MessageTypeFile,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -220,7 +232,10 @@ func convertFileEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
|
||||
// convertImageEvent handles image message type.
|
||||
// Downloads via GetMessageResource API with type=image.
|
||||
func convertImageEvent(msg *larkim.EventMessage, openID, chatID string, chatType im.ChatType, messageID string) *im.IncomingMessage {
|
||||
func convertImageEvent(
|
||||
region Region, msg *larkim.EventMessage,
|
||||
openID, chatID string, chatType im.ChatType, messageID string,
|
||||
) *im.IncomingMessage {
|
||||
if msg.Content == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -235,7 +250,7 @@ func convertImageEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: region.Platform,
|
||||
MessageType: im.MessageTypeImage,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
@@ -248,7 +263,10 @@ func convertImageEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
|
||||
// convertPostEvent handles rich-text (post) message type.
|
||||
// Extracts all plain text content and treats it as a text query for QA.
|
||||
func convertPostEvent(msg *larkim.EventMessage, openID, chatID string, chatType im.ChatType, messageID string) *im.IncomingMessage {
|
||||
func convertPostEvent(
|
||||
region Region, msg *larkim.EventMessage,
|
||||
openID, chatID string, chatType im.ChatType, messageID string,
|
||||
) *im.IncomingMessage {
|
||||
if msg.Content == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -307,7 +325,7 @@ func convertPostEvent(msg *larkim.EventMessage, openID, chatID string, chatType
|
||||
}
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformFeishu,
|
||||
Platform: region.Platform,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: openID,
|
||||
ChatID: chatID,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package feishu
|
||||
|
||||
import "github.com/Tencent/WeKnora/internal/im"
|
||||
|
||||
// Open Platform API origins. Feishu and Lark are the same product deployed on
|
||||
// two isolated clouds; the API surface is identical, only the host differs.
|
||||
const (
|
||||
feishuOpenBaseURL = "https://open.feishu.cn"
|
||||
larkOpenBaseURL = "https://open.larksuite.com"
|
||||
)
|
||||
|
||||
// Region selects which cloud an adapter talks to. Apps, tenants, tokens and
|
||||
// resource keys (image_key, file_key, card_id) are scoped to a single cloud and
|
||||
// are never valid on the other, so a Region is fixed per channel at creation.
|
||||
type Region struct {
|
||||
// Platform is the im.Platform reported on messages parsed by this adapter.
|
||||
Platform im.Platform
|
||||
// OpenBaseURL is the Open Platform API origin, without a trailing slash.
|
||||
OpenBaseURL string
|
||||
// Label prefixes log lines so operators can tell the clouds apart.
|
||||
Label string
|
||||
// ThinkingText is the placeholder shown in a streaming card before the
|
||||
// first answer chunk arrives.
|
||||
ThinkingText string
|
||||
// ImageFallbackLabel labels the plain link an image degrades to when it
|
||||
// cannot be uploaded to the platform.
|
||||
ImageFallbackLabel string
|
||||
}
|
||||
|
||||
var (
|
||||
// RegionFeishu is the Chinese mainland cloud (飞书). Its users are addressed
|
||||
// in Chinese, matching the console and app language.
|
||||
RegionFeishu = Region{
|
||||
Platform: im.PlatformFeishu,
|
||||
OpenBaseURL: feishuOpenBaseURL,
|
||||
Label: "Feishu",
|
||||
ThinkingText: "正在思考...",
|
||||
ImageFallbackLabel: "图片",
|
||||
}
|
||||
|
||||
// RegionLark is the international cloud (Lark), addressed in English.
|
||||
RegionLark = Region{
|
||||
Platform: im.PlatformLark,
|
||||
OpenBaseURL: larkOpenBaseURL,
|
||||
Label: "Lark",
|
||||
ThinkingText: "Thinking...",
|
||||
ImageFallbackLabel: "Image",
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
package feishu
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
)
|
||||
|
||||
// The two regions must stay distinct in every dimension that reaches the
|
||||
// network or the session store: sending a Lark request to open.feishu.cn fails
|
||||
// authentication, and reporting the wrong platform merges the two clouds'
|
||||
// sessions together.
|
||||
func TestRegions_AreDistinct(t *testing.T) {
|
||||
if RegionFeishu.OpenBaseURL == RegionLark.OpenBaseURL {
|
||||
t.Errorf("regions share OpenBaseURL %q", RegionFeishu.OpenBaseURL)
|
||||
}
|
||||
if RegionFeishu.Platform == RegionLark.Platform {
|
||||
t.Errorf("regions share Platform %q", RegionFeishu.Platform)
|
||||
}
|
||||
if RegionFeishu.Platform != im.PlatformFeishu {
|
||||
t.Errorf("RegionFeishu.Platform = %q, want %q", RegionFeishu.Platform, im.PlatformFeishu)
|
||||
}
|
||||
if RegionLark.Platform != im.PlatformLark {
|
||||
t.Errorf("RegionLark.Platform = %q, want %q", RegionLark.Platform, im.PlatformLark)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegions_BaseURLHosts(t *testing.T) {
|
||||
cases := []struct {
|
||||
region Region
|
||||
want string
|
||||
}{
|
||||
{RegionFeishu, "https://open.feishu.cn"},
|
||||
{RegionLark, "https://open.larksuite.com"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if c.region.OpenBaseURL != c.want {
|
||||
t.Errorf("%s OpenBaseURL = %q, want %q", c.region.Label, c.region.OpenBaseURL, c.want)
|
||||
}
|
||||
if strings.HasSuffix(c.region.OpenBaseURL, "/") {
|
||||
t.Errorf("%s OpenBaseURL has a trailing slash: %q", c.region.Label, c.region.OpenBaseURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every API call must land on the region's own cloud.
|
||||
func TestAdapterAPI_UsesRegionHost(t *testing.T) {
|
||||
cases := []struct {
|
||||
region Region
|
||||
wantPrefix string
|
||||
}{
|
||||
{RegionFeishu, "https://open.feishu.cn/open-apis/"},
|
||||
{RegionLark, "https://open.larksuite.com/open-apis/"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
a := NewAdapter(c.region, "cli_app", "secret", "", "")
|
||||
|
||||
got := a.api("/open-apis/im/v1/messages/%s/reply", "om_1")
|
||||
want := c.wantPrefix + "im/v1/messages/om_1/reply"
|
||||
if got != want {
|
||||
t.Errorf("%s api() = %q, want %q", c.region.Label, got, want)
|
||||
}
|
||||
|
||||
// A path with no format verbs must survive unchanged.
|
||||
if got := a.api("/open-apis/cardkit/v1/cards"); got != c.wantPrefix+"cardkit/v1/cards" {
|
||||
t.Errorf("%s api() = %q, want %q", c.region.Label, got, c.wantPrefix+"cardkit/v1/cards")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterPlatform_FollowsRegion(t *testing.T) {
|
||||
if got := NewAdapter(RegionFeishu, "a", "b", "", "").Platform(); got != im.PlatformFeishu {
|
||||
t.Errorf("Feishu adapter Platform() = %q, want %q", got, im.PlatformFeishu)
|
||||
}
|
||||
if got := NewAdapter(RegionLark, "a", "b", "", "").Platform(); got != im.PlatformLark {
|
||||
t.Errorf("Lark adapter Platform() = %q, want %q", got, im.PlatformLark)
|
||||
}
|
||||
}
|
||||
|
||||
// The streaming card placeholder follows the region so Lark users are not shown
|
||||
// Chinese copy.
|
||||
func TestBuildStreamingCardJSON_PlaceholderFollowsRegion(t *testing.T) {
|
||||
for _, region := range []Region{RegionFeishu, RegionLark} {
|
||||
raw := buildStreamingCardJSON(region)
|
||||
|
||||
var card struct {
|
||||
Config struct {
|
||||
StreamingMode bool `json:"streaming_mode"`
|
||||
Summary struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"summary"`
|
||||
} `json:"config"`
|
||||
Body struct {
|
||||
Elements []struct {
|
||||
Content string `json:"content"`
|
||||
ElementID string `json:"element_id"`
|
||||
} `json:"elements"`
|
||||
} `json:"body"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &card); err != nil {
|
||||
t.Fatalf("%s card is not valid JSON: %v", region.Label, err)
|
||||
}
|
||||
|
||||
if !card.Config.StreamingMode {
|
||||
t.Errorf("%s card has streaming_mode disabled", region.Label)
|
||||
}
|
||||
if card.Config.Summary.Content != region.ThinkingText {
|
||||
t.Errorf("%s summary = %q, want %q", region.Label, card.Config.Summary.Content, region.ThinkingText)
|
||||
}
|
||||
if len(card.Body.Elements) != 1 {
|
||||
t.Fatalf("%s card has %d elements, want 1", region.Label, len(card.Body.Elements))
|
||||
}
|
||||
el := card.Body.Elements[0]
|
||||
if el.ElementID != streamingElementID {
|
||||
t.Errorf("%s element_id = %q, want %q", region.Label, el.ElementID, streamingElementID)
|
||||
}
|
||||
if !strings.Contains(el.Content, region.ThinkingText) {
|
||||
t.Errorf("%s element content %q does not contain %q", region.Label, el.Content, region.ThinkingText)
|
||||
}
|
||||
}
|
||||
|
||||
// Guard the point of the whole exercise: the copy actually differs.
|
||||
if RegionFeishu.ThinkingText == RegionLark.ThinkingText {
|
||||
t.Error("Feishu and Lark share ThinkingText; Lark users would see Chinese copy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package feishu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
)
|
||||
|
||||
// testRegion returns a Lark-shaped region pointed at a fake Open Platform, so
|
||||
// the whole send path can be driven without touching the real cloud. Region
|
||||
// carries the host as a field precisely so this is possible.
|
||||
func testRegion(baseURL string) Region {
|
||||
r := RegionLark
|
||||
r.OpenBaseURL = baseURL
|
||||
return r
|
||||
}
|
||||
|
||||
// fakeOpenPlatform records what the adapter asked for, and answers as the real
|
||||
// Open Platform would.
|
||||
type fakeOpenPlatform struct {
|
||||
mu sync.Mutex
|
||||
// paths records every request path in order.
|
||||
paths []string
|
||||
// replyAuth is the Authorization header seen on the reply call.
|
||||
replyAuth string
|
||||
// replyBody is the decoded JSON body of the reply call.
|
||||
replyBody map[string]any
|
||||
// sendBody is the decoded JSON body of the fallback send call.
|
||||
sendBody map[string]any
|
||||
// sendQuery is the raw query string of the fallback send call.
|
||||
sendQuery string
|
||||
// replyCode is returned from the reply endpoint (0 = success).
|
||||
replyCode int
|
||||
}
|
||||
|
||||
func (f *fakeOpenPlatform) handler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
f.paths = append(f.paths, r.URL.Path)
|
||||
f.mu.Unlock()
|
||||
|
||||
switch {
|
||||
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"code": 0, "tenant_access_token": "t-lark-xyz", "expire": 7200,
|
||||
})
|
||||
|
||||
case strings.HasSuffix(r.URL.Path, "/reply"):
|
||||
f.mu.Lock()
|
||||
f.replyAuth = r.Header.Get("Authorization")
|
||||
_ = json.NewDecoder(r.Body).Decode(&f.replyBody)
|
||||
code := f.replyCode
|
||||
f.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"code": code, "msg": "mock"})
|
||||
|
||||
case r.URL.Path == "/open-apis/im/v1/messages":
|
||||
f.mu.Lock()
|
||||
f.sendQuery = r.URL.RawQuery
|
||||
_ = json.NewDecoder(r.Body).Decode(&f.sendBody)
|
||||
f.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"})
|
||||
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fakeOpenPlatform) sawPath(want string) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, p := range f.paths {
|
||||
if p == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SendReply must fetch a token from the region's cloud and reply under the
|
||||
// original message, carrying that token as a bearer credential.
|
||||
func TestSendReply_EndToEnd_UsesRegionCloud(t *testing.T) {
|
||||
fake := &fakeOpenPlatform{}
|
||||
srv := httptest.NewServer(fake.handler())
|
||||
defer srv.Close()
|
||||
|
||||
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformLark,
|
||||
UserID: "ou_user1",
|
||||
ChatType: im.ChatTypeDirect,
|
||||
MessageID: "om_msg1",
|
||||
}
|
||||
|
||||
if err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "hello lark"}); err != nil {
|
||||
t.Fatalf("SendReply: %v", err)
|
||||
}
|
||||
|
||||
if !fake.sawPath("/open-apis/auth/v3/tenant_access_token/internal") {
|
||||
t.Errorf("no token fetch; paths = %v", fake.paths)
|
||||
}
|
||||
if !fake.sawPath("/open-apis/im/v1/messages/om_msg1/reply") {
|
||||
t.Errorf("reply did not target the message; paths = %v", fake.paths)
|
||||
}
|
||||
if fake.replyAuth != "Bearer t-lark-xyz" {
|
||||
t.Errorf("reply Authorization = %q, want %q", fake.replyAuth, "Bearer t-lark-xyz")
|
||||
}
|
||||
if got := fake.replyBody["msg_type"]; got != "text" {
|
||||
t.Errorf("msg_type = %v, want text", got)
|
||||
}
|
||||
// content is a JSON-encoded string, per the Open Platform contract.
|
||||
var content struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
raw, _ := fake.replyBody["content"].(string)
|
||||
if err := json.Unmarshal([]byte(raw), &content); err != nil {
|
||||
t.Fatalf("content is not a JSON string: %q", raw)
|
||||
}
|
||||
if content.Text != "hello lark" {
|
||||
t.Errorf("text = %q, want %q", content.Text, "hello lark")
|
||||
}
|
||||
}
|
||||
|
||||
// A group that rejects reply-in-thread (230071) must still receive the answer
|
||||
// via the plain send-message API, addressed to the chat.
|
||||
func TestSendReply_EndToEnd_FallsBackToSendAPI(t *testing.T) {
|
||||
fake := &fakeOpenPlatform{replyCode: 230071}
|
||||
srv := httptest.NewServer(fake.handler())
|
||||
defer srv.Close()
|
||||
|
||||
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformLark,
|
||||
UserID: "ou_user1",
|
||||
ChatID: "oc_chat1",
|
||||
ChatType: im.ChatTypeGroup,
|
||||
MessageID: "om_msg1",
|
||||
}
|
||||
|
||||
if err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "grouped"}); err != nil {
|
||||
t.Fatalf("SendReply: %v", err)
|
||||
}
|
||||
|
||||
if !fake.sawPath("/open-apis/im/v1/messages") {
|
||||
t.Fatalf("no fallback to send-message API; paths = %v", fake.paths)
|
||||
}
|
||||
if fake.sendQuery != "receive_id_type=chat_id" {
|
||||
t.Errorf("send query = %q, want receive_id_type=chat_id", fake.sendQuery)
|
||||
}
|
||||
if got := fake.sendBody["receive_id"]; got != "oc_chat1" {
|
||||
t.Errorf("receive_id = %v, want oc_chat1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A non-fallback-eligible error must surface, not be silently swallowed.
|
||||
func TestSendReply_EndToEnd_HardErrorSurfaces(t *testing.T) {
|
||||
fake := &fakeOpenPlatform{replyCode: 99991663} // app ticket invalid — not retryable
|
||||
srv := httptest.NewServer(fake.handler())
|
||||
defer srv.Close()
|
||||
|
||||
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformLark, UserID: "ou_user1",
|
||||
ChatType: im.ChatTypeDirect, MessageID: "om_msg1",
|
||||
}
|
||||
|
||||
err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "x"})
|
||||
if err == nil {
|
||||
t.Fatal("SendReply returned nil for a non-retryable API error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "99991663") {
|
||||
t.Errorf("error %q does not mention the API code", err)
|
||||
}
|
||||
// The plain send API must not be tried for a hard error.
|
||||
if fake.sawPath("/open-apis/im/v1/messages") {
|
||||
t.Errorf("fell back to send-message API on a non-retryable error; paths = %v", fake.paths)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user