feat(im): add Yunzhijia integration
This commit is contained in:
@@ -296,7 +296,7 @@ export interface IMChannel {
|
||||
tenant_id?: number;
|
||||
agent_id: string;
|
||||
// 'lark' is Feishu's international edition; it shares Feishu's credentials and modes.
|
||||
platform: 'wecom' | 'feishu' | 'lark' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost' | 'wechat' | 'qqbot';
|
||||
platform: 'wecom' | 'feishu' | 'lark' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost' | 'wechat' | 'qqbot' | 'yunzhijia';
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
mode: 'webhook' | 'websocket' | 'longpoll';
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 10 KiB |
@@ -154,7 +154,8 @@
|
||||
<div class="option-chips">
|
||||
<button type="button" class="option-chip"
|
||||
:class="{ 'option-chip--active': formData.mode === 'websocket' }"
|
||||
:disabled="formData.platform === 'mattermost'" @click="formData.mode = 'websocket'">
|
||||
:disabled="formData.platform === 'mattermost'"
|
||||
@click="formData.mode = 'websocket'">
|
||||
WebSocket
|
||||
</button>
|
||||
<button type="button" class="option-chip" :class="{ 'option-chip--active': formData.mode === 'webhook' }"
|
||||
@@ -164,7 +165,8 @@
|
||||
</div>
|
||||
<p class="form-desc">
|
||||
{{ formData.platform === 'mattermost' ? $t('agentEditor.im.mattermostModeHint') :
|
||||
$t('agentEditor.im.modeHint') }}
|
||||
formData.platform === 'yunzhijia' ? $t('agentEditor.im.yunzhijiaModeHint') :
|
||||
$t('agentEditor.im.modeHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -472,6 +474,40 @@
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 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=..." />
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaSecret') }}</label>
|
||||
<t-input v-model="formData.credentials.secret" type="password"
|
||||
: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.yunzhijiaTimeout') }}</label>
|
||||
<t-input-number v-model="formData.credentials.timeout_seconds" placeholder="10" :min="1" :max="60"
|
||||
style="width: 100%;" />
|
||||
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaTimeoutHint') }}</p>
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label required">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffix') }}</label>
|
||||
<t-input v-model="formData.credentials.allowed_webhook_host_suffix" placeholder="yunzhijia.com" />
|
||||
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffixHint') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- WeChat credentials (QR code binding) -->
|
||||
<template v-if="formData.platform === 'wechat'">
|
||||
<p class="form-desc">{{ $t('agentEditor.im.wechatHint') }}</p>
|
||||
@@ -545,6 +581,7 @@ import dingtalkLogo from '@/assets/img/im/dingtalk.svg';
|
||||
import mattermostLogo from '@/assets/img/im/mattermost.svg';
|
||||
import wechatLogo from '@/assets/img/im/wechat.svg';
|
||||
import qqbotLogo from '@/assets/img/im/qqbot.png';
|
||||
import yunzhijiaLogo from '@/assets/img/im/yunzhijia.svg';
|
||||
|
||||
type IMPlatform = IMChannel['platform'];
|
||||
|
||||
@@ -558,6 +595,7 @@ const PLATFORM_LOGO: Record<string, string> = {
|
||||
mattermost: mattermostLogo,
|
||||
wechat: wechatLogo,
|
||||
qqbot: qqbotLogo,
|
||||
yunzhijia: yunzhijiaLogo,
|
||||
};
|
||||
|
||||
const platformLogo = (platform: string): string => (platform ? PLATFORM_LOGO[platform] || '' : '');
|
||||
@@ -609,6 +647,7 @@ const platformOptions = computed(() => ([
|
||||
{ value: 'mattermost' as IMPlatform, label: t('agentEditor.im.mattermost'), logo: mattermostLogo },
|
||||
{ value: 'wechat' as IMPlatform, label: t('agentEditor.im.wechat'), logo: wechatLogo },
|
||||
{ value: 'qqbot' as IMPlatform, label: t('agentEditor.im.qqbot'), logo: qqbotLogo },
|
||||
{ value: 'yunzhijia' as IMPlatform, label: t('agentEditor.im.yunzhijia'), logo: yunzhijiaLogo },
|
||||
]));
|
||||
|
||||
// Feishu and Lark are the same product on separate clouds, so each has its own
|
||||
@@ -756,6 +795,15 @@ function onPlatformChange(val: string | number | boolean) {
|
||||
if (val === 'wechat') {
|
||||
formData.value.mode = 'longpoll';
|
||||
formData.value.output_mode = 'full';
|
||||
} else if (val === 'mattermost' || val === 'yunzhijia') {
|
||||
formData.value.mode = 'webhook';
|
||||
formData.value.output_mode = 'stream';
|
||||
if (val === 'yunzhijia') {
|
||||
formData.value.credentials = {
|
||||
timeout_seconds: 10,
|
||||
allowed_webhook_host_suffix: 'yunzhijia.com',
|
||||
};
|
||||
}
|
||||
} else {
|
||||
formData.value.mode = 'websocket';
|
||||
formData.value.output_mode = 'stream';
|
||||
@@ -957,6 +1005,12 @@ 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 (editingChannel.value) {
|
||||
await updateIMChannel(editingChannel.value.id, {
|
||||
|
||||
@@ -5883,7 +5883,7 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'IM Integration',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Lark, Slack, Telegram, DingTalk, Mattermost, WeChat and QQBot',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Lark, Slack, Telegram, DingTalk, Mattermost, WeChat, QQBot and Yunzhijia',
|
||||
feishu: 'Feishu',
|
||||
lark: 'Lark',
|
||||
slack: 'Slack',
|
||||
@@ -5893,6 +5893,7 @@ export default {
|
||||
wecom: 'WeCom',
|
||||
wechat: 'WeChat',
|
||||
qqbot: 'QQBot',
|
||||
yunzhijia: 'Yunzhijia',
|
||||
addChannel: 'Add Channel',
|
||||
channelsTitle: 'IM Channels',
|
||||
disabled: 'Disabled',
|
||||
@@ -5922,6 +5923,17 @@ 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',
|
||||
yunzhijiaModeHint: 'Supports Webhook and WebSocket; WebSocket mode does not require a public callback URL.',
|
||||
yunzhijiaSendMsgUrl: 'Send Message URL',
|
||||
yunzhijiaSecret: 'Signature Secret (optional)',
|
||||
yunzhijiaSecretPlaceholder: 'HmacSHA1 signature secret from Yunzhijia robot settings',
|
||||
yunzhijiaSecretHint: 'If configured, incoming callbacks will be verified using HmacSHA1 signature',
|
||||
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',
|
||||
mattermostModeHint: 'Mattermost only supports Webhook mode (outgoing webhook + bot token).',
|
||||
mattermostPostToMain: 'Post replies in channel timeline',
|
||||
mattermostPostToMainHint:
|
||||
|
||||
@@ -5817,7 +5817,7 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 통합",
|
||||
description: "에이전트를 Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot 등 인스턴트 메시징 플랫폼에 연결",
|
||||
description: "에이전트를 Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot, Yunzhijia 등 인스턴트 메시징 플랫폼에 연결",
|
||||
wecom: "WeCom",
|
||||
feishu: "Feishu",
|
||||
lark: "Lark",
|
||||
@@ -5827,6 +5827,7 @@ export default {
|
||||
mattermost: "Mattermost",
|
||||
wechat: "WeChat",
|
||||
qqbot: "QQBot",
|
||||
yunzhijia: "Yunzhijia",
|
||||
addChannel: "채널 추가",
|
||||
channelsTitle: "IM 채널",
|
||||
disabled: "비활성",
|
||||
@@ -5856,6 +5857,17 @@ export default {
|
||||
qqbotConsole: "QQ Open Platform",
|
||||
qqbotAPIBaseURLHint: "선택 사항. 비워두면 기본 프로덕션 API 엔드포인트를 사용합니다.",
|
||||
qqbotGatewayURLHint: "선택 사항. 비워두면 공용 WebSocket gateway를 자동으로 가져옵니다.",
|
||||
yunzhijiaConsole: "Yunzhijia 로봇 콘솔",
|
||||
yunzhijiaModeHint: "Webhook과 WebSocket을 지원하며 WebSocket 모드에는 공개 콜백 URL이 필요하지 않습니다.",
|
||||
yunzhijiaSendMsgUrl: "메시지 전송 URL",
|
||||
yunzhijiaSecret: "서명 시크릿 (선택 사항)",
|
||||
yunzhijiaSecretPlaceholder: "Yunzhijia 로봇 설정의 HmacSHA1 서명 시크릿",
|
||||
yunzhijiaSecretHint: "설정하면 들어오는 콜백 요청이 HmacSHA1 서명으로 검증됩니다",
|
||||
yunzhijiaTimeout: "HTTP 타임아웃 (초)",
|
||||
yunzhijiaTimeoutHint: "메시지 전송 URL을 통한 응답 전송 타임아웃, 기본 10초",
|
||||
yunzhijiaAllowedHostSuffix: "허용 호스트 접미사",
|
||||
yunzhijiaAllowedHostSuffixHint: "보안을 위해 메시지 전송 URL 호스트를 이 접미사로 제한 (예: yunzhijia.com)",
|
||||
yunzhijiaRequiredCredentials: "메시지 전송 URL과 허용 호스트 접미사를 입력하세요",
|
||||
mattermostModeHint: "Mattermost는 Webhook(아웃고잉 웹훅 + 봇 토큰)만 지원합니다.",
|
||||
mattermostPostToMain: "답변을 채널 메인 타임라인에 표시",
|
||||
mattermostPostToMainHint:
|
||||
|
||||
@@ -5387,7 +5387,7 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'Интеграция IM',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как Feishu, Slack, Telegram, DingTalk, Mattermost и QQBot',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как Feishu, Slack, Telegram, DingTalk, Mattermost, QQBot и Yunzhijia',
|
||||
wecom: 'WeCom',
|
||||
feishu: 'Feishu',
|
||||
lark: 'Lark',
|
||||
@@ -5397,6 +5397,7 @@ export default {
|
||||
mattermost: 'Mattermost',
|
||||
wechat: 'WeChat',
|
||||
qqbot: 'QQBot',
|
||||
yunzhijia: 'Yunzhijia',
|
||||
addChannel: 'Добавить канал',
|
||||
channelsTitle: 'IM-каналы',
|
||||
disabled: 'Отключено',
|
||||
@@ -5426,6 +5427,17 @@ export default {
|
||||
qqbotConsole: 'QQ Open Platform',
|
||||
qqbotAPIBaseURLHint: 'Необязательно. Оставьте пустым, чтобы использовать стандартный production API endpoint.',
|
||||
qqbotGatewayURLHint: 'Необязательно. Оставьте пустым, чтобы автоматически получить общий WebSocket gateway.',
|
||||
yunzhijiaConsole: 'Консоль роботов Yunzhijia',
|
||||
yunzhijiaModeHint: 'Поддерживаются Webhook и WebSocket; для режима WebSocket не требуется публичный URL обратного вызова.',
|
||||
yunzhijiaSendMsgUrl: 'URL отправки сообщений',
|
||||
yunzhijiaSecret: 'Секрет подписи (необязательно)',
|
||||
yunzhijiaSecretPlaceholder: 'Секрет подписи HmacSHA1 из настроек робота Yunzhijia',
|
||||
yunzhijiaSecretHint: 'Если указано, входящие обратные вызовы будут проверяться с помощью подписи HmacSHA1',
|
||||
yunzhijiaTimeout: 'Таймаут HTTP (секунды)',
|
||||
yunzhijiaTimeoutHint: 'Таймаут отправки ответов через URL отправки сообщений, по умолчанию 10 секунд',
|
||||
yunzhijiaAllowedHostSuffix: 'Допустимый суффикс хоста',
|
||||
yunzhijiaAllowedHostSuffixHint: 'Ограничить хост URL отправки сообщений этим суффиксом для безопасности (напр. yunzhijia.com)',
|
||||
yunzhijiaRequiredCredentials: 'Укажите URL отправки сообщений и допустимый суффикс хоста',
|
||||
mattermostModeHint: 'Mattermost поддерживает только режим Webhook (исходящий вебхук + токен бота).',
|
||||
mattermostPostToMain: 'Ответы в основной ленте канала',
|
||||
mattermostPostToMainHint:
|
||||
|
||||
@@ -5838,7 +5838,7 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 集成",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉、Mattermost、微信和 QQBot",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉、Mattermost、微信、QQBot 和云之家",
|
||||
wecom: "企业微信",
|
||||
feishu: "飞书",
|
||||
lark: "Lark(飞书国际版)",
|
||||
@@ -5848,6 +5848,7 @@ export default {
|
||||
mattermost: "Mattermost",
|
||||
wechat: "微信",
|
||||
qqbot: "QQBot",
|
||||
yunzhijia: "云之家",
|
||||
addChannel: "添加渠道",
|
||||
channelsTitle: "IM 渠道",
|
||||
disabled: "已停用",
|
||||
@@ -5877,6 +5878,17 @@ export default {
|
||||
qqbotConsole: "QQ 开放平台",
|
||||
qqbotAPIBaseURLHint: "可选,留空则使用默认正式环境 API 地址。",
|
||||
qqbotGatewayURLHint: "可选,留空则自动获取通用 WebSocket 接入点。",
|
||||
yunzhijiaConsole: "云之家机器人后台",
|
||||
yunzhijiaModeHint: "支持 Webhook 和 WebSocket;WebSocket 模式无需配置公网回调地址。",
|
||||
yunzhijiaSendMsgUrl: "发送消息地址",
|
||||
yunzhijiaSecret: "签名密钥(可选)",
|
||||
yunzhijiaSecretPlaceholder: "云之家机器人设置中的 HmacSHA1 签名密钥",
|
||||
yunzhijiaSecretHint: "配置后,将对传入的回调请求进行 HmacSHA1 签名验证",
|
||||
yunzhijiaTimeout: "HTTP 超时时间(秒)",
|
||||
yunzhijiaTimeoutHint: "通过发送消息地址回复的超时时间,默认 10 秒",
|
||||
yunzhijiaAllowedHostSuffix: "允许的主机后缀",
|
||||
yunzhijiaAllowedHostSuffixHint: "限制发送消息地址的目标域名后缀,提升安全性(如 yunzhijia.com)",
|
||||
yunzhijiaRequiredCredentials: "请填写发送消息地址和允许的主机后缀",
|
||||
mattermostModeHint: "Mattermost 仅支持 Webhook(出站 Webhook + Bot Token)。",
|
||||
mattermostPostToMain: "回复显示在频道主时间线",
|
||||
mattermostPostToMainHint:
|
||||
|
||||
@@ -70,6 +70,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/im/telegram"
|
||||
"github.com/Tencent/WeKnora/internal/im/wechat"
|
||||
"github.com/Tencent/WeKnora/internal/im/wecom"
|
||||
"github.com/Tencent/WeKnora/internal/im/yunzhijia"
|
||||
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
|
||||
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
@@ -1555,6 +1556,7 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
|
||||
imService.RegisterAdapterFactory("mattermost", mattermost.NewFactory())
|
||||
imService.RegisterAdapterFactory("wechat", wechat.NewFactory())
|
||||
imService.RegisterAdapterFactory("qqbot", qqbot.NewFactory())
|
||||
imService.RegisterAdapterFactory("yunzhijia", yunzhijia.NewFactory())
|
||||
|
||||
// Load and start all enabled channels from database
|
||||
if err := imService.LoadAndStartChannels(); err != nil {
|
||||
|
||||
+19
-4
@@ -15,7 +15,7 @@ import (
|
||||
// validIMPlatforms is the set of supported IM platforms.
|
||||
var validIMPlatforms = map[string]bool{
|
||||
"wecom": true, "feishu": true, "lark": true, "slack": true, "telegram": true, "dingtalk": true,
|
||||
"mattermost": true, "wechat": true, "qqbot": true,
|
||||
"mattermost": true, "wechat": true, "qqbot": true, "yunzhijia": true,
|
||||
}
|
||||
|
||||
// invalidIMPlatformError is the 400 message listing the accepted platforms. It
|
||||
@@ -97,7 +97,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
channel.OutputMode = "full"
|
||||
} else {
|
||||
if channel.Mode == "" {
|
||||
if channel.Platform == "mattermost" {
|
||||
if channel.Platform == "mattermost" || channel.Platform == "yunzhijia" {
|
||||
channel.Mode = "webhook"
|
||||
} else {
|
||||
channel.Mode = "websocket"
|
||||
@@ -328,6 +328,21 @@ func (h *IMHandler) ToggleIMChannel(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"data": channel})
|
||||
}
|
||||
|
||||
func writeIMCallbackACK(c *gin.Context, platform string) {
|
||||
if platform == "yunzhijia" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"type": 2,
|
||||
"content": "",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// ── Callback handlers ──
|
||||
|
||||
// IMCallback handles IM platform callback requests for a specific channel.
|
||||
@@ -404,12 +419,12 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
|
||||
} else {
|
||||
logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
writeIMCallbackACK(c, channel.Platform)
|
||||
return
|
||||
}
|
||||
|
||||
// Respond immediately to avoid platform timeout
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
writeIMCallbackACK(c, channel.Platform)
|
||||
|
||||
// Detach from gin request context
|
||||
asyncCtx := context.WithoutCancel(ctx)
|
||||
|
||||
@@ -22,6 +22,7 @@ const (
|
||||
PlatformMattermost Platform = "mattermost"
|
||||
PlatformWeChat Platform = "wechat"
|
||||
PlatformQQBot Platform = "qqbot"
|
||||
PlatformYunzhijia Platform = "yunzhijia"
|
||||
)
|
||||
|
||||
// SessionMode determines how IM sessions are resolved.
|
||||
|
||||
+13
-1
@@ -1,8 +1,10 @@
|
||||
package im
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -94,7 +96,7 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
|
||||
ch.ID = uuid.New().String()
|
||||
}
|
||||
if ch.Mode == "" {
|
||||
if ch.Platform == "mattermost" {
|
||||
if ch.Platform == "mattermost" || ch.Platform == "yunzhijia" {
|
||||
ch.Mode = "webhook"
|
||||
} else {
|
||||
ch.Mode = "websocket"
|
||||
@@ -200,6 +202,16 @@ func (ch *IMChannel) computeBotIdentity() string {
|
||||
if appID := str("app_id"); appID != "" {
|
||||
return "qqbot:" + appID
|
||||
}
|
||||
case "yunzhijia":
|
||||
if sendMsgURL := str("send_msg_url"); sendMsgURL != "" {
|
||||
parsed, err := url.Parse(sendMsgURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if token := strings.TrimSpace(parsed.Query().Get("yzjtoken")); token != "" {
|
||||
return fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte(token)))
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package im
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -160,6 +162,44 @@ func TestComputeBotIdentity_LarkWithoutAppID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIMChannelComputeBotIdentity_YunzhijiaUsesYZJToken(t *testing.T) {
|
||||
makeChannel := func(sendMsgURL string) *IMChannel {
|
||||
return &IMChannel{
|
||||
Platform: "yunzhijia",
|
||||
Credentials: []byte(fmt.Sprintf(
|
||||
`{"send_msg_url":%q}`,
|
||||
sendMsgURL,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
first := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?yzjtoken=token-a&foo=1")
|
||||
second := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?yzjtoken=token-b&foo=1")
|
||||
firstWant := fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte("token-a")))
|
||||
secondWant := fmt.Sprintf("yunzhijia:%x", sha256.Sum256([]byte("token-b")))
|
||||
if first.computeBotIdentity() != firstWant {
|
||||
t.Errorf("first identity = %q, want %q", first.computeBotIdentity(), firstWant)
|
||||
}
|
||||
if second.computeBotIdentity() != secondWant {
|
||||
t.Errorf("second identity = %q, want %q", second.computeBotIdentity(), secondWant)
|
||||
}
|
||||
if first.computeBotIdentity() == second.computeBotIdentity() {
|
||||
t.Error("different yzjtoken values must produce different Yunzhijia bot identities")
|
||||
}
|
||||
|
||||
sameTokenDifferentQuery := makeChannel(
|
||||
"https://open.yunzhijia.com/gateway/robot/webhook/send?foo=2&yzjtoken=token-a",
|
||||
)
|
||||
if sameTokenDifferentQuery.computeBotIdentity() != first.computeBotIdentity() {
|
||||
t.Error("same yzjtoken must produce the same Yunzhijia bot identity")
|
||||
}
|
||||
|
||||
missingToken := makeChannel("https://open.yunzhijia.com/gateway/robot/webhook/send?foo=1")
|
||||
if missingToken.computeBotIdentity() != "" {
|
||||
t.Errorf("missing yzjtoken identity = %q, want empty", missingToken.computeBotIdentity())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelSessionThreadIDField(t *testing.T) {
|
||||
cs := ChannelSession{
|
||||
Platform: "slack",
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// textMessageType is the Yunzhijia message type value for plain text messages.
|
||||
const textMessageType = 2
|
||||
|
||||
// Compile-time check.
|
||||
var _ im.Adapter = (*Adapter)(nil)
|
||||
|
||||
// Adapter implements im.Adapter for Yunzhijia (云之家).
|
||||
type Adapter struct {
|
||||
sendMsgURL string
|
||||
secret string
|
||||
httpClient *http.Client
|
||||
allowedWebhookHostSuffix string
|
||||
}
|
||||
|
||||
// NewAdapter creates a Yunzhijia adapter.
|
||||
func NewAdapter(sendMsgURL, secret string, timeoutSeconds int, allowedHostSuffix string) *Adapter {
|
||||
if timeoutSeconds <= 0 {
|
||||
timeoutSeconds = 10
|
||||
}
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.Proxy = nil
|
||||
transport.DialContext = safeDialContext
|
||||
return &Adapter{
|
||||
sendMsgURL: strings.TrimSpace(sendMsgURL),
|
||||
secret: secret,
|
||||
allowedWebhookHostSuffix: strings.TrimSpace(allowedHostSuffix),
|
||||
httpClient: &http.Client{
|
||||
Timeout: time.Duration(timeoutSeconds) * time.Second,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
return im.PlatformYunzhijia
|
||||
}
|
||||
|
||||
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// VerifyCallback verifies the Yunzhijia callback signature (HmacSHA1).
|
||||
// If secret is not configured, verification is skipped.
|
||||
func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
if a.secret == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
var msg callbackMessage
|
||||
if err := json.Unmarshal(bodyBytes, &msg); err != nil {
|
||||
return fmt.Errorf("parse callback for verification: %w", err)
|
||||
}
|
||||
|
||||
// Read the sign header (case-insensitive via gin's GetHeader).
|
||||
sign := c.GetHeader("sign")
|
||||
if sign == "" {
|
||||
sign = c.GetHeader("Sign")
|
||||
}
|
||||
if sign == "" {
|
||||
sign = c.GetHeader("SIGN")
|
||||
}
|
||||
if sign == "" {
|
||||
return fmt.Errorf("missing sign header")
|
||||
}
|
||||
|
||||
expected := computeSignature(a.secret, &msg)
|
||||
if !hmac.Equal([]byte(sign), []byte(expected)) {
|
||||
return fmt.Errorf("invalid signature")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseCallback parses a Yunzhijia webhook callback into an IncomingMessage.
|
||||
// Returns nil for non-text messages or empty content.
|
||||
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
var msg callbackMessage
|
||||
if err := json.Unmarshal(bodyBytes, &msg); err != nil {
|
||||
return nil, fmt.Errorf("parse callback: %w", err)
|
||||
}
|
||||
|
||||
return toIncomingMessage(c.Request.Context(), &msg), nil
|
||||
}
|
||||
|
||||
func toIncomingMessage(ctx context.Context, msg *callbackMessage) *im.IncomingMessage {
|
||||
if msg.Type != textMessageType {
|
||||
logger.Infof(ctx,
|
||||
"[Yunzhijia] Skip non-text message: type=%d msgId=%s", msg.Type, msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(msg.Content)
|
||||
if content == "" {
|
||||
logger.Infof(ctx,
|
||||
"[Yunzhijia] Skip empty content: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Conversation bots should only receive messages explicitly addressed to them.
|
||||
var mentioned bool
|
||||
content, mentioned = cleanAtMention(content, msg.RobotName)
|
||||
if !mentioned {
|
||||
logger.Infof(ctx, "[Yunzhijia] Skip message without robot mention: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if content == "" {
|
||||
logger.Infof(ctx,
|
||||
"[Yunzhijia] Skip after cleaning @mention: msgId=%s", msg.MsgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
chatType := im.ChatTypeGroup
|
||||
chatID := msg.RobotID
|
||||
|
||||
return &im.IncomingMessage{
|
||||
Platform: im.PlatformYunzhijia,
|
||||
MessageType: im.MessageTypeText,
|
||||
UserID: msg.OperatorOpenid,
|
||||
UserName: msg.OperatorName,
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
Content: content,
|
||||
MessageID: msg.MsgID,
|
||||
Extra: map[string]string{
|
||||
"robot_id": msg.RobotID,
|
||||
"robot_name": msg.RobotName,
|
||||
"group_type": fmt.Sprintf("%d", msg.GroupType),
|
||||
"operator_name": msg.OperatorName,
|
||||
"time": fmt.Sprintf("%d", msg.Time),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// cleanAtMention removes @RobotName from the beginning of user content.
|
||||
func cleanAtMention(content, robotName string) (string, bool) {
|
||||
if robotName == "" {
|
||||
return content, false
|
||||
}
|
||||
prefix := "@" + robotName
|
||||
trimmed := strings.TrimLeft(content, " \t")
|
||||
if !strings.HasPrefix(trimmed, prefix) {
|
||||
return content, false
|
||||
}
|
||||
rest := trimmed[len(prefix):]
|
||||
if rest == "" {
|
||||
return "", true
|
||||
}
|
||||
separator, _ := utf8.DecodeRuneInString(rest)
|
||||
if !unicode.IsSpace(separator) && !strings.ContainsRune("::,,", separator) {
|
||||
return content, false
|
||||
}
|
||||
return strings.TrimLeftFunc(rest, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || strings.ContainsRune("::,,", r)
|
||||
}), true
|
||||
}
|
||||
|
||||
// SendReply sends a reply to Yunzhijia via the configured sendMsgUrl.
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
if a.sendMsgURL == "" {
|
||||
return fmt.Errorf("yunzhijia send_msg_url is not configured")
|
||||
}
|
||||
|
||||
// Validate the send URL to prevent SSRF.
|
||||
if err := a.validateSendURL(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
payload := sendMessagePayload{
|
||||
MsgType: textMessageType,
|
||||
Content: reply.Content,
|
||||
}
|
||||
|
||||
// When groupType == 3, don't set notifyParams (per reference implementation).
|
||||
groupType := ""
|
||||
if incoming.Extra != nil {
|
||||
groupType = incoming.Extra["group_type"]
|
||||
}
|
||||
if groupType != "3" && incoming.UserID != "" {
|
||||
payload.NotifyParams = []notifyParam{
|
||||
{
|
||||
Type: "openIds",
|
||||
Values: []string{incoming.UserID},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
jsonBody, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal reply: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.sendMsgURL, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send reply: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("yunzhijia sendMsgUrl returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid send_msg_url: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
func TestVerifyCallbackSignature(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
msg := callbackMessage{
|
||||
Type: 2, RobotID: "robot", RobotName: "WeKnora", OperatorOpenid: "user",
|
||||
OperatorName: "User", Time: 123, MsgID: "message", Content: "@WeKnora hello",
|
||||
}
|
||||
body, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/callback", bytes.NewReader(body))
|
||||
req.Header.Set("Sign", computeSignature("secret", &msg))
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = req
|
||||
|
||||
adapter := NewAdapter("https://www.yunzhijia.com/send", "secret", 10, "yunzhijia.com")
|
||||
if err := adapter.VerifyCallback(c); err != nil {
|
||||
t.Fatalf("VerifyCallback() error = %v", err)
|
||||
}
|
||||
parsed, err := adapter.ParseCallback(c)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCallback() error = %v", err)
|
||||
}
|
||||
if parsed == nil || parsed.Content != "hello" {
|
||||
t.Fatalf("parsed message = %#v, want content hello", parsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToIncomingMessageRequiresRobotMention(t *testing.T) {
|
||||
msg := &callbackMessage{
|
||||
Type: 2, RobotID: "robot", RobotName: "WeKnora", OperatorOpenid: "user",
|
||||
OperatorName: "User", Time: 123, MsgID: "message", Content: "hello",
|
||||
}
|
||||
if got := toIncomingMessage(t.Context(), msg); got != nil {
|
||||
t.Fatalf("toIncomingMessage() = %#v, want nil without robot mention", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanAtMentionRequiresNameBoundary(t *testing.T) {
|
||||
if _, mentioned := cleanAtMention("@WeKnoraPlus hello", "WeKnora"); mentioned {
|
||||
t.Fatal("longer user name must not be treated as a robot mention")
|
||||
}
|
||||
if got, mentioned := cleanAtMention("@WeKnora:你好", "WeKnora"); !mentioned || got != "你好" {
|
||||
t.Fatalf("cleanAtMention() = %q, %v; want 你好, true", got, mentioned)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendReplyAcceptsAny2xxAndBuildsPayload(t *testing.T) {
|
||||
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 {
|
||||
t.Fatalf("decode payload: %v", err)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusNoContent,
|
||||
Body: io.NopCloser(bytes.NewReader(nil)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
|
||||
incoming := &im.IncomingMessage{UserID: "user", Extra: map[string]string{"group_type": "1"}}
|
||||
if err := adapter.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "answer"}); err != nil {
|
||||
t.Fatalf("SendReply() error = %v", err)
|
||||
}
|
||||
if payload.MsgType != textMessageType || payload.Content != "answer" {
|
||||
t.Fatalf("payload = %#v", payload)
|
||||
}
|
||||
if len(payload.NotifyParams) != 1 || len(payload.NotifyParams[0].Values) != 1 || payload.NotifyParams[0].Values[0] != "user" {
|
||||
t.Fatalf("notify params = %#v", payload.NotifyParams)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// NewFactory returns an im.AdapterFactory for Yunzhijia channels.
|
||||
// Webhook remains the default; WebSocket uses yzjtoken from send_msg_url.
|
||||
func NewFactory() im.AdapterFactory {
|
||||
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
|
||||
creds, err := im.ParseCredentials(channel.Credentials)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse yunzhijia credentials: %w", err)
|
||||
}
|
||||
|
||||
sendMsgURL := im.GetString(creds, "send_msg_url")
|
||||
if sendMsgURL == "" {
|
||||
return nil, nil, fmt.Errorf("yunzhijia send_msg_url is required")
|
||||
}
|
||||
|
||||
secret := im.GetString(creds, "secret")
|
||||
allowedHostSuffix := im.GetString(creds, "allowed_webhook_host_suffix")
|
||||
|
||||
timeoutSeconds := positiveIntCredential(creds, "timeout_seconds", 10)
|
||||
|
||||
adapter := NewAdapter(sendMsgURL, secret, timeoutSeconds, allowedHostSuffix)
|
||||
if err := adapter.validateSendURL(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
mode := im.ResolveMode(channel, "webhook")
|
||||
switch mode {
|
||||
case "webhook":
|
||||
return adapter, nil, nil
|
||||
case "websocket":
|
||||
webSocketURL, err := deriveWebSocketURL(sendMsgURL, allowedHostSuffix)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := NewLongConnClient(webSocketURL, msgHandler)
|
||||
wsCtx, wsCancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
|
||||
logger.Errorf(context.Background(), "[IM] Yunzhijia WebSocket stopped for channel %s: %v", channel.ID, err)
|
||||
}
|
||||
}()
|
||||
stop := func() {
|
||||
client.Stop()
|
||||
wsCancel()
|
||||
}
|
||||
return adapter, stop, nil
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unsupported yunzhijia mode: %s", mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func positiveIntCredential(creds map[string]any, key string, fallback int) int {
|
||||
switch value := creds[key].(type) {
|
||||
case float64:
|
||||
if value > 0 {
|
||||
return int(value)
|
||||
}
|
||||
case string:
|
||||
if parsed, err := strconv.Atoi(value); err == nil && parsed > 0 {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// computeSignature builds the signature string from the callback fields
|
||||
// and returns the Base64(HMAC_SHA1(secret, signatureString)).
|
||||
//
|
||||
// The signature string is formed by joining the following fields in order
|
||||
// with commas: robotId, robotName, operatorOpenid, operatorName, time, msgId, content.
|
||||
func computeSignature(secret string, msg *callbackMessage) string {
|
||||
// Build signature string: field1,field2,...,field7
|
||||
parts := []string{
|
||||
msg.RobotID,
|
||||
msg.RobotName,
|
||||
msg.OperatorOpenid,
|
||||
msg.OperatorName,
|
||||
fmt.Sprintf("%d", msg.Time),
|
||||
msg.MsgID,
|
||||
msg.Content,
|
||||
}
|
||||
signatureString := strings.Join(parts, ",")
|
||||
|
||||
mac := hmac.New(sha1.New, []byte(secret))
|
||||
mac.Write([]byte(signatureString))
|
||||
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package yunzhijia
|
||||
|
||||
// callbackMessage is the JSON structure that Yunzhijia posts to the webhook.
|
||||
type callbackMessage struct {
|
||||
Type int `json:"type"`
|
||||
RobotID string `json:"robotId"`
|
||||
RobotName string `json:"robotName"`
|
||||
OperatorOpenid string `json:"operatorOpenid"`
|
||||
OperatorName string `json:"operatorName"`
|
||||
Time int64 `json:"time"`
|
||||
MsgID string `json:"msgId"`
|
||||
Content string `json:"content"`
|
||||
GroupType int `json:"groupType"`
|
||||
}
|
||||
|
||||
// sendMessagePayload is the JSON body POSTed to sendMsgUrl to reply.
|
||||
type sendMessagePayload struct {
|
||||
MsgType int `json:"msgtype"`
|
||||
Content string `json:"content"`
|
||||
NotifyParams []notifyParam `json:"notifyParams,omitempty"`
|
||||
}
|
||||
|
||||
// notifyParam specifies recipients in a Yunzhijia send message request.
|
||||
type notifyParam struct {
|
||||
Type string `json:"type"`
|
||||
Values []string `json:"values"`
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func deriveWebSocketURL(sendMsgURL, allowedHostSuffix string) (string, error) {
|
||||
u, err := validateEndpointURL(sendMsgURL, "https", allowedHostSuffix)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid send_msg_url for websocket: %w", err)
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(u.Query().Get("yzjtoken"))
|
||||
if token == "" {
|
||||
return "", fmt.Errorf("send_msg_url is missing yzjtoken")
|
||||
}
|
||||
|
||||
wsURL := &url.URL{
|
||||
Scheme: "wss",
|
||||
Host: u.Host,
|
||||
Path: "/xuntong/websocket",
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("yzjtoken", token)
|
||||
wsURL.RawQuery = query.Encode()
|
||||
return wsURL.String(), nil
|
||||
}
|
||||
|
||||
func validateEndpointURL(rawURL, requiredScheme, allowedHostSuffix string) (*url.URL, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !strings.EqualFold(u.Scheme, requiredScheme) {
|
||||
return nil, fmt.Errorf("URL must use %s", requiredScheme)
|
||||
}
|
||||
if u.User != nil {
|
||||
return nil, fmt.Errorf("URL must not contain user information")
|
||||
}
|
||||
|
||||
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
|
||||
if host == "" {
|
||||
return nil, fmt.Errorf("URL has empty host")
|
||||
}
|
||||
if host == "localhost" || strings.HasSuffix(host, ".localhost") || net.ParseIP(host) != nil {
|
||||
return nil, fmt.Errorf("URL host must be a DNS name")
|
||||
}
|
||||
|
||||
suffix := strings.ToLower(strings.Trim(strings.TrimSpace(allowedHostSuffix), "."))
|
||||
if suffix == "" {
|
||||
return nil, fmt.Errorf("allowed host suffix is required")
|
||||
}
|
||||
if host != suffix && !strings.HasSuffix(host, "."+suffix) {
|
||||
return nil, fmt.Errorf("URL host %q does not match allowed suffix %q", host, suffix)
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func safeDialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("split dial address: %w", err)
|
||||
}
|
||||
addresses, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve endpoint host %q: %w", host, err)
|
||||
}
|
||||
if len(addresses) == 0 {
|
||||
return nil, fmt.Errorf("endpoint host %q resolved to no addresses", host)
|
||||
}
|
||||
for _, address := range addresses {
|
||||
if !isPublicIP(address.IP) {
|
||||
return nil, fmt.Errorf("endpoint host %q resolves to a non-public address", host)
|
||||
}
|
||||
}
|
||||
|
||||
dialer := &net.Dialer{}
|
||||
var lastErr error
|
||||
for _, address := range addresses {
|
||||
conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(address.IP.String(), port))
|
||||
if dialErr == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = dialErr
|
||||
}
|
||||
return nil, fmt.Errorf("dial endpoint host %q: %w", host, lastErr)
|
||||
}
|
||||
|
||||
func isPublicIP(ip net.IP) bool {
|
||||
return ip != nil && !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast() &&
|
||||
!ip.IsLinkLocalMulticast() && !ip.IsUnspecified() && !ip.IsMulticast()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeriveWebSocketURL(t *testing.T) {
|
||||
got, err := deriveWebSocketURL(
|
||||
"https://dev.kdweibo.cn:8443/gateway/robot/webhook/send?yzjtype=12&yzjtoken=token%20value",
|
||||
"kdweibo.cn",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("deriveWebSocketURL() error = %v", err)
|
||||
}
|
||||
want := "wss://dev.kdweibo.cn:8443/xuntong/websocket?yzjtoken=token+value"
|
||||
if got != want {
|
||||
t.Fatalf("deriveWebSocketURL() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveWebSocketURLRejectsMissingToken(t *testing.T) {
|
||||
_, err := deriveWebSocketURL("https://www.yunzhijia.com/gateway/robot/webhook/send", "yunzhijia.com")
|
||||
if err == nil {
|
||||
t.Fatal("deriveWebSocketURL() expected missing-token error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateEndpointURLHostSuffixBoundary(t *testing.T) {
|
||||
valid := []string{
|
||||
"https://yunzhijia.com/path",
|
||||
"https://www.yunzhijia.com/path",
|
||||
}
|
||||
for _, rawURL := range valid {
|
||||
if _, err := validateEndpointURL(rawURL, "https", "yunzhijia.com"); err != nil {
|
||||
t.Errorf("validateEndpointURL(%q) unexpected error: %v", rawURL, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"http://www.yunzhijia.com/path",
|
||||
"https://evilyunzhijia.com/path",
|
||||
"https://127.0.0.1/path",
|
||||
"https://localhost/path",
|
||||
}
|
||||
for _, rawURL := range invalid {
|
||||
if _, err := validateEndpointURL(rawURL, "https", "yunzhijia.com"); err == nil {
|
||||
t.Errorf("validateEndpointURL(%q) expected error", rawURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateEndpointURLRequiresHostSuffix(t *testing.T) {
|
||||
if _, err := validateEndpointURL("https://www.yunzhijia.com/path", "https", ""); err == nil {
|
||||
t.Fatal("validateEndpointURL() expected missing host suffix error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPublicIP(t *testing.T) {
|
||||
for _, rawIP := range []string{"127.0.0.1", "10.0.0.1", "169.254.169.254", "::1", "fc00::1"} {
|
||||
if isPublicIP(net.ParseIP(rawIP)) {
|
||||
t.Errorf("isPublicIP(%q) = true, want false", rawIP)
|
||||
}
|
||||
}
|
||||
if !isPublicIP(net.ParseIP("8.8.8.8")) {
|
||||
t.Error("isPublicIP(8.8.8.8) = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPositiveIntCredential(t *testing.T) {
|
||||
if got := positiveIntCredential(map[string]any{"timeout": float64(25)}, "timeout", 10); got != 25 {
|
||||
t.Fatalf("numeric timeout = %d, want 25", got)
|
||||
}
|
||||
if got := positiveIntCredential(map[string]any{"timeout": "30"}, "timeout", 10); got != 30 {
|
||||
t.Fatalf("string timeout = %d, want 30", got)
|
||||
}
|
||||
if got := positiveIntCredential(map[string]any{"timeout": float64(0)}, "timeout", 10); got != 10 {
|
||||
t.Fatalf("invalid timeout = %d, want fallback 10", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
ws "github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
webSocketHeartbeatInterval = 15 * time.Second
|
||||
webSocketReadTimeout = 45 * time.Second
|
||||
webSocketHandshakeTimeout = 10 * time.Second
|
||||
webSocketMaxMessageSize = 1 << 20
|
||||
webSocketMaxInvalidFrames = 3
|
||||
webSocketMessageQueueSize = 64
|
||||
)
|
||||
|
||||
var webSocketReconnectDelays = [...]time.Duration{
|
||||
1 * time.Second,
|
||||
2 * time.Second,
|
||||
5 * time.Second,
|
||||
10 * time.Second,
|
||||
30 * time.Second,
|
||||
60 * time.Second,
|
||||
}
|
||||
|
||||
type webSocketFrame struct {
|
||||
message *callbackMessage
|
||||
ack []byte
|
||||
control string
|
||||
}
|
||||
|
||||
type LongConnClient struct {
|
||||
url string
|
||||
handler func(context.Context, *im.IncomingMessage) error
|
||||
dialer *ws.Dialer
|
||||
messages chan *im.IncomingMessage
|
||||
|
||||
mu sync.Mutex
|
||||
conn *ws.Conn
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func NewLongConnClient(webSocketURL string, handler func(context.Context, *im.IncomingMessage) error) *LongConnClient {
|
||||
dialer := *ws.DefaultDialer
|
||||
dialer.HandshakeTimeout = webSocketHandshakeTimeout
|
||||
dialer.Proxy = nil
|
||||
dialer.NetDialContext = safeDialContext
|
||||
return &LongConnClient{
|
||||
url: webSocketURL,
|
||||
handler: handler,
|
||||
dialer: &dialer,
|
||||
messages: make(chan *im.IncomingMessage, webSocketMessageQueueSize),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) Start(ctx context.Context) error {
|
||||
logger.Infof(ctx, "[IM] Yunzhijia WebSocket connecting")
|
||||
go c.handleMessages(ctx)
|
||||
attempt := 0
|
||||
for {
|
||||
if ctx.Err() != nil || c.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
connectedAt := time.Now()
|
||||
err := c.connectAndRun(ctx)
|
||||
if ctx.Err() != nil || c.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
if time.Since(connectedAt) >= webSocketReconnectDelays[len(webSocketReconnectDelays)-1] {
|
||||
attempt = 0
|
||||
}
|
||||
|
||||
delay := webSocketReconnectDelay(attempt)
|
||||
attempt++
|
||||
logger.Warnf(ctx, "[Yunzhijia] WebSocket connection lost: %v; reconnecting in %v", err, delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(delay):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) Stop() {
|
||||
c.closed.Store(true)
|
||||
c.closeConn()
|
||||
}
|
||||
|
||||
func (c *LongConnClient) connectAndRun(ctx context.Context) error {
|
||||
conn, _, err := c.dialer.DialContext(ctx, c.url, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial websocket: %w", err)
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.conn = conn
|
||||
c.mu.Unlock()
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
if c.conn == conn {
|
||||
c.conn = nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
_ = conn.Close()
|
||||
}()
|
||||
|
||||
conn.SetReadLimit(webSocketMaxMessageSize)
|
||||
_ = conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
|
||||
conn.SetPongHandler(func(string) error {
|
||||
return conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
|
||||
})
|
||||
|
||||
heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)
|
||||
defer cancelHeartbeat()
|
||||
go c.heartbeatLoop(heartbeatCtx, conn)
|
||||
|
||||
logger.Infof(ctx, "[IM] Yunzhijia WebSocket connected")
|
||||
invalidFrames := 0
|
||||
for {
|
||||
messageType, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read websocket message: %w", err)
|
||||
}
|
||||
_ = conn.SetReadDeadline(time.Now().Add(webSocketReadTimeout))
|
||||
|
||||
if messageType != ws.TextMessage {
|
||||
invalidFrames++
|
||||
if invalidFrames >= webSocketMaxInvalidFrames {
|
||||
return fmt.Errorf("too many non-text websocket frames")
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
frame, err := parseWebSocketFrame(data)
|
||||
if err != nil {
|
||||
invalidFrames++
|
||||
logger.Warnf(ctx, "[Yunzhijia] Invalid WebSocket frame: %v", err)
|
||||
if invalidFrames >= webSocketMaxInvalidFrames {
|
||||
return fmt.Errorf("too many invalid websocket frames")
|
||||
}
|
||||
continue
|
||||
}
|
||||
invalidFrames = 0
|
||||
|
||||
if len(frame.ack) > 0 {
|
||||
if err := c.writeText(conn, frame.ack); err != nil {
|
||||
return fmt.Errorf("send websocket ack: %w", err)
|
||||
}
|
||||
}
|
||||
if frame.message == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
incoming := toIncomingMessage(ctx, frame.message)
|
||||
if incoming == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case c.messages <- incoming:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) handleMessages(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg := <-c.messages:
|
||||
if err := c.handler(ctx, msg); err != nil {
|
||||
logger.Errorf(ctx, "[Yunzhijia] Handle WebSocket message failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) heartbeatLoop(ctx context.Context, conn *ws.Conn) {
|
||||
ticker := time.NewTicker(webSocketHeartbeatInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := conn.WriteControl(ws.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
|
||||
logger.Warnf(ctx, "[Yunzhijia] WebSocket heartbeat failed: %v", err)
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) writeText(conn *ws.Conn, data []byte) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.conn != conn {
|
||||
return fmt.Errorf("websocket connection changed")
|
||||
}
|
||||
return conn.WriteMessage(ws.TextMessage, data)
|
||||
}
|
||||
|
||||
func (c *LongConnClient) closeConn() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.conn != nil {
|
||||
_ = c.conn.Close()
|
||||
c.conn = nil
|
||||
}
|
||||
}
|
||||
|
||||
func webSocketReconnectDelay(attempt int) time.Duration {
|
||||
if attempt < 0 {
|
||||
attempt = 0
|
||||
}
|
||||
if attempt >= len(webSocketReconnectDelays) {
|
||||
return webSocketReconnectDelays[len(webSocketReconnectDelays)-1]
|
||||
}
|
||||
return webSocketReconnectDelays[attempt]
|
||||
}
|
||||
|
||||
func parseWebSocketFrame(data []byte) (*webSocketFrame, error) {
|
||||
trimmed := bytes.TrimSpace(data)
|
||||
if len(trimmed) == 0 {
|
||||
return nil, fmt.Errorf("empty frame")
|
||||
}
|
||||
|
||||
plain := strings.ToLower(string(trimmed))
|
||||
if plain == "ping" || plain == "pong" {
|
||||
return &webSocketFrame{control: plain}, nil
|
||||
}
|
||||
|
||||
var stringPayload string
|
||||
if err := json.Unmarshal(trimmed, &stringPayload); err == nil {
|
||||
control := strings.ToLower(strings.TrimSpace(stringPayload))
|
||||
if control == "ping" || control == "pong" {
|
||||
return &webSocketFrame{control: control}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown string frame")
|
||||
}
|
||||
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(trimmed, &fields); err != nil {
|
||||
return nil, fmt.Errorf("decode frame: %w", err)
|
||||
}
|
||||
|
||||
if msg := decodeBusinessMessage(trimmed); msg != nil {
|
||||
return &webSocketFrame{message: msg}, nil
|
||||
}
|
||||
|
||||
typeName := rawString(fields["type"])
|
||||
if strings.EqualFold(typeName, "robotMessage") {
|
||||
if msg := decodeBusinessMessage(fields["msg"]); msg != nil {
|
||||
return &webSocketFrame{message: msg}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("robotMessage envelope has invalid msg")
|
||||
}
|
||||
|
||||
cmd := strings.ToLower(strings.TrimSpace(rawString(fields["cmd"])))
|
||||
typeName = strings.ToLower(strings.TrimSpace(typeName))
|
||||
event := strings.ToLower(strings.TrimSpace(rawString(fields["event"])))
|
||||
control := cmd
|
||||
if control == "" {
|
||||
control = typeName
|
||||
}
|
||||
if control == "" {
|
||||
control = event
|
||||
}
|
||||
|
||||
frame := &webSocketFrame{control: control}
|
||||
if cmd == "directpush" || typeName == "msgchg" {
|
||||
var needAck bool
|
||||
_ = json.Unmarshal(fields["needAck"], &needAck)
|
||||
var seq int64
|
||||
if needAck && json.Unmarshal(fields["seq"], &seq) == nil {
|
||||
frame.ack, _ = json.Marshal(struct {
|
||||
Cmd string `json:"cmd"`
|
||||
Seq int64 `json:"seq"`
|
||||
}{Cmd: "ack", Seq: seq})
|
||||
}
|
||||
return frame, nil
|
||||
}
|
||||
if control != "" {
|
||||
return frame, nil
|
||||
}
|
||||
return nil, fmt.Errorf("frame has no business message or control type")
|
||||
}
|
||||
|
||||
func decodeBusinessMessage(data []byte) *callbackMessage {
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, key := range []string{"robotId", "robotName", "operatorOpenid", "operatorName", "msgId", "content"} {
|
||||
var value string
|
||||
if json.Unmarshal(fields[key], &value) != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
var messageType int
|
||||
if json.Unmarshal(fields["type"], &messageType) != nil {
|
||||
return nil
|
||||
}
|
||||
var messageTime int64
|
||||
if json.Unmarshal(fields["time"], &messageTime) != nil {
|
||||
return nil
|
||||
}
|
||||
var msg callbackMessage
|
||||
if err := json.Unmarshal(data, &msg); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &msg
|
||||
}
|
||||
|
||||
func rawString(raw json.RawMessage) string {
|
||||
var value string
|
||||
if len(raw) > 0 && json.Unmarshal(raw, &value) == nil {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package yunzhijia
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
ws "github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const testBusinessMessage = `{
|
||||
"type": 2,
|
||||
"robotId": "bot-1",
|
||||
"robotName": "WeKnora",
|
||||
"operatorOpenid": "user-1",
|
||||
"operatorName": "User",
|
||||
"time": 1719648000000,
|
||||
"msgId": "msg-1",
|
||||
"content": "@WeKnora hello",
|
||||
"groupType": 1
|
||||
}`
|
||||
|
||||
func TestParseWebSocketFrameDirectMessage(t *testing.T) {
|
||||
frame, err := parseWebSocketFrame([]byte(testBusinessMessage))
|
||||
if err != nil {
|
||||
t.Fatalf("parseWebSocketFrame() error = %v", err)
|
||||
}
|
||||
if frame.message == nil || frame.message.MsgID != "msg-1" {
|
||||
t.Fatalf("message = %#v, want msg-1", frame.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseWebSocketFrameRobotMessageEnvelope(t *testing.T) {
|
||||
frame, err := parseWebSocketFrame([]byte(`{"type":"robotMessage","msg":` + testBusinessMessage + `}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parseWebSocketFrame() error = %v", err)
|
||||
}
|
||||
if frame.message == nil || frame.message.OperatorOpenid != "user-1" {
|
||||
t.Fatalf("message = %#v, want user-1", frame.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseWebSocketFrameBuildsDirectPushACK(t *testing.T) {
|
||||
frame, err := parseWebSocketFrame([]byte(`{"cmd":"directPush","needAck":true,"seq":42}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parseWebSocketFrame() error = %v", err)
|
||||
}
|
||||
var ack struct {
|
||||
Cmd string `json:"cmd"`
|
||||
Seq int64 `json:"seq"`
|
||||
}
|
||||
if err := json.Unmarshal(frame.ack, &ack); err != nil {
|
||||
t.Fatalf("unmarshal ack: %v", err)
|
||||
}
|
||||
if ack.Cmd != "ack" || ack.Seq != 42 {
|
||||
t.Fatalf("ack = %#v, want cmd=ack seq=42", ack)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseWebSocketFrameControlAndInvalid(t *testing.T) {
|
||||
frame, err := parseWebSocketFrame([]byte(`{"event":"pong"}`))
|
||||
if err != nil || frame.control != "pong" {
|
||||
t.Fatalf("control frame = %#v, err=%v", frame, err)
|
||||
}
|
||||
if _, err := parseWebSocketFrame([]byte(`{"unknown":true}`)); err == nil {
|
||||
t.Fatal("expected invalid frame error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToIncomingMessageSharedByWebhookAndWebSocket(t *testing.T) {
|
||||
var msg callbackMessage
|
||||
if err := json.Unmarshal([]byte(testBusinessMessage), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
incoming := toIncomingMessage(t.Context(), &msg)
|
||||
if incoming == nil {
|
||||
t.Fatal("toIncomingMessage() returned nil")
|
||||
}
|
||||
if incoming.Content != "hello" {
|
||||
t.Fatalf("content = %q, want hello", incoming.Content)
|
||||
}
|
||||
if incoming.MessageID != "msg-1" || incoming.UserID != "user-1" {
|
||||
t.Fatalf("incoming = %#v", incoming)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketReconnectDelayCaps(t *testing.T) {
|
||||
if got := webSocketReconnectDelay(-1); got != webSocketReconnectDelays[0] {
|
||||
t.Fatalf("negative attempt delay = %v", got)
|
||||
}
|
||||
last := webSocketReconnectDelays[len(webSocketReconnectDelays)-1]
|
||||
if got := webSocketReconnectDelay(100); got != last {
|
||||
t.Fatalf("capped delay = %v, want %v", got, last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongConnClientProcessesMessagesInOrder(t *testing.T) {
|
||||
started := make(chan string, 2)
|
||||
releaseFirst := make(chan struct{})
|
||||
client := NewLongConnClient("wss://example.com/ws", func(_ context.Context, msg *im.IncomingMessage) error {
|
||||
started <- msg.MessageID
|
||||
if msg.MessageID == "first" {
|
||||
<-releaseFirst
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
go client.handleMessages(ctx)
|
||||
client.messages <- &im.IncomingMessage{MessageID: "first"}
|
||||
client.messages <- &im.IncomingMessage{MessageID: "second"}
|
||||
|
||||
select {
|
||||
case got := <-started:
|
||||
if got != "first" {
|
||||
t.Fatalf("first handled message = %q, want first", got)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("first message was not handled")
|
||||
}
|
||||
select {
|
||||
case got := <-started:
|
||||
t.Fatalf("second message started before first completed: %q", got)
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(releaseFirst)
|
||||
select {
|
||||
case got := <-started:
|
||||
if got != "second" {
|
||||
t.Fatalf("second handled message = %q, want second", got)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("second message was not handled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongConnClientAcknowledgesFrameAndStops(t *testing.T) {
|
||||
ackReceived := make(chan struct{})
|
||||
var ackOnce sync.Once
|
||||
upgrader := ws.Upgrader{}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.WriteMessage(ws.TextMessage, []byte(`{"cmd":"directPush","needAck":true,"seq":42}`)); err != nil {
|
||||
return
|
||||
}
|
||||
_, data, err := conn.ReadMessage()
|
||||
if err == nil && string(data) == `{"cmd":"ack","seq":42}` {
|
||||
ackOnce.Do(func() { close(ackReceived) })
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewLongConnClient("ws"+strings.TrimPrefix(server.URL, "http"), func(context.Context, *im.IncomingMessage) error {
|
||||
return nil
|
||||
})
|
||||
dialer := &net.Dialer{}
|
||||
client.dialer.NetDialContext = dialer.DialContext
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- client.Start(ctx) }()
|
||||
|
||||
select {
|
||||
case <-ackReceived:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("websocket ACK was not received")
|
||||
}
|
||||
cancel()
|
||||
client.Stop()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("Start() error after stop = %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("websocket client did not stop promptly")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user