From 11cabd5952b065ad77b46e0fa18e39086201c3ae Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 30 Mar 2026 10:57:30 +0800 Subject: [PATCH] feat(datasource): add WeCom document integration and callback setup - Implemented WeCom document connector to sync smart documents and WeDrive files into WeKnora. - Added detailed documentation for WeCom integration, including setup instructions for callback URL and API access. - Enhanced frontend localization to support WeCom-specific messages and instructions. - Updated data source management UI to include WeCom configuration options and callback URL handling. - Improved error handling and validation for WeCom API interactions. --- docs/数据源导入开发文档.md | 233 +++++++- frontend/src/i18n/locales/en-US.ts | 22 + frontend/src/i18n/locales/ko-KR.ts | 4 + frontend/src/i18n/locales/ru-RU.ts | 4 + frontend/src/i18n/locales/zh-CN.ts | 22 + .../settings/DataSourceEditorDialog.vue | 130 ++++- internal/container/container.go | 5 + internal/datasource/connector.go | 6 +- .../datasource/connector/wecom/callback.go | 109 ++++ internal/datasource/connector/wecom/client.go | 338 +++++++++++ .../datasource/connector/wecom/connector.go | 533 ++++++++++++++++++ internal/datasource/connector/wecom/types.go | 155 +++++ internal/handler/wecom_callback.go | 93 +++ internal/router/router.go | 11 + 14 files changed, 1638 insertions(+), 27 deletions(-) create mode 100644 internal/datasource/connector/wecom/callback.go create mode 100644 internal/datasource/connector/wecom/client.go create mode 100644 internal/datasource/connector/wecom/connector.go create mode 100644 internal/datasource/connector/wecom/types.go create mode 100644 internal/handler/wecom_callback.go diff --git a/docs/数据源导入开发文档.md b/docs/数据源导入开发文档.md index a475774a..2e428eaf 100644 --- a/docs/数据源导入开发文档.md +++ b/docs/数据源导入开发文档.md @@ -1,6 +1,6 @@ # 数据源导入开发文档 -WeKnora 的数据源导入模块支持从外部平台(飞书、Notion、Confluence 等)自动导入和同步内容到知识库。用户可配置数据源连接,选择需要同步的资源,并通过手动触发或定时调度自动完成内容的增量/全量同步。 +WeKnora 的数据源导入模块支持从外部平台(飞书、企业微信、Notion、Confluence 等)自动导入和同步内容到知识库。用户可配置数据源连接,选择需要同步的资源,并通过手动触发或定时调度自动完成内容的增量/全量同步。 数据源绑定到知识库,一个知识库可接入多个数据源。所有配置通过前端知识库设置页面管理,凭证使用 AES-256-GCM 加密存储在数据库中。 @@ -8,6 +8,7 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、Notion、Conflu - [快速接入指南](#快速接入指南) - [飞书知识库接入](#飞书知识库接入) + - [企业微信文档接入](#企业微信文档接入) - [前端管理](#前端管理) - [架构总览](#架构总览) - [数据模型](#数据模型) @@ -17,6 +18,7 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、Notion、Conflu - [接口定义](#接口定义) - [连接器详解](#连接器详解) - [飞书 (Feishu)](#飞书-feishu) + - [企业微信文档 (WeCom Doc)](#企业微信文档-wecom-doc) - [定时调度](#定时调度) - [关键参数与阈值](#关键参数与阈值) - [错误处理](#错误处理) @@ -30,7 +32,7 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、Notion、Conflu - WeKnora 已部署并运行 - 已创建至少一个知识库 -- 拥有外部平台(如飞书)的管理权限,可创建应用并授权 +- 拥有外部平台(如飞书、企业微信)的管理权限,可创建应用并授权 ### 飞书知识库接入 @@ -84,6 +86,82 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、Notion、Conflu > **注意**:飞书国际版(Lark)同样支持,在创建数据源时会自动适配 `https://open.larksuite.com` 的 API 地址。 +### 企业微信文档接入 + +从企业微信同步智能文档(文档、表格)和微盘文件到 WeKnora。支持智能文档分类同步和微盘空间文件递归下载。 + +#### 第一步:获取应用凭证 + +1. 登录 [企业微信管理后台](https://work.weixin.qq.com/wework_admin/frame#apps) → **应用管理** +2. 选择已有的自建应用,或点击 **创建应用** 新建一个 +3. 在应用详情页记录以下信息: + - **Corp ID**:在左侧栏 **我的企业** → **企业信息** 页面底部获取 + - **Secret**:在应用详情页点击 **查看** 获取 + +#### 第二步:配置回调 URL(解锁管理后台的 API 设置) + +企微管理后台要求先配置「接收消息服务器 URL」→ 才能配置「企业可信 IP」→ 才能设置「可调用接口的应用」。WeKnora 内置了回调验证端点来解决这个前置依赖链。 + +1. 先在 WeKnora 中创建企微文档数据源(仅填 Corp ID 和 Secret,先保存) +2. 在管理后台 **应用管理** → 你的自建应用 → **接收消息** → 点击 **设置API接收** +3. 企微后台会显示 **Token** 和 **EncodingAESKey**(可点击「随机获取」自动生成) +4. 将 Token 和 EncodingAESKey 复制到 WeKnora 数据源配置的「回调 URL 配置」区域中,并保存 +5. 在 WeKnora 中复制生成的回调 URL(格式:`https://你的域名/api/v1/wecom/callback/<数据源ID>`) +6. 将此 URL 粘贴到企微后台的「URL」字段中,点击「保存」 +7. 企微会向该 URL 发送验证请求,WeKnora 自动完成验证 + +#### 第三步:授权应用调用文档 API + +完成回调 URL 配置后,即可设置「可调用接口的应用」。如果出现 `errcode=48002 api forbidden` 错误,说明此步骤未完成。 + +**配置文档接口权限:** + +1. 在管理后台左侧栏点击 **协作** → **文档** +2. 滚动到底部找到 **API** 区域 +3. 在「可调用接口的应用」中添加你的自建应用 + +**配置微盘接口权限(可选,仅同步微盘文件时需要):** + +1. 在管理后台左侧栏点击 **协作** → **微盘** +2. 滚动到底部找到 **API** 区域 +3. 在「可调用接口的应用」中添加你的自建应用 + +> **关于企业可信 IP**:完成回调 URL 配置后,「企业可信 IP」也被解锁了。如果调用时收到 `errcode=60020` 错误,说明需要在应用详情页底部的「企业可信 IP」中添加服务器 IP。 + +#### 第四步:在 WeKnora 中完善数据源配置 + +1. 回到 WeKnora 知识库设置页 → **数据源** 标签页 +2. 编辑之前创建的企微文档数据源 +3. 点击 **测试连接**,验证凭证和权限均已就位 +4. 选择要同步的资源范围: + - **全部文档**:同步所有智能文档 + - **文档**:仅同步文档类型 + - **表格**:仅同步表格类型 +5. 配置同步策略(同飞书) +6. 点击保存 + +#### 第五步:验证 + +保存后可点击 **立即同步** 触发首次同步。在同步日志中查看同步进度和结果。 + +#### 可选:接入微盘空间 + +如需同时同步微盘空间中的文件(PDF、Word、Excel 等上传文件),需在数据源配置的 `settings` 中提供: + +```json +{ + "space_ids": ["SPACE_ID_1", "SPACE_ID_2"], + "userid": "admin_userid" +} +``` + +| 参数 | 说明 | +|------|------| +| `space_ids` | 微盘空间 ID 列表(从微盘设置页或 API 获取) | +| `userid` | 用于文件下载的操作者 userid(需有对应空间的下载权限) | + +> **注意**:企业微信目前不提供「获取空间列表」API,因此空间 ID 需要手动配置。若不配置 `space_ids`,仅同步智能文档。 + --- ## 前端管理 @@ -251,7 +329,7 @@ CREATE TABLE data_sources ( | Google Drive | `credentials_json` | OAuth2 Service Account | | OneDrive | `client_id`, `client_secret`, `tenant_id` | OAuth2 | | 钉钉文档 (dingtalk) | `app_key`, `app_secret` | OAuth2 | -| 企业微信文档 (wecom_doc) | `corp_id`, `agent_secret` | OAuth2 | +| 企业微信文档 (wecom_doc) | `corp_id`, `corp_secret` | access_token (自建应用) | | Web 爬虫 (web_crawler) | `start_urls`, `max_depth` | 无需认证 | | Slack | `bot_token` | Bot Token | | IMAP | `host`, `port`, `username`, `password` | 密码认证 | @@ -589,7 +667,7 @@ type ConnectorMetadata struct { ### 飞书 (Feishu) -飞书连接器支持从飞书知识库(Wiki)同步文档到 WeKnora,是目前唯一已实现的连接器。 +飞书连接器支持从飞书知识库(Wiki)同步文档到 WeKnora。 #### 认证机制 @@ -697,6 +775,144 @@ DownloadDriveFile → GET /drive/v1/files/{token}/download | `internal/datasource/connector/feishu/connector.go` | Connector 接口实现:Validate、ListResources、FetchAll、FetchIncremental | | `internal/datasource/connector/feishu/connector_test.go` | 单元测试:使用 HTTP Mock 模拟飞书开放平台 | +### 企业微信文档 (WeCom Doc) + +企微文档连接器支持两种数据源:**智能文档**(企微原生在线文档/表格)和 **微盘文件**(上传的 PDF/Word/Excel 等)。 + +#### 认证机制 + +``` +Corp ID + Corp Secret + │ + ▼ + GET /cgi-bin/gettoken?corpid=xxx&corpsecret=xxx + │ + ▼ + 获取 access_token(有效期 7200 秒 / 2 小时) + │ + ▼ + Token 缓存,提前 5 分钟刷新 +``` + +- **认证类型**:企业自建应用,access_token +- **Token 有效期**:7200 秒(2 小时),内置缓存,提前 5 分钟自动刷新 +- **API 地址**:`https://qyapi.weixin.qq.com` +- **Token 传递方式**:通过 URL 参数 `access_token=xxx` + +#### 资源发现 + +`ListResources` 返回文档分类资源和可选的微盘空间: + +**智能文档分类(始终返回):** + +| 资源 ExternalID | 名称 | 对应 API 参数 | +|----------------|------|-------------| +| `all_documents` | 全部文档 | `doc_type=0` | +| `documents` | 文档 | `doc_type=3` | +| `sheets` | 表格 | `doc_type=4` | + +**微盘空间(仅当 `settings.space_ids` 配置时返回):** + +| 资源 ExternalID | 名称 | 类型 | +|----------------|------|------| +| `wedrive:` | 微盘空间: {id} | `wedrive_space` | + +#### 智能文档同步 + +**列举文档:** + +``` +POST /cgi-bin/wedoc/doc_list?access_token=xxx +Body: { "doc_type": 0, "limit": 50, "cursor": "" } + +返回: { "doc_info_list": [{"docid": "...", "doc_name": "..."}], "has_more": true, "next_cursor": "..." } +``` + +**获取文档元数据(用于增量同步时间对比):** + +``` +POST /cgi-bin/wedoc/get_doc_base_info?access_token=xxx +Body: { "docid": "xxx" } + +返回: { "doc_base_info": { "docid": "...", "doc_name": "...", "create_time": 1700000000, "modify_time": 1700001000, "doc_type": 3 } } +``` + +每个文档映射为一个 `FetchedItem`: + +| 字段 | 值 | +|------|------| +| `ExternalID` | docid | +| `Title` | doc_name | +| `URL` | `https://doc.weixin.qq.com/doc/{docid}` 或 `sheet/{docid}` | +| `ContentType` | `text/html` | +| `Metadata.channel` | `wecom` | +| `Metadata.doc_type` | 文档类型(3=文档, 4=表格) | + +#### 微盘文件同步 + +**列举文件(递归遍历子目录):** + +``` +POST /cgi-bin/wedrive/file_list?access_token=xxx +Body: { "spaceid": "xxx", "sort_type": 5, "start": 0, "limit": 1000 } + +返回: { "file_list": { "item": [...], "has_more": false } } +``` + +**文件类型:** + +| `file_type` | 类型 | 同步行为 | +|-------------|------|---------| +| 1 | 文件夹 | 递归遍历子项 | +| 2 | 上传文件 | 通过 file_download 下载二进制内容 | +| 3 | 智能文档 | 通过 URL 导入 | +| 4 | 智能表格 | 通过 URL 导入 | +| 5 | 收集表 | 通过 URL 导入 | + +**下载上传文件(file_type=2):** + +``` +POST /cgi-bin/wedrive/file_download?access_token=xxx +Body: { "fileid": "xxx", "userid": "admin_userid" } + +返回: { "download_url": "https://...", "cookie_name": "...", "cookie_value": "..." } +``` + +下载时需携带返回的 Cookie 请求 `download_url` 获取文件内容。 + +#### 增量同步 (FetchIncremental) + +增量同步基于文档 `modify_time` 对比: + +``` +1. 加载上次游标 (wecomCursor) + └─ DocModifyTimes[docid] = 上次记录的修改时间 + +2. 对每个选中的资源类别: + └─ 列举所有文档 (ListSmartDocuments) + └─ 对每个文档获取元数据 (GetDocBaseInfo) + +3. 对比变更: + ├─ 新文档(游标中不存在)→ 加入变更列表 + ├─ modify_time 变更 → 加入变更列表 + ├─ modify_time 未变 → 跳过 + └─ 游标中存在但本次不存在 → 标记为 IsDeleted + +4. 微盘空间: + └─ 列举所有文件 (ListAllDriveFilesRecursive) + └─ 对比 mtime,逻辑同上 + +5. 返回新游标(含本轮每个文档/文件的最新修改时间) +``` + +#### 源码文件 + +| 文件 | 职责 | +|------|------| +| `internal/datasource/connector/wecom/types.go` | WeCom API 类型定义、配置结构、常量(文档/微盘类型) | +| `internal/datasource/connector/wecom/client.go` | API 客户端:Token 管理、智能文档列表/详情、微盘文件列表/递归/下载 | +| `internal/datasource/connector/wecom/connector.go` | Connector 接口实现:Validate、ListResources、FetchAll、FetchIncremental | + --- ## 定时调度 @@ -766,10 +982,13 @@ Cron 触发时: | 参数 | 值 | 说明 | |------|------|------| -| Token 缓存安全余量 | 5 min | Token 过期前提前刷新 | +| Token 缓存安全余量 | 5 min | Token 过期前提前刷新(飞书/企微通用) | | 飞书 Wiki Space 分页大小 | 50 | ListResources 每页返回数 | -| 导出任务轮询间隔 | 2s | 飞书 Export API 状态检查间隔 | -| 导出任务最大等待 | ~60s | 导出任务超时时间 | +| 飞书导出任务轮询间隔 | 2s | 飞书 Export API 状态检查间隔 | +| 飞书导出任务最大等待 | ~60s | 导出任务超时时间 | +| 企微文档列表分页大小 | 50 | wedoc/doc_list 每页返回数 | +| 企微微盘文件列表分页大小 | 1000 | wedrive/file_list 每次拉取最大数 | +| 企微 access_token 有效期 | 7200s | 2 小时,缓存提前 5 分钟刷新 | | 同步日志保留天数 | 30 天 | 默认值,可配置 | | 同步日志默认分页 | 10 | GetSyncLogs 默认 limit | | Cron 表达式格式 | 6 段含秒 | robfig/cron WithSeconds() | diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 8734bcd4..f28da96c 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3392,10 +3392,14 @@ export default { resourceLoadFailed: 'Failed to load resources', noResources: 'No wiki spaces found', noResourcesDesc: 'The app needs wiki access via a group chat to fetch content', + noResourcesDesc_wecom_doc: 'Ensure the app is added as a "Callable App" in Admin Console > Collaboration > Docs > API', retryLoadResources: 'Retry', guideStep1: 'Create a group chat in Feishu, then add your app as a bot in the group settings', guideStep2: 'Open wiki "Settings" > "Member Settings" > "Add Member", search for the group chat and add it', guideStep3: 'Ensure the group chat role is at least "Can Read", then come back and click Retry', + guideStep1_wecom_doc: 'Add the app as a "Callable App" in Admin Console > Collaboration > Docs > API', + guideStep2_wecom_doc: 'Ensure the app "Visible Scope" includes the members/departments to sync', + guideStep3_wecom_doc: 'Fill in Corp ID and Secret, then click retry', permissionDocLink: 'View Feishu wiki permission docs', syncScheduleLabel: 'Sync schedule', conflictLabel: 'Conflict strategy', @@ -3465,9 +3469,22 @@ export default { }, comingSoon: 'Coming soon', docHint: 'Get credentials at:', + wecomCallbackTitle: 'Callback URL Setup (unlocks "Callable Apps" setting)', + wecomCallbackDesc: 'WeCom admin requires configuring a "Message Receiving Server URL" before you can set "Trusted IPs" and "Callable Apps". Enter the Token and EncodingAESKey from WeCom admin here, save, then paste the generated callback URL into WeCom admin.', + wecomCallbackUrl: 'Callback URL (paste into WeCom admin "Message Receiving Server URL")', + wecomCallbackSaveFirst: 'Save the data source first to generate the callback URL', + copyUrl: 'Copy URL', + copied: 'Copied', pleaseTestFirst: 'Please test connection first', prereqTitle: 'Complete these steps before connecting (all required)', prereqBarText: 'First time? Click to see Feishu app setup guide', + prereqBarText_wecom_doc: 'First time? Click to expand WeCom app setup guide', + prereqStep1Brief_wecom_doc: 'Configure Callback URL (unlocks further settings)', + prereqStep1Desc_wecom_doc: 'Save data source first → Expand "Callback URL Setup" below → Enter Token/EncodingAESKey from WeCom admin → Paste generated URL into WeCom admin "Message Receiving Server URL"', + prereqStep2Brief_wecom_doc: 'Authorize app for Docs API', + prereqStep2Desc_wecom_doc: 'Admin Console → Collaboration → Docs → Scroll to API section at bottom → Add your app to "Callable Apps"', + prereqStep3Brief_wecom_doc: 'Confirm app visible scope', + prereqStep3Desc_wecom_doc: 'Admin Console → App Management → App detail → Ensure "Visible Scope" includes target members/departments', prereqBotBrief: 'Add "Bot" capability to your app', prereqBotDesc: 'Open Platform > Add App Capability > Bot > create version and publish', prereqBotLabel: '1. Add "Bot" capability to your app (otherwise the app won\'t appear in wiki member search):', @@ -3497,6 +3514,11 @@ export default { }, addCard: 'Add Data Source', wikiSpace: 'Wiki Space', + resourceType: { + wikiSpace: 'Wiki Space', + docCategory: 'Document Category', + wedriveSpace: 'WeDrive Space', + }, neverSynced: 'Never synced', justNow: 'Just now', minutesAgo: '{n}m ago', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index cf32266a..a1af4292 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3480,6 +3480,7 @@ export default { yuque: "위큐 (Yuque)", github: "GitHub", web_crawler: "웹 크롤러", + wecom_doc: "WeCom 문서", }, connectorDesc: { feishu: "페이슈 위키에서 문서, 스프레드시트, 파일 동기화", @@ -3488,6 +3489,7 @@ export default { yuque: "위큐 지식베이스에서 문서 동기화", github: "GitHub 리포지토리에서 문서 및 위키 동기화", web_crawler: "사이트맵을 통해 웹사이트 크롤링", + wecom_doc: "WeCom(기업 위챗)에서 문서 동기화", }, field: { appId: "App ID", @@ -3498,6 +3500,8 @@ export default { apiToken: "API Token", personalToken: "Personal Access Token", sitemapUrl: "사이트맵 URL", + corpId: "Corp ID", + corpSecret: "Corp Secret", }, comingSoon: "곧 지원 예정", docHint: "다음에서 인증 정보를 받으세요:", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 39097579..aafa8654 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3387,6 +3387,7 @@ export default { yuque: 'Yuque (Юйцюэ)', github: 'GitHub', web_crawler: 'Веб-краулер', + wecom_doc: 'WeCom Документы', }, connectorDesc: { feishu: 'Синхронизация документов, таблиц и файлов из Feishu Wiki', @@ -3395,6 +3396,7 @@ export default { yuque: 'Синхронизация документов из баз знаний Yuque', github: 'Синхронизация документов и вики из репозиториев GitHub', web_crawler: 'Сканирование веб-сайтов через Sitemap', + wecom_doc: 'Синхронизация документов из WeCom (корпоративный WeChat)', }, field: { appId: 'App ID', @@ -3405,6 +3407,8 @@ export default { apiToken: 'API Token', personalToken: 'Personal Access Token', sitemapUrl: 'Sitemap URL', + corpId: 'Corp ID', + corpSecret: 'Corp Secret', }, comingSoon: 'Скоро', docHint: 'Получить учётные данные можно здесь:', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index acebfaba..7b9319c8 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3390,10 +3390,14 @@ export default { resourceLoadFailed: "加载资源列表失败", noResources: "未找到可同步的知识库空间", noResourcesDesc: "应用需要通过群聊获得知识库访问权限才能拉取内容", + noResourcesDesc_wecom_doc: "请确认已在管理后台「协作→文档→API」中将应用添加为「可调用接口的应用」", retryLoadResources: "重新加载", guideStep1: "在飞书中创建一个群聊,在群设置「群机器人」中添加你的应用", guideStep2: "打开知识库「设置」→「成员设置」→ 添加成员,搜索该群聊名称并添加", guideStep3: "确保群聊角色至少为「可阅读」,然后回到这里点重新加载", + guideStep1_wecom_doc: "在管理后台「协作→文档→API」中将自建应用添加为「可调用接口的应用」", + guideStep2_wecom_doc: "确认应用「可见范围」包含了需要同步文档的成员或部门", + guideStep3_wecom_doc: "填入 Corp ID 和 Secret 后点击重新加载", permissionDocLink: "查看飞书知识库权限配置文档", syncScheduleLabel: "同步频率", conflictLabel: "冲突策略", @@ -3463,9 +3467,22 @@ export default { }, comingSoon: "即将支持", docHint: "在以下地址获取凭证:", + wecomCallbackTitle: "回调 URL 配置(解锁「可调用接口的应用」设置)", + wecomCallbackDesc: "企微管理后台要求配置「接收消息服务器URL」后才能设置「企业可信IP」和「可调用接口的应用」。在此填入 Token 和 EncodingAESKey(从企微后台获取),保存后将生成的回调 URL 粘贴到企微后台。", + wecomCallbackUrl: "回调 URL(粘贴到企微后台「接收消息服务器URL」)", + wecomCallbackSaveFirst: "请先保存数据源,保存后会生成回调 URL", + copyUrl: "复制 URL", + copied: "已复制", pleaseTestFirst: "请先测试连接", prereqTitle: "使用前请先完成以下配置(缺一不可)", prereqBarText: "首次使用?点击查看飞书应用配置指引", + prereqBarText_wecom_doc: "首次使用?点击展开企微应用配置指引", + prereqStep1Brief_wecom_doc: "配置回调 URL(解锁后续设置)", + prereqStep1Desc_wecom_doc: "先保存数据源 → 展开下方「回调 URL 配置」→ 填入企微后台的 Token/EncodingAESKey → 将生成的 URL 粘贴到企微后台「接收消息服务器URL」", + prereqStep2Brief_wecom_doc: "授权应用调用文档 API", + prereqStep2Desc_wecom_doc: "管理后台 → 协作 → 文档 → 滚动到底部 API 区域 → 将自建应用添加到「可调用接口的应用」", + prereqStep3Brief_wecom_doc: "确认应用可见范围", + prereqStep3Desc_wecom_doc: "管理后台 → 应用管理 → 自建应用详情 → 确保「可见范围」包含需要同步文档的成员或部门", prereqBotBrief: "为应用添加「机器人」能力", prereqBotDesc: "开放平台 → 添加应用能力 → 机器人 → 创建版本并发布", prereqBotLabel: "1. 为应用添加「机器人」能力(否则知识库中搜不到该应用):", @@ -3495,6 +3512,11 @@ export default { }, addCard: "添加数据源", wikiSpace: "知识库空间", + resourceType: { + wikiSpace: "知识库空间", + docCategory: "文档分类", + wedriveSpace: "微盘空间", + }, neverSynced: "未同步", justNow: "刚刚", minutesAgo: "{n} 分钟前", diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue index 7cc79eda..1af12c52 100644 --- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue +++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue @@ -53,6 +53,8 @@ const testErrorMsg = ref('') // Collapsible prereq in Step 1 const prereqExpanded = ref(false) +// WeCom callback section +const callbackExpanded = ref(false) // Temp data source for resource listing const tempDsId = ref('') @@ -119,13 +121,13 @@ const connectorDefs = computed(() => [ }, { type: 'wecom_doc', - available: false, - docUrl: 'https://developer.work.weixin.qq.com/', + available: true, + docUrl: 'https://work.weixin.qq.com/wework_admin/frame#apps', permissionDocUrl: '', - permissionPageUrl: '', - requiredPermissions: [], + permissionPageUrl: 'https://work.weixin.qq.com/wework_admin/frame#apps', + requiredPermissions: ['wedoc:callable_app'], fields: [ - { key: 'corp_id', labelKey: 'datasource.field.corpId', placeholder: '' }, + { key: 'corp_id', labelKey: 'datasource.field.corpId', placeholder: 'ww_xxxx' }, { key: 'corp_secret', labelKey: 'datasource.field.corpSecret', placeholder: '', secret: true }, ], }, @@ -142,6 +144,7 @@ watch(visible, (v) => { testErrorMsg.value = '' tempDsId.value = '' prereqExpanded.value = false + callbackExpanded.value = false resources.value = [] selectedResourceIds.value = [] @@ -315,6 +318,27 @@ async function handleClose() { visible.value = false } +const resourceTypeLabelMap: Record = { + wiki_space: 'datasource.resourceType.wikiSpace', + doc_category: 'datasource.resourceType.docCategory', + wedrive_space: 'datasource.resourceType.wedriveSpace', +} + +function resourceTypeLabel(type: string): string { + const key = resourceTypeLabelMap[type] + return key ? t(key) : type +} + +const wecomCallbackUrl = computed(() => { + if (!tempDsId.value) return '' + return `${window.location.origin}/api/v1/wecom/callback/${tempDsId.value}` +}) + +function copyCallbackUrl() { + navigator.clipboard.writeText(wecomCallbackUrl.value) + MessagePlugin.success(t('datasource.copied')) +} + const stepTitles = computed(() => [ t('datasource.step.selectType'), t('datasource.step.credentials'), @@ -367,31 +391,34 @@ const stepTitles = computed(() => [
- {{ t('datasource.prereqBarText') }} + {{ t(`datasource.prereqBarText_${form.type}`, t('datasource.prereqBarText')) }}
1
-
{{ t('datasource.prereqBotBrief') }}
-
{{ t('datasource.prereqBotDesc') }}
+
{{ t(`datasource.prereqStep1Brief_${form.type}`, t('datasource.prereqBotBrief')) }}
+
{{ t(`datasource.prereqStep1Desc_${form.type}`, t('datasource.prereqBotDesc')) }}
2
-
{{ t('datasource.prereqPermBrief') }}
+
{{ t(`datasource.prereqStep2Brief_${form.type}`, t('datasource.prereqPermBrief')) }}
- {{ perm }} + +
3
-
{{ t('datasource.prereqMemberBrief') }}
-
{{ t('datasource.prereqMemberDesc') }}
+
{{ t(`datasource.prereqStep3Brief_${form.type}`, t('datasource.prereqMemberBrief')) }}
+
{{ t(`datasource.prereqStep3Desc_${form.type}`, t('datasource.prereqMemberDesc')) }}
@@ -419,6 +446,34 @@ const stepTitles = computed(() => [ />
+ +
+
+ + {{ t('datasource.wecomCallbackTitle') }} + +
+
+

{{ t('datasource.wecomCallbackDesc') }}

+
+ + +
+
+ + +
+
+ + + + {{ t('datasource.copyUrl') }} + +
+

{{ t('datasource.wecomCallbackSaveFirst') }}

+
+
+
{{ t('datasource.testConnection') }} @@ -455,7 +510,7 @@ const stepTitles = computed(() => [
{{ r.name }}
- {{ r.type === 'wiki_space' ? t('datasource.wikiSpace') : r.type }} + {{ resourceTypeLabel(r.type) }} {{ r.description }}
@@ -465,19 +520,19 @@ const stepTitles = computed(() => [

{{ t('datasource.noResources') }}

-

{{ t('datasource.noResourcesDesc') }}

+

{{ t(`datasource.noResourcesDesc_${form.type}`, t('datasource.noResourcesDesc')) }}

1 - {{ t('datasource.guideStep1') }} + {{ t(`datasource.guideStep1_${form.type}`, t('datasource.guideStep1')) }}
2 - {{ t('datasource.guideStep2') }} + {{ t(`datasource.guideStep2_${form.type}`, t('datasource.guideStep2')) }}
3 - {{ t('datasource.guideStep3') }} + {{ t(`datasource.guideStep3_${form.type}`, t('datasource.guideStep3')) }}
@@ -681,6 +736,47 @@ const stepTitles = computed(() => [ padding-left: 30px; } +/* --- WeCom callback section --- */ +.ds-callback-section { + margin-bottom: 16px; +} +.ds-callback-header { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 12px; + background: var(--td-bg-color-component); + border-radius: 6px; + font-size: 12px; + color: var(--td-text-color-secondary); + cursor: pointer; + user-select: none; +} +.ds-callback-header:hover { + background: var(--td-bg-color-container-hover); +} +.ds-callback-body { + border: 1px solid var(--td-border-level-2-color); + border-radius: 0 0 8px 8px; + padding: 14px; + margin-top: -2px; +} +.ds-callback-desc { + font-size: 12px; + color: var(--td-text-color-secondary); + margin-bottom: 12px; + line-height: 1.6; +} +.ds-callback-url { + margin-top: 8px; +} +.ds-callback-hint { + font-size: 12px; + color: var(--td-text-color-placeholder); + margin-top: 8px; + font-style: italic; +} + /* --- Step 1: doc link & form --- */ .ds-doc-link { display: flex; diff --git a/internal/container/container.go b/internal/container/container.go index 9c34adff..51973f12 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -52,6 +52,7 @@ import ( "github.com/Tencent/WeKnora/internal/database" "github.com/Tencent/WeKnora/internal/datasource" feishuConnector "github.com/Tencent/WeKnora/internal/datasource/connector/feishu" + wecomConnector "github.com/Tencent/WeKnora/internal/datasource/connector/wecom" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/handler" "github.com/Tencent/WeKnora/internal/handler/session" @@ -257,6 +258,7 @@ func BuildContainer(container *dig.Container) *dig.Container { // Data source handler must(container.Provide(handler.NewDataSourceHandler)) + must(container.Provide(handler.NewWecomCallbackHandler)) // IM integration logger.Debugf(ctx, "[Container] Registering IM integration...") @@ -1281,6 +1283,9 @@ func initConnectorRegistry() *datasource.ConnectorRegistry { // Register Feishu connector _ = registry.Register(feishuConnector.NewConnector()) + // Register WeCom document connector + _ = registry.Register(wecomConnector.NewConnector()) + // Future connectors will be registered here: // _ = registry.Register(notionConnector.NewConnector()) // _ = registry.Register(confluenceConnector.NewConnector()) diff --git a/internal/datasource/connector.go b/internal/datasource/connector.go index 29cf1492..c98bf38b 100644 --- a/internal/datasource/connector.go +++ b/internal/datasource/connector.go @@ -153,10 +153,10 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{ types.ConnectorTypeWecomDoc: { Type: types.ConnectorTypeWecomDoc, Name: "WeCom Docs (企微文档)", - Description: "Sync documents and content from WeCom", + Description: "Sync smart documents and WeDrive files from WeCom", Priority: 8, - AuthType: "api_key", - Capabilities: []string{"incremental"}, + AuthType: "corp_secret", + Capabilities: []string{"incremental", "deletion_sync"}, }, types.ConnectorTypeWebCrawler: { Type: types.ConnectorTypeWebCrawler, diff --git a/internal/datasource/connector/wecom/callback.go b/internal/datasource/connector/wecom/callback.go new file mode 100644 index 00000000..e8aa42f8 --- /dev/null +++ b/internal/datasource/connector/wecom/callback.go @@ -0,0 +1,109 @@ +package wecom + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "fmt" + "sort" + "strings" +) + +// CallbackConfig holds the parameters needed for WeCom callback URL verification. +// These are generated by the WeCom admin console when configuring "接收消息服务器URL". +type CallbackConfig struct { + Token string `json:"callback_token"` + EncodingAESKey string `json:"callback_aes_key"` + CorpID string `json:"corp_id"` +} + +// VerifyCallback verifies a WeCom callback URL verification request and returns +// the decrypted echostr that should be sent back as the HTTP response body. +// +// WeCom sends a GET request with query params: msg_signature, timestamp, nonce, echostr. +// We must verify the signature, decrypt echostr, and return the plaintext. +func VerifyCallback(cfg CallbackConfig, msgSignature, timestamp, nonce, echostr string) ([]byte, error) { + if cfg.Token == "" || cfg.EncodingAESKey == "" || cfg.CorpID == "" { + return nil, fmt.Errorf("incomplete callback config: token, encoding_aes_key, and corp_id are all required") + } + + // Step 1: Verify signature = SHA1(sort(token, timestamp, nonce, echostr)) + if err := verifySignature(cfg.Token, timestamp, nonce, echostr, msgSignature); err != nil { + return nil, fmt.Errorf("signature verification failed: %w", err) + } + + // Step 2: Decode the AES key (EncodingAESKey is 43-char base64 without trailing '=') + aesKey, err := base64.StdEncoding.DecodeString(cfg.EncodingAESKey + "=") + if err != nil { + return nil, fmt.Errorf("decode EncodingAESKey: %w", err) + } + if len(aesKey) != 32 { + return nil, fmt.Errorf("invalid AES key length: got %d, want 32", len(aesKey)) + } + + // Step 3: Base64-decode the echostr ciphertext + ciphertext, err := base64.StdEncoding.DecodeString(echostr) + if err != nil { + return nil, fmt.Errorf("base64 decode echostr: %w", err) + } + + // Step 4: AES-256-CBC decrypt (IV = first 16 bytes of AES key) + plaintext, err := aesDecrypt(ciphertext, aesKey) + if err != nil { + return nil, fmt.Errorf("AES decrypt: %w", err) + } + + // Step 5: Parse plaintext: 16-byte random + 4-byte msg_len (big-endian) + msg + corp_id + if len(plaintext) < 20 { + return nil, fmt.Errorf("decrypted data too short: %d bytes", len(plaintext)) + } + msgLen := binary.BigEndian.Uint32(plaintext[16:20]) + if 20+int(msgLen) > len(plaintext) { + return nil, fmt.Errorf("invalid msg_len %d, plaintext only %d bytes", msgLen, len(plaintext)) + } + msg := plaintext[20 : 20+msgLen] + receivedCorpID := string(plaintext[20+msgLen:]) + + if receivedCorpID != cfg.CorpID { + return nil, fmt.Errorf("corp_id mismatch: expected %q, got %q", cfg.CorpID, receivedCorpID) + } + + return msg, nil +} + +func verifySignature(token, timestamp, nonce, echostr, expected string) error { + parts := []string{token, timestamp, nonce, echostr} + sort.Strings(parts) + h := sha1.New() + h.Write([]byte(strings.Join(parts, ""))) + got := fmt.Sprintf("%x", h.Sum(nil)) + if got != expected { + return fmt.Errorf("got %s, expected %s", got, expected) + } + return nil +} + +func aesDecrypt(ciphertext, key []byte) ([]byte, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + if len(ciphertext)%aes.BlockSize != 0 { + return nil, fmt.Errorf("ciphertext length %d is not a multiple of block size %d", len(ciphertext), aes.BlockSize) + } + iv := key[:aes.BlockSize] + mode := cipher.NewCBCDecrypter(block, iv) + plaintext := make([]byte, len(ciphertext)) + mode.CryptBlocks(plaintext, ciphertext) + // PKCS#7 unpadding + if len(plaintext) == 0 { + return nil, fmt.Errorf("empty plaintext after decryption") + } + padLen := int(plaintext[len(plaintext)-1]) + if padLen < 1 || padLen > aes.BlockSize || padLen > len(plaintext) { + return nil, fmt.Errorf("invalid PKCS7 padding: %d", padLen) + } + return plaintext[:len(plaintext)-padLen], nil +} diff --git a/internal/datasource/connector/wecom/client.go b/internal/datasource/connector/wecom/client.go new file mode 100644 index 00000000..8536a598 --- /dev/null +++ b/internal/datasource/connector/wecom/client.go @@ -0,0 +1,338 @@ +package wecom + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "sync" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// Client wraps the WeCom API for document and WeDrive operations. +type Client struct { + corpID string + corpSecret string + httpClient *http.Client + + tokenMu sync.Mutex + tokenCache string + tokenExpAt time.Time +} + +// NewClient creates a new WeCom API client. +func NewClient(config *Config) *Client { + return &Client{ + corpID: config.CorpID, + corpSecret: config.CorpSecret, + httpClient: &http.Client{Timeout: 30 * time.Second}, + } +} + +// getAccessToken retrieves (or returns cached) access token. +// WeCom tokens expire in 7200s (2 hours); we cache with a 5-minute safety margin. +func (c *Client) getAccessToken(ctx context.Context) (string, error) { + c.tokenMu.Lock() + defer c.tokenMu.Unlock() + + if c.tokenCache != "" && time.Now().Before(c.tokenExpAt) { + return c.tokenCache, nil + } + + url := fmt.Sprintf("%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s", BaseURL, c.corpID, c.corpSecret) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", fmt.Errorf("create token request: %w", err) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return "", fmt.Errorf("request token: %w", err) + } + defer resp.Body.Close() + + var result tokenResponse + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return "", fmt.Errorf("decode token response: %w", err) + } + if !result.ok() { + return "", result.wrapError("wecom auth") + } + + c.tokenCache = result.AccessToken + ttl := time.Duration(result.ExpiresIn) * time.Second + if ttl > 5*time.Minute { + ttl -= 5 * time.Minute + } + c.tokenExpAt = time.Now().Add(ttl) + + logger.Infof(ctx, "[WeCom] got access_token: %s...%s expires_in=%ds", + safePrefix(result.AccessToken, 8), safeSuffix(result.AccessToken, 4), result.ExpiresIn) + + return c.tokenCache, nil +} + +// doPost executes an authenticated POST request and decodes the JSON response. +func (c *Client) doPost(ctx context.Context, path string, body interface{}, result interface{}) error { + token, err := c.getAccessToken(ctx) + if err != nil { + return err + } + + var bodyReader io.Reader + if body != nil { + bodyBytes, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal request body: %w", err) + } + bodyReader = bytes.NewReader(bodyBytes) + } + + url := fmt.Sprintf("%s%s?access_token=%s", BaseURL, path, token) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bodyReader) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + req.Header.Set("Content-Type", "application/json; charset=utf-8") + + logger.Infof(ctx, "[WeCom] POST %s", path) + + resp, err := c.httpClient.Do(req) + if err != nil { + return fmt.Errorf("execute request: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("read response body: %w", err) + } + + logger.Infof(ctx, "[WeCom] POST %s → status=%d bodyLen=%d body=%s", + path, resp.StatusCode, len(respBody), truncate(string(respBody), 1000)) + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("wecom api error: status=%d body=%s", resp.StatusCode, string(respBody)) + } + + if result != nil { + if err := json.Unmarshal(respBody, result); err != nil { + return fmt.Errorf("decode response: %w", err) + } + } + + return nil +} + +// Ping verifies the credentials by attempting to get an access token. +func (c *Client) Ping(ctx context.Context) error { + _, err := c.getAccessToken(ctx) + return err +} + +// ────────────────────────────────────────────────────────────────────── +// Smart Document APIs (wedoc) +// ────────────────────────────────────────────────────────────────────── + +// ListSmartDocuments lists all smart documents accessible to the app. +// docType: 0=all, 3=doc, 4=sheet, 10=form. +func (c *Client) ListSmartDocuments(ctx context.Context, docType int) ([]docListItem, error) { + var allDocs []docListItem + cursor := "" + + for { + body := map[string]interface{}{ + "limit": 50, + } + if docType != DocFilterAll { + body["doc_type"] = docType + } + if cursor != "" { + body["cursor"] = cursor + } + + var resp docListResponse + if err := c.doPost(ctx, "/cgi-bin/wedoc/doc_list", body, &resp); err != nil { + return nil, fmt.Errorf("list smart documents: %w", err) + } + if !resp.ok() { + return nil, resp.wrapError("list smart documents") + } + + logger.Infof(ctx, "[WeCom] ListSmartDocuments: got %d docs, has_more=%v", len(resp.DocInfoList), resp.HasMore) + + allDocs = append(allDocs, resp.DocInfoList...) + + if !resp.HasMore || resp.NextCursor == "" { + break + } + cursor = resp.NextCursor + } + + logger.Infof(ctx, "[WeCom] ListSmartDocuments: total %d docs (type=%d)", len(allDocs), docType) + return allDocs, nil +} + +// GetDocBaseInfo retrieves metadata for a single document. +func (c *Client) GetDocBaseInfo(ctx context.Context, docID string) (*docBaseInfo, error) { + body := map[string]string{"docid": docID} + + var resp docBaseInfoResponse + if err := c.doPost(ctx, "/cgi-bin/wedoc/get_doc_base_info", body, &resp); err != nil { + return nil, fmt.Errorf("get doc base info: %w", err) + } + if !resp.ok() { + return nil, resp.wrapError("get doc base info") + } + + return &resp.DocBaseInfo, nil +} + +// ────────────────────────────────────────────────────────────────────── +// WeDrive APIs (微盘) +// ────────────────────────────────────────────────────────────────────── + +// ListDriveFiles lists all files in a WeDrive space folder recursively. +// If fatherID is empty, lists files in the space root. +func (c *Client) ListDriveFiles(ctx context.Context, spaceID, fatherID string) ([]driveFileItem, error) { + var allFiles []driveFileItem + start := 0 + + for { + body := map[string]interface{}{ + "spaceid": spaceID, + "sort_type": 5, // sort by modify time desc + "start": start, + "limit": 1000, + } + if fatherID != "" { + body["fatherid"] = fatherID + } + + var resp driveFileListResponse + if err := c.doPost(ctx, "/cgi-bin/wedrive/file_list", body, &resp); err != nil { + return nil, fmt.Errorf("list drive files: %w", err) + } + if !resp.ok() { + return nil, resp.wrapError("list drive files") + } + + allFiles = append(allFiles, resp.FileList.Item...) + + if !resp.FileList.HasMore || len(resp.FileList.Item) == 0 { + break + } + start += len(resp.FileList.Item) + } + + return allFiles, nil +} + +// ListAllDriveFilesRecursive recursively lists all files in a WeDrive space. +func (c *Client) ListAllDriveFilesRecursive(ctx context.Context, spaceID string) ([]driveFileItem, error) { + topFiles, err := c.ListDriveFiles(ctx, spaceID, "") + if err != nil { + return nil, err + } + + var allFiles []driveFileItem + var walk func(files []driveFileItem) error + + walk = func(files []driveFileItem) error { + for _, f := range files { + allFiles = append(allFiles, f) + if f.FileType == FileTypeFolder { + children, err := c.ListDriveFiles(ctx, spaceID, f.FileID) + if err != nil { + return fmt.Errorf("list children of %s: %w", f.FileID, err) + } + if err := walk(children); err != nil { + return err + } + } + } + return nil + } + + if err := walk(topFiles); err != nil { + return nil, err + } + return allFiles, nil +} + +// GetDriveFileDownloadURL gets the temporary download URL for a WeDrive file. +func (c *Client) GetDriveFileDownloadURL(ctx context.Context, fileID, userID string) (*driveFileDownloadResponse, error) { + body := map[string]string{ + "fileid": fileID, + "userid": userID, + } + + var resp driveFileDownloadResponse + if err := c.doPost(ctx, "/cgi-bin/wedrive/file_download", body, &resp); err != nil { + return nil, fmt.Errorf("get drive file download url: %w", err) + } + if !resp.ok() { + return nil, resp.wrapError("get drive file download url") + } + + return &resp, nil +} + +// DownloadFromURL downloads the file content from a temporary download URL with cookie auth. +func (c *Client) DownloadFromURL(ctx context.Context, downloadURL, cookieName, cookieValue string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil) + if err != nil { + return nil, fmt.Errorf("create download request: %w", err) + } + if cookieName != "" && cookieValue != "" { + req.AddCookie(&http.Cookie{Name: cookieName, Value: cookieValue}) + } + + logger.Infof(ctx, "[WeCom] download GET %s", truncate(downloadURL, 100)) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("download request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, truncate(string(body), 500)) + } + + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read download body: %w", err) + } + + logger.Infof(ctx, "[WeCom] download → OK, %d bytes", len(data)) + return data, nil +} + +// --- Helper functions --- + +func truncate(s string, maxLen int) string { + if len(s) <= maxLen { + return s + } + return s[:maxLen] + "..." +} + +func safePrefix(s string, n int) string { + if len(s) < n { + return s + } + return s[:n] +} + +func safeSuffix(s string, n int) string { + if len(s) < n { + return s + } + return s[len(s)-n:] +} diff --git a/internal/datasource/connector/wecom/connector.go b/internal/datasource/connector/wecom/connector.go new file mode 100644 index 00000000..1d623b3f --- /dev/null +++ b/internal/datasource/connector/wecom/connector.go @@ -0,0 +1,533 @@ +package wecom + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// Connector implements the datasource.Connector interface for WeCom (企业微信). +type Connector struct{} + +// NewConnector creates a new WeCom document connector. +func NewConnector() *Connector { + return &Connector{} +} + +// Type returns the connector type identifier. +func (c *Connector) Type() string { + return types.ConnectorTypeWecomDoc +} + +// Validate verifies that the WeCom configuration is valid by testing connectivity. +func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error { + wecomConfig, err := parseWecomConfig(config) + if err != nil { + return err + } + + client := NewClient(wecomConfig) + if err := client.Ping(ctx); err != nil { + return fmt.Errorf("wecom connection failed: %w", err) + } + + return nil +} + +// ListResources lists available smart document categories as selectable resources. +// Each "resource" represents a document type category (all, docs, sheets). +func (c *Connector) ListResources(ctx context.Context, config *types.DataSourceConfig) ([]types.Resource, error) { + wecomConfig, err := parseWecomConfig(config) + if err != nil { + return nil, err + } + + // Verify connectivity + client := NewClient(wecomConfig) + if err := client.Ping(ctx); err != nil { + return nil, fmt.Errorf("wecom connection failed: %w", err) + } + + // Fetch actual doc counts per category to show the user + allDocs, err := client.ListSmartDocuments(ctx, DocFilterAll) + if err != nil { + logger.Warnf(ctx, "[WeCom] failed to list documents for resource discovery: %v", err) + } + + docCount, sheetCount := 0, 0 + for _, d := range allDocs { + switch d.DocType { + case DocFilterDoc: + docCount++ + case DocFilterSheet: + sheetCount++ + } + } + + resources := []types.Resource{ + { + ExternalID: ResourceAllDocs, + Name: "全部文档", + Type: "doc_category", + Description: fmt.Sprintf("所有智能文档 (%d 个)", len(allDocs)), + }, + { + ExternalID: ResourceDocs, + Name: "文档", + Type: "doc_category", + Description: fmt.Sprintf("仅智能文档类型 (%d 个)", docCount), + }, + { + ExternalID: ResourceSheets, + Name: "表格", + Type: "doc_category", + Description: fmt.Sprintf("仅智能表格类型 (%d 个)", sheetCount), + }, + } + + // If WeDrive space IDs are configured in settings, list them too + if spaceIDs := getSettingStringSlice(config, "space_ids"); len(spaceIDs) > 0 { + for _, sid := range spaceIDs { + resources = append(resources, types.Resource{ + ExternalID: "wedrive:" + sid, + Name: "微盘空间: " + sid, + Type: "wedrive_space", + Description: "企业微信微盘空间", + }) + } + } + + return resources, nil +} + +// FetchAll performs a full sync of all documents from the selected resources. +func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error) { + wecomConfig, err := parseWecomConfig(config) + if err != nil { + return nil, err + } + + client := NewClient(wecomConfig) + + var allItems []types.FetchedItem + + for _, resID := range resourceIDs { + if strings.HasPrefix(resID, "wedrive:") { + spaceID := strings.TrimPrefix(resID, "wedrive:") + items, err := c.fetchDriveFiles(ctx, client, config, spaceID) + if err != nil { + return nil, fmt.Errorf("fetch wedrive space %s: %w", spaceID, err) + } + allItems = append(allItems, items...) + } else { + items, err := c.fetchSmartDocs(ctx, client, resID) + if err != nil { + return nil, fmt.Errorf("fetch smart docs (resource=%s): %w", resID, err) + } + allItems = append(allItems, items...) + } + } + + return allItems, nil +} + +// FetchIncremental performs an incremental sync by comparing document modify times. +func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) { + wecomConfig, err := parseWecomConfig(config) + if err != nil { + return nil, nil, err + } + + client := NewClient(wecomConfig) + + var prevCursor wecomCursor + if cursor != nil && cursor.ConnectorCursor != nil { + cursorBytes, _ := json.Marshal(cursor.ConnectorCursor) + _ = json.Unmarshal(cursorBytes, &prevCursor) + } + + newCursor := wecomCursor{ + LastSyncTime: time.Now(), + DocModifyTimes: make(map[string]int64), + } + + var changedItems []types.FetchedItem + + resourceIDs := config.ResourceIDs + if len(resourceIDs) == 0 { + return nil, nil, fmt.Errorf("no resource IDs configured") + } + + for _, resID := range resourceIDs { + if strings.HasPrefix(resID, "wedrive:") { + spaceID := strings.TrimPrefix(resID, "wedrive:") + items, driveModTimes, err := c.fetchDriveFilesIncremental(ctx, client, config, spaceID, prevCursor.DocModifyTimes) + if err != nil { + return nil, nil, fmt.Errorf("incremental fetch wedrive space %s: %w", spaceID, err) + } + changedItems = append(changedItems, items...) + for k, v := range driveModTimes { + newCursor.DocModifyTimes[k] = v + } + continue + } + + docFilter, ok := docFilterForResource[resID] + if !ok { + docFilter = DocFilterAll + } + + docs, err := client.ListSmartDocuments(ctx, docFilter) + if err != nil { + return nil, nil, fmt.Errorf("list smart docs for incremental: %w", err) + } + + currentDocIDs := make(map[string]bool) + + for _, doc := range docs { + currentDocIDs[doc.DocID] = true + + info, err := client.GetDocBaseInfo(ctx, doc.DocID) + if err != nil { + logger.Warnf(ctx, "[WeCom] failed to get doc info for %s: %v", doc.DocID, err) + changedItems = append(changedItems, types.FetchedItem{ + ExternalID: doc.DocID, + Title: doc.DocName, + Metadata: map[string]string{"error": err.Error()}, + }) + newCursor.DocModifyTimes[doc.DocID] = 0 + continue + } + + newCursor.DocModifyTimes[doc.DocID] = info.ModifyTime + + if prevModTime, exists := prevCursor.DocModifyTimes[doc.DocID]; exists { + if prevModTime == info.ModifyTime { + continue // unchanged + } + } + + item := c.buildSmartDocItem(doc.DocID, info) + changedItems = append(changedItems, item) + } + + // Detect deleted docs + for docID := range prevCursor.DocModifyTimes { + if !currentDocIDs[docID] && !strings.HasPrefix(docID, "wedrive:") { + changedItems = append(changedItems, types.FetchedItem{ + ExternalID: docID, + IsDeleted: true, + }) + } + } + } + + nextCursorMap := make(map[string]interface{}) + cursorBytes, _ := json.Marshal(newCursor) + _ = json.Unmarshal(cursorBytes, &nextCursorMap) + + nextSyncCursor := &types.SyncCursor{ + LastSyncTime: time.Now(), + ConnectorCursor: nextCursorMap, + } + + return changedItems, nextSyncCursor, nil +} + +// ────────────────────────────────────────────────────────────────────── +// Internal fetch helpers +// ────────────────────────────────────────────────────────────────────── + +// fetchSmartDocs fetches all smart documents for a given resource category. +func (c *Connector) fetchSmartDocs(ctx context.Context, client *Client, resourceID string) ([]types.FetchedItem, error) { + docFilter, ok := docFilterForResource[resourceID] + if !ok { + docFilter = DocFilterAll + } + + docs, err := client.ListSmartDocuments(ctx, docFilter) + if err != nil { + return nil, err + } + + var items []types.FetchedItem + for _, doc := range docs { + info, err := client.GetDocBaseInfo(ctx, doc.DocID) + if err != nil { + items = append(items, types.FetchedItem{ + ExternalID: doc.DocID, + Title: doc.DocName, + Metadata: map[string]string{"error": err.Error()}, + }) + continue + } + + items = append(items, c.buildSmartDocItem(doc.DocID, info)) + } + + return items, nil +} + +// buildSmartDocItem constructs a FetchedItem for a smart document. +func (c *Connector) buildSmartDocItem(docID string, info *docBaseInfo) types.FetchedItem { + docURL := buildDocURL(docID, info.DocType) + modTime := time.Unix(info.ModifyTime, 0) + + return types.FetchedItem{ + ExternalID: docID, + Title: info.DocName, + URL: docURL, + ContentType: "text/html", + UpdatedAt: modTime, + Metadata: map[string]string{ + "doc_type": fmt.Sprintf("%d", info.DocType), + "create_time": fmt.Sprintf("%d", info.CreateTime), + "modify_time": fmt.Sprintf("%d", info.ModifyTime), + "channel": types.ChannelWecom, + }, + } +} + +// fetchDriveFiles fetches all files from a WeDrive space. +func (c *Connector) fetchDriveFiles(ctx context.Context, client *Client, config *types.DataSourceConfig, spaceID string) ([]types.FetchedItem, error) { + files, err := client.ListAllDriveFilesRecursive(ctx, spaceID) + if err != nil { + return nil, err + } + + userID := getSettingString(config, "userid") + + var items []types.FetchedItem + for _, f := range files { + if f.FileType == FileTypeFolder { + continue + } + + item, err := c.fetchDriveFileContent(ctx, client, f, spaceID, userID) + if err != nil { + items = append(items, types.FetchedItem{ + ExternalID: "wedrive:" + f.FileID, + Title: f.FileName, + SourceResourceID: "wedrive:" + spaceID, + Metadata: map[string]string{"error": err.Error()}, + }) + continue + } + if item != nil { + items = append(items, *item) + } + } + + return items, nil +} + +// fetchDriveFilesIncremental performs incremental fetch for a WeDrive space. +func (c *Connector) fetchDriveFilesIncremental(ctx context.Context, client *Client, config *types.DataSourceConfig, spaceID string, prevModTimes map[string]int64) ([]types.FetchedItem, map[string]int64, error) { + files, err := client.ListAllDriveFilesRecursive(ctx, spaceID) + if err != nil { + return nil, nil, err + } + + userID := getSettingString(config, "userid") + modTimes := make(map[string]int64) + currentIDs := make(map[string]bool) + var changed []types.FetchedItem + + for _, f := range files { + if f.FileType == FileTypeFolder { + continue + } + key := "wedrive:" + f.FileID + currentIDs[key] = true + modTimes[key] = f.ModifyTime + + if prevMod, exists := prevModTimes[key]; exists && prevMod == f.ModifyTime { + continue // unchanged + } + + item, err := c.fetchDriveFileContent(ctx, client, f, spaceID, userID) + if err != nil { + changed = append(changed, types.FetchedItem{ + ExternalID: key, + Title: f.FileName, + SourceResourceID: "wedrive:" + spaceID, + Metadata: map[string]string{"error": err.Error()}, + }) + continue + } + if item != nil { + changed = append(changed, *item) + } + } + + // Detect deletions + for prevKey := range prevModTimes { + if strings.HasPrefix(prevKey, "wedrive:") && !currentIDs[prevKey] { + changed = append(changed, types.FetchedItem{ + ExternalID: prevKey, + IsDeleted: true, + SourceResourceID: "wedrive:" + spaceID, + }) + } + } + + return changed, modTimes, nil +} + +// fetchDriveFileContent downloads file content for a WeDrive file. +func (c *Connector) fetchDriveFileContent(ctx context.Context, client *Client, f driveFileItem, spaceID, userID string) (*types.FetchedItem, error) { + modTime := time.Unix(f.ModifyTime, 0) + externalID := "wedrive:" + f.FileID + baseMeta := map[string]string{ + "file_type": fmt.Sprintf("%d", f.FileType), + "file_id": f.FileID, + "space_id": spaceID, + "create_userid": f.CreateUserID, + "update_userid": f.UpdateUserID, + "channel": types.ChannelWecom, + } + + switch f.FileType { + case FileTypeFile: + // Binary uploaded file — download via WeDrive API + if userID == "" { + return &types.FetchedItem{ + ExternalID: externalID, + Title: f.FileName, + URL: f.URL, + UpdatedAt: modTime, + SourceResourceID: "wedrive:" + spaceID, + Metadata: baseMeta, + }, nil + } + + dlResp, err := client.GetDriveFileDownloadURL(ctx, f.FileID, userID) + if err != nil { + return nil, fmt.Errorf("get download url for %s: %w", f.FileName, err) + } + + data, err := client.DownloadFromURL(ctx, dlResp.DownloadURL, dlResp.CookieName, dlResp.CookieValue) + if err != nil { + return nil, fmt.Errorf("download file %s: %w", f.FileName, err) + } + + return &types.FetchedItem{ + ExternalID: externalID, + Title: f.FileName, + Content: data, + ContentType: "application/octet-stream", + FileName: f.FileName, + URL: f.URL, + UpdatedAt: modTime, + SourceResourceID: "wedrive:" + spaceID, + Metadata: baseMeta, + }, nil + + case FileTypeDoc, FileTypeSheet, FileTypeForm: + // Smart doc in WeDrive — import via URL + url := f.URL + if url == "" { + url = buildDocURL(f.FileID, f.FileType) + } + + return &types.FetchedItem{ + ExternalID: externalID, + Title: f.FileName, + URL: url, + ContentType: "text/html", + UpdatedAt: modTime, + SourceResourceID: "wedrive:" + spaceID, + Metadata: baseMeta, + }, nil + + default: + return nil, nil + } +} + +// ────────────────────────────────────────────────────────────────────── +// Helper functions +// ────────────────────────────────────────────────────────────────────── + +func parseWecomConfig(config *types.DataSourceConfig) (*Config, error) { + if config == nil { + return nil, fmt.Errorf("config is nil") + } + + credBytes, err := json.Marshal(config.Credentials) + if err != nil { + return nil, fmt.Errorf("marshal credentials: %w", err) + } + + var wecomConfig Config + if err := json.Unmarshal(credBytes, &wecomConfig); err != nil { + return nil, fmt.Errorf("parse wecom credentials: %w", err) + } + + if wecomConfig.CorpID == "" || wecomConfig.CorpSecret == "" { + return nil, fmt.Errorf("wecom corp_id and corp_secret are required") + } + + return &wecomConfig, nil +} + +// buildDocURL constructs the WeCom document URL based on doc type. +// docType can be either DocFilter* or FileType* constants (4 = sheet in both). +func buildDocURL(docID string, docType int) string { + switch docType { + case FileTypeSheet: // also matches DocFilterSheet (both are 4) + return fmt.Sprintf("https://doc.weixin.qq.com/sheet/%s", docID) + case FileTypeForm, DocFilterForm: + return fmt.Sprintf("https://doc.weixin.qq.com/forms/%s", docID) + default: + return fmt.Sprintf("https://doc.weixin.qq.com/doc/%s", docID) + } +} + +// getSettingString retrieves a string value from config.Settings. +func getSettingString(config *types.DataSourceConfig, key string) string { + if config == nil || config.Settings == nil { + return "" + } + v, ok := config.Settings[key] + if !ok { + return "" + } + s, _ := v.(string) + return s +} + +// getSettingStringSlice retrieves a string slice from config.Settings. +func getSettingStringSlice(config *types.DataSourceConfig, key string) []string { + if config == nil || config.Settings == nil { + return nil + } + v, ok := config.Settings[key] + if !ok { + return nil + } + switch val := v.(type) { + case []string: + return val + case []interface{}: + result := make([]string, 0, len(val)) + for _, item := range val { + if s, ok := item.(string); ok { + result = append(result, s) + } + } + return result + case string: + if val == "" { + return nil + } + return strings.Split(val, ",") + default: + return nil + } +} diff --git a/internal/datasource/connector/wecom/types.go b/internal/datasource/connector/wecom/types.go new file mode 100644 index 00000000..b7eb1511 --- /dev/null +++ b/internal/datasource/connector/wecom/types.go @@ -0,0 +1,155 @@ +// Package wecom implements the WeCom (企业微信) document data source connector for WeKnora. +// +// It syncs smart documents and WeDrive files from WeCom into WeKnora knowledge bases. +// +// WeCom API docs: +// - Auth: https://developer.work.weixin.qq.com/document/path/91039 +// - Smart doc list: https://developer.work.weixin.qq.com/document/path/97460 +// - Doc base info: https://developer.work.weixin.qq.com/document/path/97461 +// - WeDrive file list: https://developer.work.weixin.qq.com/document/path/95859 +// - WeDrive download: https://developer.work.weixin.qq.com/document/path/98021 +package wecom + +import ( + "fmt" + "time" +) + +// Config holds WeCom-specific configuration for the data source connector. +type Config struct { + CorpID string `json:"corp_id"` + CorpSecret string `json:"corp_secret"` +} + +// BaseURL is the WeCom API base URL. +const BaseURL = "https://qyapi.weixin.qq.com" + +// Smart document type filter values for POST /cgi-bin/wedoc/doc_list. +const ( + DocFilterAll = 0 // All types + DocFilterDoc = 3 // Documents (文档) + DocFilterSheet = 4 // Spreadsheets (表格) + DocFilterForm = 10 // Collect forms (收集表) +) + +// WeDrive file_type values returned by file_list / file_info. +const ( + FileTypeFolder = 1 // Folder + FileTypeFile = 2 // Uploaded file (binary) + FileTypeDoc = 3 // Smart doc (文档) + FileTypeSheet = 4 // Smart sheet (表格) + FileTypeForm = 5 // Collect form (收集表) +) + +// Resource type identifiers used by ListResources. +const ( + ResourceAllDocs = "all_documents" + ResourceDocs = "documents" + ResourceSheets = "sheets" +) + +// docFilterForResource maps resource type IDs to doc/list type parameters. +var docFilterForResource = map[string]int{ + ResourceAllDocs: DocFilterAll, + ResourceDocs: DocFilterDoc, + ResourceSheets: DocFilterSheet, +} + +// --- WeCom API response structures --- + +type apiResponse struct { + ErrCode int `json:"errcode"` + ErrMsg string `json:"errmsg"` +} + +func (r *apiResponse) ok() bool { return r.ErrCode == 0 } + +func (r *apiResponse) wrapError(action string) error { + hint := "" + switch r.ErrCode { + case 48002: + hint = " (应用未被授权调用此接口,请在管理后台「协作→文档→API」中将应用添加为「可调用接口的应用」,并检查「企业可信IP」配置)" + case 60020: + hint = " (IP 不在企业可信 IP 白名单中,请在应用详情页底部添加服务器 IP)" + case 40014, 42001: + hint = " (access_token 无效或已过期)" + case 301002: + hint = " (应用无文档访问权限,请检查可见范围设置)" + } + return fmt.Errorf("%s: errcode=%d errmsg=%s%s", action, r.ErrCode, r.ErrMsg, hint) +} + +type tokenResponse struct { + apiResponse + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` // seconds, typically 7200 +} + +// docListItem is a single item returned by the doc list API. +type docListItem struct { + DocID string `json:"docid"` + DocName string `json:"doc_name"` + DocType int `json:"doc_type,omitempty"` +} + +// docListResponse is the response for POST /cgi-bin/wedoc/doc_list. +type docListResponse struct { + apiResponse + DocInfoList []docListItem `json:"doc_info_list"` + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor"` +} + +// docBaseInfo is the detailed metadata of a single document. +type docBaseInfo struct { + DocID string `json:"docid"` + DocName string `json:"doc_name"` + CreateTime int64 `json:"create_time"` // unix timestamp + ModifyTime int64 `json:"modify_time"` // unix timestamp + DocType int `json:"doc_type"` // 3=doc, 4=sheet +} + +// docBaseInfoResponse is the response for POST /cgi-bin/wedoc/get_doc_base_info. +type docBaseInfoResponse struct { + apiResponse + DocBaseInfo docBaseInfo `json:"doc_base_info"` +} + +// driveFileItem represents a file/folder in WeDrive. +type driveFileItem struct { + FileID string `json:"fileid"` + FileName string `json:"file_name"` + SpaceID string `json:"spaceid"` + FatherID string `json:"fatherid"` + FileSize int64 `json:"file_size"` + CreateTime int64 `json:"ctime"` + ModifyTime int64 `json:"mtime"` + FileType int `json:"file_type"` // 1=folder, 2=file, 3=doc, 4=sheet, 5=form + FileStatus int `json:"file_status"` + CreateUserID string `json:"create_userid"` + UpdateUserID string `json:"update_userid"` + URL string `json:"url"` // non-empty for smart doc types +} + +// driveFileListResponse is the response for POST /cgi-bin/wedrive/file_list. +type driveFileListResponse struct { + apiResponse + FileList struct { + Item []driveFileItem `json:"item"` + HasMore bool `json:"has_more"` + } `json:"file_list"` +} + +// driveFileDownloadResponse is the response for POST /cgi-bin/wedrive/file_download. +type driveFileDownloadResponse struct { + apiResponse + DownloadURL string `json:"download_url"` + CookieName string `json:"cookie_name"` + CookieValue string `json:"cookie_value"` +} + +// wecomCursor stores incremental sync state for WeCom. +type wecomCursor struct { + LastSyncTime time.Time `json:"last_sync_time"` + DocModifyTimes map[string]int64 `json:"doc_modify_times,omitempty"` // docid -> modify_time +} diff --git a/internal/handler/wecom_callback.go b/internal/handler/wecom_callback.go new file mode 100644 index 00000000..4500bcfc --- /dev/null +++ b/internal/handler/wecom_callback.go @@ -0,0 +1,93 @@ +package handler + +import ( + "encoding/json" + "net/http" + + "github.com/Tencent/WeKnora/internal/datasource/connector/wecom" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// WecomCallbackHandler handles WeCom callback URL verification. +// This is needed so the WeCom admin console can verify the callback URL, +// which unlocks the "企业可信IP" configuration, which in turn unlocks +// the "可调用接口的应用" setting for document/drive APIs. +type WecomCallbackHandler struct { + dsService interfaces.DataSourceService +} + +// NewWecomCallbackHandler creates a new handler. +func NewWecomCallbackHandler(dsService interfaces.DataSourceService) *WecomCallbackHandler { + return &WecomCallbackHandler{dsService: dsService} +} + +// HandleCallback responds to WeCom's callback URL verification (GET) and +// message push (POST). Only GET verification is needed for our use case. +// +// Route: GET /api/v1/wecom/callback/:datasource_id +// +// WeCom sends: ?msg_signature=xxx×tamp=xxx&nonce=xxx&echostr=xxx +// We decrypt echostr and return the plaintext. +func (h *WecomCallbackHandler) HandleCallback(c *gin.Context) { + ctx := c.Request.Context() + dsID := c.Param("datasource_id") + + ds, err := h.dsService.GetDataSource(ctx, dsID) + if err != nil { + logger.Warnf(ctx, "[WecomCallback] data source %s not found: %v", dsID, err) + c.String(http.StatusNotFound, "data source not found") + return + } + + if ds.Type != "wecom_doc" { + c.String(http.StatusBadRequest, "not a wecom_doc data source") + return + } + + var dsConfig struct { + Credentials map[string]interface{} `json:"credentials"` + Settings map[string]interface{} `json:"settings"` + } + if err := json.Unmarshal(ds.Config, &dsConfig); err != nil { + logger.Warnf(ctx, "[WecomCallback] failed to parse config for %s: %v", dsID, err) + c.String(http.StatusInternalServerError, "config parse error") + return + } + + getString := func(m map[string]interface{}, key string) string { + if m == nil { + return "" + } + v, _ := m[key].(string) + return v + } + + cfg := wecom.CallbackConfig{ + Token: getString(dsConfig.Settings, "callback_token"), + EncodingAESKey: getString(dsConfig.Settings, "callback_aes_key"), + CorpID: getString(dsConfig.Credentials, "corp_id"), + } + + if cfg.Token == "" || cfg.EncodingAESKey == "" { + logger.Warnf(ctx, "[WecomCallback] ds %s missing callback_token or callback_aes_key in settings", dsID) + c.String(http.StatusBadRequest, "callback_token and callback_aes_key must be configured in data source settings") + return + } + + msgSignature := c.Query("msg_signature") + timestamp := c.Query("timestamp") + nonce := c.Query("nonce") + echostr := c.Query("echostr") + + plaintext, err := wecom.VerifyCallback(cfg, msgSignature, timestamp, nonce, echostr) + if err != nil { + logger.Warnf(ctx, "[WecomCallback] verification failed for ds %s: %v", dsID, err) + c.String(http.StatusForbidden, "verification failed") + return + } + + logger.Infof(ctx, "[WecomCallback] callback URL verified successfully for ds %s", dsID) + c.String(http.StatusOK, string(plaintext)) +} diff --git a/internal/router/router.go b/internal/router/router.go index 67df9dd9..9aa17f82 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -61,6 +61,7 @@ type RouterParams struct { OrganizationHandler *handler.OrganizationHandler IMHandler *handler.IMHandler DataSourceHandler *handler.DataSourceHandler + WecomCallbackHandler *handler.WecomCallbackHandler } // NewRouter 创建新的路由 @@ -109,6 +110,9 @@ func NewRouter(params RouterParams) *gin.Engine { // IM 回调路由(在认证中间件之前注册,使用各平台自身的签名验证) RegisterIMRoutes(r, params.IMHandler) + // WeCom callback verification (before auth — WeCom uses its own signature) + RegisterWecomCallbackRoutes(r, params.WecomCallbackHandler) + // 认证中间件 r.Use(middleware.Auth(params.TenantService, params.UserService, params.Config)) @@ -775,3 +779,10 @@ func RegisterDataSourceRoutes(r *gin.RouterGroup, handler *handler.DataSourceHan ds.GET("/logs/:log_id", handler.GetSyncLog) } } + +// RegisterWecomCallbackRoutes registers the WeCom callback verification route. +// Must be registered BEFORE auth middleware since WeCom uses its own msg_signature verification. +func RegisterWecomCallbackRoutes(r *gin.Engine, h *handler.WecomCallbackHandler) { + r.GET("/api/v1/wecom/callback/:datasource_id", h.HandleCallback) + r.POST("/api/v1/wecom/callback/:datasource_id", h.HandleCallback) +}