Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(im): support Yunzhijia image messages

jacentsao85c9b61ad051
diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue
index b9f3d346f..b3067f585 100644
--- a/frontend/src/components/IMChannelPanel.vue
+++ b/frontend/src/components/IMChannelPanel.vue
@@ -477,17 +477,17 @@
<!-- Yunzhijia credentials -->
<template v-if="formData.platform === 'yunzhijia'">
- <div class="platform-link-hint">
- <a href="https://open.yunzhijia.com/" target="_blank" rel="noopener noreferrer" class="doc-link">
- {{ $t('agentEditor.im.yunzhijiaConsole') }}
- <t-icon name="link" class="link-icon" />
- </a>
- <span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
- </div>
<div class="form-item">
<label class="form-label required">{{ $t('agentEditor.im.yunzhijiaSendMsgUrl') }}</label>
<t-input v-model="formData.credentials.send_msg_url"
placeholder="https://www.yunzhijia.com/gateway/robot/webhook/send?yzjtype=0&yzjtoken=..." />
+ <p class="form-desc">
+ {{ $t('agentEditor.im.yunzhijiaSendMsgUrlHint') }}
+ <a href="https://www.yunzhijia.com/opendocs/docs.html#/guide/im/robot" target="_blank"
+ rel="noopener noreferrer" class="doc-link">
+ {{ $t('agentEditor.im.yunzhijiaRobotDoc') }}
+ </a>
+ </p>
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaSecret') }}</label>
@@ -495,6 +495,23 @@
:placeholder="$t('agentEditor.im.yunzhijiaSecretPlaceholder')" />
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaSecretHint') }}</p>
</div>
+ <div class="form-item">
+ <label class="form-label">{{ $t('agentEditor.im.yunzhijiaAppId') }}</label>
+ <t-input v-model="formData.credentials.app_id"
+ :placeholder="$t('agentEditor.im.yunzhijiaAppIdPlaceholder')" />
+ <p class="form-desc">
+ {{ $t('agentEditor.im.yunzhijiaAppCredentialHint') }}
+ <a href="https://www.yunzhijia.com/developers/" target="_blank" rel="noopener noreferrer"
+ class="doc-link">
+ {{ $t('agentEditor.im.yunzhijiaImageDoc') }}
+ </a>
+ </p>
+ </div>
+ <div class="form-item">
+ <label class="form-label">{{ $t('agentEditor.im.yunzhijiaAppSecret') }}</label>
+ <t-input v-model="formData.credentials.app_secret" type="password"
+ :placeholder="$t('agentEditor.im.yunzhijiaAppSecretPlaceholder')" />
+ </div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaTimeout') }}</label>
<t-input-number v-model="formData.credentials.timeout_seconds" placeholder="10" :min="1" :max="60"
@@ -813,6 +830,16 @@ function onPlatformChange(val: string | number | boolean) {
}
}
+function normalizeYunzhijiaCredentials() {
+ if (formData.value.platform !== 'yunzhijia') return;
+ if (!formData.value.credentials.allowed_webhook_host_suffix) {
+ formData.value.credentials.allowed_webhook_host_suffix = 'yunzhijia.com';
+ }
+ if (!formData.value.credentials.timeout_seconds) {
+ formData.value.credentials.timeout_seconds = 10;
+ }
+}
+
async function startWeChatBinding() {
stopWeChatPolling();
wechatLoading.value = true;
@@ -972,6 +999,7 @@ async function editChannel(channel: IMChannel | IMChannelOverview) {
knowledge_base_id: fullChannel.knowledge_base_id || '',
credentials: { ...fullChannel.credentials },
};
+ normalizeYunzhijiaCredentials();
showCreateDialog.value = true;
}
@@ -1005,11 +1033,16 @@ async function handleSave() {
MessagePlugin.warning(t('agentEditor.im.wechatScanBind'));
return;
}
- if (formData.value.platform === 'yunzhijia' &&
- (!String(formData.value.credentials.send_msg_url || '').trim() ||
- !String(formData.value.credentials.allowed_webhook_host_suffix || '').trim())) {
- MessagePlugin.warning(t('agentEditor.im.yunzhijiaRequiredCredentials'));
- return;
+ if (formData.value.platform === 'yunzhijia') {
+ normalizeYunzhijiaCredentials();
+ if (!String(formData.value.credentials.send_msg_url || '').trim()) {
+ MessagePlugin.warning(t('agentEditor.im.yunzhijiaSendMsgUrlRequired'));
+ return;
+ }
+ if (!String(formData.value.credentials.allowed_webhook_host_suffix || '').trim()) {
+ MessagePlugin.warning(t('agentEditor.im.yunzhijiaAllowedHostSuffixRequired'));
+ return;
+ }
}
if (editingChannel.value) {
@@ -1246,6 +1279,11 @@ onUnmounted(() => {
font-size: 12px;
line-height: 1.45;
color: var(--td-text-color-placeholder);
+
+ .doc-link {
+ margin-left: 4px;
+ color: var(--td-brand-color);
+ }
}
.option-chips {
@@ -1338,6 +1376,7 @@ onUnmounted(() => {
.platform-link-hint {
display: flex;
align-items: center;
+ flex-wrap: wrap;
gap: 6px;
font-size: 12px;
line-height: 1.4;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index fb744a520..8f63bab8e 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5967,17 +5967,27 @@ export default {
qqbotConsole: 'QQ Open Platform',
qqbotAPIBaseURLHint: 'Optional. Leave empty to use the default production API endpoint.',
qqbotGatewayURLHint: 'Optional. Leave empty to fetch the common WebSocket gateway automatically.',
- yunzhijiaConsole: 'Yunzhijia Robot Console',
+ yunzhijiaConsole: 'Yunzhijia Open Platform',
+ yunzhijiaRobotDoc: 'Robot messaging docs',
+ yunzhijiaImageDoc: 'Developer platform (images)',
yunzhijiaModeHint: 'Supports Webhook and WebSocket; WebSocket mode does not require a public callback URL.',
yunzhijiaSendMsgUrl: 'Send Message URL',
+ yunzhijiaSendMsgUrlHint: 'Used for robot replies.',
yunzhijiaSecret: 'Signature Secret (optional)',
yunzhijiaSecretPlaceholder: 'HmacSHA1 signature secret from Yunzhijia robot settings',
yunzhijiaSecretHint: 'If configured, incoming callbacks will be verified using HmacSHA1 signature',
+ yunzhijiaAppId: 'App ID (image download)',
+ yunzhijiaAppIdPlaceholder: 'Yunzhijia Open Platform App ID',
+ yunzhijiaAppSecret: 'App Secret (image download)',
+ yunzhijiaAppSecretPlaceholder: 'Yunzhijia Open Platform App Secret',
+ yunzhijiaAppCredentialHint: 'Used to obtain appAccessToken and download images sent by users.',
yunzhijiaTimeout: 'HTTP Timeout (seconds)',
yunzhijiaTimeoutHint: 'Timeout for sending replies via Send Message URL, default 10 seconds',
yunzhijiaAllowedHostSuffix: 'Allowed Host Suffix',
yunzhijiaAllowedHostSuffixHint: 'Restrict Send Message URL host to this suffix for security (e.g. yunzhijia.com)',
yunzhijiaRequiredCredentials: 'Enter the Send Message URL and allowed host suffix',
+ yunzhijiaSendMsgUrlRequired: 'Enter the Send Message URL from Yunzhijia robot settings',
+ yunzhijiaAllowedHostSuffixRequired: 'Enter the allowed host suffix',
mattermostModeHint: 'Mattermost only supports Webhook mode (outgoing webhook + bot token).',
mattermostPostToMain: 'Post replies in channel timeline',
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 0fa8c4639..217e4a1d6 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5898,17 +5898,27 @@ export default {
qqbotConsole: "QQ Open Platform",
qqbotAPIBaseURLHint: "선택 사항. 비워두면 기본 프로덕션 API 엔드포인트를 사용합니다.",
qqbotGatewayURLHint: "선택 사항. 비워두면 공용 WebSocket gateway를 자동으로 가져옵니다.",
- yunzhijiaConsole: "Yunzhijia 로봇 콘솔",
+ yunzhijiaConsole: "Yunzhijia Open Platform",
+ yunzhijiaRobotDoc: "로봇 메시지 문서",
+ yunzhijiaImageDoc: "개발자 플랫폼 (이미지)",
yunzhijiaModeHint: "Webhook과 WebSocket을 지원하며 WebSocket 모드에는 공개 콜백 URL이 필요하지 않습니다.",
yunzhijiaSendMsgUrl: "메시지 전송 URL",
+ yunzhijiaSendMsgUrlHint: "로봇 응답 전송에 사용됩니다.",
yunzhijiaSecret: "서명 시크릿 (선택 사항)",
yunzhijiaSecretPlaceholder: "Yunzhijia 로봇 설정의 HmacSHA1 서명 시크릿",
yunzhijiaSecretHint: "설정하면 들어오는 콜백 요청이 HmacSHA1 서명으로 검증됩니다",
+ yunzhijiaAppId: "App ID (이미지 다운로드)",
+ yunzhijiaAppIdPlaceholder: "Yunzhijia Open Platform App ID",
+ yunzhijiaAppSecret: "App Secret (이미지 다운로드)",
+ yunzhijiaAppSecretPlaceholder: "Yunzhijia Open Platform App Secret",
+ yunzhijiaAppCredentialHint: "사용자가 보낸 이미지를 다운로드하기 위한 appAccessToken 발급에 사용됩니다.",
yunzhijiaTimeout: "HTTP 타임아웃 (초)",
yunzhijiaTimeoutHint: "메시지 전송 URL을 통한 응답 전송 타임아웃, 기본 10초",
yunzhijiaAllowedHostSuffix: "허용 호스트 접미사",
yunzhijiaAllowedHostSuffixHint: "보안을 위해 메시지 전송 URL 호스트를 이 접미사로 제한 (예: yunzhijia.com)",
yunzhijiaRequiredCredentials: "메시지 전송 URL과 허용 호스트 접미사를 입력하세요",
+ yunzhijiaSendMsgUrlRequired: "Yunzhijia 로봇 설정의 메시지 전송 URL을 입력하세요",
+ yunzhijiaAllowedHostSuffixRequired: "허용 호스트 접미사를 입력하세요",
mattermostModeHint: "Mattermost는 Webhook(아웃고잉 웹훅 + 봇 토큰)만 지원합니다.",
mattermostPostToMain: "답변을 채널 메인 타임라인에 표시",
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 486b67b11..fde3ad1a1 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5470,17 +5470,27 @@ export default {
qqbotConsole: 'QQ Open Platform',
qqbotAPIBaseURLHint: 'Необязательно. Оставьте пустым, чтобы использовать стандартный production API endpoint.',
qqbotGatewayURLHint: 'Необязательно. Оставьте пустым, чтобы автоматически получить общий WebSocket gateway.',
- yunzhijiaConsole: 'Консоль роботов Yunzhijia',
+ yunzhijiaConsole: 'Yunzhijia Open Platform',
+ yunzhijiaRobotDoc: 'Документация робота',
+ yunzhijiaImageDoc: 'Платформа разработчика (изображения)',
yunzhijiaModeHint: 'Поддерживаются Webhook и WebSocket; для режима WebSocket не требуется публичный URL обратного вызова.',
yunzhijiaSendMsgUrl: 'URL отправки сообщений',
+ yunzhijiaSendMsgUrlHint: 'Используется для ответов робота.',
yunzhijiaSecret: 'Секрет подписи (необязательно)',
yunzhijiaSecretPlaceholder: 'Секрет подписи HmacSHA1 из настроек робота Yunzhijia',
yunzhijiaSecretHint: 'Если указано, входящие обратные вызовы будут проверяться с помощью подписи HmacSHA1',
+ yunzhijiaAppId: 'App ID (загрузка изображений)',
+ yunzhijiaAppIdPlaceholder: 'App ID открытой платформы Yunzhijia',
+ yunzhijiaAppSecret: 'App Secret (загрузка изображений)',
+ yunzhijiaAppSecretPlaceholder: 'App Secret открытой платформы Yunzhijia',
+ yunzhijiaAppCredentialHint: 'Используется для получения appAccessToken и загрузки изображений от пользователей.',
yunzhijiaTimeout: 'Таймаут HTTP (секунды)',
yunzhijiaTimeoutHint: 'Таймаут отправки ответов через URL отправки сообщений, по умолчанию 10 секунд',
yunzhijiaAllowedHostSuffix: 'Допустимый суффикс хоста',
yunzhijiaAllowedHostSuffixHint: 'Ограничить хост URL отправки сообщений этим суффиксом для безопасности (напр. yunzhijia.com)',
yunzhijiaRequiredCredentials: 'Укажите URL отправки сообщений и допустимый суффикс хоста',
+ yunzhijiaSendMsgUrlRequired: 'Укажите URL отправки сообщений из настроек робота Yunzhijia',
+ yunzhijiaAllowedHostSuffixRequired: 'Укажите допустимый суффикс хоста',
mattermostModeHint: 'Mattermost поддерживает только режим Webhook (исходящий вебхук + токен бота).',
mattermostPostToMain: 'Ответы в основной ленте канала',
mattermostPostToMainHint:
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index e47bd964a..883796093 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5951,17 +5951,27 @@ export default {
qqbotConsole: "QQ 开放平台",
qqbotAPIBaseURLHint: "可选,留空则使用默认正式环境 API 地址。",
qqbotGatewayURLHint: "可选,留空则自动获取通用 WebSocket 接入点。",
- yunzhijiaConsole: "云之家机器人后台",
+ yunzhijiaConsole: "云之家开放平台",
+ yunzhijiaRobotDoc: "机器人消息文档",
+ yunzhijiaImageDoc: "开发者平台(图片功能)",
yunzhijiaModeHint: "支持 Webhook 和 WebSocket;WebSocket 模式无需配置公网回调地址。",
yunzhijiaSendMsgUrl: "发送消息地址",
+ yunzhijiaSendMsgUrlHint: "用于机器人回复消息。",
yunzhijiaSecret: "签名密钥(可选)",
yunzhijiaSecretPlaceholder: "云之家机器人设置中的 HmacSHA1 签名密钥",
yunzhijiaSecretHint: "配置后,将对传入的回调请求进行 HmacSHA1 签名验证",
+ yunzhijiaAppId: "应用 App ID(图片下载)",
+ yunzhijiaAppIdPlaceholder: "云之家开放平台应用 App ID",
+ yunzhijiaAppSecret: "应用 App Secret(图片下载)",
+ yunzhijiaAppSecretPlaceholder: "云之家开放平台应用 Secret",
+ yunzhijiaAppCredentialHint: "用于获取 appAccessToken 并下载用户发送的图片文件。",
yunzhijiaTimeout: "HTTP 超时时间(秒)",
yunzhijiaTimeoutHint: "通过发送消息地址回复的超时时间,默认 10 秒",
yunzhijiaAllowedHostSuffix: "允许的主机后缀",
yunzhijiaAllowedHostSuffixHint: "限制发送消息地址的目标域名后缀,提升安全性(如 yunzhijia.com)",
yunzhijiaRequiredCredentials: "请填写发送消息地址和允许的主机后缀",
+ yunzhijiaSendMsgUrlRequired: "请填写云之家机器人设置中的发送消息地址",
+ yunzhijiaAllowedHostSuffixRequired: "请填写允许的主机后缀",
mattermostModeHint: "Mattermost 仅支持 Webhook(出站 Webhook + Bot Token)。",
mattermostPostToMain: "回复显示在频道主时间线",
mattermostPostToMainHint:
diff --git a/internal/im/yunzhijia/adapter.go b/internal/im/yunzhijia/adapter.go
index a1ff9777a..0f2b30dde 100644
--- a/internal/im/yunzhijia/adapter.go
+++ b/internal/im/yunzhijia/adapter.go
@@ -7,8 +7,12 @@ import (
"encoding/json"
"fmt"
"io"
+ "mime"
"net/http"
+ "net/url"
+ "path/filepath"
"strings"
+ "sync"
"time"
"unicode"
"unicode/utf8"
@@ -27,17 +31,31 @@ const markdownFormatType = "markdown"
// Compile-time check.
var _ im.Adapter = (*Adapter)(nil)
+var _ im.FileDownloader = (*Adapter)(nil)
+
+var yunzhijiaAuthURL = "https://yunzhijia.com/api/oauth2_v12/auth/getAppAccessToken"
+var yunzhijiaDownloadFileBaseURL = "https://yunzhijia.com/gateway/docrest/doc/file/downloadfileOpen"
+
+var validateDownloadFileURL = func(rawURL string) error {
+ _, err := validateEndpointURL(rawURL, "https", "yunzhijia.com")
+ return err
+}
// Adapter implements im.Adapter for Yunzhijia (云之家).
type Adapter struct {
sendMsgURL string
secret string
+ appID string
+ appSecret string
httpClient *http.Client
allowedWebhookHostSuffix string
+ tokenMu sync.Mutex
+ accessToken string
+ accessTokenExpiresAt time.Time
}
// NewAdapter creates a Yunzhijia adapter.
-func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
+func NewAdapter(sendMsgURL, secret, appID, appSecret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
if timeoutSeconds <= 0 {
timeoutSeconds = 10
}
@@ -46,7 +64,9 @@ func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix
transport.DialContext = safeDialContext
return &Adapter{
sendMsgURL: strings.TrimSpace(sendMsgURL),
- secret: secret,
+ secret: strings.TrimSpace(secret),
+ appID: strings.TrimSpace(appID),
+ appSecret: strings.TrimSpace(appSecret),
allowedWebhookHostSuffix: strings.TrimSpace(allowedHostSuffix),
httpClient: &http.Client{
Timeout: time.Duration(timeoutSeconds) * time.Second,
@@ -128,8 +148,14 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
return nil
}
+ param, err := parseMessageParam(msg.MsgParam)
+ if err != nil {
+ logger.Warnf(ctx, "[Yunzhijia] Failed to parse msgParam: msgId=%s err=%v", msg.MsgID, err)
+ }
+ image, hasImage := param.firstImage()
+
content := strings.TrimSpace(msg.Content)
- if content == "" {
+ if content == "" && !hasImage {
logger.Infof(ctx,
"[Yunzhijia] Skip empty content: msgId=%s", msg.MsgID)
return nil
@@ -138,25 +164,30 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
// Conversation bots should only receive messages explicitly addressed to them.
var mentioned bool
content, mentioned = cleanAtMention(content, msg.RobotName)
+ if !mentioned {
+ mentioned = messageParamMentionsRobot(param, msg.RobotID)
+ }
if !mentioned {
logger.Infof(ctx, "[Yunzhijia] Skip message without robot mention: msgId=%s", msg.MsgID)
return nil
}
- if content == "" {
+ if content == "" && !hasImage {
logger.Infof(ctx,
"[Yunzhijia] Skip after cleaning @mention: msgId=%s", msg.MsgID)
return nil
}
+ userID := firstNonEmpty(msg.OperatorOpenid, msg.OperatorOID, msg.OpenID, msg.SenderID, msg.OperatorID, msg.OperatorUserID)
+ userName := firstNonEmpty(msg.OperatorName, msg.SenderName)
chatType := im.ChatTypeGroup
- chatID := msg.RobotID
+ chatID := firstNonEmpty(msg.GroupID, msg.RobotID)
- return &im.IncomingMessage{
+ incoming := &im.IncomingMessage{
Platform: im.PlatformYunzhijia,
MessageType: im.MessageTypeText,
- UserID: msg.OperatorOpenid,
- UserName: msg.OperatorName,
+ UserID: userID,
+ UserName: userName,
ChatID: chatID,
ChatType: chatType,
Content: content,
@@ -164,11 +195,53 @@ func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMe
Extra: map[string]string{
"robot_id": msg.RobotID,
"robot_name": msg.RobotName,
+ "group_id": msg.GroupID,
"group_type": fmt.Sprintf("%d", msg.GroupType),
- "operator_name": msg.OperatorName,
+ "operator_name": userName,
"time": fmt.Sprintf("%d", msg.Time),
},
}
+ if hasImage {
+ incoming.MessageType = im.MessageTypeImage
+ incoming.FileKey = image.Data
+ incoming.FileName = defaultImageFileName(msg.MsgID)
+ incoming.Extra["yunzhijia_image_width"] = fmt.Sprintf("%d", image.Width)
+ incoming.Extra["yunzhijia_image_height"] = fmt.Sprintf("%d", image.Height)
+ }
+ return incoming
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if trimmed := strings.TrimSpace(value); trimmed != "" {
+ return trimmed
+ }
+ }
+ return ""
+}
+
+func messageParamMentionsRobot(param *messageParam, robotID string) bool {
+ if param == nil || robotID == "" {
+ return false
+ }
+ for _, notifyTo := range param.NotifyTo {
+ if notifyTo == robotID {
+ return true
+ }
+ }
+ for _, desc := range param.Desc {
+ if desc.Type == "at" && desc.Data == robotID {
+ return true
+ }
+ }
+ return false
+}
+
+func defaultImageFileName(msgID string) string {
+ if msgID == "" {
+ return "yunzhijia-image.png"
+ }
+ return msgID + ".png"
}
// cleanAtMention removes @RobotName from the beginning of user content.
@@ -262,6 +335,163 @@ func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, r
return nil
}
+// DownloadFile downloads a file/image resource sent by Yunzhijia.
+func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
+ if msg.FileKey == "" {
+ return nil, "", fmt.Errorf("yunzhijia file id is required")
+ }
+ fileID := strings.TrimSpace(msg.FileKey)
+ if err := validateFileID(fileID); err != nil {
+ return nil, "", fmt.Errorf("invalid yunzhijia file id: %w", err)
+ }
+
+ accessToken, err := a.getAppAccessToken(ctx)
+ if err != nil {
+ return nil, "", err
+ }
+
+ downloadURL := buildDownloadFileURL(fileID)
+ if err := validateDownloadFileURL(downloadURL); err != nil {
+ return nil, "", fmt.Errorf("download url rejected: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
+ if err != nil {
+ return nil, "", fmt.Errorf("create download request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ resp, err := a.httpClient.Do(req)
+ if err != nil {
+ return nil, "", fmt.Errorf("download file: %w", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ return nil, "", fmt.Errorf("download file returned %d: %s", resp.StatusCode, string(body))
+ }
+
+ fileName := msg.FileName
+ if fileName == "" {
+ fileName = fileID
+ }
+ fileName = resolveDownloadFileName(fileName, resp)
+ return resp.Body, fileName, nil
+}
+
+func buildDownloadFileURL(fileID string) string {
+ u, _ := url.Parse(yunzhijiaDownloadFileBaseURL)
+ query := url.Values{}
+ query.Set("fileId", fileID)
+ u.RawQuery = query.Encode()
+ return u.String()
+}
+
+func validateFileID(fileID string) error {
+ if fileID == "" {
+ return fmt.Errorf("empty")
+ }
+ if len(fileID) > 256 {
+ return fmt.Errorf("too long")
+ }
+ if strings.ContainsAny(fileID, `/\?#&`) {
+ return fmt.Errorf("contains path or query separators")
+ }
+ for _, r := range fileID {
+ if unicode.IsControl(r) || unicode.IsSpace(r) {
+ return fmt.Errorf("contains whitespace or control character")
+ }
+ }
+ return nil
+}
+
+func (a *Adapter) getAppAccessToken(ctx context.Context) (string, error) {
+ if a.appID == "" || a.appSecret == "" {
+ return "", fmt.Errorf("yunzhijia app_id and app_secret are required to download files")
+ }
+
+ a.tokenMu.Lock()
+ if a.accessToken != "" && time.Now().Before(a.accessTokenExpiresAt) {
+ token := a.accessToken
+ a.tokenMu.Unlock()
+ return token, nil
+ }
+ a.tokenMu.Unlock()
+
+ payload := map[string]any{
+ "appId": a.appID,
+ "secret": a.appSecret,
+ "timestamp": time.Now().UnixMilli(),
+ }
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return "", fmt.Errorf("marshal yunzhijia token request: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, yunzhijiaAuthURL, bytes.NewReader(body))
+ if err != nil {
+ return "", fmt.Errorf("create yunzhijia token request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := a.httpClient.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("request yunzhijia app access token: %w", err)
+ }
+ defer resp.Body.Close()
+ respBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", fmt.Errorf("read yunzhijia token response: %w", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("yunzhijia token endpoint returned %d: %s", resp.StatusCode, string(respBody))
+ }
+
+ var tokenResp appAccessTokenResponse
+ if err := json.Unmarshal(respBody, &tokenResp); err != nil {
+ return "", fmt.Errorf("parse yunzhijia token response: %w", err)
+ }
+ if !tokenResp.Success || tokenResp.ErrorCode != 0 || tokenResp.Data.AccessToken == "" {
+ return "", fmt.Errorf("yunzhijia token response failed: errorCode=%d error=%v", tokenResp.ErrorCode, tokenResp.Error)
+ }
+
+ expiresIn := tokenResp.Data.ExpireIn
+ if expiresIn <= 0 {
+ expiresIn = 3600
+ }
+ expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
+ if expiresIn > 120 {
+ expiresAt = expiresAt.Add(-60 * time.Second)
+ }
+
+ a.tokenMu.Lock()
+ a.accessToken = tokenResp.Data.AccessToken
+ a.accessTokenExpiresAt = expiresAt
+ a.tokenMu.Unlock()
+ return tokenResp.Data.AccessToken, nil
+}
+
+func resolveDownloadFileName(fallback string, resp *http.Response) string {
+ fileName := fallback
+ if cd := resp.Header.Get("Content-Disposition"); cd != "" {
+ if _, params, err := mime.ParseMediaType(cd); err == nil {
+ if name := strings.TrimSpace(params["filename"]); name != "" {
+ fileName = name
+ }
+ }
+ }
+ if filepath.Ext(fileName) == "" {
+ switch strings.ToLower(strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])) {
+ case "image/jpeg":
+ fileName += ".jpg"
+ case "image/png":
+ fileName += ".png"
+ case "image/gif":
+ fileName += ".gif"
+ }
+ }
+ return fileName
+}
+
// validateSendURL checks that sendMsgUrl is safe to call (HTTPS, no internal IPs, allowed host).
func (a *Adapter) validateSendURL() error {
_, err := validateEndpointURL(a.sendMsgURL, "https", a.allowedWebhookHostSuffix)
diff --git a/internal/im/yunzhijia/adapter_test.go b/internal/im/yunzhijia/adapter_test.go
index 72ca22438..ec6511b9a 100644
--- a/internal/im/yunzhijia/adapter_test.go
+++ b/internal/im/yunzhijia/adapter_test.go
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"github.com/gin-gonic/gin"
@@ -36,7 +37,7 @@ func TestVerifyCallbackSignature(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = req
- adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", 10, "yunzhijia.com")
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", "", "", 10, "yunzhijia.com")
if err := adapter.VerifyCallback(c); err != nil {
t.Fatalf("VerifyCallback() error = %v", err)
}
@@ -68,8 +69,94 @@ func TestCleanAtMentionRequiresNameBoundary(t *testing.T) {
}
}
+func TestToIncomingMessageParsesMsgParamImage(t *testing.T) {
+ msg := &callbackMessage{
+ Type: 2,
+ MsgType: 23,
+ RobotID: "BOT-1",
+ RobotName: "Websocket",
+ GroupID: "group-1",
+ OperatorOpenid: "user",
+ OperatorName: "User",
+ Time: 123,
+ MsgID: "message",
+ Content: "@Websocket 图片测试一下看看[图片]",
+ GroupType: 2,
+ MsgParam: `{"desc":[{"data":"BOT-1","length":10,"start":0,"type":"at"},` +
+ `{"data":"file-1","h":1032,"length":4,"start":19,"type":"image","w":1920}],` +
+ `"notifyTo":["BOT-1"],"notifyType":1}`,
+ }
+
+ got := toIncomingMessage(t.Context(), msg)
+ if got == nil {
+ t.Fatal("toIncomingMessage() returned nil")
+ }
+ if got.MessageType != im.MessageTypeImage {
+ t.Fatalf("MessageType = %q, want image", got.MessageType)
+ }
+ if got.FileKey != "file-1" {
+ t.Fatalf("FileKey = %q, want file-1", got.FileKey)
+ }
+ if got.FileName != "message.png" {
+ t.Fatalf("FileName = %q, want message.png", got.FileName)
+ }
+ if got.ChatID != "group-1" {
+ t.Fatalf("ChatID = %q, want group-1", got.ChatID)
+ }
+ if got.Content != "图片测试一下看看[图片]" {
+ t.Fatalf("Content = %q", got.Content)
+ }
+ if got.Extra["yunzhijia_image_width"] != "1920" || got.Extra["yunzhijia_image_height"] != "1032" {
+ t.Fatalf("image dimensions extra = %#v", got.Extra)
+ }
+}
+
+func TestToIncomingMessageAcceptsMsgParamMention(t *testing.T) {
+ msg := &callbackMessage{
+ Type: 2,
+ RobotID: "BOT-1",
+ RobotName: "Websocket",
+ OperatorOpenid: "user",
+ OperatorName: "User",
+ Time: 123,
+ MsgID: "message",
+ Content: "图片测试一下看看[图片]",
+ MsgParam: `{"desc":[{"data":"BOT-1","type":"at"},{"data":"file-1","type":"image"}]}`,
+ }
+
+ got := toIncomingMessage(t.Context(), msg)
+ if got == nil {
+ t.Fatal("toIncomingMessage() returned nil")
+ }
+ if got.FileKey != "file-1" {
+ t.Fatalf("FileKey = %q, want file-1", got.FileKey)
+ }
+}
+
+func TestToIncomingMessageAcceptsImageWithoutText(t *testing.T) {
+ msg := &callbackMessage{
+ Type: 2,
+ RobotID: "BOT-1",
+ RobotName: "Websocket",
+ OperatorOpenid: "user",
+ OperatorName: "User",
+ Time: 123,
+ MsgID: "message",
+ Content: "",
+ MsgParam: `{"desc":[{"data":"BOT-1","type":"at"},{"data":"file-1","type":"image"}]}`,
+ }
+
+ got := toIncomingMessage(t.Context(), msg)
+ if got == nil {
+ t.Fatal("toIncomingMessage() returned nil")
+ }
+ if got.MessageType != im.MessageTypeImage || got.FileKey != "file-1" || got.Content != "" {
+ t.Fatalf("incoming = %#v", got)
+ }
+}
+
func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
- adapter := NewAdapter("https://www.yunzhijia.com/send", "", 10, "yunzhijia.com")
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
var payload sendMessagePayload
adapter.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
@@ -98,7 +185,7 @@ func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
}
func TestSendReplyFormatTypeOverride(t *testing.T) {
- adapter := NewAdapter("https://www.yunzhijia.com/send", "", 10, "yunzhijia.com")
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
var payload sendMessagePayload
adapter.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
@@ -135,3 +222,91 @@ func TestSendReplyFormatTypeOverride(t *testing.T) {
t.Fatalf("expected overridden format type 'text', got %#v", payload.Param)
}
}
+
+func TestBuildDownloadFileURL(t *testing.T) {
+ got := buildDownloadFileURL("file-1")
+ if got != "https://yunzhijia.com/gateway/docrest/doc/file/downloadfileOpen?fileId=file-1" {
+ t.Fatalf("download URL = %q", got)
+ }
+}
+
+func TestDownloadFile(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/oauth2_v12/auth/getAppAccessToken":
+ if r.Method != http.MethodPost {
+ t.Fatalf("token method = %s", r.Method)
+ }
+ var tokenReq map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&tokenReq); err != nil {
+ t.Fatalf("decode token request: %v", err)
+ }
+ if tokenReq["appId"] != "app-id" || tokenReq["secret"] != "app-secret" {
+ t.Fatalf("token request = %#v", tokenReq)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"data":{"accessToken":"token-1","expireIn":7136},"error":null,"errorCode":0,"success":true}`))
+ case "/gateway/docrest/doc/file/downloadfileOpen":
+ if r.Header.Get("Authorization") != "Bearer token-1" {
+ t.Fatalf("Authorization = %q", r.Header.Get("Authorization"))
+ }
+ if r.URL.Query().Get("fileId") != "file-1" {
+ t.Fatalf("query = %q", r.URL.RawQuery)
+ }
+ w.Header().Set("Content-Type", "image/png")
+ _, _ = w.Write([]byte("image-bytes"))
+ default:
+ t.Fatalf("path = %q", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ oldAuthURL := yunzhijiaAuthURL
+ oldBaseURL := yunzhijiaDownloadFileBaseURL
+ oldValidator := validateDownloadFileURL
+ yunzhijiaAuthURL = server.URL + "/api/oauth2_v12/auth/getAppAccessToken"
+ yunzhijiaDownloadFileBaseURL = server.URL + "/gateway/docrest/doc/file/downloadfileOpen"
+ validateDownloadFileURL = func(string) error { return nil }
+ defer func() {
+ yunzhijiaAuthURL = oldAuthURL
+ yunzhijiaDownloadFileBaseURL = oldBaseURL
+ validateDownloadFileURL = oldValidator
+ }()
+
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "", "app-id", "app-secret", 10, "yunzhijia.com")
+ adapter.httpClient = server.Client()
+ reader, fileName, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{
+ FileKey: "file-1",
+ FileName: "message.png",
+ })
+ if err != nil {
+ t.Fatalf("DownloadFile() error = %v", err)
+ }
+ defer reader.Close()
+ body, err := io.ReadAll(reader)
+ if err != nil {
+ t.Fatalf("read body: %v", err)
+ }
+ if string(body) != "image-bytes" || fileName != "message.png" {
+ t.Fatalf("body=%q fileName=%q", string(body), fileName)
+ }
+}
+
+func TestDownloadFileRequiresAppCredentials(t *testing.T) {
+ adapter := NewAdapter("https://www.yunzhijia.com/send", "", "", "", 10, "yunzhijia.com")
+ _, _, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{FileKey: "file-1"})
+ if err == nil || !strings.Contains(err.Error(), "app_id and app_secret") {
+ t.Fatalf("DownloadFile() error = %v, want app credential error", err)
+ }
+}
+
+func TestValidateFileIDRejectsURLishValues(t *testing.T) {
+ for _, fileID := range []string{"", "a/b", "a?b", "a&b", "a b"} {
+ if err := validateFileID(fileID); err == nil {
+ t.Fatalf("validateFileID(%q) = nil, want error", fileID)
+ }
+ }
+ if err := validateFileID("6a605afe5dda8e000121fcea"); err != nil {
+ t.Fatalf("validateFileID(valid) error = %v", err)
+ }
+}
diff --git a/internal/im/yunzhijia/factory.go b/internal/im/yunzhijia/factory.go
index 205907172..40252c363 100644
--- a/internal/im/yunzhijia/factory.go
+++ b/internal/im/yunzhijia/factory.go
@@ -24,11 +24,13 @@ func NewFactory() im.AdapterFactory {
}
secret := im.GetString(creds, "secret")
+ appID := im.GetString(creds, "app_id")
+ appSecret := im.GetString(creds, "app_secret")
allowedHostSuffix := im.GetString(creds, "allowed_webhook_host_suffix")
timeoutSeconds := positiveIntCredential(creds, "timeout_seconds", 10)
- adapter := NewAdapter(sendMsgURL, secret, timeoutSeconds, allowedHostSuffix)
+ adapter := NewAdapter(sendMsgURL, secret, appID, appSecret, timeoutSeconds, allowedHostSuffix)
if err := adapter.validateSendURL(); err != nil {
return nil, nil, err
}
diff --git a/internal/im/yunzhijia/types.go b/internal/im/yunzhijia/types.go
index d154b1973..f7b86f669 100644
--- a/internal/im/yunzhijia/types.go
+++ b/internal/im/yunzhijia/types.go
@@ -1,16 +1,44 @@
package yunzhijia
+import "encoding/json"
+
// callbackMessage is the JSON structure that Yunzhijia posts to the webhook.
type callbackMessage struct {
Type int `json:"type"`
+ MsgType int `json:"msgType"`
+ EID string `json:"eid"`
+ ClientID string `json:"clientId"`
RobotID string `json:"robotId"`
RobotName string `json:"robotName"`
+ OpenID string `json:"openId"`
+ GroupID string `json:"groupId"`
OperatorOpenid string `json:"operatorOpenid"`
+ OperatorOID string `json:"operatorOid"`
+ OperatorID string `json:"operatorId"`
+ OperatorUserID string `json:"operatorUserId"`
OperatorName string `json:"operatorName"`
+ SenderID string `json:"senderId"`
+ SenderName string `json:"senderName"`
Time int64 `json:"time"`
MsgID string `json:"msgId"`
Content string `json:"content"`
GroupType int `json:"groupType"`
+ MsgParam string `json:"msgParam"`
+}
+
+type messageParam struct {
+ Desc []messageParamDesc `json:"desc"`
+ NotifyTo []string `json:"notifyTo"`
+ NotifyType int `json:"notifyType"`
+}
+
+type messageParamDesc struct {
+ Type string `json:"type"`
+ Data string `json:"data"`
+ Start int `json:"start"`
+ Length int `json:"length"`
+ Width int `json:"w"`
+ Height int `json:"h"`
}
// sendMessagePayload is the JSON body POSTed to sendMsgUrl to reply.
@@ -32,3 +60,39 @@ type notifyParam struct {
type sendMessageParam struct {
FormatType string `json:"formatType,omitempty"`
}
+
+type appAccessTokenResponse struct {
+ Data appAccessTokenData `json:"data"`
+ Error any `json:"error"`
+ ErrorCode int `json:"errorCode"`
+ Success bool `json:"success"`
+}
+
+type appAccessTokenData struct {
+ AccessToken string `json:"accessToken"`
+ ExpireIn int64 `json:"expireIn"`
+ RefreshToken string `json:"refreshToken"`
+}
+
+func (m *messageParam) firstImage() (messageParamDesc, bool) {
+ if m == nil {
+ return messageParamDesc{}, false
+ }
+ for _, desc := range m.Desc {
+ if desc.Type == "image" && desc.Data != "" {
+ return desc, true
+ }
+ }
+ return messageParamDesc{}, false
+}
+
+func parseMessageParam(raw string) (*messageParam, error) {
+ if raw == "" {
+ return nil, nil
+ }
+ var param messageParam
+ if err := json.Unmarshal([]byte(raw), &param); err != nil {
+ return nil, err
+ }
+ return &param, nil
+}