feat(im): add file support and knowledge base integration
This commit is contained in:
@@ -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]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user