feat(im): add file support and knowledge base integration

This commit is contained in:
wizardchen
2026-03-17 11:17:17 +08:00
committed by lyingbug
parent d89e5db0f6
commit 09d9fe5ddb
22 changed files with 1765 additions and 137 deletions
+176 -15
View File
@@ -51,12 +51,14 @@ type wsFrame struct {
}
// botMessage is the body of an aibot_msg_callback frame.
// Supports text, image, file, voice, and mixed message types.
// Reference: https://developer.work.weixin.qq.com/document/path/100719
type botMessage struct {
MsgID string `json:"msgid"`
AiBotID string `json:"aibotid"`
ChatID string `json:"chatid"`
ChatType string `json:"chattype"` // "single" or "group"
MsgType string `json:"msgtype"` // "text", "image", "event", ...
MsgType string `json:"msgtype"` // "text", "image", "file", "voice", "video", "mixed", "stream"
CreateTime int64 `json:"create_time"`
From struct {
UserID string `json:"userid"`
@@ -64,6 +66,37 @@ type botMessage struct {
Text struct {
Content string `json:"content"`
} `json:"text"`
Image struct {
URL string `json:"url"` // encrypted download URL, valid for 5 minutes
AESKey string `json:"aeskey"` // per-message AES key for decrypting downloaded content
} `json:"image"`
File struct {
URL string `json:"url"` // encrypted download URL, valid for 5 minutes
AESKey string `json:"aeskey"` // per-message AES key for decrypting downloaded content
} `json:"file"`
Voice struct {
Content string `json:"content"` // speech-to-text result
} `json:"voice"`
Video struct {
URL string `json:"url"` // encrypted download URL, valid for 5 minutes
AESKey string `json:"aeskey"` // per-message AES key for decrypting downloaded content
} `json:"video"`
Mixed struct {
MsgItem []botMixedItem `json:"msg_item"`
} `json:"mixed"`
Quote *botMessage `json:"quote,omitempty"` // quoted message (optional)
}
// botMixedItem is one element in a mixed (text+image) message.
type botMixedItem struct {
MsgType string `json:"msgtype"` // "text" or "image"
Text struct {
Content string `json:"content"`
} `json:"text"`
Image struct {
URL string `json:"url"`
AESKey string `json:"aeskey"`
} `json:"image"`
}
// streamReplyBody is the body for a streaming text reply.
@@ -380,17 +413,18 @@ func (c *LongConnClient) heartbeatLoop(ctx context.Context) {
}
func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) {
// Log raw message body for debugging
logger.Debugf(ctx, "[WeCom] Raw callback body: %s", string(frame.Body))
var msg botMessage
if err := json.Unmarshal(frame.Body, &msg); err != nil {
logger.Warnf(ctx, "[WeCom] Failed to unmarshal callback body: %v", err)
return
}
// Only handle text messages for now
if msg.MsgType != "text" {
logger.Infof(ctx, "[WeCom] Ignoring non-text message type: %s", msg.MsgType)
return
}
logger.Debugf(ctx, "[WeCom] Parsed message: msgid=%s msgtype=%s from=%s chattype=%s text=%q image_url=%q file_url=%q voice=%q mixed_items=%d",
msg.MsgID, msg.MsgType, msg.From.UserID, msg.ChatType,
msg.Text.Content, msg.Image.URL, msg.File.URL, msg.Voice.Content, len(msg.Mixed.MsgItem))
chatType := im.ChatTypeDirect
chatID := ""
@@ -405,15 +439,87 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) {
reqID = frame.Headers["req_id"]
}
incoming := &im.IncomingMessage{
Platform: im.PlatformWeCom,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(msg.Text.Content),
MessageID: msg.MsgID,
Extra: map[string]string{"req_id": reqID},
var incoming *im.IncomingMessage
switch msg.MsgType {
case "text":
incoming = &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeText,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(msg.Text.Content),
MessageID: msg.MsgID,
Extra: map[string]string{"req_id": reqID},
}
case "voice":
// WeCom returns speech-to-text content directly — treat as text query
if msg.Voice.Content == "" {
logger.Infof(ctx, "[WeCom] Ignoring voice message with empty content")
return
}
incoming = &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeText,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(msg.Voice.Content),
MessageID: msg.MsgID,
Extra: map[string]string{"req_id": reqID},
}
case "image":
if msg.Image.URL == "" {
logger.Infof(ctx, "[WeCom] Ignoring image message with empty URL")
return
}
incoming = &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeImage,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
FileKey: msg.Image.URL, // store encrypted URL in FileKey
FileName: msg.MsgID + ".png",
Extra: map[string]string{"req_id": reqID, "aes_key": msg.Image.AESKey},
}
case "file":
if msg.File.URL == "" {
logger.Infof(ctx, "[WeCom] Ignoring file message with empty URL")
return
}
incoming = &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeFile,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
FileKey: msg.File.URL, // store encrypted URL in FileKey
FileName: msg.MsgID, // WeCom doesn't provide file name directly
Extra: map[string]string{"req_id": reqID, "aes_key": msg.File.AESKey},
}
case "mixed":
// Extract text parts for QA content, and detect if any images are present
incoming = convertMixedMessage(&msg, chatID, chatType, reqID)
if incoming == nil {
logger.Infof(ctx, "[WeCom] Ignoring empty mixed message")
return
}
default:
logger.Infof(ctx, "[WeCom] Ignoring unsupported message type: %s", msg.MsgType)
return
}
if err := c.handler(ctx, incoming); err != nil {
@@ -421,6 +527,61 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) {
}
}
// convertMixedMessage converts a WeCom mixed (text+image) message.
// Extracts all text content for QA; if there's only images, treat as image message.
func convertMixedMessage(msg *botMessage, chatID string, chatType im.ChatType, reqID string) *im.IncomingMessage {
var textParts []string
var firstImageURL string
var firstImageAESKey string
for _, item := range msg.Mixed.MsgItem {
switch item.MsgType {
case "text":
if t := strings.TrimSpace(item.Text.Content); t != "" {
textParts = append(textParts, t)
}
case "image":
if firstImageURL == "" && item.Image.URL != "" {
firstImageURL = item.Image.URL
firstImageAESKey = item.Image.AESKey
}
}
}
// If there's text content, treat as text message (QA query)
if len(textParts) > 0 {
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeText,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
Content: strings.Join(textParts, "\n"),
MessageID: msg.MsgID,
Extra: map[string]string{"req_id": reqID},
}
}
// Only images, treat as image message (save to KB)
if firstImageURL != "" {
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeImage,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
FileKey: firstImageURL,
FileName: msg.MsgID + ".png",
Extra: map[string]string{"req_id": reqID, "aes_key": firstImageAESKey},
}
}
return nil
}
func (c *LongConnClient) writeJSON(v interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
+198 -20
View File
@@ -22,7 +22,10 @@ import (
"encoding/xml"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path"
"sort"
"strings"
"sync"
@@ -33,7 +36,7 @@ import (
"github.com/gin-gonic/gin"
)
var httpClient = &http.Client{Timeout: 10 * time.Second}
var httpClient = &http.Client{Timeout: 30 * time.Second}
// WebhookAdapter implements im.Adapter for WeCom in webhook (self-built app callback) mode.
// Messages arrive via HTTP callback; replies are sent via the WeCom REST API.
@@ -51,6 +54,9 @@ type WebhookAdapter struct {
tokenExpAt time.Time
}
// Compile-time check that WebhookAdapter implements im.FileDownloader.
var _ im.FileDownloader = (*WebhookAdapter)(nil)
// NewWebhookAdapter creates a new WeCom webhook adapter.
func NewWebhookAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*WebhookAdapter, error) {
// Decode the AES key from base64
@@ -146,37 +152,63 @@ func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, err
return nil, fmt.Errorf("decrypt message: %w", err)
}
// Log raw decrypted message for debugging
logger.Debugf(c.Request.Context(), "[WeCom] Raw decrypted callback: %s", string(decrypted))
var msg wecomMessage
if err := xml.Unmarshal(decrypted, &msg); err != nil {
return nil, fmt.Errorf("unmarshal decrypted message: %w", err)
}
// Only handle text messages
if msg.MsgType != "text" {
logger.Infof(c.Request.Context(), "[WeCom] Ignoring non-text message type: %s", msg.MsgType)
return nil, nil
}
logger.Debugf(c.Request.Context(), "[WeCom] Parsed webhook message: msgid=%s msgtype=%s from=%s content=%q picurl=%q mediaid=%q",
msg.MsgID, msg.MsgType, msg.FromUserName, msg.Content, msg.PicUrl, msg.MediaId)
// Determine chat type
chatType := im.ChatTypeDirect
chatID := ""
content := msg.Content
// Check if this is a group message (has ChatId field in WeCom smart bot callback)
// In group chats, the content may contain @bot mention prefix that should be stripped
if msg.ChatID != "" {
chatType = im.ChatTypeGroup
chatID = msg.ChatID
}
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
UserID: msg.FromUserName,
UserName: msg.FromUserName,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(content),
MessageID: msg.MsgID,
}, nil
switch msg.MsgType {
case "text":
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeText,
UserID: msg.FromUserName,
UserName: msg.FromUserName,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(msg.Content),
MessageID: msg.MsgID,
}, nil
case "image":
// Image via webhook: has PicUrl (direct download) and MediaId
if msg.PicUrl == "" && msg.MediaId == "" {
return nil, nil
}
fileKey := msg.PicUrl
if fileKey == "" {
fileKey = msg.MediaId
}
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
MessageType: im.MessageTypeImage,
UserID: msg.FromUserName,
UserName: msg.FromUserName,
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
FileKey: fileKey,
FileName: msg.MsgID + ".png",
}, nil
default:
logger.Infof(c.Request.Context(), "[WeCom] Ignoring unsupported message type: %s", msg.MsgType)
return nil, nil
}
}
// SendReply sends a reply message via WeCom API.
@@ -357,14 +389,160 @@ type callbackRequestBody struct {
}
// wecomMessage is the decrypted WeCom message structure.
// Supports text, image, voice, video, location, and link message types.
// Reference: https://developer.work.weixin.qq.com/document/path/90375
type wecomMessage struct {
XMLName xml.Name `xml:"xml"`
ToUserName string `xml:"ToUserName"`
FromUserName string `xml:"FromUserName"`
CreateTime int64 `xml:"CreateTime"`
MsgType string `xml:"MsgType"`
Content string `xml:"Content"`
Content string `xml:"Content"` // text
PicUrl string `xml:"PicUrl"` // image: download URL
MediaId string `xml:"MediaId"` // image/voice/video: media ID for download
Format string `xml:"Format"` // voice: audio format (amr/speex)
ThumbMediaId string `xml:"ThumbMediaId"` // video: thumbnail media ID
MsgID string `xml:"MsgId"`
AgentID string `xml:"AgentID"`
ChatID string `xml:"ChatId"`
}
// ──────────────────────────────────────────────────────────────────────
// File download support for WeCom webhook mode
// ──────────────────────────────────────────────────────────────────────
// DownloadFile downloads a file/image from WeCom.
// For webhook mode, images come with MediaId (temporary media) which can be
// downloaded via the GetMedia API, or PicUrl for direct download.
func (a *WebhookAdapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
if msg.FileKey == "" {
return nil, "", fmt.Errorf("no file key (URL or media_id) in message")
}
fileName := msg.FileName
if fileName == "" {
fileName = msg.FileKey
}
// If FileKey looks like a URL, download directly
if strings.HasPrefix(msg.FileKey, "http://") || strings.HasPrefix(msg.FileKey, "https://") {
return downloadFromURL(ctx, msg.FileKey, fileName)
}
// Otherwise treat as media_id, download via temporary media API
accessToken, err := a.getAccessToken(ctx)
if err != nil {
return nil, "", fmt.Errorf("get access token: %w", err)
}
apiURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s",
accessToken, msg.FileKey)
return downloadFromURL(ctx, apiURL, fileName)
}
// downloadFromURL performs a GET request and returns the response body.
// It tries to resolve the real filename from HTTP response headers:
// 1. Content-Disposition: attachment; filename="xxx.pdf"
// 2. Content-Type → extension mapping (fallback for platforms like WeCom that
// don't provide the original filename in the callback JSON)
func downloadFromURL(ctx context.Context, rawURL, fileName string) (io.ReadCloser, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, "", fmt.Errorf("download: %w", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, "", fmt.Errorf("download failed: status=%d", resp.StatusCode)
}
logger.Debugf(ctx, "[WeCom] Download response: status=%d content-type=%s content-disposition=%s",
resp.StatusCode, resp.Header.Get("Content-Type"), resp.Header.Get("Content-Disposition"))
// Try to extract filename from Content-Disposition header.
// Supports both standard filename and RFC 5987 filename* parameters.
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
// Prefer filename* (RFC 5987, already decoded by mime.ParseMediaType)
if fn := params["filename"]; fn != "" {
fileName = fn
}
} else {
// Fallback: manual extraction for malformed headers
if idx := strings.Index(cd, "filename="); idx >= 0 {
extracted := strings.Trim(cd[idx+len("filename="):], "\" ")
if extracted != "" {
fileName = extracted
}
}
}
}
// URL-decode the filename if it contains percent-encoded characters.
// Some servers (e.g. WeCom COS) return URL-encoded Chinese filenames.
if strings.Contains(fileName, "%") {
if decoded, err := url.QueryUnescape(fileName); err == nil && decoded != "" {
fileName = decoded
}
}
// Also try to extract a meaningful filename from the URL path itself,
// in case Content-Disposition is missing but the URL contains the real name.
if !strings.Contains(fileName, ".") {
if u, err := url.Parse(rawURL); err == nil {
base := path.Base(u.Path)
if base != "" && base != "." && base != "/" && strings.Contains(base, ".") {
// URL-decode the path component as well
if decoded, err := url.QueryUnescape(base); err == nil {
fileName = decoded
} else {
fileName = base
}
}
}
}
// If filename still has no extension, try to infer from Content-Type.
// This handles platforms (e.g. WeCom aibot) where the callback only provides
// a hash ID as the filename without any extension.
if !strings.Contains(fileName, ".") {
if ext := contentTypeToExt(resp.Header.Get("Content-Type")); ext != "" {
fileName = fileName + "." + ext
}
}
return resp.Body, fileName, nil
}
// contentTypeToExt maps common Content-Type values to file extensions.
func contentTypeToExt(ct string) string {
// Normalize: take only the media type, ignore parameters like charset
if idx := strings.Index(ct, ";"); idx >= 0 {
ct = strings.TrimSpace(ct[:idx])
}
ct = strings.ToLower(ct)
mapping := map[string]string{
"application/pdf": "pdf",
"application/msword": "doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
"application/vnd.ms-excel": "xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
"application/vnd.ms-powerpoint": "ppt",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
"text/plain": "txt",
"text/markdown": "md",
"text/csv": "csv",
"image/png": "png",
"image/jpeg": "jpg",
"image/gif": "gif",
"image/webp": "webp",
}
return mapping[ct]
}
+113 -2
View File
@@ -1,17 +1,24 @@
package wecom
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
"io"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/gin-gonic/gin"
)
// Compile-time checks.
var (
_ im.Adapter = (*WSAdapter)(nil)
_ im.StreamSender = (*WSAdapter)(nil)
_ im.Adapter = (*WSAdapter)(nil)
_ im.StreamSender = (*WSAdapter)(nil)
_ im.FileDownloader = (*WSAdapter)(nil)
)
// WSAdapter implements im.Adapter and im.StreamSender for WeCom in WebSocket
@@ -60,3 +67,107 @@ func (a *WSAdapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMe
func (a *WSAdapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
return a.client.EndStream(ctx, incoming, streamID)
}
// ── FileDownloader implementation ──
// WeCom aibot provides AES-256-CBC encrypted URLs for image/file/video messages.
// Each message carries its own aeskey for decryption.
func (a *WSAdapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
if msg.FileKey == "" {
return nil, "", fmt.Errorf("no file URL in message")
}
fileName := msg.FileName
if fileName == "" {
fileName = msg.FileKey
}
// Download the (encrypted) file content
reader, fileName, err := downloadFromURL(ctx, msg.FileKey, fileName)
if err != nil {
return nil, "", err
}
// If an AES key is provided, the downloaded content is AES-256-CBC encrypted
// and must be decrypted before use. This is the case for WeCom aibot long
// connection mode where each file/image message carries a per-message aeskey.
aesKeyB64 := msg.Extra["aes_key"]
if aesKeyB64 == "" {
// No encryption — return raw content (e.g. webhook mode uses media API)
return reader, fileName, nil
}
// Read all encrypted content
encryptedData, err := io.ReadAll(reader)
reader.Close()
if err != nil {
return nil, "", fmt.Errorf("read encrypted file: %w", err)
}
logger.Debugf(ctx, "[WeCom] Decrypting file: name=%s encrypted_size=%d aes_key_len=%d",
fileName, len(encryptedData), len(aesKeyB64))
// Decrypt
decrypted, err := decryptAESCBC(encryptedData, aesKeyB64)
if err != nil {
return nil, "", fmt.Errorf("decrypt file: %w", err)
}
logger.Debugf(ctx, "[WeCom] File decrypted: name=%s decrypted_size=%d", fileName, len(decrypted))
return io.NopCloser(bytes.NewReader(decrypted)), fileName, nil
}
// decryptAESCBC decrypts data encrypted with AES-256-CBC using PKCS#7 padding.
// The aesKeyB64 is the base64-encoded AES key provided per-message by WeCom.
// IV is the first 16 bytes of the decoded AES key.
func decryptAESCBC(ciphertext []byte, aesKeyB64 string) ([]byte, error) {
// WeCom's per-message aeskey is base64-encoded (43 chars → 32 bytes after decode)
aesKey, err := base64.StdEncoding.DecodeString(aesKeyB64 + "=")
if err != nil {
// Try without padding
aesKey, err = base64.RawStdEncoding.DecodeString(aesKeyB64)
if err != nil {
return nil, fmt.Errorf("base64 decode aes key: %w", err)
}
}
if len(aesKey) < 16 {
return nil, fmt.Errorf("aes key too short: %d bytes", len(aesKey))
}
block, err := aes.NewCipher(aesKey)
if err != nil {
return nil, fmt.Errorf("new aes cipher: %w", err)
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short: %d bytes", len(ciphertext))
}
if len(ciphertext)%aes.BlockSize != 0 {
return nil, fmt.Errorf("ciphertext not a multiple of block size: %d bytes", len(ciphertext))
}
// IV = first 16 bytes of the AES key
iv := aesKey[:aes.BlockSize]
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
// Remove PKCS#7 padding
if len(plaintext) == 0 {
return nil, fmt.Errorf("empty plaintext after decryption")
}
padLen := int(plaintext[len(plaintext)-1])
if padLen > aes.BlockSize || padLen == 0 || padLen > len(plaintext) {
// No valid PKCS#7 padding — return as-is (some implementations may not pad)
return plaintext, nil
}
// Verify padding bytes
for i := 0; i < padLen; i++ {
if plaintext[len(plaintext)-1-i] != byte(padLen) {
// Invalid padding — return as-is
return plaintext, nil
}
}
return plaintext[:len(plaintext)-padLen], nil
}