From 664d193ca7b035bf30e081bf006fa9990969baa6 Mon Sep 17 00:00:00 2001 From: joeyczheng Date: Wed, 12 Aug 2026 11:34:28 +0800 Subject: [PATCH] feat(datasource): add Tencent IMA datasource Signed-off-by: joeyczheng --- frontend/src/assets/img/datasource-ima.png | Bin 0 -> 20919 bytes frontend/src/components/doc-content.vue | 1 + frontend/src/i18n/locales/en-US.ts | 13 + frontend/src/i18n/locales/ko-KR.ts | 13 + frontend/src/i18n/locales/ru-RU.ts | 13 + frontend/src/i18n/locales/zh-CN.ts | 13 + .../components/tool-results/DocumentInfo.vue | 1 + .../src/views/knowledge/KnowledgeBase.vue | 1 + .../knowledge/components/DocumentCardView.vue | 1 + .../knowledge/components/DocumentListView.vue | 1 + .../settings/DataSourceEditorDialog.vue | 15 + .../knowledge/settings/DataSourceSettings.vue | 1 + .../knowledge/settings/DataSourceTypeIcon.vue | 2 + .../knowledge/settings/datasourceIcons.ts | 2 + internal/container/container.go | 4 + internal/datasource/connector.go | 8 + internal/datasource/connector/ima/client.go | 358 ++++++++++++ .../datasource/connector/ima/connector.go | 514 ++++++++++++++++++ internal/datasource/connector/ima/types.go | 353 ++++++++++++ internal/types/datasource.go | 1 + internal/types/knowledge.go | 1 + 21 files changed, 1316 insertions(+) create mode 100644 frontend/src/assets/img/datasource-ima.png create mode 100644 internal/datasource/connector/ima/client.go create mode 100644 internal/datasource/connector/ima/connector.go create mode 100644 internal/datasource/connector/ima/types.go diff --git a/frontend/src/assets/img/datasource-ima.png b/frontend/src/assets/img/datasource-ima.png new file mode 100644 index 0000000000000000000000000000000000000000..8e70f2f5af1ffe8273d6eb80bc1406342862150c GIT binary patch literal 20919 zcmWh!1yEaC5Do4Sq_{i9p}4yjE5$8nad&rjFYa!|-QC@_xEJ@IKTLQtndIHP-MzbK z&)FNU^j!)C5g!o%0HDZ7i>rXIx&Oc5VZr|+r_C6_7g8f>6$Jpmg9-rf3j_e3Kf%`% z0Kl0A05~-O0C>{?036!{{Xt3aXJJ8dQsR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z^TIGR4@C$er33&HLI}_ENJJ = { dingtalk: 'knowledgeBase.channelDingtalk', slack: 'knowledgeBase.channelSlack', im: 'knowledgeBase.channelIm', + ima: 'knowledgeBase.channelIma', }; const getChannelLabel = (channel: string) => { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 8e981a89..99bdea59 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -466,6 +466,7 @@ export default { channelIm: 'IM Channel', channelNotion: 'Notion', channelYuque: 'Yuque', + channelIma: 'Tencent IMA', channelUpload: 'Upload', channelManual: 'Manual', channelUrl: 'Web', @@ -5475,6 +5476,7 @@ export default { lark_drive: 'Lark Drive', notion: 'Notion', yuque: 'Yuque', + ima: 'Tencent IMA', rss: 'RSS / Atom Feed' }, connectorDesc: { @@ -5484,6 +5486,7 @@ export default { lark_drive: 'Sync documents, spreadsheets and files from a Lark Drive folder (Feishu international)', notion: 'Sync pages and databases from Notion', yuque: 'Sync documents from Yuque knowledge bases', + ima: 'Sync documents, notes and files from Tencent IMA knowledge bases', rss: 'Sync articles from RSS / Atom feeds' }, drive: { @@ -5504,6 +5507,8 @@ export default { appSecret: 'App Secret', integrationToken: 'Integration Token', apiToken: 'API Token', + imaClientId: 'IMA ClientID', + imaApiKey: 'IMA APIKey', baseUrl: 'Base URL (optional)', baseUrlHint: 'Leave empty to use the default public cloud address. For private/enterprise deployments or when accessing via reverse proxy, enter your custom address (e.g. https://api-proxy.example.com).', feedUrls: 'Feed URLs', @@ -5547,6 +5552,14 @@ export default { prereqStep3Brief_lark_drive: 'Configure app permissions', prereqStep3Desc_lark_drive: 'Enable drive:drive:readonly, drive:export:readonly, docx:document:readonly permissions', prereqOpenConsole_yuque: 'Open Yuque Token settings', + prereqBarText_ima: 'First time? Click to see the Tencent IMA OpenAPI setup guide', + prereqStep1Brief_ima: 'Enable IMA agent OpenAPI access', + prereqStep1Desc_ima: 'Sign in to https://ima.qq.com/agent-interface and apply for OpenAPI access', + prereqStep2Brief_ima: 'Obtain the ClientID and APIKey', + prereqStep2Desc_ima: 'Copy the ima-openapi-clientid and ima-openapi-apikey credentials from the agent-interface page', + prereqStep3Brief_ima: 'Grant the credential access to the target knowledge bases', + prereqStep3Desc_ima: 'In the IMA client, authorize the credential for the knowledge bases you want to sync; unauthorized bases will not appear in the list', + prereqOpenConsole_ima: 'Open Tencent IMA OpenAPI console', prereqBotBrief: 'Add "Bot" capability to your app', prereqBotDesc: 'Open Platform > Add App Capability > Bot > create version and publish', prereqPermBrief: 'Grant API permissions', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index d60272ed..796cbf9f 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -644,6 +644,14 @@ export default { prereqStep3Brief_lark_drive: "앱 권한 구성", prereqStep3Desc_lark_drive: "drive:drive:readonly, drive:export:readonly, docx:document:readonly 권한 활성화", prereqOpenConsole_yuque: 'Yuque Token 설정으로 이동', + prereqBarText_ima: '처음 사용하시나요? 클릭하여 Tencent IMA OpenAPI 설정 가이드를 확인하세요', + prereqStep1Brief_ima: 'IMA 에이전트 OpenAPI 액세스 활성화', + prereqStep1Desc_ima: 'https://ima.qq.com/agent-interface 에 로그인하여 OpenAPI 액세스를 신청하세요', + prereqStep2Brief_ima: 'ClientID 및 APIKey 획득', + prereqStep2Desc_ima: '에이전트 접속 페이지에서 ima-openapi-clientid 와 ima-openapi-apikey 자격 증명을 복사하세요', + prereqStep3Brief_ima: '대상 지식베이스에 자격 증명 권한 부여', + prereqStep3Desc_ima: 'IMA 클라이언트에서 동기화하려는 지식베이스에 대해 자격 증명을 승인하세요. 승인되지 않은 지식베이스는 목록에 나타나지 않습니다', + prereqOpenConsole_ima: 'Tencent IMA OpenAPI 콘솔로 이동', prereqBotBrief: '앱에 \'봇\' 기능 추가', prereqBotDesc: '오픈 플랫폼 → 앱 기능 추가 → 봇 → 버전 생성 후 게시', prereqPermBrief: 'API 권한 활성화', @@ -680,6 +688,8 @@ export default { appSecret: 'App Secret', integrationToken: 'Integration Token', apiToken: 'API Token', + imaClientId: 'IMA ClientID', + imaApiKey: 'IMA APIKey', baseUrl: 'Base URL', baseUrlHint: "비워두면 기본 퍼블릭 클라우드 주소가 사용됩니다. 프라이빗/엔터프라이즈 배포거나 리버스 프록시를 통해 액세스해야 하는 경우 사용자 정의 주소를 입력하세요 (예: https://api-proxy.example.com)", feedUrls: '피드 주소', @@ -694,6 +704,7 @@ export default { lark_drive: "Lark 드라이브 폴더에서 문서, 스프레드시트, 파일 동기화", notion: 'Notion에서 페이지 및 데이터베이스 동기화', yuque: '위큐 지식베이스에서 문서 동기화', + ima: 'Tencent IMA 지식베이스에서 문서, 노트 및 파일 동기화', rss: 'RSS / Atom 피드에서 글 동기화' }, connector: { @@ -703,6 +714,7 @@ export default { lark_drive: "Lark 드라이브", notion: 'Notion', yuque: '위큐 (Yuque)', + ima: 'Tencent IMA', rss: 'RSS / Atom 피드' }, logDetail: { @@ -5588,6 +5600,7 @@ export default { channelIm: 'IM 채널', channelNotion: 'Notion', channelYuque: 'Yuque', + channelIma: 'Tencent IMA', channelUpload: '업로드', channelManual: '수동', channelUrl: '웹', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index d8b6569d..a19624b8 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -620,6 +620,14 @@ export default { prereqStep3Brief_yuque: '(Опционально) Для Enterprise укажите Base URL', prereqStep3Desc_yuque: 'Пользователям публичного облака указывать не нужно. Для Yuque Enterprise или приватного развёртывания укажите корпоративный домен', prereqOpenConsole_yuque: 'Перейти к настройкам Yuque Token', + prereqBarText_ima: 'В первый раз? Нажмите, чтобы увидеть руководство по настройке Tencent IMA OpenAPI', + prereqStep1Brief_ima: 'Включите доступ к IMA agent OpenAPI', + prereqStep1Desc_ima: 'Войдите на https://ima.qq.com/agent-interface и подайте заявку на доступ к OpenAPI', + prereqStep2Brief_ima: 'Получите ClientID и APIKey', + prereqStep2Desc_ima: 'Скопируйте учётные данные ima-openapi-clientid и ima-openapi-apikey на странице agent-interface', + prereqStep3Brief_ima: 'Предоставьте учётным данным доступ к целевым базам знаний', + prereqStep3Desc_ima: 'В клиенте IMA авторизуйте учётные данные для баз знаний, которые нужно синхронизировать; неавторизованные базы в списке не отобразятся', + prereqOpenConsole_ima: 'Открыть консоль Tencent IMA OpenAPI', prereqStep1Brief_feishu: 'Создать частное приложение Feishu', prereqStep1Desc_feishu: 'Войдите в Feishu Open Platform → Создать корпоративное частное приложение', prereqStep2Brief_feishu: 'Добавить возможность бота', @@ -680,6 +688,8 @@ export default { appSecret: 'App Secret', integrationToken: 'Integration Token', apiToken: 'API Token', + imaClientId: 'IMA ClientID', + imaApiKey: 'IMA APIKey', baseUrl: 'Base URL', baseUrlHint: 'Оставьте пустым, чтобы использовать адрес общедоступного облака по умолчанию. Для частных/корпоративных развертываний или при доступе через обратный прокси введите ваш собственный адрес (например, https://api-proxy.example.com)', feedUrls: 'Адреса лент', @@ -694,6 +704,7 @@ export default { lark_drive: 'Синхронизация документов, таблиц и файлов из папки Lark Drive', notion: 'Синхронизация страниц и баз данных из Notion', yuque: 'Синхронизация документов из баз знаний Yuque', + ima: 'Синхронизация документов, заметок и файлов из баз знаний Tencent IMA', rss: 'Синхронизация статей из лент RSS / Atom' }, connector: { @@ -703,6 +714,7 @@ export default { lark_drive: 'Lark Drive', notion: 'Notion', yuque: 'Yuque (Юйцюэ)', + ima: 'Tencent IMA', rss: 'RSS / Atom лента' }, logDetail: { @@ -5588,6 +5600,7 @@ export default { channelIm: 'IM канал', channelNotion: 'Notion', channelYuque: 'Yuque', + channelIma: 'Tencent IMA', channelUpload: 'Загрузка', channelManual: 'Вручную', channelUrl: 'Веб', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 5347e1c4..a6bc1778 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -620,6 +620,14 @@ export default { prereqStep3Brief_yuque: '(可选)企业版填写 Base URL', prereqStep3Desc_yuque: '公有云用户无需填写;语雀企业版或私有部署请填写企业域名', prereqOpenConsole_yuque: '前往语雀 Token 设置', + prereqBarText_ima: '首次使用?点击查看腾讯 IMA OpenAPI 授权指引', + prereqStep1Brief_ima: '开通 IMA 智能体接入', + prereqStep1Desc_ima: '登录 https://ima.qq.com/agent-interface 并申请 OpenAPI 接入', + prereqStep2Brief_ima: '获取 ClientID 与 APIKey', + prereqStep2Desc_ima: '在智能体接入页复制 ima-openapi-clientid 与 ima-openapi-apikey 两个凭证', + prereqStep3Brief_ima: '授权目标知识库', + prereqStep3Desc_ima: '在 IMA 客户端为该凭证授权需要同步的知识库,未授权的知识库不会出现在列表中', + prereqOpenConsole_ima: '前往 IMA OpenAPI 控制台', prereqStep1Brief_feishu: "创建飞书自建应用", prereqStep1Desc_feishu: "登录飞书开放平台 → 创建企业自建应用", prereqStep2Brief_feishu: "添加机器人能力", @@ -680,6 +688,8 @@ export default { appSecret: 'App Secret', integrationToken: 'Integration Token', apiToken: 'API Token', + imaClientId: 'IMA ClientID', + imaApiKey: 'IMA APIKey', baseUrl: 'Base URL(可选)', baseUrlHint: '留空将使用默认公有云地址;如果是私有部署/企业内网部署,或需要通过反向代理访问,请填写自定义地址(例如 https://api-proxy.example.com)', feedUrls: '订阅源地址', @@ -694,6 +704,7 @@ export default { lark_drive: "同步 Lark 云盘文件夹中的文档、表格、文件(飞书国际版)", notion: '同步 Notion 中的页面和数据库', yuque: '同步语雀知识库中的文档', + ima: '同步腾讯 IMA 知识库中的文档、笔记与文件', rss: '同步 RSS / Atom 订阅源中的文章' }, connector: { @@ -703,6 +714,7 @@ export default { lark_drive: "Lark 云盘", notion: 'Notion', yuque: '语雀', + ima: '腾讯 IMA', rss: 'RSS / Atom 订阅' }, logDetail: { @@ -5588,6 +5600,7 @@ export default { channelIm: 'IM 渠道', channelNotion: 'Notion', channelYuque: '语雀', + channelIma: '腾讯 IMA', channelUpload: '上传', channelManual: '手动', channelUrl: '网页', diff --git a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue index a8d1dc3f..be30673a 100644 --- a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue +++ b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue @@ -111,6 +111,7 @@ const channelLabelMap: Record = { dingtalk: 'knowledgeBase.channelDingtalk', slack: 'knowledgeBase.channelSlack', im: 'knowledgeBase.channelIm', + ima: 'knowledgeBase.channelIma', }; const getChannelLabel = (channel: string) => { diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 9ef0ce59..8181faa5 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -599,6 +599,7 @@ const sourceOptions = computed(() => [ { label: t('knowledgeBase.channelFeishuDrive'), value: 'feishu_drive' }, { label: t('knowledgeBase.channelNotion'), value: 'notion' }, { label: t('knowledgeBase.channelYuque'), value: 'yuque' }, + { label: t('knowledgeBase.channelIma'), value: 'ima' }, { label: t('knowledgeBase.channelWechat'), value: 'wechat' }, { label: t('knowledgeBase.channelWecom'), value: 'wecom' }, { label: t('knowledgeBase.channelDingtalk'), value: 'dingtalk' }, diff --git a/frontend/src/views/knowledge/components/DocumentCardView.vue b/frontend/src/views/knowledge/components/DocumentCardView.vue index dcf35c70..b3e5342e 100644 --- a/frontend/src/views/knowledge/components/DocumentCardView.vue +++ b/frontend/src/views/knowledge/components/DocumentCardView.vue @@ -157,6 +157,7 @@ const channelLabelMap: Record = { dingtalk: 'knowledgeBase.channelDingtalk', slack: 'knowledgeBase.channelSlack', im: 'knowledgeBase.channelIm', + ima: 'knowledgeBase.channelIma', }; const getChannelLabel = (channel: string) => { diff --git a/frontend/src/views/knowledge/components/DocumentListView.vue b/frontend/src/views/knowledge/components/DocumentListView.vue index 7bb6bfb8..92348c32 100644 --- a/frontend/src/views/knowledge/components/DocumentListView.vue +++ b/frontend/src/views/knowledge/components/DocumentListView.vue @@ -114,6 +114,7 @@ const getSourceInfo = (item: KnowledgeItem): { icon: string; label: string } => if (ch === 'lark_drive') return { icon: 'cloud-download', label: t('knowledgeBase.channelLarkDrive') }; if (ch === 'notion') return { icon: 'cloud-download', label: t('knowledgeBase.channelNotion') }; if (ch === 'yuque') return { icon: 'cloud-download', label: t('knowledgeBase.channelYuque') }; + if (ch === 'ima') return { icon: 'cloud-download', label: t('knowledgeBase.channelIma') }; if (ch === 'wechat') return { icon: 'cloud-download', label: t('knowledgeBase.channelWechat') }; if (ch === 'wecom') return { icon: 'cloud-download', label: t('knowledgeBase.channelWecom') }; if (ch === 'dingtalk') return { icon: 'cloud-download', label: t('knowledgeBase.channelDingtalk') }; diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue index cd3cf4cc..2346cde4 100644 --- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue +++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue @@ -585,6 +585,21 @@ const connectorDefs = computed(() => [ { key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://www.yuque.com', optional: true, hintKey: 'datasource.field.baseUrlHint' }, ], }, + { + // Tencent IMA (ima.qq.com). Uses the OpenAPI at /openapi/wiki/v1 with two + // static headers (ima-openapi-clientid + ima-openapi-apikey); no OAuth. + type: 'ima', + available: true, + docUrl: 'https://ima.qq.com/agent-interface', + permissionDocUrl: 'https://ima.qq.com/agent-interface', + permissionPageUrl: 'https://ima.qq.com/agent-interface', + requiredPermissions: [], + fields: [ + { key: 'client_id', labelKey: 'datasource.field.imaClientId', placeholder: '', secret: true }, + { key: 'api_key', labelKey: 'datasource.field.imaApiKey', placeholder: '', secret: true }, + { key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://ima.qq.com', optional: true, hintKey: 'datasource.field.baseUrlHint' }, + ], + }, { type: 'rss', available: true, diff --git a/frontend/src/views/knowledge/settings/DataSourceSettings.vue b/frontend/src/views/knowledge/settings/DataSourceSettings.vue index ca727c34..d8ed8ed5 100644 --- a/frontend/src/views/knowledge/settings/DataSourceSettings.vue +++ b/frontend/src/views/knowledge/settings/DataSourceSettings.vue @@ -464,6 +464,7 @@ onBeforeUnmount(stopPolling) &--feishu .ds-card__badge, &--notion .ds-card__badge, &--yuque .ds-card__badge, + &--ima .ds-card__badge, &--rss .ds-card__badge { background: var(--td-bg-color-container, #fff); box-shadow: inset 0 0 0 1px var(--td-component-stroke); diff --git a/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue b/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue index 163c38ea..a3cf664a 100644 --- a/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue +++ b/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue @@ -23,6 +23,8 @@ function fallbackText(type: string) { return 'N' case 'yuque': return 'Y' + case 'ima': + return 'I' default: return type.slice(0, 1).toUpperCase() || '?' } diff --git a/frontend/src/views/knowledge/settings/datasourceIcons.ts b/frontend/src/views/knowledge/settings/datasourceIcons.ts index 670636f8..deae2617 100644 --- a/frontend/src/views/knowledge/settings/datasourceIcons.ts +++ b/frontend/src/views/knowledge/settings/datasourceIcons.ts @@ -3,6 +3,7 @@ import larkIcon from '@/assets/img/datasource-lark.svg' import notionIcon from '@/assets/img/datasource-notion.ico' import yuqueIcon from '@/assets/img/datasource-yuque.ico' import rssIcon from '@/assets/img/datasource-rss.svg' +import imaIcon from '@/assets/img/datasource-ima.png' export const datasourceIconMap: Record = { feishu: feishuIcon, @@ -13,6 +14,7 @@ export const datasourceIconMap: Record = { notion: notionIcon, yuque: yuqueIcon, rss: rssIcon, + ima: imaIcon, } export function getDatasourceIconUrl(type: string): string | undefined { diff --git a/internal/container/container.go b/internal/container/container.go index daef8152..aaf2a1fa 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -57,6 +57,7 @@ import ( "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core" "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/drive" "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/wiki" + imaConnector "github.com/Tencent/WeKnora/internal/datasource/connector/ima" notionConnector "github.com/Tencent/WeKnora/internal/datasource/connector/notion" rssConnector "github.com/Tencent/WeKnora/internal/datasource/connector/rss" yuqueConnector "github.com/Tencent/WeKnora/internal/datasource/connector/yuque" @@ -1653,6 +1654,9 @@ func initConnectorRegistry() (*datasource.ConnectorRegistry, error) { if err := registry.Register(yuqueConnector.NewConnector()); err != nil { errs = errors.Join(errs, fmt.Errorf("register yuque connector: %w", err)) } + if err := registry.Register(imaConnector.NewConnector()); err != nil { + errs = errors.Join(errs, fmt.Errorf("register ima connector: %w", err)) + } if err := registry.Register(rssConnector.NewConnector()); err != nil { errs = errors.Join(errs, fmt.Errorf("register rss connector: %w", err)) } diff --git a/internal/datasource/connector.go b/internal/datasource/connector.go index bce382eb..9e1bec4b 100644 --- a/internal/datasource/connector.go +++ b/internal/datasource/connector.go @@ -205,6 +205,14 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{ AuthType: "api_key", Capabilities: []string{"incremental"}, }, + types.ConnectorTypeIMA: { + Type: types.ConnectorTypeIMA, + Name: "Tencent IMA (ima.qq.com)", + Description: "Sync knowledge bases and documents from Tencent IMA", + Priority: 3, + AuthType: "api_key", + Capabilities: []string{"incremental", "deletion_sync"}, + }, types.ConnectorTypeGitHub: { Type: types.ConnectorTypeGitHub, Name: "GitHub", diff --git a/internal/datasource/connector/ima/client.go b/internal/datasource/connector/ima/client.go new file mode 100644 index 00000000..95a8395e --- /dev/null +++ b/internal/datasource/connector/ima/client.go @@ -0,0 +1,358 @@ +package ima + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "sync" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/logger" +) + +const ( + defaultTimeout = 60 * time.Second + defaultPageSize = 50 + userAgent = "WeKnora-IMA-Connector/1.0" + + // IMA hard limit: get_knowledge_list max limit=50; search_knowledge_base max=20. + searchPageSize = 20 + + // Default per-item download timeout — IMA COS URLs can be slow for large PDFs. + downloadTimeout = 120 * time.Second + + // Max body we accept from get_media_info-URLs. 200MB matches IMA's largest + maxDownloadBytes = 200 * 1024 * 1024 +) + +// client wraps the IMA OpenAPI. It is safe for concurrent use. +type client struct { + baseURL string + clientID string + apiKey string + httpClient *http.Client + // downloadClient is a separate client with a longer timeout for pulling + // media bodies from COS/CDN URLs returned by get_media_info. + downloadClient *http.Client + logCredentialOnce sync.Once +} + +// newClient constructs a client with a normalized base URL. +func newClient(cfg *Config) *client { + return &client{ + baseURL: cfg.GetBaseURL(), + clientID: cfg.ClientID, + apiKey: cfg.APIKey, + httpClient: datasource.NewConnectorHTTPClient(defaultTimeout), + downloadClient: datasource.NewConnectorHTTPClient(downloadTimeout), + } +} + +// callAPI executes an authenticated POST to /openapi/wiki/v1/. +// It parses the standard {code, msg, data} envelope and unmarshals `data` +// into `result`. A non-zero business code is returned as a plain error so the +// caller can surface `msg` to the user +func (c *client) callAPI(ctx context.Context, action string, req interface{}, result interface{}) error { + const ( + maxRetries = 3 + max5xxRetries = 1 + retry5xxDelay = 2 * time.Second + ) + backoff := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second} + + c.logCredentialOnce.Do(func() { + logger.Infof(ctx, "[IMA] client configured client_id=%s api_key=%s base=%s", + redact(c.clientID), redact(c.apiKey), c.baseURL) + }) + + var body []byte + if req != nil { + b, err := json.Marshal(req) + if err != nil { + return fmt.Errorf("marshal request: %w", err) + } + body = b + } else { + body = []byte("{}") + } + + url := c.baseURL + apiBasePath + "/" + action + + var lastErr error + for attempt := 0; attempt <= maxRetries; attempt++ { + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + httpReq.Header.Set("ima-openapi-clientid", c.clientID) + httpReq.Header.Set("ima-openapi-apikey", c.apiKey) + httpReq.Header.Set("Content-Type", "application/json; charset=utf-8") + httpReq.Header.Set("User-Agent", userAgent) + + if attempt == 0 { + logger.Infof(ctx, "[IMA] POST %s", action) + } else { + logger.Infof(ctx, "[IMA] POST %s (retry %d/%d)", action, attempt, maxRetries) + } + + resp, err := c.httpClient.Do(httpReq) + if err != nil { + lastErr = fmt.Errorf("execute request: %w", err) + if attempt < maxRetries { + if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil { + return sErr + } + continue + } + return lastErr + } + + respBody, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + if readErr != nil { + lastErr = fmt.Errorf("read response: %w", readErr) + if attempt < maxRetries { + if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil { + return sErr + } + continue + } + return lastErr + } + + bodyPreview := truncate(string(respBody), 500) + logger.Infof(ctx, "[IMA] POST %s → status=%d bodyLen=%d body=%s", + action, resp.StatusCode, len(respBody), bodyPreview) + + // HTTP-level auth failures: surface as ErrInvalidCredentials. + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + return fmt.Errorf("%w: status=%d body=%s", + datasource.ErrInvalidCredentials, resp.StatusCode, bodyPreview) + } + + if resp.StatusCode == http.StatusTooManyRequests { + wait := backoff[minInt(attempt, len(backoff)-1)] + lastErr = fmt.Errorf("ima rate limited: status=429 body=%s", bodyPreview) + if attempt < maxRetries { + if sErr := sleepCtx(ctx, wait); sErr != nil { + return sErr + } + continue + } + return lastErr + } + + if resp.StatusCode >= 500 && resp.StatusCode < 600 { + lastErr = fmt.Errorf("ima server error: status=%d body=%s", resp.StatusCode, bodyPreview) + if attempt < max5xxRetries { + if sErr := sleepCtx(ctx, retry5xxDelay); sErr != nil { + return sErr + } + continue + } + return lastErr + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("ima api http error: status=%d body=%s", resp.StatusCode, bodyPreview) + } + + var env apiEnvelope + if err := json.Unmarshal(respBody, &env); err != nil { + return fmt.Errorf("decode envelope: %w", err) + } + + // Business-level errors. + // 110030 (无权限) / 110001 (参数非法) with common auth hint patterns are + // mapped to ErrInvalidCredentials so the service marks the source in + // `error` state and stops scheduling until re-authenticated. + if env.Code != 0 { + if env.Code == 110030 { + return fmt.Errorf("%w: ima code=%d msg=%s", + datasource.ErrInvalidCredentials, env.Code, env.Msg) + } + if env.Code == 110021 && attempt < maxRetries { + lastErr = fmt.Errorf("ima rate limited: code=%d msg=%s", env.Code, env.Msg) + if sErr := sleepCtx(ctx, backoff[minInt(attempt, len(backoff)-1)]); sErr != nil { + return sErr + } + continue + } + return fmt.Errorf("ima api error: code=%d msg=%s", env.Code, env.Msg) + } + + if result != nil && len(env.Data) > 0 && string(env.Data) != "null" { + if err := json.Unmarshal(env.Data, result); err != nil { + return fmt.Errorf("decode data: %w", err) + } + } + return nil + } + return lastErr +} + +// SearchKnowledgeBase — POST /search_knowledge_base. Empty query returns the +// list of every knowledge base visible to the current token (see api.md §7). +func (c *client) SearchKnowledgeBase( + ctx context.Context, query, cursor string, limit int, +) (*searchKnowledgeBaseResp, error) { + if limit <= 0 || limit > searchPageSize { + limit = searchPageSize + } + req := map[string]interface{}{ + "query": query, + "cursor": cursor, + "limit": uint64(limit), + } + var resp searchKnowledgeBaseResp + if err := c.callAPI(ctx, "search_knowledge_base", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// GetKnowledgeBase — POST /get_knowledge_base for a batch of ids (1-20). +func (c *client) GetKnowledgeBase(ctx context.Context, ids []string) (map[string]knowledgeBaseInfo, error) { + if len(ids) == 0 { + return map[string]knowledgeBaseInfo{}, nil + } + req := map[string]interface{}{"ids": ids} + var resp getKnowledgeBaseResp + if err := c.callAPI(ctx, "get_knowledge_base", req, &resp); err != nil { + return nil, err + } + if resp.Infos == nil { + resp.Infos = map[string]knowledgeBaseInfo{} + } + return resp.Infos, nil +} + +// GetAddableKnowledgeBaseList — POST /get_addable_knowledge_base_list. +// Lists knowledge bases the current token has permission to add content to. +// This is the authoritative "what KBs can this credential see?" endpoint +// (see api.md §7). Used as the primary enumeration source in ListResources — +// search_knowledge_base with empty query has been observed to return an empty +// list even when the token owns KBs, so we prefer this endpoint. +func (c *client) GetAddableKnowledgeBaseList( + ctx context.Context, cursor string, limit int, +) (*getAddableKnowledgeBaseListResp, error) { + if limit <= 0 || limit > defaultPageSize { + limit = defaultPageSize + } + req := map[string]interface{}{ + "cursor": cursor, + "limit": uint64(limit), + } + var resp getAddableKnowledgeBaseListResp + if err := c.callAPI(ctx, "get_addable_knowledge_base_list", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// GetKnowledgeList — POST /get_knowledge_list. folderID may be empty for root. +func (c *client) GetKnowledgeList( + ctx context.Context, kbID, folderID, cursor string, limit int, +) (*getKnowledgeListResp, error) { + if limit <= 0 || limit > defaultPageSize { + limit = defaultPageSize + } + req := map[string]interface{}{ + "cursor": cursor, + "limit": uint64(limit), + "knowledge_base_id": kbID, + } + if folderID != "" { + req["folder_id"] = folderID + } + var resp getKnowledgeListResp + if err := c.callAPI(ctx, "get_knowledge_list", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// GetMediaInfo — POST /get_media_info. Returns URL access info and (for notes) +// the notebook_id under notebook_ext_info. +func (c *client) GetMediaInfo(ctx context.Context, mediaID string) (*getMediaInfoResp, error) { + req := map[string]interface{}{"media_id": mediaID} + var resp getMediaInfoResp + if err := c.callAPI(ctx, "get_media_info", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// DownloadURL fetches a URL returned by GetMediaInfo, respecting the auth +// headers IMA may return alongside it. Enforces maxDownloadBytes to avoid a +// runaway body blowing up sync memory. +func (c *client) DownloadURL(ctx context.Context, u urlInfo) ([]byte, string, error) { + if u.URL == "" { + return nil, "", fmt.Errorf("empty url") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.URL, nil) + if err != nil { + return nil, "", fmt.Errorf("create download request: %w", err) + } + for k, v := range u.Headers { + req.Header.Set(k, v) + } + req.Header.Set("User-Agent", userAgent) + + resp, err := c.downloadClient.Do(req) + if err != nil { + return nil, "", fmt.Errorf("download: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, "", fmt.Errorf("download http error: status=%d", resp.StatusCode) + } + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadBytes+1)) + if err != nil { + return nil, "", fmt.Errorf("read download body: %w", err) + } + if int64(len(body)) > maxDownloadBytes { + return nil, "", fmt.Errorf("download body exceeds %d bytes", maxDownloadBytes) + } + return body, resp.Header.Get("Content-Type"), nil +} + +// sleepCtx pauses for d, returning early if ctx is cancelled. +func sleepCtx(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func truncate(s string, maxLen int) string { + if len(s) <= maxLen { + return s + } + return s[:maxLen] + "..." +} + +// redact returns a masked form of a credential for logging (never log full). +func redact(t string) string { + if len(t) < 12 { + return "***" + } + return t[:6] + "..." + t[len(t)-4:] +} + +func minInt(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/internal/datasource/connector/ima/connector.go b/internal/datasource/connector/ima/connector.go new file mode 100644 index 00000000..b21a9c82 --- /dev/null +++ b/internal/datasource/connector/ima/connector.go @@ -0,0 +1,514 @@ +package ima + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "strings" + "time" + "unicode/utf8" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// Compile-time proof that *Connector satisfies the datasource.Connector interface. +var _ datasource.Connector = (*Connector)(nil) + +// Connector implements datasource.Connector for Tencent IMA (ima.qq.com). +type Connector struct{} + +// NewConnector creates a new IMA connector. +func NewConnector() *Connector { return &Connector{} } + +// Type returns the connector type identifier. +func (c *Connector) Type() string { return types.ConnectorTypeIMA } + +// Validate verifies the credentials by calling get_addable_knowledge_base_list +// — the endpoint most likely to succeed even when the token has zero KBs, and +// the same one ListResources uses. It returns 110030 (无权限) when the token +// itself is invalid, which client.callAPI already maps to ErrInvalidCredentials. +func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error { + cfg, err := parseIMAConfig(config) + if err != nil { + return err + } + cli := newClient(cfg) + if _, err := cli.GetAddableKnowledgeBaseList(ctx, "", defaultPageSize); err != nil { + return fmt.Errorf("ima connection failed: %w", err) + } + return nil +} + +// ResolveResourceAncestors: IMA knowledge bases are exposed as a flat list of +// top-level resources, so a lazy-loaded picker has no ancestors to reveal. +func (c *Connector) ResolveResourceAncestors( + ctx context.Context, config *types.DataSourceConfig, resourceIDs []string, +) ([]string, error) { + return []string{}, nil +} + +// ListResources returns the flat list of knowledge bases the token can read. +// parentID is honoured only for the "no children" contract — see the note on +// Connector.ListResources in internal/datasource/connector.go. +// +// Primary source is get_addable_knowledge_base_list, which returns the KBs the +// current OpenAPI credential has permission to operate on. When that endpoint +// returns an empty list (e.g. a legacy tenant only exposes read scopes) we +// fall back to search_knowledge_base with an empty query so users still see +// something to pick. +func (c *Connector) ListResources( + ctx context.Context, config *types.DataSourceConfig, parentID string, +) ([]types.Resource, error) { + if parentID != "" { + return []types.Resource{}, nil + } + + cfg, err := parseIMAConfig(config) + if err != nil { + return nil, err + } + cli := newClient(cfg) + + type kbLite struct { + ID string + Name string + CoverURL string + } + var bases []kbLite + + cursor := "" + for { + resp, err := cli.GetAddableKnowledgeBaseList(ctx, cursor, defaultPageSize) + if err != nil { + return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err) + } + for _, b := range resp.AddableKnowledgeBaseList { + bases = append(bases, kbLite{ID: b.ID, Name: b.Name}) + } + if resp.IsEnd || resp.NextCursor == "" { + break + } + cursor = resp.NextCursor + } + logger.Infof(ctx, "[IMA] get_addable_knowledge_base_list returned %d knowledge bases", len(bases)) + + if len(bases) == 0 { + cursor = "" + for { + resp, err := cli.SearchKnowledgeBase(ctx, "", cursor, searchPageSize) + if err != nil { + return nil, fmt.Errorf("search_knowledge_base fallback: %w", err) + } + for _, b := range resp.InfoList { + bases = append(bases, kbLite{ID: b.ID, Name: b.Name, CoverURL: b.CoverURL}) + } + if resp.IsEnd || resp.NextCursor == "" { + break + } + cursor = resp.NextCursor + } + logger.Infof(ctx, "[IMA] search_knowledge_base fallback returned %d knowledge bases", len(bases)) + } + + ids := make([]string, 0, len(bases)) + for _, b := range bases { + ids = append(ids, b.ID) + } + details := map[string]knowledgeBaseInfo{} + for i := 0; i < len(ids); i += 20 { + end := i + 20 + if end > len(ids) { + end = len(ids) + } + batch, err := cli.GetKnowledgeBase(ctx, ids[i:end]) + if err != nil { + logger.Warnf(ctx, "[IMA] get_knowledge_base batch failed (skipping enrichment): %v", err) + continue + } + for k, v := range batch { + details[k] = v + } + } + + out := make([]types.Resource, 0, len(bases)) + for _, b := range bases { + desc := "" + coverURL := b.CoverURL + if d, ok := details[b.ID]; ok { + desc = d.Description + if coverURL == "" { + coverURL = d.CoverURL + } + } + out = append(out, types.Resource{ + ExternalID: b.ID, + Name: b.Name, + Type: "knowledge_base", + Description: desc, + URL: cfg.GetBaseURL(), + Metadata: map[string]interface{}{ + "cover_url": coverURL, + }, + }) + } + sort.Slice(out, func(i, j int) bool { return out[i].ExternalID < out[j].ExternalID }) + logger.Infof(ctx, "[IMA] ListResources returning %d knowledge bases to UI", len(out)) + return out, nil +} + +// FetchAll performs a full sync of every knowledge base in resourceIDs. +func (c *Connector) FetchAll( + ctx context.Context, config *types.DataSourceConfig, resourceIDs []string, +) ([]types.FetchedItem, error) { + items, _, err := c.walk(ctx, config, resourceIDs, nil, false) + return items, err +} + +// FetchIncremental syncs new / replaced / removed items against the cursor. +// +// Each IMA item is identified by a stable logical_key (see logicalKey), NOT by +// media_id — because IMA reassigns media_id whenever a same-named file is +// replaced in place, and we want that replacement to surface as an UPDATE to +// the same knowledge item rather than a delete-plus-insert pair. +// +// Emitted this cycle: +// +// - logical_key new since last sync → add (new content) +// - logical_key present, media_id changed → update (re-fetched content; +// ingest layer's existing +// external_id match triggers +// delete-and-recreate) +// - logical_key unchanged, media_id unchanged → skip +// - logical_key present last sync, absent this sync → IsDeleted tombstone +// +// LIMITATION: IMA still exposes no per-item updated_at, so an in-place edit +// that keeps the SAME media_id (same file bytes replaced under the hood by +// IMA, if that ever happens) is invisible to us. Users needing a full content +// refresh should periodically run a Full sync. +func (c *Connector) FetchIncremental( + ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor, +) ([]types.FetchedItem, *types.SyncCursor, error) { + resourceIDs := config.ResourceIDs + if len(resourceIDs) == 0 { + return nil, nil, fmt.Errorf("no resource IDs (knowledge base IDs) configured") + } + + var prev *imaCursor + if cursor != nil && cursor.ConnectorCursor != nil { + var p imaCursor + b, _ := json.Marshal(cursor.ConnectorCursor) + _ = json.Unmarshal(b, &p) + prev = &p + } + + items, newCursor, err := c.walk(ctx, config, resourceIDs, prev, true) + if err != nil { + return nil, nil, err + } + + cursorMap := make(map[string]interface{}) + b, _ := json.Marshal(newCursor) + _ = json.Unmarshal(b, &cursorMap) + + return items, &types.SyncCursor{ + LastSyncTime: newCursor.LastSyncTime, + ConnectorCursor: cursorMap, + }, nil +} + +// walk is the shared implementation for FetchAll / FetchIncremental. +// When incremental is false, prev is ignored and returned cursor is nil. +func (c *Connector) walk( + ctx context.Context, + config *types.DataSourceConfig, + resourceIDs []string, + prev *imaCursor, + incremental bool, +) ([]types.FetchedItem, *imaCursor, error) { + cfg, err := parseIMAConfig(config) + if err != nil { + return nil, nil, err + } + cli := newClient(cfg) + + newCursor := &imaCursor{ + LastSyncTime: time.Now(), + KBLogical: make(map[string]map[string]string), + KBMedia: make(map[string]map[string]string), + } + var out []types.FetchedItem + + for _, kbID := range resourceIDs { + files, folderPath, err := listAllKBFiles(ctx, cli, kbID) + if err != nil { + return nil, nil, fmt.Errorf("list KB %s: %w", kbID, err) + } + + currentLogical := make(map[string]string, len(files)) + currentMedia := make(map[string]string, len(files)) + keys := make([]string, len(files)) + for i, f := range files { + // f.MediaType is 0 in list responses (IMA omits it there); we rely on + // (kb_id, parent_folder_id, title) which IMA enforces uniqueness on + // via check_repeated_names. Encoding media_type as 0 is fine as long + // as it stays consistent across syncs — which it does, since 0 is a + // constant here. + key := logicalKey(kbID, f.ParentFolderID, f.Title, f.MediaType) + keys[i] = key + currentLogical[key] = f.MediaID + currentMedia[f.MediaID] = f.Title + } + newCursor.KBLogical[kbID] = currentLogical + newCursor.KBMedia[kbID] = currentMedia + + replaced := 0 + for i, f := range files { + key := keys[i] + + // Incremental skip / replacement detection. + if incremental && prev != nil && prev.KBLogical != nil { + if prevSet, ok := prev.KBLogical[kbID]; ok { + if prevMediaID, seen := prevSet[key]; seen { + if prevMediaID == f.MediaID { + continue // unchanged + } + replaced++ // media_id changed → replacement, fall through to re-fetch + } + } + } + + item, ok := fetchOneMedia(ctx, cli, cfg, kbID, key, f, folderPath) + if !ok { + continue + } + out = append(out, item) + } + + // Deletion detection (incremental only) — based on logical_key vanishing, + // so a same-name replacement (media_id churns but logical_key stays) + // never fires a spurious delete. + deleted := 0 + if incremental && prev != nil && prev.KBLogical != nil { + if prevSet, ok := prev.KBLogical[kbID]; ok { + for prevKey := range prevSet { + if _, still := currentLogical[prevKey]; !still { + out = append(out, types.FetchedItem{ + ExternalID: prevKey, + IsDeleted: true, + SourceResourceID: kbID, + }) + deleted++ + } + } + } + } + + logger.Infof(ctx, "[IMA] KB %s: total=%d replaced=%d deleted=%d", + kbID, len(files), replaced, deleted) + } + + if !incremental { + return out, nil, nil + } + return out, newCursor, nil +} + +// walkedFile is an internal representation of a knowledge item after we've +// resolved its folder location within the KB tree. +type walkedFile struct { + knowledgeInfo + // FolderPath is the "/A/B" style path (folder names, no leading slash) + // of the containing folder — empty for root-level items. + FolderPath string +} + +// listAllKBFiles recursively enumerates a knowledge base into a flat list of +// files, resolving each item's folder path from the on-the-fly folder tree. +// folderPath maps folder_id → readable path (for metadata). +func listAllKBFiles( + ctx context.Context, cli *client, kbID string, +) ([]walkedFile, map[string]string, error) { + folderPath := map[string]string{} + var out []walkedFile + + // BFS/DFS over folders. Start from root (empty folder_id). + type todo struct { + folderID string + path string + } + stack := []todo{{folderID: "", path: ""}} + + for len(stack) > 0 { + cur := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + cursor := "" + for { + resp, err := cli.GetKnowledgeList(ctx, kbID, cur.folderID, cursor, defaultPageSize) + if err != nil { + return nil, nil, err + } + for _, raw := range resp.KnowledgeList { + // Probe each entry: an entry with a non-empty folder_id is a + // folder; otherwise it's a knowledge item (file / note / etc.). + var probe struct { + FolderID string `json:"folder_id"` + MediaID string `json:"media_id"` + } + _ = json.Unmarshal(raw, &probe) + + if probe.FolderID != "" && probe.MediaID == "" { + var fi folderInfo + if err := json.Unmarshal(raw, &fi); err != nil { + continue + } + child := cur.path + if child == "" { + child = fi.Name + } else { + child = cur.path + "/" + fi.Name + } + folderPath[fi.FolderID] = child + stack = append(stack, todo{folderID: fi.FolderID, path: child}) + continue + } + if probe.MediaID == "" { + continue // unrecognized shape, skip defensively + } + var ki knowledgeInfo + if err := json.Unmarshal(raw, &ki); err != nil { + continue + } + out = append(out, walkedFile{ + knowledgeInfo: ki, + FolderPath: cur.path, + }) + } + if resp.IsEnd || resp.NextCursor == "" { + break + } + cursor = resp.NextCursor + } + } + return out, folderPath, nil +} + +// fetchOneMedia calls get_media_info for a single item and, when possible, +// downloads its body. Returns false if the item should be skipped (unsupported +// media type, download error, note-type, etc.). +// +// externalID is the stable logical_key computed by the caller — same value +// across syncs even after an IMA same-name replacement mints a new media_id. +// The raw media_id is still preserved in metadata for observability. +func fetchOneMedia( + ctx context.Context, cli *client, cfg *Config, + kbID string, externalID string, f walkedFile, folderPath map[string]string, +) (types.FetchedItem, bool) { + info, err := cli.GetMediaInfo(ctx, f.MediaID) + if err != nil { + logger.Warnf(ctx, "[IMA] get_media_info(%s) failed, skipping: %v", f.MediaID, err) + return types.FetchedItem{}, false + } + + if isSkippableMediaType(info.MediaType) { + logger.Infof(ctx, "[IMA] skip media %s (title=%q media_type=%d): unsupported by wiki OpenAPI", + f.MediaID, f.Title, info.MediaType) + return types.FetchedItem{}, false + } + + if info.URLInfo.URL == "" { + logger.Warnf(ctx, "[IMA] media %s (title=%q) has no url_info.url, skipping", f.MediaID, f.Title) + return types.FetchedItem{}, false + } + + ext := extensionForMediaType(info.MediaType) + if ext == "" { + return types.FetchedItem{ + ExternalID: externalID, + Title: f.Title, + URL: info.URLInfo.URL, + SourceResourceID: kbID, + UpdatedAt: time.Now(), + Metadata: baseMetadata(externalID, f, folderPath, info, kbID), + }, true + } + + body, ct, err := cli.DownloadURL(ctx, info.URLInfo) + if err != nil { + logger.Warnf(ctx, "[IMA] download media %s (title=%q) failed, skipping: %v", f.MediaID, f.Title, err) + return types.FetchedItem{}, false + } + if ct == "" || strings.HasPrefix(ct, "application/octet-stream") { + ct = mimeForExtension(ext) + } + + fileName := sanitizeFileName(f.Title) + if !strings.HasSuffix(strings.ToLower(fileName), "."+ext) { + fileName = fileName + "." + ext + } + + return types.FetchedItem{ + ExternalID: externalID, + Title: f.Title, + Content: body, + ContentType: ct, + FileName: fileName, + URL: info.URLInfo.URL, + UpdatedAt: time.Now(), + SourceResourceID: kbID, + Metadata: baseMetadata(externalID, f, folderPath, info, kbID), + }, true +} + +// baseMetadata builds the metadata map preserved on every ingested item. +// externalID (the caller's logical_key) is stored so operators can join the +// stable identity back to the raw media_id — useful when debugging why a +// same-name replacement showed up as an update instead of an add. +func baseMetadata(externalID string, f walkedFile, folderPath map[string]string, info *getMediaInfoResp, kbID string) map[string]string { + m := map[string]string{ + "channel": types.ChannelIMA, + "media_id": f.MediaID, + "ima_logical_key": externalID, + "knowledge_base_id": kbID, + "folder_path": f.FolderPath, + "media_type": fmt.Sprintf("%d", info.MediaType), + } + if f.ParentFolderID != "" { + m["parent_folder_id"] = f.ParentFolderID + } + if fp, ok := folderPath[f.ParentFolderID]; ok && fp != "" { + m["folder_path"] = fp + } + if info.NotebookExtInfo.NotebookID != "" { + m["notebook_id"] = info.NotebookExtInfo.NotebookID + } + return m +} + +// sanitizeFileName removes filesystem-hostile characters and truncates to a +// safe UTF-8 boundary. +func sanitizeFileName(name string) string { + if name == "" { + return "untitled" + } + replacer := strings.NewReplacer( + "/", "_", "\\", "_", ":", "_", "*", "_", + "?", "_", "\"", "_", "<", "_", ">", "_", "|", "_", + ) + result := replacer.Replace(name) + const maxBytes = 200 + if len(result) > maxBytes { + result = result[:maxBytes] + for len(result) > 0 { + r, size := utf8.DecodeLastRuneInString(result) + if r != utf8.RuneError || size != 1 { + break + } + result = result[:len(result)-1] + } + } + return result +} diff --git a/internal/datasource/connector/ima/types.go b/internal/datasource/connector/ima/types.go new file mode 100644 index 00000000..5c8feee1 --- /dev/null +++ b/internal/datasource/connector/ima/types.go @@ -0,0 +1,353 @@ +package ima + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +// DefaultBaseURL is the IMA OpenAPI base URL. The Path prefix is baked into +// the client (see client.go); users only configure the host. +const DefaultBaseURL = "https://ima.qq.com" + +// Base path for every OpenAPI request. +const apiBasePath = "/openapi/wiki/v1" + +// Config holds IMA-specific configuration decoded from +// DataSourceConfig.Credentials. Both credentials are opaque strings and +// stored encrypted at rest by DataSourceConfig.ToJSON (see internal/types/datasource.go). +type Config struct { + // ClientID: value of the `ima-openapi-clientid` request header, + // obtained from https://ima.qq.com/agent-interface. + ClientID string `json:"client_id"` + + // APIKey: value of the `ima-openapi-apikey` request header. + APIKey string `json:"api_key"` + + // BaseURL lets users point at an on-prem / test IMA endpoint. + // Defaults to https://ima.qq.com when empty. + BaseURL string `json:"base_url,omitempty"` +} + +// GetBaseURL returns the normalized base URL (empty → default, no trailing slash). +func (c *Config) GetBaseURL() string { + url := strings.TrimSpace(c.BaseURL) + if url == "" { + return DefaultBaseURL + } + if !strings.Contains(url, "://") { + url = "https://" + url + } + return strings.TrimRight(url, "/") +} + +// parseIMAConfig extracts and validates IMA-specific configuration. +// Uses JSON marshal/unmarshal roundtrip so extra fields are ignored gracefully. +func parseIMAConfig(config *types.DataSourceConfig) (*Config, error) { + if config == nil { + return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig) + } + credBytes, err := json.Marshal(config.Credentials) + if err != nil { + return nil, fmt.Errorf("marshal credentials: %w", err) + } + var cfg Config + if err := json.Unmarshal(credBytes, &cfg); err != nil { + return nil, fmt.Errorf("parse ima credentials: %w", err) + } + if strings.TrimSpace(cfg.ClientID) == "" { + return nil, fmt.Errorf("%w: client_id is required", datasource.ErrInvalidCredentials) + } + if strings.TrimSpace(cfg.APIKey) == "" { + return nil, fmt.Errorf("%w: api_key is required", datasource.ErrInvalidCredentials) + } + if err := datasource.ValidateConnectorBaseURL(cfg.GetBaseURL()); err != nil { + return nil, err + } + return &cfg, nil +} + +// apiEnvelope is the uniform IMA response wrapper: `{ code, msg, data }`. +// A non-zero code is a business-level error and MUST be surfaced to the user +type apiEnvelope struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data json.RawMessage `json:"data"` +} + +// KnowledgeBaseInfo mirrors IMA's KnowledgeBaseInfo (get_knowledge_base). +type knowledgeBaseInfo struct { + ID string `json:"id"` + Name string `json:"name"` + CoverURL string `json:"cover_url"` + Description string `json:"description"` + RecommendedQuestions []string `json:"recommended_questions"` +} + +// searchedKnowledgeBaseInfo — search_knowledge_base returns fewer fields. +type searchedKnowledgeBaseInfo struct { + ID string `json:"id"` + Name string `json:"name"` + CoverURL string `json:"cover_url"` +} + +// searchKnowledgeBaseResp — search_knowledge_base response. +type searchKnowledgeBaseResp struct { + InfoList []searchedKnowledgeBaseInfo `json:"info_list"` + IsEnd bool `json:"is_end"` + NextCursor string `json:"next_cursor"` +} + +// addableKnowledgeBaseInfo — get_addable_knowledge_base_list item. +// Contains only id + name (no cover_url), see api.md §7. +type addableKnowledgeBaseInfo struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// getAddableKnowledgeBaseListResp — get_addable_knowledge_base_list response. +// NOTE: the JSON field is `addable_knowledge_base_list`, not `info_list`. +type getAddableKnowledgeBaseListResp struct { + AddableKnowledgeBaseList []addableKnowledgeBaseInfo `json:"addable_knowledge_base_list"` + IsEnd bool `json:"is_end"` + NextCursor string `json:"next_cursor"` +} + +// getKnowledgeBaseResp — get_knowledge_base response (map keyed by id). +type getKnowledgeBaseResp struct { + Infos map[string]knowledgeBaseInfo `json:"infos"` +} + +// knowledgeInfo mirrors IMA's KnowledgeInfo (files, notes, etc.). +// IMPORTANT: IMA does not expose media_type in the list response, we must call +// get_media_info to discover it. However, folders are distinguished by presence +// of a non-empty folder_id — see folderInfo below. +type knowledgeInfo struct { + MediaID string `json:"media_id"` + Title string `json:"title"` + ParentFolderID string `json:"parent_folder_id"` + MediaType int32 `json:"media_type,omitempty"` +} + +// folderInfo mirrors IMA's FolderInfo. +type folderInfo struct { + FolderID string `json:"folder_id"` + Name string `json:"name"` + FileNumber json.Number `json:"file_number"` + FolderNumber json.Number `json:"folder_number"` + ParentFolderID string `json:"parent_folder_id"` + IsTop bool `json:"is_top"` +} + +// FileCount safely converts FileNumber to int64 (0 on empty/invalid). +func (f folderInfo) FileCount() int64 { + if f.FileNumber == "" { + return 0 + } + n, err := f.FileNumber.Int64() + if err != nil { + return 0 + } + return n +} + +// FolderCount safely converts FolderNumber to int64 (0 on empty/invalid). +func (f folderInfo) FolderCount() int64 { + if f.FolderNumber == "" { + return 0 + } + n, err := f.FolderNumber.Int64() + if err != nil { + return 0 + } + return n +} + +// getKnowledgeListResp — get_knowledge_list response. +// According to `references/api.md`, the response returns knowledge_list mixed +// with folders; we decode a loose JSON view so entries without a folder_id are +// treated as knowledge and those with folder_id are treated as folders. +type getKnowledgeListResp struct { + // KnowledgeList is a loose slice of raw JSON objects because IMA returns + // files and folders in the same array. We iterate and inspect fields. + KnowledgeList []json.RawMessage `json:"knowledge_list"` + IsEnd bool `json:"is_end"` + NextCursor string `json:"next_cursor"` + CurrentPath []folderInfo `json:"current_path"` +} + +// urlInfo mirrors IMA's URLInfo (present on get_media_info for URL-backed media). +type urlInfo struct { + URL string `json:"url"` + Headers map[string]string `json:"headers"` +} + +// notebookExtInfo — set on notes (media_type=11). +type notebookExtInfo struct { + NotebookID string `json:"notebook_id"` +} + +// getMediaInfoResp — get_media_info response. +type getMediaInfoResp struct { + MediaType int32 `json:"media_type"` + URLInfo urlInfo `json:"url_info"` + NotebookExtInfo notebookExtInfo `json:"notebook_ext_info"` +} + +// imaCursor tracks per-knowledge-base state seen during the last sync. +// +// Two parallel maps are kept, both keyed by kb_id: +// +// - KBLogical: { logical_key: media_id } — the authoritative source for +// both delete detection AND "replacement" detection. IMA reassigns +// media_id whenever a same-named file is replaced in place, so a logical +// key (see logicalKey) is what we treat as a document's stable identity. +// A logical_key present last sync but absent this sync ⇒ delete. +// A logical_key whose media_id changed ⇒ replacement (re-fetch content; +// the emitted FetchedItem carries the same ExternalID so the ingest +// layer's "existing external_id → delete-and-recreate" path (see +// datasource_service.go applyFetchedItem) treats it as an update. +// +// - KBMedia (legacy): { media_id: title } — retained so cursors persisted +// by older versions still deserialize; not consulted for new detection. +// New cursors write this too, purely for observability in logs. +type imaCursor struct { + LastSyncTime time.Time `json:"last_sync_time"` + KBLogical map[string]map[string]string `json:"kb_logical,omitempty"` + KBMedia map[string]map[string]string `json:"kb_media,omitempty"` +} + +// logicalKey derives a stable identity for an IMA item that survives +// same-name replacement (which mints a new media_id server-side). +// +// The key is a short SHA-256 hex over (kb_id, parent_folder_id, title, +// media_type). Rationale: +// +// - kb_id keeps identities isolated across knowledge bases (same file +// copied into two KBs is two distinct docs from WeKnora's perspective). +// - parent_folder_id + title anchor the doc to its folder location and +// display name — the tuple IMA's own check_repeated_names uses to gate +// uploads (see api.md), so IMA's own uniqueness constraint enforces +// this key's uniqueness inside a KB. +// - media_type distinguishes "notes.md" (Markdown) from "notes.md" +// (Word) in the same folder — pathologically rare but cheap to guard. +// +// Emitted as "ima_" + first 32 hex chars (128 bits) — small enough to fit +// well within Postgres varchar(64) external_id columns, still >> collision +// resistant for any realistic KB size. +func logicalKey(kbID, parentFolderID, title string, mediaType int32) string { + h := sha256.New() + // Delimiter can't appear in any component because it's neither a valid + // IMA id character nor allowed in titles once we've folded to bytes. + fmt.Fprintf(h, "%s\x1f%s\x1f%s\x1f%d", kbID, parentFolderID, title, mediaType) + return "ima_" + hex.EncodeToString(h.Sum(nil))[:32] +} + +// IMA MediaType enum (see api.md §MediaType). +const ( + mediaTypePDF int32 = 1 + mediaTypeWeb int32 = 2 + mediaTypeWord int32 = 3 + mediaTypePPT int32 = 4 + mediaTypeExcel int32 = 5 + mediaTypeMPArticle int32 = 6 + mediaTypeMarkdown int32 = 7 + mediaTypeImage int32 = 9 + mediaTypeNote int32 = 11 + mediaTypeAISession int32 = 12 + mediaTypeTXT int32 = 13 + mediaTypeXmind int32 = 14 + mediaTypeAudio int32 = 15 + mediaTypeVideo int32 = 16 + mediaTypeHTML int32 = 20 + mediaTypeEPUB int32 = 21 +) + +// extensionForMediaType maps IMA media types to a file extension. +// Returns "" when the media type has no downloadable body (web page, note, AI +// session, video-parse) — callers should skip those or treat them as URL-only. +func extensionForMediaType(t int32) string { + switch t { + case mediaTypePDF: + return "pdf" + case mediaTypeWord: + return "docx" + case mediaTypePPT: + return "pptx" + case mediaTypeExcel: + return "xlsx" + case mediaTypeMarkdown: + return "md" + case mediaTypeImage: + return "png" + case mediaTypeTXT: + return "txt" + case mediaTypeXmind: + return "xmind" + case mediaTypeAudio: + return "mp3" + case mediaTypeHTML: + return "html" + case mediaTypeEPUB: + return "epub" + default: + return "" + } +} + +// mimeForExtension maps a file extension to a canonical MIME type. +// Used when the downloaded URL response omits (or misreports) Content-Type. +func mimeForExtension(ext string) string { + switch strings.ToLower(strings.TrimPrefix(ext, ".")) { + case "pdf": + return "application/pdf" + case "doc": + return "application/msword" + case "docx": + return "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + case "ppt": + return "application/vnd.ms-powerpoint" + case "pptx": + return "application/vnd.openxmlformats-officedocument.presentationml.presentation" + case "xls": + return "application/vnd.ms-excel" + case "xlsx": + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + case "md": + return "text/markdown" + case "txt": + return "text/plain" + case "html", "htm": + return "text/html" + case "png": + return "image/png" + case "jpg", "jpeg": + return "image/jpeg" + case "webp": + return "image/webp" + case "epub": + return "application/epub+zip" + case "xmind": + return "application/x-xmind" + case "mp3": + return "audio/mpeg" + case "m4a": + return "audio/x-m4a" + case "wav": + return "audio/wav" + case "aac": + return "audio/aac" + default: + return "application/octet-stream" + } +} + +func isSkippableMediaType(t int32) bool { + return t == mediaTypeNote || t == mediaTypeAISession || t == mediaTypeVideo +} diff --git a/internal/types/datasource.go b/internal/types/datasource.go index 914e6b28..b53dd8e9 100644 --- a/internal/types/datasource.go +++ b/internal/types/datasource.go @@ -36,6 +36,7 @@ const ( ConnectorTypeSlack = "slack" ConnectorTypeIMAP = "imap" ConnectorTypeRSS = "rss" + ConnectorTypeIMA = "ima" // Sync modes SyncModeIncremental = "incremental" diff --git a/internal/types/knowledge.go b/internal/types/knowledge.go index 2133997a..feb69d38 100644 --- a/internal/types/knowledge.go +++ b/internal/types/knowledge.go @@ -35,6 +35,7 @@ const ( ChannelNotion = "notion" // Notion ChannelYuque = "yuque" // Yuque (语雀) ChannelRSS = "rss" // RSS / Atom feed + ChannelIMA = "ima" // Tencent IMA (ima.qq.com) ) // Knowledge parse status constants