From 19542f2a1d958d26383bbb586adecae6be07a7d5 Mon Sep 17 00:00:00 2001 From: zaqqmm <565121253@qq.com> Date: Thu, 8 Oct 2026 16:18:09 +0800 Subject: [PATCH] feat(datasource): add Seafile data source connector (#3616) * fix(datasource): omit last_sync_cursor from the data source list response The settings page polls GET /datasource every few seconds during a sync, and connector cursors can grow to megabytes. No list consumer reads the cursor, so NewDataSourceResponses now blanks it; detail, create and update responses still return it through NewDataSourceResponse. * feat(datasource): add Seafile connector with fingerprint-based incremental sync Sync folders and files from one Seafile library per data source. The connector walks the selected scope one directory level at a time, downloads files through the link + fileserver flow without credentials, and reconciles deletions against a per-file oid/mtime/size fingerprint cursor that is checkpointed every 50 mutations. - resource ids are ":"; ancestors collapse, one library - per-file failures become coded error items and keep the path pending - directory failures and Retry-After > 60s abort without deletions - forced full runs keep the old cursor as a deletion baseline - API token never reaches cursors, metadata, logs or error text - share the supported import extension set through internal/utils * feat(datasource): add Seafile frontend connector and docs Wire the Seafile data source into the editor dialog, channel labels and the five locales, and document how to connect a Seafile 10.0.1 library. - connector definition with base_url + API token fields and icon - picker guard: one library per data source, at least one selection - "library" resource type and icon in the lazy tree - channel label in the knowledge base filter, document views and chat - i18n for labels, guide steps and the eight seafile_* sync error codes - website-docs integration guide, data source and extension point doc updates, and Seafile in the README data source lists --------- Co-authored-by: zaqqmm --- README.md | 4 +- README_CN.md | 4 +- README_JA.md | 4 +- README_KO.md | 4 +- .../src/assets/img/datasource-seafile.png | Bin 0 -> 7568 bytes frontend/src/components/doc-content.vue | 1 + frontend/src/i18n/localeKeyAudit.test.ts | 22 + frontend/src/i18n/locales/en-US.ts | 30 +- frontend/src/i18n/locales/ja-JP.ts | 30 +- frontend/src/i18n/locales/ko-KR.ts | 30 +- frontend/src/i18n/locales/ru-RU.ts | 30 +- frontend/src/i18n/locales/zh-CN.ts | 30 +- .../components/tool-results/DocumentInfo.vue | 1 + .../src/views/knowledge/KnowledgeBase.vue | 1 + .../knowledge/components/DocumentCardView.vue | 1 + .../knowledge/components/DocumentListView.vue | 1 + .../settings/DataSourceEditorDialog.test.ts | 141 ++- .../settings/DataSourceEditorDialog.vue | 41 + .../knowledge/settings/datasourceIcons.ts | 2 + .../service/datasource_seafile_test.go | 415 ++++++++ .../application/service/knowledge_create.go | 2 +- .../application/service/knowledge_util.go | 30 +- .../service/knowledge_util_filetype_test.go | 19 +- internal/container/container.go | 4 + .../container/datasource_registry_test.go | 18 + internal/datasource/connector.go | 8 + .../datasource/connector/seafile/client.go | 354 +++++++ .../connector/seafile/client_test.go | 538 ++++++++++ .../datasource/connector/seafile/connector.go | 246 +++++ .../connector/seafile/connector_test.go | 163 +++ .../datasource/connector/seafile/cursor.go | 91 ++ .../connector/seafile/cursor_test.go | 114 ++ .../connector/seafile/fake_seafile_test.go | 410 ++++++++ .../datasource/connector/seafile/filename.go | 39 + .../connector/seafile/filename_test.go | 63 ++ internal/datasource/connector/seafile/sync.go | 458 ++++++++ .../connector/seafile/sync_scale_test.go | 107 ++ .../datasource/connector/seafile/sync_test.go | 989 ++++++++++++++++++ .../datasource/connector/seafile/types.go | 235 +++++ .../connector/seafile/types_test.go | 169 +++ internal/handler/dto/datasource.go | 11 +- internal/handler/dto/datasource_test.go | 27 + internal/types/datasource.go | 1 + internal/types/knowledge.go | 1 + internal/utils/import_filetypes.go | 47 + internal/utils/import_filetypes_test.go | 59 ++ website-docs/03-features/10-datasource.md | 17 +- website-docs/03-features/25-seafile.md | 97 ++ .../06-development/03-extension-points.md | 1 + 49 files changed, 5051 insertions(+), 59 deletions(-) create mode 100644 frontend/src/assets/img/datasource-seafile.png create mode 100644 internal/application/service/datasource_seafile_test.go create mode 100644 internal/datasource/connector/seafile/client.go create mode 100644 internal/datasource/connector/seafile/client_test.go create mode 100644 internal/datasource/connector/seafile/connector.go create mode 100644 internal/datasource/connector/seafile/connector_test.go create mode 100644 internal/datasource/connector/seafile/cursor.go create mode 100644 internal/datasource/connector/seafile/cursor_test.go create mode 100644 internal/datasource/connector/seafile/fake_seafile_test.go create mode 100644 internal/datasource/connector/seafile/filename.go create mode 100644 internal/datasource/connector/seafile/filename_test.go create mode 100644 internal/datasource/connector/seafile/sync.go create mode 100644 internal/datasource/connector/seafile/sync_scale_test.go create mode 100644 internal/datasource/connector/seafile/sync_test.go create mode 100644 internal/datasource/connector/seafile/types.go create mode 100644 internal/datasource/connector/seafile/types_test.go create mode 100644 internal/utils/import_filetypes.go create mode 100644 internal/utils/import_filetypes_test.go create mode 100644 website-docs/03-features/25-seafile.md diff --git a/README.md b/README.md index 4c97affa..e3c7d1ac 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Use RAG to look things up, the agent for multi-step tasks, and the wiki to organ Beyond the three modes: - **Memory and curation**: cross-session long-term memory keeps the profile, preferences and facts a user has confirmed. Folder uploads keep their directory tree, and retrieval chunks can be edited, diffed and rolled back. -- **Data sources and formats**: auto-sync from Feishu wiki / Feishu Drive / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS, with more on the way. 10+ document formats including PDF, Word, images, Excel and XMind; Office files are parsed in-process by anydoc. +- **Data sources and formats**: auto-sync from Feishu wiki / Feishu Drive / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS, with more on the way. 10+ document formats including PDF, Word, images, Excel and XMind; Office files are parsed in-process by anydoc. - **Channels and integrations**: Q&A in WeCom, Feishu, Slack, Telegram and other IM apps; an embed widget for external websites; a built-in MCP Server for Cursor, Claude and other AI tools; scoped API keys with a principal model for programmatic access. - **Models**: 27 built-in vendors with a generated model catalog, including OpenAI, DeepSeek, Qwen (Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM and Ollama. - **Permissions and operations**: multi-workspace RBAC (four roles, per-resource ownership, per-workspace audit log), several storage instances per workspace, a runtime task-queue dashboard with worker-pool governance, and Langfuse tracing for agent steps, token usage and pipelines. @@ -318,7 +318,7 @@ A modular pipeline from document parsing, vectorization and retrieval to LLM inf | Vector databases | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB | | [Object storage](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | Local / Tencent Cloud COS / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS | | [Document formats](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / images | -| [Data sources](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu wiki / Feishu Drive / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS | +| [Data sources](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu wiki / Feishu Drive / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS | | [IM channels](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeCom / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia | | [Web search](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply | | Deployment | Docker Compose / Kubernetes (Helm) / Lite single binary / desktop app; offline and private-cloud installs; UI in Chinese, English, Japanese, Korean and Russian | diff --git a/README_CN.md b/README_CN.md index d8ecc25f..aaba0de0 100644 --- a/README_CN.md +++ b/README_CN.md @@ -58,7 +58,7 @@ https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f 除此之外: - **记忆与知识整理**:跨会话长期记忆保存用户确认过的个人信息、偏好与事实;文件夹上传保留原始目录结构;检索分块可以编辑、比对与回滚。 -- **数据源与格式**:飞书知识库 / 飞书云盘 / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / RSS 自动同步,更多数据源持续接入中;覆盖 PDF、Word、图片、Excel、XMind 等十余种格式,Office 文档由 anydoc 在 Go 进程内解析。 +- **数据源与格式**:飞书知识库 / 飞书云盘 / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / Seafile / RSS 自动同步,更多数据源持续接入中;覆盖 PDF、Word、图片、Excel、XMind 等十余种格式,Office 文档由 anydoc 在 Go 进程内解析。 - **渠道与集成**:企业微信、飞书、Slack、Telegram 等 IM 频道内直接问答;网站嵌入 Widget 把智能体发布到外部站点;内置 MCP Server 供 Cursor、Claude 等 AI 工具连接;权限范围 API Key 与 Principal 模型用于程序化集成。 - **模型**:内置 27 家模型厂商与自动生成的模型目录,兼容 OpenAI、DeepSeek、Qwen(阿里云)、智谱、混元、Gemini、MiniMax、NVIDIA、LiteLLM、Ollama 等。 - **权限与运维**:多空间 RBAC(四级角色、资源归属、空间审计日志)、每空间多实例存储后端、运行时任务队列面板与 Worker 池治理,并通过 Langfuse 追踪 Agent 步骤、Token 用量与任务流水线。 @@ -318,7 +318,7 @@ docker compose up -d # 用新镜像重建容器 | 向量数据库 | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / 腾讯云 VectorDB | | [对象存储](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | 本地 / 腾讯云 COS / MinIO / AWS S3 / 火山引擎 TOS / 阿里云 OSS / 金山云 KS3 / 华为云 OBS | | [文档格式](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 图片 | -| [数据源](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | 飞书知识库 / 飞书云盘 / Lark / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / RSS | +| [数据源](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | 飞书知识库 / 飞书云盘 / Lark / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / Seafile / RSS | | [IM 渠道](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | 企业微信 / 飞书 / Lark / QQBot / Slack / Telegram / 钉钉 / Mattermost / 微信 / 云之家 | | [网络搜索](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / 智谱 AI / Exa / Metaso / 博查 / Serply | | 部署 | Docker Compose / Kubernetes (Helm) / Lite 单二进制 / 桌面版;支持离线与私有云部署;界面支持中文、英文、日文、韩文、俄文 | diff --git a/README_JA.md b/README_JA.md index 48135dc0..dac8f511 100644 --- a/README_JA.md +++ b/README_JA.md @@ -58,7 +58,7 @@ https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f そのほか: - **メモリとナレッジ整理**:クロスセッション長期メモリが、ユーザーが確認したプロフィール・好み・事実を保持します。フォルダーアップロードは元のディレクトリ構造を保ち、検索チャンクは編集・差分比較・ロールバックできます。 -- **データソースとフォーマット**:Feishu ナレッジベース / Feishu クラウドドライブ / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS の自動同期(順次拡充中)。PDF、Word、画像、Excel、XMind など 10 以上のフォーマットに対応し、Office 文書は anydoc でプロセス内解析します。 +- **データソースとフォーマット**:Feishu ナレッジベース / Feishu クラウドドライブ / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS の自動同期(順次拡充中)。PDF、Word、画像、Excel、XMind など 10 以上のフォーマットに対応し、Office 文書は anydoc でプロセス内解析します。 - **チャネルと連携**:WeChat Work、Feishu、Slack、Telegram などの IM で直接 Q&A、ウェブサイト埋め込み Widget で外部サイトにエージェントを公開、組み込み MCP Server で Cursor や Claude などの AI ツールと接続、スコープ付き API キーと Principal モデルでプログラム連携。 - **モデル**:27 の組み込みベンダーと自動生成のモデルカタログ。OpenAI、DeepSeek、Qwen(Alibaba Cloud)、Zhipu、Hunyuan、Gemini、MiniMax、NVIDIA、LiteLLM、Ollama などに対応。 - **権限と運用**:マルチワークスペース RBAC(4 階層ロール、リソース所有権、ワークスペース監査ログ)、ワークスペースごとの複数ストレージインスタンス、ランタイムタスクキューダッシュボードと Worker プール統治、Langfuse による Agent ステップ・トークン消費・パイプラインのトレーシング。 @@ -318,7 +318,7 @@ docker compose up -d # 新しいイメージでコンテナを再作成 | ベクトル DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB | | [オブジェクトストレージ](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | ローカル / Tencent Cloud COS / MinIO / AWS S3 / 火山引擎 TOS / Alibaba Cloud OSS / 金山雲 KS3 / 華為雲 OBS | | [文書フォーマット](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 画像 | -| [データソース](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu ナレッジベース / Feishu クラウドドライブ / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS | +| [データソース](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu ナレッジベース / Feishu クラウドドライブ / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS | | [IM 統合](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeChat Work / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia | | [Web 検索](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply | | デプロイ | Docker Compose / Kubernetes (Helm) / Lite シングルバイナリ / デスクトップアプリ。オフライン・プライベートクラウドに対応。UI は中国語 / 英語 / 日本語 / 韓国語 / ロシア語 | diff --git a/README_KO.md b/README_KO.md index dab7cc71..ecb7bf11 100644 --- a/README_KO.md +++ b/README_KO.md @@ -58,7 +58,7 @@ https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f 그 밖에: - **메모리와 지식 정리**: 크로스 세션 장기 메모리가 사용자가 확인한 프로필, 선호, 사실을 보관합니다. 폴더 업로드는 원래 디렉터리 구조를 유지하고, 검색 청크는 편집·비교·롤백할 수 있습니다. -- **데이터 소스와 포맷**: Feishu 지식베이스 / Feishu 클라우드 드라이브 / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS 자동 동기화(지속 확장 중). PDF, Word, 이미지, Excel, XMind 등 10가지 이상의 포맷을 지원하며, Office 문서는 anydoc으로 프로세스 내 파싱합니다. +- **데이터 소스와 포맷**: Feishu 지식베이스 / Feishu 클라우드 드라이브 / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS 자동 동기화(지속 확장 중). PDF, Word, 이미지, Excel, XMind 등 10가지 이상의 포맷을 지원하며, Office 문서는 anydoc으로 프로세스 내 파싱합니다. - **채널과 연동**: WeChat Work, Feishu, Slack, Telegram 등 IM에서 바로 Q&A, 웹사이트 임베드 Widget으로 외부 사이트에 에이전트 게시, 내장 MCP Server로 Cursor·Claude 등 AI 도구와 연결, 범위 지정 API 키와 Principal 모델로 프로그램 연동. - **모델**: 27개 내장 벤더와 자동 생성 모델 카탈로그. OpenAI, DeepSeek, Qwen(Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM, Ollama 등을 지원합니다. - **권한과 운영**: 멀티 워크스페이스 RBAC(4단계 역할, 리소스 소유권, 워크스페이스 감사 로그), 워크스페이스별 다중 스토리지 인스턴스, 런타임 작업 큐 대시보드와 Worker 풀 거버넌스, Langfuse를 통한 Agent 단계·토큰 사용량·파이프라인 추적. @@ -328,7 +328,7 @@ docker compose up -d # 새 이미지로 컨테이너 재생성 | 벡터 DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB | | [오브젝트 스토리지](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | 로컬 / Tencent Cloud COS / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS | | [문서 포맷](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 이미지 | -| [데이터 소스](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu 지식베이스 / Feishu 클라우드 드라이브 / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS | +| [데이터 소스](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu 지식베이스 / Feishu 클라우드 드라이브 / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS | | [IM 통합](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeChat Work / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia | | [웹 검색](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply | | 배포 | Docker Compose / Kubernetes (Helm) / Lite 단일 바이너리 / 데스크톱 앱. 오프라인·프라이빗 클라우드 배포 지원. UI는 중국어 / 영어 / 일본어 / 한국어 / 러시아어 지원 | diff --git a/frontend/src/assets/img/datasource-seafile.png b/frontend/src/assets/img/datasource-seafile.png new file mode 100644 index 0000000000000000000000000000000000000000..7467f3bef2196f58c2ff919d01d3442e67542317 GIT binary patch literal 7568 zcmcIpWmr|))?S;2O-YNy7L3%Gd#v^U}g zg8kM>ZuIyUwgB4Ac+1VZk=slDMsDZ7M+r-33oD4ajWg02VdLxqk&=QishGoUoo?sM z0086U;uhqB3Bq_GTs*f5H~-B(W6}PK@GT4U?@Y5${)*-i$qxwU zicsB{uwCR05C8xsz7-JgCXE6BP@mXp>m&75lm+3=jvVHxcvy4-pKggpgsR7WeM zImFY^!3iPgDMI%fA$X(TE<@=czadC_5juSpb%>O+n-zqQgOh`kP80_Mfe5=MG4-OA*4re!OD3^eM0F)C3g~8Zw5bOvqC#1P2yAy)`4=4Zf zBW;C%yV<%RZJnJUw|>nnoZXQkbac0Y{<{9m)6wOxKu(B1cXhKrsHeFLl#7EC`kzQv zp0@u^?|-pwE&r8Xupf`M~=cb6%~|nvoc3IyJ++?4QN?~o|Ymz)g=0H8=#ke1N)1nrn$Cu_IYlot8aTZi5aHPO9eK!So| zPA&mLM+x-D&=$vXeb$j5KDeIm=Y?_U>o?f8;?rR>*2WZu67+W4LY++G&Yf>b1ZXmr zUR``m%FtgEUe|RhQfk~rYV%)aed~S>AMJdpEmpl;A1l;aPb<390u@F1|GBL>Q4W-| z(?!3Os`CgWLg`NP!f=fAb>*L$xNIwDi|K9l8Gy1(w5G!fc)KPnIBmCBUOO=Jl7fjq z@gptkn#Q|Qm|sX>C)%iAo!^fSD!kbBN2)pir!W=%Y<%3@RsC9HjPcA@8 z2kq9ZX9s3cNIb00H4wkDm1{>076J~6b4 zpW+od#21pqL&LkdAyqm0a<5S^r+DkRF1r5*Rpt*eM+%WA%!Sb>MS>*PrshvL5Ae+8 ze!_ySSciC%IHC7IEvYLXQiSJVMd{q39SwFbC zHF&aBNe3LAwq;q32y?5cge6)#SBIzjGbcc4_kY?YE zUtT9Z=ap~y@=(UJyTayTgBrSU6f&>@N9qJQ!+915&RL@`dNwh1AIcp+g(qbhNCd(*oEF_}$TM=%`YK9kV-$){N!^%0{EbBc5 zV@8V07`awA;4w|TF|n(h`NW7qs57kFql?E27C%1S4Nkz58gDIH*w#k(|3Wh}R*57( zT4yxeiq?$aV}V4N&#c{-F5&7-cvV6W=6{C&^|748d4w5%xyrGDW}=C%-rS8t|Dz~b ztN}E_t^O3cVT5g=Zq5BLQJV1%zBZ=paf-6h8Ok8lpTnPfp9*T)4aewunnchzQk_NaZP`;uX;1v5_~x&=x1$WBUhzrZi<3@-qV7=0~E0E0&7erS+ zH$7T3w4ywX-UW_}@3r%QK*I5s!>S8MlUE`WqwKOz)ab{;?^kbDeh`FuiiNgVlB%OS z=)hCR;l5N4#~fS)$vu+glwaR@uZ7sB9Q9kL0u{bS_t;~9QuZ}dr8HKNf%5Dkrx7Kg zF#$BLOfS%0Vf2a?xmXn*fHDiHyn96Vb)RDjzBD50?~YfKf5=D}Ogh)HA_qH|vb+z`z`#56H>^I; z5O`HZ`J5M2@=_sD)%(A`i8GR`LcR6Y30>DbT*1)L1 zEBB_7HUFKLq4+&}hSe4B5w>yRUEQgkdQzzp19{q*jhNv>3>)?jSw9Bf1%5-#c*{q7 zpX{_>TMp=4C8E+;h1DnPR%KN>m8R3X7E`QDj0{U zr!J=UWevBsr0vSMu6_Rq>c+J!ZKafgz0hjnd}8N-V-a8O?Eefm0UI+?n@>Cw>*#qg z-Juw@>xbxR#GNcVSH%L>;`rh$Z!RjpRfLmge{%e$B~cdjNfbZY0jWg zjCJKcC9gj_n1c^DV2>Gv>2ACXYUDDt_};KHX`-RLCL7oH7h-Yg^8$vc1Eclid>;bQ zpOH}UQ9zgbgr^kC(*x(au|ycoGb}{E<`X2&hXjw^+1pAlhjWirOcOqC=MG*W{g`-t zZ*)wka?mKX*pqFi%%0@g`K8ho7Wk*?jN^BTV4bh<+#X-vDS4%u7uBxv zV60I~Wvp5_TJr}!Xzb;@Fk#t?Ioj!<@+87=W|@X@Hf!)QD!czhh`X%D;o>CLy>7IU zn+kqZt{3n*G{%Uib&X@kH@iIF3xFS_RE3thTIH8**FJ&zpAml+a`@6iyxu#9-Iv*Y zigg_1fAzURL<20Uch&l{~QlRAQm7ql@kwHBW!Rl(SJF-(PcHoc1 z!7U81EC?CV?x#k@kxikNJ&{#MBOra(d;O}9ao=a$`BEf--FY%OC`|c5I6&Mjy4Oc4 zIMeE-K}cJvTyfa)Tz#2S#ba@eMP|!OU~i{}@e^YD-ZRef)aWjP2O55P7w7rBTO;Jc zCes>*&eEt-t3$jsV5x~p$572ZUH0=K0{f^eDzn3kY2uKSj)x{|2x?i;dpt|fwI+|N zbTLLULs1sBN1|>bvghe$-k7HK5-P3EnI~hLU!&D4)PT?j8J(kU=%qBTQRiopFL*vb z+Vj9t?yv5(FW@6D{<%wU{9%EX;X zH<@cRy;r*8-SYkHI=GKMCMc%$W3x6z+mV1ZmYFi}AOsj+bs@tGVepdPX1Syl*hF-? zt@)x0NyBlk0*ulXf5>Bqad*pR;BH|>NphFs0OzC9rsC;gtFTTJ-vGB2a5-X4$ac$U zW#i@fQAy3E942m!A`4|lZ(nk@LG7`?%%nk);U^ll5X=Ji;S2hK*MS@%mOh2G?TWzFQuQV;oic`cH(r8Q+en6ZZD^T{gIqR4@WTdbH)~sY#dBN3a*O+$?~y+k zu`k*2$%TzM2y1PybuS&NEJ?Z7tt|$Ave3dW;R_ZRn3#}nB>|g_^8eb>bo}tVl?xB) zn2D1zyV~VZ+;6EEGV#hdujUyhjuc0m@YKc1k92LjqHP1|#ch~Rooja<*8(qa0|W zK2W$|?Y1}^gcRaee}DWD`52%`Yf$2Q9$q`Y=brbHBj-h&?Ch}nS2t3$R_Z=($?4un zmZD$B_WU-nUx!BeW!3C}N31199EPLzoUqV*&9Kif9g&29-6^&%@tO?1?&GME)Virs zYm}x5))Lu+obVu;K_0cp)UbRla`Co6L9uj}_~+kKfH2-!bG?l_X>5KyRLTsU*T(E9 zgn)w`LdWCg^Tyt2R8S5>CU^MY21-y%Mc1n}k|$tcnu^l8p10D~3pClJZ{)SS_*!C&(nigPR`+kSK)OI^cy`oD>p$#pLbf^N*55X;rUD5 zn8uhs`txk4OFw24(u)pQ>K}-zc)v}hwADMg=YqHHDbo-Uwv4;?FgRBhqR`7raYfsL zs59wlimS9?(p1BY43m(NP+*5p%|hnMr8qInb4TM3DZE-E?H?wdp9I#y8l9&lPPD5Oxu8AnJW|MbT04g&uFWIMp-Nc9U3ZywjvI4-P?IeA8kY}o z)lBhoyta@C+k8+ou?Ug0w8I@6ej`}Km&GdN0T_P+4A6KOF3Q`tjm*1S5(#QTRhu3ymK*{!6hnGR1K+ zzMs9?zY1x}R=%MniM;e>ETMrZ1Rsl{SpP^*bI~FL7447hT1p+@k`3ScV_&`HIpbm6bH+V*1-@t{Y=%#$ zYVx`iW>_7lmFg-f{lt3(MFOi(e#kmBhBB(nuE|5TyK{Of>tDVVzuWTN*&LzlF~QKl zu!>+I>{|YbwT&j|UvV5yw53)_HcEcYbJ#v{4ms#d_lGEn(P@^d1#ebilYZ~2{R2|bY0XFmWh#KNs7cbXK(4)LCpr64u>Q6QM#aCH+ zR6lWWs5*m{+UMZR)3o*U6xsI;x267_JszV6Bz+La>zDeuk|iqqCDoC8319ZRQPYds zqo*^n+LXpG#${{YB!=S$;og**`~U=~@yb+0#nOf7tQQE2s@$!fx7 z2Qg?N)YkUJdYnCHx*gpY7z_6vweh3Ai}n$|{2tdiF0naM!)ezCW4|0 z%sV1D%5jo|J5%u!88)}J8i|au`KnBNg(K$bgJaqZ)1#&1G6;ODhcbo53Tv9Xv9#Cb z2h<^&F^cuWHA@Q4E?U+*6;M1uTqjiUYYlyO+t<}Y?6pRQ9&oADNCB&#yP=zt*boc@ z)eDfdld~G*j~MvHesv&4SI zCMNX&rCIt+%5vt}^NcUIM4&Hpp=Jw(_sMFFV&?I>co>Fw91vFk*9K$fvqqu0+Q>7| zMgqc+?o14C#E0ECdlnKNT7?X+{jpfzrb#eyRSXkDrZ-qTH(WnzZcWN>jl;aNBza6C zDLw!SD|n1z7O&S`A!L_Oi7xDL&TANGH3wMB#7YS3H*o@n5#^rwUMU+mhrQELsbVASu1leWs>w7l*m;jaoMS~dqNuJ z7h0j;D5-jK6{Y=2E@Ij=n6O)rZ9Xmry6N|)qZixcoxDHLW(ZKNiD3!_`oRh86i&aqb2Vk;td&52C%=DF)=Xb zhmL)IFIg-YN$>=QG=>x zZ$?tL56wx;-9Bc%+Uh5Hn*6dt;sax1@peS8BBFTv8-iH&8=BksgE+yVPP=(?zu3I` zX5SZRB~Bni6*YwAepiBpo|S6ibbPc*#bgrz+G|livKjAA!B2_ zZorPA?s-~%eqq$|cNZGfeX$&?d&)`FtR+Hq>`9`_NU{^QJxNy?fUtn#JF@964O_=t zOnF_p0+(#P?r3rSrcO`bX;_4^U!6#H!|{q_`UQKXrO@3ufY^b2OF)z%xo`}yzvJh zp4$B>?cGUV{*KONHNA!XqVG>HY4Eq3NXofrvX!5cnk7)j1qeSaoA`xnWgI*u>({X+ zy@aJd)K}?yIh!=k9aFTES=B%k;%P_LZ{HKw%xM0~AyJEV6eYkFC4#}ibW#<{I~T&FK_cLz!Z|IpWE#h90y``&W7kbey{@8$M?hsJ z^~uZl96@F}lF(rm`SGTn$akJnrJuPE*}XM_x8@<%X&H-4hC<<_DaUeqAYaV;omi?3 z8tv}Fi=$b`O}U>BwSBRZK0bov0YwE5P#+_n-U(+Unq9J;0q|242ZADwKIYIbQ}?$C zl^r_nzh(LrdupSpD%e&!os`b2#d2xk-ir`!Jh7Q(yW2C+w31CToGJr9^fFFoE5-6} zSZhkMSrL#1sp)Q?$vCVG-f532{pGNtw-J0*95&Q^)W3$4;C&cS7ul#3%)B1G;_{Id zW#LHDkU+fUOVfUdP2Z|sU+W_|9tXG9@L9e&AZh4jnwzDN;IVoiV#)3LTL)`}=m*o3 zUcOm&Mq0znp@-`uyr9@uF;`eZ9yoTFpxqxNx=g+_7zZ0Nt$7CUtL}kn!3%!vQ{!gV zSnh024|wSOGqoy)rc*$m!fJhPrFK!sg@e~Y0O*fj8pv05*o4yP0hY6xl@9b>EZx7^@HN z_o_`Z{ls-FvwCeU4J@e)gWJX6t*C9d&DF8HC)j4VLOG#wstxYCIu}bmlDbmL3t@K-s}dsi)o_`qngrnoUdC5>FBnf?DsYkkZW9E<8P+jKhdiw zsg@piZ(!eHpl)@~>08#6%|Ae+(!-p9gdigf2xwc#z#tSF(zOTd6BFv)2!hEGK0@&+7 zJEcUYxv5J|bJJt1;lKl;K(w%|Futb86t#i;Z3Yo<1Kl3E9TCrTt?`P?RDZz=#-XBY zktcb9;D_h-`M;>BRvsYCcRcOUPxWj6|M`9|ic%Ncbd3rhOS&jc)OWxA_opDEDqSjR G7WhAotv)>f literal 0 HcmV?d00001 diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 8d48de17..7b481658 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -966,6 +966,7 @@ const channelLabelMap: Record = { wecom: 'knowledgeBase.channelWecom', feishu: 'knowledgeBase.channelFeishu', gitlab: 'knowledgeBase.channelGitLab', + seafile: 'knowledgeBase.channelSeafile', confluence: 'knowledgeBase.channelConfluence', // Drive (云盘) connectors get their own channel so Drive docs show // "飞书云盘" / "Lark 云盘", distinct from the wiki connector's "飞书". diff --git a/frontend/src/i18n/localeKeyAudit.test.ts b/frontend/src/i18n/localeKeyAudit.test.ts index 1be52f30..d744ae45 100644 --- a/frontend/src/i18n/localeKeyAudit.test.ts +++ b/frontend/src/i18n/localeKeyAudit.test.ts @@ -292,6 +292,28 @@ test('locale messages compile with vue-i18n syntax rules', () => { assert.deepEqual(summary, [], summary.slice(0, 20).join('\n')) }) +test('Seafile picker texts and sync error codes remain localized after pruning', () => { + const seafileErrors = [ + 'permission_denied', 'not_found', 'file_too_large', 'empty_file', + 'source_changed', 'invalid_response', 'ssrf_blocked', 'fetch_failed', + ] + const keys = [ + 'connector.seafile', 'connectorDesc.seafile', + 'seafile.baseUrl', 'seafile.apiToken', 'seafile.apiTokenHint', + 'seafile.singleLibraryOnly', 'seafile.selectionRequired', + 'resourceType.library', 'noResourcesDesc_seafile', + ...[1, 2, 3].map(step => `guideStep${step}_seafile`), + ...seafileErrors.map(code => `syncError.seafile_${code}`), + ].map(key => `datasource.${key}`) + keys.push('knowledgeBase.channelSeafile') + for (const key of keys) { + assert.ok(referencedKeys.has(key), `pruning would remove ${key}`) + for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) { + assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`) + } + } +}) + test('DingTalk configuration and sync failures remain localized after pruning', () => { const keys = [ 'connector.dingtalk', 'connectorDesc.dingtalk', diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index d0c7b4b7..d7eec140 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -810,6 +810,7 @@ export default { channelConfluence: 'Confluence', channelYuque: 'Yuque', channelGitLab: 'GitLab', + channelSeafile: 'Seafile', channelIma: 'Tencent IMA', channelUpload: 'Upload', channelManual: 'Manual', @@ -6869,6 +6870,12 @@ export default { paths: 'Directories', pathsPlaceholder: 'One directory per line; leave empty to sync the whole project', addProject: 'Add project', projectRequired: 'Add at least one GitLab project', }, + seafile: { + baseUrl: 'Seafile URL', apiToken: 'API token', + apiTokenHint: 'Generate it under "Settings → Web API token" in Seafile; the account only needs read access to the libraries you select, and the token is never sent with file downloads.', + singleLibraryOnly: 'A data source syncs one library; clear the current library before selecting another.', + selectionRequired: 'Select at least one library, folder or file', + }, resourceHint: 'Select the spaces or folders to sync', untitled: 'Untitled', resourceLoadFailed: 'Failed to load resources', @@ -6882,6 +6889,10 @@ export default { guideStep1_notion: 'Open the page or database you want to sync in Notion', guideStep2_notion: 'Click the "···" menu at the top right, select "Connect to" or "Add connections"', guideStep3_notion: 'Search and select your Integration app, then come back and click Retry', + noResourcesDesc_seafile: 'The token can reach no libraries, or every library is encrypted (encrypted libraries cannot be synced)', + guideStep1_seafile: 'Sign in to Seafile and confirm the account can read at least one unencrypted library', + guideStep2_seafile: 'Generate or regenerate the token under "Settings → Web API token"', + guideStep3_seafile: 'Come back, enter the new token and click Retry', permissionDocLink: 'View Feishu wiki permission docs', syncScheduleLabel: 'Sync schedule', conflictLabel: 'Conflict strategy', @@ -6940,7 +6951,8 @@ export default { dingtalk: 'DingTalk Docs', rss: 'RSS / Atom Feed', ima: 'Tencent IMA', - gitlab: 'GitLab' + gitlab: 'GitLab', + seafile: 'Seafile' }, connectorDesc: { feishu: 'Sync documents, spreadsheets and files from Feishu Wiki', @@ -6953,7 +6965,8 @@ export default { dingtalk: 'Sync online documents from DingTalk knowledge bases', rss: 'Sync articles from RSS / Atom feeds', ima: 'Sync documents, notes and files from Tencent IMA knowledge bases (AI sessions and video parses are not supported)', - gitlab: 'Sync files from GitLab projects' + gitlab: 'Sync files from GitLab projects', + seafile: 'Sync folders and files from Seafile libraries' }, drive: { folderTokenLabel: 'Drive folder token', @@ -7078,7 +7091,8 @@ export default { resourceType: { wikiSpace: 'Wiki Space', docCategory: 'Document Tag', - book: 'Yuque Book' + book: 'Yuque Book', + library: 'Seafile Library' }, neverSynced: 'Never synced', justNow: 'Just now', @@ -7090,7 +7104,15 @@ export default { dingtalk_resource_failed: 'DingTalk resource is unavailable; check access and the saved selection, then retry.', deletion_lookup_failed: 'Failed to look up the item before deletion; see server logs', deletion_failed: 'Deletion failed; see server logs', - ingest_failed: 'Ingest failed; see server logs' + ingest_failed: 'Ingest failed; see server logs', + seafile_permission_denied: 'Access to the Seafile file was denied; check the library permissions of the token owner.', + seafile_not_found: 'The Seafile file no longer exists or was moved; the next sync retries it.', + seafile_file_too_large: 'The Seafile file exceeds the size limit; raise MAX_FILE_SIZE_MB or shrink the file.', + seafile_empty_file: 'The Seafile file is empty and was skipped.', + seafile_source_changed: 'The Seafile file changed while it was being fetched; the next sync retries it.', + seafile_invalid_response: 'Seafile returned a response that could not be parsed; check the server version and reverse proxy.', + seafile_ssrf_blocked: 'The Seafile download URL was blocked by the SSRF policy; add the fileserver host to SSRF_WHITELIST.', + seafile_fetch_failed: 'Failed to fetch the file from Seafile; the next sync retries it.' } }, integrations: { diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 1cbb54ec..44fdae7c 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -810,6 +810,7 @@ export default { channelConfluence: 'Confluence', channelYuque: 'Yuque', channelGitLab: 'GitLab', + channelSeafile: 'Seafile', channelIma: 'Tencent IMA', channelUpload: 'アップロード', channelManual: '手動作成', @@ -6869,6 +6870,12 @@ export default { paths: 'ディレクトリ', pathsPlaceholder: '1行に1つのディレクトリを入力します。空欄の場合はプロジェクト全体を同期します', addProject: 'プロジェクトを追加', projectRequired: 'GitLabプロジェクトを1つ以上追加してください', }, + seafile: { + baseUrl: 'Seafile URL', apiToken: 'APIトークン', + apiTokenHint: 'Seafileの「設定 → Web APIトークン」で生成します。アカウントに選択したライブラリの読み取り権限があれば十分で、トークンはファイルのダウンロード要求には送信されません。', + singleLibraryOnly: '1つのデータソースは1つのライブラリのみ同期できます。別のライブラリを選ぶ前に現在の選択を解除してください。', + selectionRequired: 'ライブラリ、フォルダまたはファイルを1つ以上選択してください', + }, resourceHint: '同期するスペースまたはフォルダを選択してください', untitled: '無題', resourceLoadFailed: 'リソースの読み込みに失敗しました', @@ -6882,6 +6889,10 @@ export default { guideStep1_notion: '同期したいページまたはデータベースをNotionで開きます', guideStep2_notion: '右上の「···」メニューをクリックし、「Connect to」または「Add connections」を選択します', guideStep3_notion: '作成したIntegrationアプリを検索して選択し、戻って「再試行」をクリックします', + noResourcesDesc_seafile: 'このトークンでアクセスできるライブラリがないか、すべて暗号化ライブラリです(暗号化ライブラリは同期できません)', + guideStep1_seafile: 'Seafileにサインインし、アカウントが暗号化されていないライブラリを1つ以上読めることを確認します', + guideStep2_seafile: '「設定 → Web APIトークン」でトークンを生成または再生成します', + guideStep3_seafile: 'ここに戻って新しいトークンを入力し、「再試行」をクリックします', permissionDocLink: 'FeishuのWiki権限ドキュメントを見る', syncScheduleLabel: '同期スケジュール', conflictLabel: '競合時の処理', @@ -6940,7 +6951,8 @@ export default { dingtalk: 'DingTalkドキュメント', rss: 'RSS / Atomフィード', ima: 'Tencent IMA', - gitlab: 'GitLab' + gitlab: 'GitLab', + seafile: 'Seafile' }, connectorDesc: { feishu: 'Feishu Wikiからドキュメント、スプレッドシート、ファイルを同期します', @@ -6953,7 +6965,8 @@ export default { dingtalk: 'DingTalkナレッジベースのオンラインドキュメントを同期', rss: 'RSS / Atomフィードから記事を同期します', ima: 'Tencent IMAのナレッジベースからドキュメント、ノート、ファイルを同期します(AIセッションと動画の解析は非対応)', - gitlab: 'GitLabプロジェクトからファイルを同期します' + gitlab: 'GitLabプロジェクトからファイルを同期します', + seafile: 'Seafileライブラリのフォルダとファイルを同期します' }, drive: { folderTokenLabel: 'Driveフォルダトークン', @@ -7078,7 +7091,8 @@ export default { resourceType: { wikiSpace: 'Wikiスペース', docCategory: 'ドキュメントタグ', - book: 'Yuqueナレッジベース' + book: 'Yuqueナレッジベース', + library: 'Seafileライブラリ' }, neverSynced: '未同期', justNow: 'たった今', @@ -7090,7 +7104,15 @@ export default { dingtalk_resource_failed: 'DingTalkリソースを利用できません。アクセス権限と選択したリソースを確認して再試行してください。', deletion_lookup_failed: '削除前の項目の照会に失敗しました。サーバログを確認してください', deletion_failed: '削除に失敗しました。サーバログを確認してください', - ingest_failed: '取り込みに失敗しました。サーバログを確認してください' + ingest_failed: '取り込みに失敗しました。サーバログを確認してください', + seafile_permission_denied: 'Seafileファイルへのアクセスが拒否されました。トークン所有者のライブラリ権限を確認してください。', + seafile_not_found: 'Seafileファイルが存在しないか移動されました。次回の同期で再試行します。', + seafile_file_too_large: 'Seafileファイルがサイズ上限を超えています。MAX_FILE_SIZE_MBを引き上げるかファイルを小さくしてください。', + seafile_empty_file: 'Seafileファイルが空のためスキップしました。', + seafile_source_changed: '取得中にSeafileファイルが変更されました。次回の同期で再試行します。', + seafile_invalid_response: 'Seafileから解析できない応答が返されました。サーバのバージョンとリバースプロキシを確認してください。', + seafile_ssrf_blocked: 'SeafileのダウンロードURLがSSRFポリシーでブロックされました。fileserverのホストをSSRF_WHITELISTに追加してください。', + seafile_fetch_failed: 'Seafileからファイルを取得できませんでした。次回の同期で再試行します。' } }, integrations: { diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 2af18593..9340e67e 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -992,6 +992,12 @@ export default { paths: '디렉터리', pathsPlaceholder: '한 줄에 하나씩 입력하세요. 비워 두면 전체 프로젝트를 동기화합니다', addProject: '프로젝트 추가', projectRequired: 'GitLab 프로젝트를 하나 이상 추가하세요', }, + seafile: { + baseUrl: 'Seafile URL', apiToken: 'API 토큰', + apiTokenHint: 'Seafile의 \'설정 → Web API 토큰\'에서 생성하세요. 계정에 선택한 라이브러리의 읽기 권한만 있으면 되며 토큰은 파일 다운로드 요청에 전송되지 않습니다.', + singleLibraryOnly: '데이터 소스 하나는 라이브러리 하나만 동기화합니다. 다른 라이브러리를 선택하기 전에 현재 선택을 해제하세요.', + selectionRequired: '라이브러리, 폴더 또는 파일을 하나 이상 선택하세요', + }, resourceHint: '동기화할 공간/폴더를 선택하세요', untitled: '제목 없음', resourceLoadFailed: '리소스 목록 로드 실패', @@ -1005,6 +1011,10 @@ export default { guideStep1_notion: 'Notion에서 동기화하려는 페이지나 데이터베이스를 엽니다', guideStep2_notion: '오른쪽 상단의 \'···\' 메뉴를 클릭하고 \'Connect to\' 또는 \'Add connections\'를 선택합니다', guideStep3_notion: 'Integration 앱을 검색하여 선택한 후, 돌아와서 다시 시도를 클릭하세요', + noResourcesDesc_seafile: '이 토큰으로 접근할 수 있는 라이브러리가 없거나 모두 암호화 라이브러리입니다(암호화 라이브러리는 동기화할 수 없음)', + guideStep1_seafile: 'Seafile에 로그인하여 계정이 암호화되지 않은 라이브러리를 하나 이상 읽을 수 있는지 확인하세요', + guideStep2_seafile: '\'설정 → Web API 토큰\'에서 토큰을 생성하거나 다시 생성하세요', + guideStep3_seafile: '여기로 돌아와 새 토큰을 입력하고 다시 시도를 클릭하세요', permissionDocLink: '페이슈 위키 권한 설정 문서 보기', syncScheduleLabel: '동기화 주기', conflictLabel: '충돌 전략', @@ -1097,7 +1107,8 @@ export default { resourceType: { wikiSpace: '위키 공간', docCategory: '문서 태그', - book: 'Yuque 지식베이스' + book: 'Yuque 지식베이스', + library: 'Seafile 라이브러리' }, scheduleHuman: { '30min': '30분마다', @@ -1145,7 +1156,8 @@ export default { dingtalk: 'DingTalk 지식베이스의 온라인 문서 동기화', ima: 'Tencent IMA 지식베이스에서 문서, 노트 및 파일 동기화 (AI 세션과 동영상 분석은 지원되지 않음)', rss: 'RSS / Atom 피드에서 글 동기화', - gitlab: 'GitLab 프로젝트의 파일 동기화' + gitlab: 'GitLab 프로젝트의 파일 동기화', + seafile: 'Seafile 라이브러리의 폴더와 파일 동기화' }, connector: { feishu: '페이슈 (Feishu)', @@ -1158,7 +1170,8 @@ export default { dingtalk: 'DingTalk 문서', ima: 'Tencent IMA', rss: 'RSS / Atom 피드', - gitlab: 'GitLab' + gitlab: 'GitLab', + seafile: 'Seafile' }, logDetail: { startTime: '시작 시간', @@ -1222,7 +1235,15 @@ export default { dingtalk_resource_failed: 'DingTalk 리소스를 사용할 수 없습니다. 접근 권한과 선택한 리소스를 확인한 후 다시 시도하세요.', deletion_lookup_failed: '삭제 전 항목 조회에 실패했습니다. 서버 로그를 확인하세요', deletion_failed: '삭제에 실패했습니다. 서버 로그를 확인하세요', - ingest_failed: '가져오기에 실패했습니다. 서버 로그를 확인하세요' + ingest_failed: '가져오기에 실패했습니다. 서버 로그를 확인하세요', + seafile_permission_denied: 'Seafile 파일에 접근할 수 없습니다. 토큰 소유자의 라이브러리 권한을 확인하세요.', + seafile_not_found: 'Seafile 파일이 존재하지 않거나 이동되었습니다. 다음 동기화에서 다시 시도합니다.', + seafile_file_too_large: 'Seafile 파일이 크기 제한을 초과합니다. MAX_FILE_SIZE_MB를 늘리거나 파일을 줄이세요.', + seafile_empty_file: 'Seafile 파일이 비어 있어 건너뛰었습니다.', + seafile_source_changed: '가져오는 동안 Seafile 파일이 변경되었습니다. 다음 동기화에서 다시 시도합니다.', + seafile_invalid_response: 'Seafile이 해석할 수 없는 응답을 반환했습니다. 서버 버전과 리버스 프록시 설정을 확인하세요.', + seafile_ssrf_blocked: 'Seafile 다운로드 URL이 SSRF 정책에 의해 차단되었습니다. fileserver 호스트를 SSRF_WHITELIST에 추가하세요.', + seafile_fetch_failed: 'Seafile에서 파일을 가져오지 못했습니다. 다음 동기화에서 다시 시도합니다.' }, }, ollama: { @@ -7164,6 +7185,7 @@ export default { channelConfluence: 'Confluence', channelYuque: 'Yuque', channelGitLab: 'GitLab', + channelSeafile: 'Seafile', channelIma: 'Tencent IMA', channelUpload: '업로드', channelManual: '수동', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 7adf0269..77e67691 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -992,6 +992,12 @@ export default { paths: 'Каталоги', pathsPlaceholder: 'По одному каталогу в строке; оставьте пустым для синхронизации всего проекта', addProject: 'Добавить проект', projectRequired: 'Добавьте хотя бы один проект GitLab', }, + seafile: { + baseUrl: 'URL Seafile', apiToken: 'API-токен', + apiTokenHint: 'Создайте его в Seafile: «Настройки → Web API токен». Учётной записи достаточно прав на чтение выбранных библиотек; токен не передаётся при скачивании файлов.', + singleLibraryOnly: 'Один источник данных синхронизирует одну библиотеку. Снимите текущий выбор, прежде чем выбрать другую библиотеку.', + selectionRequired: 'Выберите хотя бы одну библиотеку, папку или файл', + }, resourceHint: 'Выберите пространства или папки для синхронизации', untitled: 'Без названия', resourceLoadFailed: 'Не удалось загрузить список ресурсов', @@ -1005,6 +1011,10 @@ export default { guideStep1_notion: 'Откройте страницу или базу данных, которую хотите синхронизировать в Notion', guideStep2_notion: 'Нажмите меню «···» в правом верхнем углу, выберите «Connect to» или «Add connections»', guideStep3_notion: 'Найдите и выберите ваше интеграционное приложение, затем вернитесь и нажмите Повторить', + noResourcesDesc_seafile: 'Токену недоступна ни одна библиотека, либо все библиотеки зашифрованы (зашифрованные библиотеки не синхронизируются)', + guideStep1_seafile: 'Войдите в Seafile и убедитесь, что у аккаунта есть доступ на чтение хотя бы к одной незашифрованной библиотеке', + guideStep2_seafile: 'Создайте или пересоздайте токен в разделе «Настройки → Web API токен»', + guideStep3_seafile: 'Вернитесь сюда, введите новый токен и нажмите Повторить', permissionDocLink: 'Документация по настройке прав доступа', syncScheduleLabel: 'Расписание синхронизации', conflictLabel: 'Стратегия конфликтов', @@ -1097,7 +1107,8 @@ export default { resourceType: { wikiSpace: 'Пространство вики', docCategory: 'Тег документа', - book: 'База знаний Yuque' + book: 'База знаний Yuque', + library: 'Библиотека Seafile' }, scheduleHuman: { '30min': 'Каждые 30 мин', @@ -1145,7 +1156,8 @@ export default { dingtalk: 'Синхронизация онлайн-документов из баз знаний DingTalk', ima: 'Синхронизация документов, заметок и файлов из баз знаний Tencent IMA (ИИ-сессии и разбор видео не поддерживаются)', rss: 'Синхронизация статей из лент RSS / Atom', - gitlab: 'Синхронизация файлов из проектов GitLab' + gitlab: 'Синхронизация файлов из проектов GitLab', + seafile: 'Синхронизация папок и файлов из библиотек Seafile' }, connector: { feishu: 'Feishu (Фэйшу)', @@ -1158,7 +1170,8 @@ export default { dingtalk: 'Документы DingTalk', ima: 'Tencent IMA', rss: 'RSS / Atom лента', - gitlab: 'GitLab' + gitlab: 'GitLab', + seafile: 'Seafile' }, logDetail: { startTime: 'Время начала', @@ -1222,7 +1235,15 @@ export default { dingtalk_resource_failed: 'Ресурс DingTalk недоступен. Проверьте права доступа и выбранные ресурсы, затем повторите попытку.', deletion_lookup_failed: 'Не удалось найти элемент перед удалением; подробности в журнале сервера', deletion_failed: 'Не удалось удалить элемент; подробности в журнале сервера', - ingest_failed: 'Не удалось импортировать элемент; подробности в журнале сервера' + ingest_failed: 'Не удалось импортировать элемент; подробности в журнале сервера', + seafile_permission_denied: 'Доступ к файлу Seafile запрещён. Проверьте права владельца токена на библиотеку.', + seafile_not_found: 'Файл Seafile не существует или был перемещён; при следующей синхронизации попытка повторится.', + seafile_file_too_large: 'Файл Seafile превышает ограничение размера. Увеличьте MAX_FILE_SIZE_MB или уменьшите файл.', + seafile_empty_file: 'Файл Seafile пуст и был пропущен.', + seafile_source_changed: 'Файл Seafile изменился во время получения; при следующей синхронизации попытка повторится.', + seafile_invalid_response: 'Seafile вернул ответ, который не удалось разобрать. Проверьте версию сервера и обратный прокси.', + seafile_ssrf_blocked: 'URL скачивания Seafile заблокирован политикой SSRF. Добавьте хост fileserver в SSRF_WHITELIST.', + seafile_fetch_failed: 'Не удалось получить файл из Seafile; при следующей синхронизации попытка повторится.' }, }, ollama: { @@ -7164,6 +7185,7 @@ export default { channelConfluence: 'Confluence', channelYuque: 'Yuque', channelGitLab: 'GitLab', + channelSeafile: 'Seafile', channelIma: 'Tencent IMA', channelUpload: 'Загрузка', channelManual: 'Вручную', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 01245a89..ce80d25e 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -994,6 +994,12 @@ export default { paths: '同步目录', pathsPlaceholder: '每行一个目录;留空同步整个项目', addProject: '添加项目', projectRequired: '请至少添加一个 GitLab 项目', }, + seafile: { + baseUrl: 'Seafile 地址', apiToken: 'API 令牌', + apiTokenHint: '在 Seafile「设置 → Web API 令牌」中生成;账号对所选资料库有读权限即可,令牌不会随文件下载请求发送。', + singleLibraryOnly: '一个数据源只能同步一个资料库,请先取消已选资料库中的内容再改选。', + selectionRequired: '请至少勾选一个资料库、目录或文件', + }, resourceHint: '选择要同步的内容空间/文件夹', untitled: '无标题', resourceLoadFailed: '加载资源列表失败', @@ -1007,6 +1013,10 @@ export default { guideStep1_notion: '在 Notion 中打开你想要同步的页面或数据库', guideStep2_notion: '点击右上角的「···」菜单,选择「Connect to」或「Add connections」', guideStep3_notion: '搜索并选择你的集成应用(Integration),然后回到这里点重新加载', + noResourcesDesc_seafile: '该令牌能访问的资料库为空,或全部为加密资料库(不支持同步)', + guideStep1_seafile: '登录 Seafile,确认账号至少拥有一个未加密资料库的读取权限', + guideStep2_seafile: '在「设置 → Web API 令牌」中生成或重新生成令牌', + guideStep3_seafile: '回到这里填入新令牌并点重新加载', permissionDocLink: '查看飞书知识库权限配置文档', syncScheduleLabel: '同步频率', conflictLabel: '冲突策略', @@ -1099,7 +1109,8 @@ export default { resourceType: { wikiSpace: '知识库空间', docCategory: '文档标签', - book: '语雀知识库' + book: '语雀知识库', + library: 'Seafile 资料库' }, scheduleHuman: { '30min': '每 30 分钟', @@ -1147,7 +1158,8 @@ export default { dingtalk: '同步钉钉知识库中的在线文档', ima: '同步腾讯 IMA 知识库中的文档、笔记与文件(暂不支持 AI 会话与视频解析)', rss: '同步 RSS / Atom 订阅源中的文章', - gitlab: '同步 GitLab 项目中的文件' + gitlab: '同步 GitLab 项目中的文件', + seafile: '同步 Seafile 资料库中的目录与文件' }, connector: { feishu: '飞书', @@ -1160,7 +1172,8 @@ export default { dingtalk: '钉钉文档', ima: '腾讯 IMA', rss: 'RSS / Atom 订阅', - gitlab: 'GitLab' + gitlab: 'GitLab', + seafile: 'Seafile' }, logDetail: { startTime: '开始时间', @@ -1224,7 +1237,15 @@ export default { dingtalk_resource_failed: '钉钉资源不可用,请检查访问权限和已选资源后重试。', deletion_lookup_failed: '删除前查找文档失败,请查看服务器日志', deletion_failed: '删除失败,请查看服务器日志', - ingest_failed: '导入失败,请查看服务器日志' + ingest_failed: '导入失败,请查看服务器日志', + seafile_permission_denied: '无权访问该 Seafile 文件,请检查令牌所属账号的资料库权限。', + seafile_not_found: 'Seafile 文件不存在或已被移动,下次同步将重试。', + seafile_file_too_large: 'Seafile 文件超过大小限制,请调大 MAX_FILE_SIZE_MB 或缩小该文件。', + seafile_empty_file: 'Seafile 文件内容为空,已跳过。', + seafile_source_changed: 'Seafile 文件在获取过程中发生变化,下次同步将重试。', + seafile_invalid_response: 'Seafile 返回了无法解析的响应,请检查服务器版本与反向代理配置。', + seafile_ssrf_blocked: 'Seafile 文件下载地址被 SSRF 策略拦截,请将 fileserver 域名加入 SSRF_WHITELIST。', + seafile_fetch_failed: '从 Seafile 获取文件失败,下次同步将重试。' }, }, ollama: { @@ -7166,6 +7187,7 @@ export default { channelConfluence: 'Confluence', channelYuque: '语雀', channelGitLab: 'GitLab', + channelSeafile: 'Seafile', channelIma: '腾讯 IMA', channelUpload: '上传', channelManual: '手动', diff --git a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue index 838da19c..315aecea 100644 --- a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue +++ b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue @@ -109,6 +109,7 @@ const channelLabelMap: Record = { wecom: 'knowledgeBase.channelWecom', feishu: 'knowledgeBase.channelFeishu', gitlab: 'knowledgeBase.channelGitLab', + seafile: 'knowledgeBase.channelSeafile', confluence: 'knowledgeBase.channelConfluence', dingtalk: 'knowledgeBase.channelDingtalk', slack: 'knowledgeBase.channelSlack', diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 15b931f8..b7dc04df 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -689,6 +689,7 @@ const sourceOptions = computed(() => [ { label: t('knowledgeBase.channelYuque'), value: 'yuque' }, { label: t('knowledgeBase.channelConfluence'), value: 'confluence' }, { label: t('knowledgeBase.channelGitLab'), value: 'gitlab' }, + { label: t('knowledgeBase.channelSeafile'), value: 'seafile' }, { label: t('knowledgeBase.channelIma'), value: 'ima' }, { label: t('knowledgeBase.channelWechat'), value: 'wechat' }, { label: t('knowledgeBase.channelWecom'), value: 'wecom' }, diff --git a/frontend/src/views/knowledge/components/DocumentCardView.vue b/frontend/src/views/knowledge/components/DocumentCardView.vue index 28b279b0..717975c6 100644 --- a/frontend/src/views/knowledge/components/DocumentCardView.vue +++ b/frontend/src/views/knowledge/components/DocumentCardView.vue @@ -154,6 +154,7 @@ const channelLabelMap: Record = { wecom: 'knowledgeBase.channelWecom', feishu: 'knowledgeBase.channelFeishu', gitlab: 'knowledgeBase.channelGitLab', + seafile: 'knowledgeBase.channelSeafile', confluence: 'knowledgeBase.channelConfluence', dingtalk: 'knowledgeBase.channelDingtalk', slack: 'knowledgeBase.channelSlack', diff --git a/frontend/src/views/knowledge/components/DocumentListView.vue b/frontend/src/views/knowledge/components/DocumentListView.vue index 6e94d74e..1c03f32e 100644 --- a/frontend/src/views/knowledge/components/DocumentListView.vue +++ b/frontend/src/views/knowledge/components/DocumentListView.vue @@ -103,6 +103,7 @@ const getSourceInfo = (item: KnowledgeItem): { icon: string; label: string } => if (ch === 'yuque') return { icon: 'cloud-download', label: t('knowledgeBase.channelYuque') }; if (ch === 'confluence') return { icon: 'cloud-download', label: t('knowledgeBase.channelConfluence') }; if (ch === 'gitlab') return { icon: 'cloud-download', label: t('knowledgeBase.channelGitLab') }; + if (ch === 'seafile') return { icon: 'cloud-download', label: t('knowledgeBase.channelSeafile') }; 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') }; diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts index e6002c92..0ada5970 100644 --- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts +++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts @@ -18,18 +18,29 @@ const compiled = ts.transpileModule(script, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, }).outputText +// Lets un-awaited API calls (e.g. loadResources fired by nextStep) settle. +const flush = async () => { + await new Promise(resolve => setImmediate(resolve)) + await nextTick() +} + async function fixture({ configured = true, create = false, type = 'gitlab', settings = { projects: [{ project_id: '123', paths: [] }] }, + resources = [], + dataSource = null, }: { configured?: boolean create?: boolean type?: string settings?: Record + resources?: any[] + dataSource?: any } = {}) { const calls: Array<{ method: string; args: any[] }> = [] + const warnings: string[] = [] let storedToken = configured ? 'expired-token' : '' const api = { async validateCredentials(type: string, credentials: Record) { @@ -48,10 +59,23 @@ async function fixture({ calls.push({ method: 'putDataSourceCredentials', args: [id, { ...credentials }] }) storedToken = credentials.access_token }, + async createDataSource(data: any) { + calls.push({ method: 'createDataSource', args: [JSON.parse(JSON.stringify(data))] }) + return { data: { id: 'source-temp' } } + }, + // Lazy picker: the first call lists roots, later calls list one level. + async listResources(id: string, parentId?: string) { + calls.push({ method: 'listResources', args: [id, parentId] }) + return { data: resources.filter(r => (parentId ? r.parent_id === parentId : !r.parent_id)) } + }, + async resolveResourceAncestors(id: string, ids: string[]) { + calls.push({ method: 'resolveResourceAncestors', args: [id, ids] }) + return { data: { ancestors: [] } } + }, } const props = reactive({ visible: false, kbId: 'kb-one', - dataSource: create ? null : { + dataSource: create ? null : dataSource || { id: 'source-one', name: 'GitLab', type, credentials: { credentials: { configured } }, config: { resource_ids: [], settings }, @@ -65,7 +89,7 @@ async function fixture({ require(name: string) { if (name === 'vue') return require('vue') if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) } - if (name === 'tdesign-vue-next') return { MessagePlugin: { warning() {}, success() {}, error() {} } } + if (name === 'tdesign-vue-next') return { MessagePlugin: { warning(msg: string) { warnings.push(msg) }, success() {}, error() {} } } if (name === '@/api/datasource') return api return { default: {} } }, @@ -89,7 +113,7 @@ async function fixture({ vm.form.config.credentials = { base_url: 'https://gitlab.example.com', access_token: token } await nextTick() } - return { vm, calls, replace, storedToken: () => storedToken, close: () => app.unmount() } + return { vm, calls, warnings, replace, storedToken: () => storedToken, close: () => app.unmount() } } test('rotated GitLab credentials are tested without updating the saved data source', async () => { @@ -168,6 +192,117 @@ test('new GitLab data sources continue to test credentials without persistence', } finally { f.close() } }) +const seafileRepoA = '0f1e2d3c-4b5a-4968-8776-655443322110' +const seafileRepoB = 'ffffffff-0000-4000-8000-000000000001' + +// A lazy Seafile tree: two libraries, one with a folder that holds a file. +const seafileResources = [ + { external_id: `${seafileRepoA}:/`, name: 'Docs', type: 'library', has_children: true }, + { external_id: `${seafileRepoB}:/`, name: 'Design', type: 'library', has_children: true }, + { external_id: `${seafileRepoA}:/guides`, name: 'guides', type: 'directory', parent_id: `${seafileRepoA}:/`, has_children: true }, + { external_id: `${seafileRepoA}:/guides/a.pdf`, name: 'a.pdf', type: 'file', parent_id: `${seafileRepoA}:/guides`, has_children: false }, +] + +// Opens a new Seafile data source on the picker step with the roots listed. +async function seafileFixture(resources = seafileResources) { + const f = await fixture({ create: true, resources }) + f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'seafile')) + f.vm.form.config.credentials = { base_url: 'https://seafile.example.com', api_token: 'rotated-token' } + f.vm.testResult = 'success' + await f.vm.nextStep() + await flush() + return f +} + +test('Seafile picker lists libraries lazily and shows the library icon', async () => { + const f = await seafileFixture() + try { + assert.equal(f.vm.step, 2) + assert.deepEqual(f.calls.map(call => call.method), ['createDataSource', 'listResources']) + assert.deepEqual([...f.vm.resources].map((r: any) => r.external_id), [`${seafileRepoA}:/`, `${seafileRepoB}:/`]) + assert.equal(f.vm.resourceIconName(f.vm.resources[0]), 'root-list') + assert.equal(f.vm.resourceTypeLabel('library'), 'datasource.resourceType.library') + await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/`) + await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/guides`) + assert.equal(f.vm.resourceIconName(f.vm.resources.find((r: any) => r.name === 'guides')), 'folder') + assert.equal(f.vm.resourceIconName(f.vm.resources.find((r: any) => r.name === 'a.pdf')), 'file') + } finally { f.close() } +}) + +test('Seafile selection stays within one library until it is cleared', async () => { + const f = await seafileFixture() + try { + await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/`) + await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/guides`) + f.vm.toggleResource(`${seafileRepoA}:/guides/a.pdf`) + f.vm.toggleResource(`${seafileRepoB}:/`) + assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoA}:/guides/a.pdf`]) + assert.deepEqual(f.warnings, ['datasource.seafile.singleLibraryOnly']) + // Clearing library A first lets the user pick library B before saving. + f.vm.toggleResource(`${seafileRepoA}:/guides/a.pdf`) + f.vm.toggleResource(`${seafileRepoB}:/`) + assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoB}:/`]) + assert.equal(f.warnings.length, 1) + } finally { f.close() } +}) + +test('Seafile requires a selection before the strategy step', async () => { + const f = await seafileFixture() + try { + await f.vm.nextStep() + assert.equal(f.vm.step, 2) + assert.deepEqual(f.warnings, ['datasource.seafile.selectionRequired']) + f.vm.toggleResource(`${seafileRepoA}:/`) + await f.vm.nextStep() + assert.equal(f.vm.step, 3) + } finally { f.close() } +}) + +test('a vanished saved Seafile selection is cleared by unchecking its library', async () => { + const f = await fixture({ resources: seafileResources, dataSource: { + id: 'source-one', name: 'Seafile', type: 'seafile', + credentials: { credentials: { configured: true } }, + config: { resource_ids: [`${seafileRepoA}:/guides/vanished.pdf`], settings: {} }, + sync_schedule: '0 0 */6 * * *', sync_mode: 'incremental', + conflict_strategy: 'overwrite', sync_deletions: true, + } }) + try { + await f.vm.nextStep() + await flush() + assert.equal(f.vm.step, 2) + assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoA}:/guides/vanished.pdf`]) + // The stale path is invisible, so library B is refused until A is cleared. + f.vm.toggleResource(`${seafileRepoB}:/`) + assert.deepEqual(f.warnings, ['datasource.seafile.singleLibraryOnly']) + // Checking then unchecking library A sweeps the stale path with it. + f.vm.toggleResource(`${seafileRepoA}:/`) + f.vm.toggleResource(`${seafileRepoA}:/`) + assert.deepEqual([...f.vm.selectedResourceIds], []) + f.vm.toggleResource(`${seafileRepoB}:/`) + assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoB}:/`]) + } finally { f.close() } +}) + +test('the single-library guard leaves Feishu and Lark Drive selections alone', async () => { + for (const type of ['feishu_drive', 'lark_drive']) { + const f = await fixture({ create: true }) + try { + f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === type)) + // Drive IDs are "folderToken:fileToken"; roots under two folders must + // both stay selectable. + f.vm.resources = [ + { external_id: 'folderA:fileA', name: 'A', type: 'file', has_children: false }, + { external_id: 'folderB:fileB', name: 'B', type: 'file', has_children: false }, + ] + await nextTick() + f.vm.toggleResource('folderA:fileA') + f.vm.toggleResource('folderB:fileB') + assert.deepEqual([...f.vm.selectedResourceIds].sort(), ['folderA:fileA', 'folderB:fileB'], type) + assert.deepEqual(f.warnings, [], type) + } finally { f.close() } + } +}) + test('a new Yuque data source adopts the TOC folder layout, but not the filter', async () => { const f = await fixture({ create: true }) try { diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue index 27249eaa..02b73be3 100644 --- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue +++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue @@ -253,6 +253,18 @@ const driveFolderTokenError = ref('') const driveRootLoaded = ref(false) const isDriveConnector = (type: string) => type === 'feishu_drive' || type === 'lark_drive' const isGitLabConnector = (type: string) => type === 'gitlab' +// Seafile resource IDs are ":"; one data source syncs one +// library, so the picker refuses a selection that spans two libraries. +const isSeafileConnector = (type: string) => type === 'seafile' +const seafileLibraryOf = (id: string) => id.split(':')[0] +// Seafile IDs encode the hierarchy, so a saved selection whose node has +// vanished from the tree can still be recognised as living under `parent`. +function seafileWithin(id: string, parent: string): boolean { + const [repo, path] = [seafileLibraryOf(id), id.slice(id.indexOf(':') + 1)] + const parentPath = parent.slice(parent.indexOf(':') + 1) + return repo === seafileLibraryOf(parent) && + (parentPath === '/' || path === parentPath || path.startsWith(parentPath + '/')) +} interface GitLabProjectInput { project_id: string; ref: string; pathsText: string } const gitlabProjects = ref([]) @@ -728,6 +740,14 @@ const connectorDefs = computed(() => [ { key: 'access_token', labelKey: 'datasource.gitlab.accessToken', placeholder: '', secret: true }, ], }, + { + type: 'seafile', available: true, docUrl: 'https://help.seafile.com/', + permissionDocUrl: '', permissionPageUrl: '', requiredPermissions: [], + fields: [ + { key: 'base_url', labelKey: 'datasource.seafile.baseUrl', placeholder: 'https://seafile.example.com' }, + { key: 'api_token', labelKey: 'datasource.seafile.apiToken', placeholder: '', secret: true, hintKey: 'datasource.seafile.apiTokenHint' }, + ], + }, ]) @@ -1069,10 +1089,22 @@ function uncheckResource(id: string, cover: Set) { function toggleResource(id: string) { const cover = new Set(selectedResourceIds.value) + const seafile = isSeafileConnector(form.value.type) if ((checkStates.value.get(id) || 'unchecked') === 'unchecked') { checkResource(id, cover) } else { uncheckResource(id, cover) + // Unchecking also drops saved Seafile selections below this node that + // the tree no longer lists; otherwise they could never be cleared. + if (seafile) { + for (const sel of [...cover]) { + if (seafileWithin(sel, id)) cover.delete(sel) + } + } + } + if (seafile && new Set([...cover].map(seafileLibraryOf)).size > 1) { + MessagePlugin.warning(t('datasource.seafile.singleLibraryOnly')) + return } selectedResourceIds.value = [...cover] } @@ -1128,6 +1160,11 @@ async function nextStep() { return } } + // Seafile has no "whole account" scope: the backend rejects an empty selection. + if (step.value === 2 && isSeafileConnector(form.value.type) && selectedResourceIds.value.length === 0) { + MessagePlugin.warning(t('datasource.seafile.selectionRequired')) + return + } step.value++ if (step.value === 2) { // Drive connectors need a user-supplied folder_token before listing. @@ -1272,6 +1309,9 @@ const selectedResourceCount = computed(() => { const hasExpandableNodes = computed(() => resources.value.some(r => r.has_children)) function resourceIconName(r: Resource): string { + // Seafile libraries expand like folders but are the top-level unit a data + // source binds to, so they keep the root icon. + if (r.type === 'library') return 'root-list' if (r.has_children) return 'folder' switch (r.type) { case 'wiki_space': @@ -1302,6 +1342,7 @@ const resourceTypeLabelMap: Record = { wiki_space: 'datasource.resourceType.wikiSpace', doc_category: 'datasource.resourceType.docCategory', book: 'datasource.resourceType.book', + library: 'datasource.resourceType.library', } function resourceTypeLabel(type: string): string { diff --git a/frontend/src/views/knowledge/settings/datasourceIcons.ts b/frontend/src/views/knowledge/settings/datasourceIcons.ts index 90620b25..5ebea7b8 100644 --- a/frontend/src/views/knowledge/settings/datasourceIcons.ts +++ b/frontend/src/views/knowledge/settings/datasourceIcons.ts @@ -7,6 +7,7 @@ import rssIcon from '@/assets/img/datasource-rss.svg' import confluenceIcon from '@/assets/img/datasource-confluence.svg' import dingtalkIcon from '@/assets/img/im/dingtalk.svg' import imaIcon from '@/assets/img/datasource-ima.png' +import seafileIcon from '@/assets/img/datasource-seafile.png' export const datasourceIconMap: Record = { feishu: feishuIcon, @@ -21,6 +22,7 @@ export const datasourceIconMap: Record = { confluence: confluenceIcon, gitlab: gitlabIcon, ima: imaIcon, + seafile: seafileIcon, } export function getDatasourceIconUrl(type: string): string | undefined { diff --git a/internal/application/service/datasource_seafile_test.go b/internal/application/service/datasource_seafile_test.go new file mode 100644 index 00000000..2a72ef79 --- /dev/null +++ b/internal/application/service/datasource_seafile_test.go @@ -0,0 +1,415 @@ +package service + +import ( + "context" + "crypto/sha1" + "encoding/json" + "fmt" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/url" + "path" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + seafileConnector "github.com/Tencent/WeKnora/internal/datasource/connector/seafile" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/hibiken/asynq" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + seafileTestRepo = "0f1e2d3c-4b5a-4968-8776-655443322110" + seafileTestOtherRepo = "ffffffff-0000-4000-8000-000000000001" +) + +// seafileFakeServer is the smallest Seafile 10.0.1 stand-in the streaming +// service path needs: one library, one directory level and a separate +// fileserver. Directories are implied by the file paths. +type seafileFakeServer struct { + api, fileserver *httptest.Server + + mu sync.Mutex + files map[string][]byte // absolute path → body + forbidden map[string]bool // paths whose download link answers 403 + requests int +} + +func newSeafileFakeServer(t *testing.T) *seafileFakeServer { + t.Helper() + f := &seafileFakeServer{files: map[string][]byte{}, forbidden: map[string]bool{}} + f.fileserver = httptest.NewServer(http.HandlerFunc(f.handleDownload)) + t.Cleanup(f.fileserver.Close) + f.api = httptest.NewServer(http.HandlerFunc(f.handleAPI)) + t.Cleanup(f.api.Close) + return f +} + +func (f *seafileFakeServer) requestCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.requests +} + +func (f *seafileFakeServer) handleAPI(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + f.requests++ + w.Header().Set("Content-Type", "application/json") + p := r.URL.Query().Get("p") + switch r.URL.Path { + case "/api2/repos/": + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "id": seafileTestRepo, "name": "Library", "type": "repo", "encrypted": false, "permission": "rw", + }}) + case "/api2/repos/" + seafileTestRepo + "/dir/": + entries, ok := f.listDir(p) + if !ok { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(entries) + case "/api2/repos/" + seafileTestRepo + "/file/": + body, ok := f.files[p] + switch { + case !ok: + http.NotFound(w, r) + case f.forbidden[p]: + w.WriteHeader(http.StatusForbidden) + default: + w.Header().Set("oid", fmt.Sprintf("%x", sha1.Sum(body))) + _ = json.NewEncoder(w).Encode(f.fileserver.URL + "/f/" + url.PathEscape(p)) + } + default: + http.NotFound(w, r) + } +} + +// listDir renders the direct children of dir; dirs carry no size key. +func (f *seafileFakeServer) listDir(dir string) ([]map[string]any, bool) { + entries := make([]map[string]any, 0) + children := map[string]bool{} + found := dir == "/" + for p, body := range f.files { + if path.Dir(p) == dir { + found = true + entries = append(entries, map[string]any{ + "id": fmt.Sprintf("%x", sha1.Sum(body)), "name": path.Base(p), "type": "file", + "mtime": 1, "size": len(body), "permission": "rw", + }) + continue + } + if strings.HasPrefix(p, strings.TrimSuffix(dir, "/")+"/") { + found = true + rest := strings.TrimPrefix(p, strings.TrimSuffix(dir, "/")+"/") + children[strings.SplitN(rest, "/", 2)[0]] = true + } + } + for name := range children { + entries = append(entries, map[string]any{ + "id": "dir-" + name, "name": name, "type": "dir", "mtime": 1, "permission": "rw", + }) + } + sort.Slice(entries, func(i, j int) bool { return entries[i]["name"].(string) < entries[j]["name"].(string) }) + return entries, found +} + +func (f *seafileFakeServer) handleDownload(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + f.requests++ + p, err := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/f/")) + body, ok := f.files[p] + if err != nil || !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + _, _ = w.Write(body) +} + +// seafileKnowledgeRepo keys live knowledge by data source and external ID so +// deletion scoping is observable. +type seafileKnowledgeRepo struct { + interfaces.KnowledgeRepository + live map[string]*types.Knowledge + hardDeleted []string +} + +func (r *seafileKnowledgeRepo) FindByDataSourceExternalID( + _ context.Context, _ uint64, _, dataSourceID, externalID string, +) (*types.Knowledge, error) { + return r.live[dataSourceID+"|"+externalID], nil +} + +func (r *seafileKnowledgeRepo) HardDeleteKnowledge(_ context.Context, _ uint64, id string) error { + r.hardDeleted = append(r.hardDeleted, id) + return nil +} + +type seafileCreatedFile struct { + fileName string + channel string + metadata map[string]string +} + +// seafileKnowledgeService records what the ingest path hands to the +// knowledge base. +type seafileKnowledgeService struct { + interfaces.KnowledgeService + repo *seafileKnowledgeRepo + created []seafileCreatedFile + deleted []string +} + +func (k *seafileKnowledgeService) GetRepository() interfaces.KnowledgeRepository { return k.repo } + +func (k *seafileKnowledgeService) DeleteKnowledge(_ context.Context, id string) error { + k.deleted = append(k.deleted, id) + return nil +} + +func (k *seafileKnowledgeService) CreateKnowledgeFromFile( + _ context.Context, _ string, _ *multipart.FileHeader, metadata map[string]string, + _ *bool, customFileName string, _ []string, channel string, _ *types.KnowledgeProcessOverrides, +) (*types.Knowledge, error) { + k.created = append(k.created, seafileCreatedFile{fileName: customFileName, channel: channel, metadata: metadata}) + return &types.Knowledge{ID: "created-" + customFileName}, nil +} + +// seafileSyncHarness wires the real DataSourceService streaming path to the +// real Seafile connector against the fake server. +type seafileSyncHarness struct { + server *seafileFakeServer + ds *types.DataSource + syncLog *types.SyncLog + syncLogRepo *processSyncSyncLogRepo + repo *seafileKnowledgeRepo + knowledge *seafileKnowledgeService + svc *DataSourceService +} + +func newSeafileSyncHarness(t *testing.T, syncDeletions bool, cursor *types.SyncCursor) *seafileSyncHarness { + t.Helper() + withSSRFWhitelist(t, "127.0.0.1,localhost") + server := newSeafileFakeServer(t) + configJSON, err := (&types.DataSourceConfig{ + Type: types.ConnectorTypeSeafile, + Credentials: map[string]any{"base_url": server.api.URL, "api_token": "secret-token"}, + ResourceIDs: []string{seafileTestRepo + ":/docs"}, + }).ToJSON() + require.NoError(t, err) + + ds := &types.DataSource{ + ID: "ds-seafile", TenantID: 1, KnowledgeBaseID: "kb-1", Name: "Seafile", + Type: types.ConnectorTypeSeafile, Config: configJSON, + SyncMode: types.SyncModeIncremental, Status: types.DataSourceStatusActive, + SyncDeletions: syncDeletions, + } + if cursor != nil { + ds.LastSyncCursor, err = cursor.ToJSON() + require.NoError(t, err) + } + syncLog := &types.SyncLog{ + ID: "log-seafile", DataSourceID: ds.ID, TenantID: ds.TenantID, + Status: types.SyncLogStatusRunning, StartedAt: time.Now().UTC(), + } + repo := &seafileKnowledgeRepo{live: map[string]*types.Knowledge{}} + knowledge := &seafileKnowledgeService{repo: repo} + syncLogRepo := &processSyncSyncLogRepo{logs: map[string]*types.SyncLog{syncLog.ID: syncLog}} + registry := datasource.NewConnectorRegistry() + require.NoError(t, registry.Register(seafileConnector.NewConnector())) + kb := &types.KnowledgeBase{ID: ds.KnowledgeBaseID, TenantID: ds.TenantID} + + return &seafileSyncHarness{ + server: server, ds: ds, syncLog: syncLog, syncLogRepo: syncLogRepo, repo: repo, knowledge: knowledge, + svc: &DataSourceService{ + dsRepo: newKBDeleteDSRepo(ds.KnowledgeBaseID, ds), + syncLogRepo: syncLogRepo, + knowledgeService: knowledge, + kbService: &processSyncKBService{kb: kb}, + connectorRegistry: registry, + tenantRepo: &processSyncTenantRepo{tenant: &types.Tenant{ID: ds.TenantID}}, + tagService: &processSyncTagService{}, + }, + } +} + +func (h *seafileSyncHarness) run(t *testing.T, forceFull bool) (*types.SyncLog, error) { + t.Helper() + payload, err := json.Marshal(types.DataSourceSyncPayload{ + DataSourceID: h.ds.ID, TenantID: h.ds.TenantID, SyncLogID: h.syncLog.ID, ForceFull: forceFull, + }) + require.NoError(t, err) + err = h.svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload)) + return h.syncLogRepo.logs[h.syncLog.ID], err +} + +// cursorFiles decodes the persisted connector cursor's file map. +func (h *seafileSyncHarness) cursorFiles(t *testing.T) map[string]string { + t.Helper() + cur, err := h.ds.ParseSyncCursor() + require.NoError(t, err) + require.NotNil(t, cur) + raw, err := json.Marshal(cur.ConnectorCursor["files"]) + require.NoError(t, err) + files := map[string]string{} + require.NoError(t, json.Unmarshal(raw, &files)) + return files +} + +func seafileCursor(repoID string, files map[string]string) *types.SyncCursor { + return &types.SyncCursor{ConnectorCursor: map[string]any{ + "schema_version": 1, "repo_id": repoID, "repo_name": "Library", "files": files, + }} +} + +func seafileExternalID(p string) string { return "seafile:" + seafileTestRepo + ":" + p } + +// A connector error item reaches the sync log as a coded SyncItemError with +// the HTTP status as parameter, and the run ends partial rather than failed. +func TestProcessSync_SeafileErrorItemBecomesSyncItemError(t *testing.T) { + h := newSeafileSyncHarness(t, false, nil) + h.server.files["/docs/ok.pdf"] = []byte("ok") + h.server.files["/docs/bad.pdf"] = []byte("bad") + h.server.forbidden["/docs/bad.pdf"] = true + + log, err := h.run(t, false) + require.NoError(t, err) + assert.Equal(t, types.SyncLogStatusPartial, log.Status) + assert.Equal(t, 1, log.ItemsCreated) + assert.Equal(t, 1, log.ItemsFailed) + result, err := log.ParseResult() + require.NoError(t, err) + require.Len(t, result.Errors, 1) + assert.Equal(t, "seafile_permission_denied", result.Errors[0].Code) + assert.Equal(t, map[string]string{"code": "403"}, result.Errors[0].Params) + assert.Equal(t, "Library/docs/bad.pdf", result.Errors[0].Title) + assert.NotContains(t, result.Errors[0].Message, "secret-token") + + files := h.cursorFiles(t) + assert.NotEmpty(t, files["/docs/ok.pdf"]) + _, known := files["/docs/bad.pdf"] + assert.False(t, known, "a path that never synced must not enter the cursor") +} + +// Same bytes under two paths are two documents: each reaches the knowledge +// base with its own external ID under the Seafile channel, whose duplicate +// check is scoped by source identity. +func TestProcessSync_SeafileSameContentDifferentPathsStayIndependent(t *testing.T) { + h := newSeafileSyncHarness(t, false, nil) + h.server.files["/docs/a.pdf"] = []byte("same bytes") + h.server.files["/docs/sub/b.pdf"] = []byte("same bytes") + + log, err := h.run(t, false) + require.NoError(t, err) + assert.Equal(t, types.SyncLogStatusSuccess, log.Status) + assert.Equal(t, 2, log.ItemsCreated) + require.Len(t, h.knowledge.created, 2) + assert.Equal(t, "Library/docs/a.pdf", h.knowledge.created[0].fileName) + assert.Equal(t, "Library/docs/sub/b.pdf", h.knowledge.created[1].fileName) + for _, created := range h.knowledge.created { + assert.Equal(t, types.ChannelSeafile, created.channel) + assert.Equal(t, h.ds.ID, created.metadata["datasource_id"]) + assert.Equal(t, seafileTestRepo+":/", created.metadata["source_resource_id"]) + assert.True(t, usesSourceIdentityDuplicateCheck(created.channel)) + } + assert.NotEqual(t, h.knowledge.created[0].metadata["external_id"], h.knowledge.created[1].metadata["external_id"]) + assert.Len(t, h.cursorFiles(t), 2) +} + +// Deletions follow the data source's SyncDeletions switch and only touch the +// knowledge owned by this data source, even when another data source +// synced the same Seafile path. +func TestProcessSync_SeafileDeletionsGatedAndScoped(t *testing.T) { + for _, syncDeletions := range []bool{true, false} { + t.Run(fmt.Sprintf("sync_deletions=%v", syncDeletions), func(t *testing.T) { + gone := seafileExternalID("/docs/gone.pdf") + h := newSeafileSyncHarness(t, syncDeletions, seafileCursor(seafileTestRepo, map[string]string{ + "/docs/gone.pdf": "o:old|m:1|s:4", + })) + // The selected directory must still exist; only the tracked file is gone. + h.server.files["/docs/keep.pdf"] = []byte("keep") + h.repo.live["ds-seafile|"+gone] = &types.Knowledge{ID: "knowledge-mine"} + h.repo.live["ds-other|"+gone] = &types.Knowledge{ID: "knowledge-other"} + + log, err := h.run(t, false) + require.NoError(t, err) + assert.Equal(t, types.SyncLogStatusSuccess, log.Status) + assert.Equal(t, 1, log.ItemsCreated) + if syncDeletions { + assert.Equal(t, 1, log.ItemsDeleted) + assert.Equal(t, []string{"knowledge-mine"}, h.knowledge.deleted) + assert.Equal(t, []string{"knowledge-mine"}, h.repo.hardDeleted) + } else { + assert.Equal(t, 0, log.ItemsDeleted) + assert.Empty(t, h.knowledge.deleted) + assert.Empty(t, h.repo.hardDeleted) + } + // The connector forgets the path either way; a later re-enable + // cannot resurrect the deletion, matching the other connectors. + assert.Equal(t, []string{"/docs/keep.pdf"}, keysOf(h.cursorFiles(t))) + }) + } +} + +// A forced full run must receive the stored cursor as its deletion baseline: +// a file present in that cursor but gone from Seafile is deleted even though +// every surviving file is re-downloaded. +func TestProcessSync_SeafileFullStreamReceivesStoredCursor(t *testing.T) { + gone := seafileExternalID("/docs/gone.pdf") + h := newSeafileSyncHarness(t, true, seafileCursor(seafileTestRepo, map[string]string{ + "/docs/gone.pdf": "o:old|m:1|s:4", + "/docs/keep.pdf": "o:stale|m:1|s:4", + })) + h.server.files["/docs/keep.pdf"] = []byte("keep") + h.repo.live["ds-seafile|"+gone] = &types.Knowledge{ID: "knowledge-gone"} + + log, err := h.run(t, true) + require.NoError(t, err) + assert.Equal(t, types.SyncLogStatusSuccess, log.Status) + assert.Equal(t, 1, log.ItemsDeleted) + assert.Equal(t, 1, log.ItemsCreated) + assert.Equal(t, []string{"knowledge-gone"}, h.knowledge.deleted) + cur, err := h.ds.ParseSyncCursor() + require.NoError(t, err) + assert.Nil(t, cur.ConnectorCursor["full_sync"], "completed full sync must clear its state") + assert.Equal(t, []string{"/docs/keep.pdf"}, keysOf(h.cursorFiles(t))) +} + +// Pointing an already synced data source at another library fails before any +// request and leaves the stored cursor untouched. +func TestProcessSync_SeafileLibraryMismatchFailsWithoutTouchingCursor(t *testing.T) { + h := newSeafileSyncHarness(t, true, seafileCursor(seafileTestOtherRepo, map[string]string{ + "/docs/a.pdf": "o:a|m:1|s:1", + })) + before := string(h.ds.LastSyncCursor) + + log, err := h.run(t, false) + require.Error(t, err) + assert.ErrorIs(t, err, datasource.ErrInvalidConfig) + assert.Equal(t, types.SyncLogStatusFailed, log.Status) + assert.Contains(t, log.ErrorMessage, "Library") + assert.Equal(t, types.DataSourceStatusError, h.ds.Status) + assert.Equal(t, before, string(h.ds.LastSyncCursor)) + assert.Zero(t, h.server.requestCount()) + assert.Empty(t, h.knowledge.created) + assert.Empty(t, h.knowledge.deleted) +} + +func keysOf(m map[string]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/internal/application/service/knowledge_create.go b/internal/application/service/knowledge_create.go index 5b1212a4..f34c26c8 100644 --- a/internal/application/service/knowledge_create.go +++ b/internal/application/service/knowledge_create.go @@ -1168,7 +1168,7 @@ func (s *knowledgeService) markKnowledgeEnqueueFailed(ctx context.Context, knowl func usesSourceIdentityDuplicateCheck(channel string) bool { switch channel { - case types.ConnectorTypeGitLab, types.ChannelConfluence: + case types.ConnectorTypeGitLab, types.ChannelConfluence, types.ChannelSeafile: return true default: return false diff --git a/internal/application/service/knowledge_util.go b/internal/application/service/knowledge_util.go index e520edbc..1bb5eaa4 100644 --- a/internal/application/service/knowledge_util.go +++ b/internal/application/service/knowledge_util.go @@ -25,39 +25,23 @@ import ( // unknownFileType is returned by getFileType when a name carries no extension. const unknownFileType = "unknown" -// supportedImportFileExtensions is the single source of truth for extensions -// accepted by every knowledge import path: direct upload, file-URL download, -// and the worker's post-download re-check. Keeping one set avoids the drift -// that let direct upload accept xlsx while URL import rejected it (#2447). -var supportedImportFileExtensions = map[string]struct{}{ - "pdf": {}, "txt": {}, "docx": {}, "doc": {}, "epub": {}, - "html": {}, "htm": {}, "mhtml": {}, "md": {}, "markdown": {}, - "xmind": {}, - "png": {}, "jpg": {}, "jpeg": {}, "gif": {}, - "csv": {}, "xlsx": {}, "xls": {}, "pptx": {}, "ppt": {}, "json": {}, - "mp3": {}, "wav": {}, "m4a": {}, "flac": {}, "ogg": {}, -} - // dataTableFileExtensions are the spreadsheet formats that get an extra // table-summary task after their document-process task. var dataTableFileExtensions = map[string]struct{}{ "csv": {}, "xlsx": {}, "xls": {}, } -// normalizeFileExtension lowercases an extension and strips a leading dot so -// callers can pass either "xlsx", ".XLSX", or a raw user-supplied file_type. +// normalizeFileExtension delegates to the shared helper; kept so the many +// package-private call sites stay untouched. func normalizeFileExtension(ext string) string { - return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(ext), ".")) + return secutils.NormalizeImportExtension(ext) } -// isSupportedImportExtension reports whether a bare extension can be imported. +// isSupportedImportExtension delegates to the shared set in internal/utils so +// data source connectors filter on the same extensions as direct upload and +// URL import. The "unknown" sentinel from getFileType is not in the set. func isSupportedImportExtension(ext string) bool { - ext = normalizeFileExtension(ext) - if ext == "" || ext == unknownFileType { - return false - } - _, ok := supportedImportFileExtensions[ext] - return ok + return secutils.IsSupportedImportExtension(ext) } // isValidFileType checks if a filename's extension is supported for import. diff --git a/internal/application/service/knowledge_util_filetype_test.go b/internal/application/service/knowledge_util_filetype_test.go index 5ab482a3..1ef96c77 100644 --- a/internal/application/service/knowledge_util_filetype_test.go +++ b/internal/application/service/knowledge_util_filetype_test.go @@ -1,6 +1,11 @@ package service -import "testing" +import ( + "slices" + "testing" + + secutils "github.com/Tencent/WeKnora/internal/utils" +) func TestIsValidFileTypeHTML(t *testing.T) { tests := []struct { @@ -57,8 +62,18 @@ func TestIsSupportedImportExtension(t *testing.T) { // Direct upload and URL import must agree on the accepted extension set, // otherwise #2447 (xlsx accepted on upload, rejected on URL import) regresses. +// The set is pinned so moving it to internal/utils cannot silently change it. func TestImportExtensionSetIsSharedAcrossPaths(t *testing.T) { - for ext := range supportedImportFileExtensions { + want := []string{ + "csv", "doc", "docx", "epub", "flac", "gif", "htm", "html", "jpeg", "jpg", + "json", "m4a", "markdown", "md", "mhtml", "mp3", "ogg", "pdf", "png", "ppt", + "pptx", "txt", "wav", "xls", "xlsx", "xmind", + } + exts := secutils.SupportedImportExtensions() + if !slices.Equal(exts, want) { + t.Fatalf("SupportedImportExtensions() = %v, want %v", exts, want) + } + for _, ext := range exts { if !isValidFileType("file." + ext) { t.Errorf("isValidFileType rejects supported extension %q", ext) } diff --git a/internal/container/container.go b/internal/container/container.go index 37d87ba3..f5a26ff9 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -68,6 +68,7 @@ import ( 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" + seafileConnector "github.com/Tencent/WeKnora/internal/datasource/connector/seafile" yuqueConnector "github.com/Tencent/WeKnora/internal/datasource/connector/yuque" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/handler" @@ -1882,6 +1883,9 @@ func initConnectorRegistry() (*datasource.ConnectorRegistry, error) { if err := registry.Register(gitlabConnector.NewConnector()); err != nil { errs = errors.Join(errs, fmt.Errorf("register gitlab connector: %w", err)) } + if err := registry.Register(seafileConnector.NewConnector()); err != nil { + errs = errors.Join(errs, fmt.Errorf("register seafile connector: %w", err)) + } // Future connectors will be registered here: // if err := registry.Register(githubConnector.NewConnector()); err != nil { ... } diff --git a/internal/container/datasource_registry_test.go b/internal/container/datasource_registry_test.go index afb94bba..0ffc3306 100644 --- a/internal/container/datasource_registry_test.go +++ b/internal/container/datasource_registry_test.go @@ -3,6 +3,7 @@ package container import ( "testing" + "github.com/Tencent/WeKnora/internal/datasource" "github.com/Tencent/WeKnora/internal/types" ) @@ -19,3 +20,20 @@ func TestConnectorRegistryIncludesDingTalk(t *testing.T) { t.Fatalf("connector.Type() = %q", connector.Type()) } } + +func TestConnectorRegistryIncludesSeafile(t *testing.T) { + registry, err := initConnectorRegistry() + if err != nil { + t.Fatalf("initConnectorRegistry() error = %v", err) + } + connector, err := registry.Get(types.ConnectorTypeSeafile) + if err != nil { + t.Fatalf("Seafile connector is not registered: %v", err) + } + if connector.Type() != types.ConnectorTypeSeafile { + t.Fatalf("connector.Type() = %q", connector.Type()) + } + if _, ok := connector.(datasource.FullStreamingConnector); !ok { + t.Fatal("Seafile connector must implement datasource.FullStreamingConnector") + } +} diff --git a/internal/datasource/connector.go b/internal/datasource/connector.go index 67568c4c..0a8d8b85 100644 --- a/internal/datasource/connector.go +++ b/internal/datasource/connector.go @@ -310,6 +310,14 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{ AuthType: "token", Capabilities: []string{"incremental", "hierarchical"}, }, + types.ConnectorTypeSeafile: { + Type: types.ConnectorTypeSeafile, + Name: "Seafile", + Description: "Sync folders and files from Seafile libraries", + Priority: 13, + AuthType: "token", + Capabilities: []string{"incremental", "hierarchical", "deletion_sync"}, + }, } // ListAvailableConnectors returns all available connector metadata diff --git a/internal/datasource/connector/seafile/client.go b/internal/datasource/connector/seafile/client.go new file mode 100644 index 00000000..07a7165b --- /dev/null +++ b/internal/datasource/connector/seafile/client.go @@ -0,0 +1,354 @@ +package seafile + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/utils" +) + +const ( + userAgent = "WeKnora-Seafile-Connector/1.0" + apiTimeout = 30 * time.Second + downloadTimeout = 120 * time.Second + + // maxAttempts is the initial request plus two retries. + maxAttempts = 3 + // maxRetryAfter bounds an honoured Retry-After; anything longer aborts the run. + maxRetryAfter = 60 * time.Second + + listingJSONLimit = int64(32 << 20) + smallJSONLimit = int64(64 << 10) +) + +var ( + errRetryAfterTooLong = errors.New("seafile asked to retry after more than 60 seconds") + errInvalidResponse = errors.New("seafile returned an unexpected response") + errSSRFBlocked = errors.New("seafile download URL was blocked by the SSRF policy") + errTooLarge = errors.New("seafile file exceeds the size limit") + errEmptyFile = errors.New("seafile file is empty") + errSourceChanged = errors.New("seafile file changed while it was being fetched") + + // sleep performs every backoff wait; tests replace it to avoid real waits. + sleep = sleepCtx +) + +// client talks to one Seafile deployment. API requests carry the token; the +// fileserver client never does, and both keep the shared SSRF redirect policy. +type client struct { + baseURL string + token string + api *http.Client + files *http.Client +} + +func newClient(cfg config) *client { + return &client{ + baseURL: cfg.baseURL, + token: cfg.token, + api: datasource.NewConnectorHTTPClient(apiTimeout), + files: datasource.NewConnectorHTTPClient(downloadTimeout), + } +} + +// httpError reports a non-success status. Op is a fixed label, never a URL, +// path or response body, so the message is safe to surface. +type httpError struct { + Op string + Status int + retryAfter string +} + +func (e *httpError) Error() string { return fmt.Sprintf("seafile %s: HTTP %d", e.Op, e.Status) } +func (e *httpError) Unwrap() error { return datasource.ErrFetchFailed } + +// statusOf returns the HTTP status carried by err, or 0. +func statusOf(err error) int { + var statusErr *httpError + if errors.As(err, &statusErr) { + return statusErr.Status + } + return 0 +} + +// transportError hides the request URL (a *url.Error would echo a signed +// download link) while remembering whether a retry is worthwhile. +type transportError struct { + Op string + transient bool +} + +func (e *transportError) Error() string { return "seafile " + e.Op + ": request failed" } +func (e *transportError) Unwrap() error { return datasource.ErrFetchFailed } + +func invalidResponse(op string) error { + return fmt.Errorf("%w: seafile %s: %w", datasource.ErrFetchFailed, op, errInvalidResponse) +} + +func isTransientNetworkError(err error) bool { + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + return true + } + var opErr *net.OpError + return errors.As(err, &opErr) && opErr.Op == "dial" +} + +func retryableStatus(status int) bool { + return status == http.StatusTooManyRequests || status == http.StatusBadGateway || + status == http.StatusServiceUnavailable || status == http.StatusGatewayTimeout +} + +func backoff(attempt int) time.Duration { + return time.Second << attempt +} + +// retryAfter parses a Retry-After header (delta seconds or HTTP date). Values +// above maxRetryAfter, including unparsable huge numbers, are run-fatal. +func retryAfter(value string, now time.Time) (time.Duration, error) { + value = strings.TrimSpace(value) + if value == "" { + return 0, nil + } + if strings.Trim(value, "0123456789") == "" { + seconds, err := strconv.ParseInt(value, 10, 64) + if err != nil || seconds > int64(maxRetryAfter/time.Second) { + return 0, errRetryAfterTooLong + } + return time.Duration(seconds) * time.Second, nil + } + date, err := http.ParseTime(value) + if err != nil { + return 0, nil + } + if wait := date.Sub(now); wait > maxRetryAfter { + return 0, errRetryAfterTooLong + } else if wait > 0 { + return wait, nil + } + return 0, nil +} + +// get performs a GET with retries on throttling, upstream 5xx and transient +// network errors. authenticated selects the API client and token; otherwise +// the fileserver client is used without credentials and only 200 is accepted. +func (c *client) get( + ctx context.Context, target, op string, authenticated bool, limit int64, +) ([]byte, http.Header, error) { + for attempt := 0; ; attempt++ { + body, headers, err := c.once(ctx, target, op, authenticated, limit) + if err == nil { + return body, headers, nil + } + delay, retry, err := classify(err, attempt) + if !retry || attempt == maxAttempts-1 { + return nil, nil, err + } + if err := sleep(ctx, delay); err != nil { + return nil, nil, err + } + } +} + +// classify decides whether err is worth retrying and how long to wait. +func classify(err error, attempt int) (time.Duration, bool, error) { + var statusErr *httpError + var netErr *transportError + switch { + case errors.As(err, &statusErr): + if !retryableStatus(statusErr.Status) { + return 0, false, err + } + wait, raErr := retryAfter(statusErr.retryAfter, time.Now()) + if raErr != nil { + return 0, false, fmt.Errorf("%w: %w", statusErr, raErr) + } + return max(backoff(attempt), wait), true, err + case errors.As(err, &netErr): + return backoff(attempt), netErr.transient, err + default: + return 0, false, err + } +} + +func (c *client) once( + ctx context.Context, target, op string, authenticated bool, limit int64, +) ([]byte, http.Header, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return nil, nil, invalidResponse(op) + } + req.Header.Set("User-Agent", userAgent) + httpClient := c.files + if authenticated { + httpClient = c.api + req.Header.Set("Authorization", "Token "+c.token) + req.Header.Set("Accept", "application/json") + } + + resp, err := httpClient.Do(req) + if err != nil { + return nil, nil, c.transport(ctx, op, err) + } + defer func() { _ = resp.Body.Close() }() + + ok := resp.StatusCode == http.StatusOK + if authenticated { + ok = resp.StatusCode >= 200 && resp.StatusCode < 300 + } + if !ok { + return nil, nil, &httpError{Op: op, Status: resp.StatusCode, retryAfter: resp.Header.Get("Retry-After")} + } + if !authenticated && resp.ContentLength > limit { + return nil, nil, errTooLarge + } + body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil { + return nil, nil, c.transport(ctx, op, err) + } + if int64(len(body)) > limit { + if authenticated { + return nil, nil, invalidResponse(op) + } + return nil, nil, errTooLarge + } + return body, resp.Header, nil +} + +func (c *client) transport(ctx context.Context, op string, err error) error { + if ctx.Err() != nil { + return ctx.Err() + } + if errors.Is(err, utils.ErrSSRFRedirectBlocked) { + return fmt.Errorf("%w: %w", datasource.ErrFetchFailed, errSSRFBlocked) + } + return &transportError{Op: op, transient: isTransientNetworkError(err)} +} + +func (c *client) getJSON(ctx context.Context, endpoint, op string, limit int64, out any) (http.Header, error) { + body, headers, err := c.get(ctx, c.baseURL+endpoint, op, true, limit) + if err != nil { + return nil, err + } + if err := json.Unmarshal(body, out); err != nil { + return nil, invalidResponse(op) + } + return headers, nil +} + +// credentialError maps 401/403 on account-level endpoints to +// ErrInvalidCredentials. Directory-level 403s are scoping problems and are +// left to the connector. +func credentialError(err error) error { + if status := statusOf(err); status == http.StatusUnauthorized || status == http.StatusForbidden { + return fmt.Errorf("%w: %w", datasource.ErrInvalidCredentials, err) + } + return err +} + +func (c *client) ping(ctx context.Context) error { + var pong string + if _, err := c.getJSON(ctx, "/api2/auth/ping/", "ping", smallJSONLimit, &pong); err != nil { + return credentialError(err) + } + if pong != "pong" { + return invalidResponse("ping") + } + return nil +} + +func (c *client) listRepos(ctx context.Context) ([]repoInfo, error) { + var repos []repoInfo + if _, err := c.getJSON(ctx, "/api2/repos/", "repos", listingJSONLimit, &repos); err != nil { + return nil, credentialError(err) + } + if repos == nil { + return nil, invalidResponse("repos") + } + return repos, nil +} + +func repoEndpoint(repoID, kind string, query url.Values) string { + return "/api2/repos/" + url.PathEscape(repoID) + "/" + kind + "/?" + query.Encode() +} + +// listDir returns one directory level. Non-2xx statuses come back as +// *httpError so the connector can tell 403/404 apart. +func (c *client) listDir(ctx context.Context, repoID, path string) ([]dirent, error) { + var entries []dirent + endpoint := repoEndpoint(repoID, "dir", url.Values{"p": {path}}) + if _, err := c.getJSON(ctx, endpoint, "dir", listingJSONLimit, &entries); err != nil { + return nil, err + } + if entries == nil { + return nil, invalidResponse("dir") + } + return entries, nil +} + +// downloadLink resolves a reusable fileserver URL and the file's object id +// from the response header (empty when the server omits it). +func (c *client) downloadLink(ctx context.Context, repoID, path string) (link, oid string, err error) { + endpoint := repoEndpoint(repoID, "file", url.Values{"p": {path}, "reuse": {"1"}}) + headers, err := c.getJSON(ctx, endpoint, "file", smallJSONLimit, &link) + if err != nil { + return "", "", err + } + if !validDownloadURL(link) { + return "", "", invalidResponse("file") + } + return link, headers.Get("oid"), nil +} + +// validDownloadURL accepts absolute http(s) URLs without userinfo, which Go +// would otherwise turn into a Basic Authorization header. +func validDownloadURL(link string) bool { + u, err := url.Parse(link) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && u.User == nil +} + +// download fetches a fileserver link without credentials. The body must be +// exactly expectedSize bytes and at most limit bytes. +func (c *client) download(ctx context.Context, link string, expectedSize, limit int64) ([]byte, error) { + if !validDownloadURL(link) { + return nil, invalidResponse("download") + } + if err := utils.ValidateURLForSSRF(link); err != nil { + return nil, fmt.Errorf("%w: %w", datasource.ErrFetchFailed, errSSRFBlocked) + } + body, _, err := c.get(ctx, link, "download", false, limit) + if err != nil { + return nil, err + } + if len(body) == 0 { + return nil, errEmptyFile + } + if int64(len(body)) != expectedSize { + return nil, errSourceChanged + } + return body, nil +} + +func sleepCtx(ctx context.Context, d time.Duration) error { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} diff --git a/internal/datasource/connector/seafile/client_test.go b/internal/datasource/connector/seafile/client_test.go new file mode 100644 index 00000000..20ef823a --- /dev/null +++ b/internal/datasource/connector/seafile/client_test.go @@ -0,0 +1,538 @@ +package seafile + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "os" + "slices" + "strings" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/utils" +) + +// noWait replaces the package sleep with a recorder so tests never wait. +func noWait(t *testing.T) *[]time.Duration { + t.Helper() + original := sleep + var waits []time.Duration + sleep = func(ctx context.Context, d time.Duration) error { + waits = append(waits, d) + return ctx.Err() + } + t.Cleanup(func() { sleep = original }) + return &waits +} + +func testClient(t *testing.T) (*fakeSeafile, *client, *[]time.Duration) { + t.Helper() + waits := noWait(t) + f := newFakeSeafile(t) + f.addRepo(testRepoID, "Library", "repo", false) + c := newClient(config{baseURL: f.baseURL(), token: testToken}) + t.Cleanup(c.api.CloseIdleConnections) + t.Cleanup(c.files.CloseIdleConnections) + return f, c, waits +} + +func assertNoCredentials(t *testing.T, requests []fakeRequest) { + t.Helper() + for _, req := range requests { + if req.Headers.Get("Authorization") != "" || req.Headers.Get("Cookie") != "" { + t.Fatal("fileserver received credentials") + } + } +} + +func TestPing(t *testing.T) { + for _, tc := range []struct { + name string + body string + status int + want error + }{ + {name: "pong"}, + {name: "unauthorized", status: 401, want: datasource.ErrInvalidCredentials}, + {name: "forbidden", status: 403, want: datasource.ErrInvalidCredentials}, + {name: "object", body: `{"ok":true}`, want: datasource.ErrFetchFailed}, + {name: "wrong string", body: `"not pong"`, want: datasource.ErrFetchFailed}, + {name: "malformed", body: testToken, want: datasource.ErrFetchFailed}, + {name: "server error", status: 500, want: datasource.ErrFetchFailed}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, waits := testClient(t) + if tc.body != "" { + f.rawBody["ping"] = tc.body + } + if tc.status != 0 { + f.fail("ping", tc.status, 1) + } + err := c.ping(t.Context()) + if !errors.Is(err, tc.want) { + t.Fatalf("ping = %v, want %v", err, tc.want) + } + if err != nil && strings.Contains(err.Error(), testToken) { + t.Fatalf("ping error leaked the token: %v", err) + } + if f.count("ping") != 1 || len(*waits) != 0 { + t.Fatalf("unexpected retries: counts=%v waits=%v", f.counts(), *waits) + } + }) + } +} + +func TestAPIHeadersAndDeploymentPrefix(t *testing.T) { + f, c, _ := testClient(t) + f.prefix = "/seafile" + c.baseURL = f.baseURL() + f.addFile(testRepoID, "/file", []byte("body"), 123) + f.addRepo(otherRepoID, "Encrypted", "srepo", true) + + if c.api.Timeout != apiTimeout || c.files.Timeout != downloadTimeout || + c.api.CheckRedirect == nil || c.files.CheckRedirect == nil { + t.Fatal("clients must come from the shared SSRF-guarded constructor") + } + if err := c.ping(t.Context()); err != nil { + t.Fatal(err) + } + repos, err := c.listRepos(t.Context()) + if err != nil || len(repos) != 2 || !repos[1].Encrypted || repos[1].Type != "srepo" { + t.Fatalf("listRepos = %+v, %v", repos, err) + } + if _, err := c.listDir(t.Context(), testRepoID, "/"); err != nil { + t.Fatal(err) + } + link, oid, err := c.downloadLink(t.Context(), testRepoID, "/file") + if err != nil || oid == "" { + t.Fatalf("downloadLink oid = %q, %v", oid, err) + } + body, err := c.download(t.Context(), link, 4, 4) + if err != nil || string(body) != "body" { + t.Fatalf("download = %q, %v", body, err) + } + for _, key := range []string{"ping", "repos", "dir:/", "file:/file"} { + requests := f.requests(key) + if len(requests) != 1 { + t.Fatalf("%s requests = %d", key, len(requests)) + } + h := requests[0].Headers + if h.Get("Authorization") != "Token "+testToken || h.Get("Accept") != "application/json" || + h.Get("User-Agent") != userAgent { + t.Fatalf("%s missing API headers: %v", key, h) + } + } + assertNoCredentials(t, f.requests("download:/file")) +} + +func TestListReposCredentials(t *testing.T) { + for _, status := range []int{401, 403} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + f, c, waits := testClient(t) + f.fail("repos", status, -1) + _, err := c.listRepos(t.Context()) + if !errors.Is(err, datasource.ErrInvalidCredentials) || statusOf(err) != status || + f.count("repos") != 1 || len(*waits) != 0 { + t.Fatalf("listRepos = %v, counts = %v", err, f.counts()) + } + }) + } +} + +func TestListDirQueryAndOptionalSize(t *testing.T) { + f, c, _ := testClient(t) + f.addDir(testRepoID, "/产品/Z目录") + f.addFile(testRepoID, "/产品/a.pdf", []byte("pdf"), 42) + entries, err := c.listDir(t.Context(), testRepoID, "/产品") + if err != nil || len(entries) != 2 { + t.Fatalf("listDir = %+v, %v", entries, err) + } + if entries[0].Type != "dir" || entries[0].Size != nil || + entries[1].Size == nil || *entries[1].Size != 3 || entries[1].Mtime != 42 { + t.Fatalf("unexpected entries: %+v", entries) + } + if got := f.requests("dir:/产品")[0].RawQuery; got != "p=%2F%E4%BA%A7%E5%93%81" { + t.Fatalf("path encoded incorrectly: %s", got) + } + f.addDir(testRepoID, "/a:%2Fb") + if _, err := c.listDir(t.Context(), testRepoID, "/a:%2Fb"); err != nil { + t.Fatal(err) + } + if got := f.requests("dir:/a:%2Fb")[0].RawQuery; got != "p=%2Fa%3A%252Fb" { + t.Fatalf("literal percent encoded incorrectly: %s", got) + } +} + +func TestListDirRetries(t *testing.T) { + twoWaits := []time.Duration{time.Second, 2 * time.Second} + for _, tc := range []struct { + name string + status int + failures int + retryAfter string + calls int + final int + waits []time.Duration + tooLong bool + }{ + {name: "503 twice", status: 503, failures: 2, calls: 3, waits: twoWaits}, + {name: "503 exhausted", status: 503, failures: 3, calls: 3, final: 503, waits: twoWaits}, + {name: "502", status: 502, failures: 1, calls: 2, waits: []time.Duration{time.Second}}, + {name: "504", status: 504, failures: 1, calls: 2, waits: []time.Duration{time.Second}}, + { + name: "429 retry-after", status: 429, failures: 1, retryAfter: "3", + calls: 2, waits: []time.Duration{3 * time.Second}, + }, + {name: "429 too long", status: 429, failures: 3, retryAfter: "120", calls: 1, final: 429, tooLong: true}, + {name: "401", status: 401, failures: 3, calls: 1, final: 401}, + {name: "403", status: 403, failures: 3, calls: 1, final: 403}, + {name: "404", status: 404, failures: 3, calls: 1, final: 404}, + {name: "500", status: 500, failures: 3, calls: 1, final: 500}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, waits := testClient(t) + f.failWithRetryAfter("dir:/", tc.status, tc.failures, tc.retryAfter) + _, err := c.listDir(t.Context(), testRepoID, "/") + if statusOf(err) != tc.final || (err == nil) != (tc.final == 0) { + t.Fatalf("listDir = %v, want status %d", err, tc.final) + } + if errors.Is(err, datasource.ErrInvalidCredentials) { + t.Fatal("listDir must not map directory 401/403 to ErrInvalidCredentials") + } + if tc.tooLong && (!errors.Is(err, errRetryAfterTooLong) || !errors.Is(err, datasource.ErrFetchFailed)) { + t.Fatalf("missing run-fatal Retry-After sentinels: %v", err) + } + if tc.final != 0 && !errors.Is(err, datasource.ErrFetchFailed) { + t.Fatalf("status error must wrap ErrFetchFailed: %v", err) + } + if f.count("dir:/") != tc.calls || !slices.Equal(*waits, tc.waits) { + t.Fatalf("counts = %v, waits = %v", f.counts(), *waits) + } + }) + } +} + +func TestListDirInvalidJSON(t *testing.T) { + for _, body := range []string{"{", "null", `[] []`} { + t.Run(body, func(t *testing.T) { + f, c, waits := testClient(t) + f.rawBody["dir:/"] = body + _, err := c.listDir(t.Context(), testRepoID, "/") + if !errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed) || + f.count("dir:/") != 1 || len(*waits) != 0 { + t.Fatalf("invalid listing = %v, counts = %v", err, f.counts()) + } + }) + } +} + +func TestRetryAfter(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + value string + want time.Duration + fatal bool + }{ + {"", 0, false}, + {"0", 0, false}, + {"3", 3 * time.Second, false}, + {"60", 60 * time.Second, false}, + {"61", 0, true}, + {"120", 0, true}, + {"9223372037", 0, true}, + {"999999999999999999999999999999", 0, true}, + {"invalid", 0, false}, + {now.Add(-time.Hour).Format(http.TimeFormat), 0, false}, + {now.Add(30 * time.Second).Format(http.TimeFormat), 30 * time.Second, false}, + {now.Add(61 * time.Second).Format(http.TimeFormat), 0, true}, + } { + wait, err := retryAfter(tc.value, now) + if wait != tc.want || errors.Is(err, errRetryAfterTooLong) != tc.fatal { + t.Fatalf("retryAfter(%q) = (%v, %v), want (%v, fatal=%v)", tc.value, wait, err, tc.want, tc.fatal) + } + } +} + +func TestDownloadLink(t *testing.T) { + for _, body := range []string{ + `"http://user:secret@localhost/files/token"`, `"/relative"`, + `"ftp://localhost/file"`, `""`, `null`, `{"link":"x"}`, + `"http://localhost/file" "extra"`, + } { + t.Run(body, func(t *testing.T) { + f, c, waits := testClient(t) + f.addFile(testRepoID, "/file", []byte("body"), 1) + f.rawBody["file:/file"] = body + _, _, err := c.downloadLink(t.Context(), testRepoID, "/file") + if !errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed) || + f.count("file:/file") != 1 || len(*waits) != 0 { + t.Fatalf("invalid link = %v", err) + } + if strings.Contains(err.Error(), "secret") { + t.Fatalf("invalid link leaked in error: %v", err) + } + }) + } + for _, oid := range []string{"override-oid", ""} { + t.Run("oid="+oid, func(t *testing.T) { + f, c, _ := testClient(t) + f.addFile(testRepoID, "/a:b%.pdf", []byte("body"), 1) + f.linkOID["/a:b%.pdf"] = oid + link, got, err := c.downloadLink(t.Context(), testRepoID, "/a:b%.pdf") + if err != nil || got != oid || !strings.HasPrefix(link, f.fileserver.URL+"/files/") { + t.Fatalf("downloadLink = (%q, %q, %v)", link, got, err) + } + if query := f.requests("file:/a:b%.pdf")[0].RawQuery; query != "p=%2Fa%3Ab%25.pdf&reuse=1" { + t.Fatalf("file query = %s", query) + } + }) + } +} + +func TestJSONCaps(t *testing.T) { + for _, tc := range []struct { + name string + key string + body string + limit int64 + call func(*client, context.Context) error + }{ + {"repos", "repos", "[]", listingJSONLimit, func(c *client, ctx context.Context) error { + _, err := c.listRepos(ctx) + return err + }}, + {"dir", "dir:/", "[]", listingJSONLimit, func(c *client, ctx context.Context) error { + _, err := c.listDir(ctx, testRepoID, "/") + return err + }}, + {"ping", "ping", `"pong"`, smallJSONLimit, func(c *client, ctx context.Context) error { + return c.ping(ctx) + }}, + { + "link", "file:/file", `"http://localhost/files/token"`, smallJSONLimit, + func(c *client, ctx context.Context) error { + _, _, err := c.downloadLink(ctx, testRepoID, "/file") + return err + }, + }, + } { + for _, extra := range []int{0, 1} { + t.Run(fmt.Sprintf("%s/extra=%d", tc.name, extra), func(t *testing.T) { + f, c, waits := testClient(t) + f.addFile(testRepoID, "/file", []byte("body"), 1) + f.rawBody[tc.key] = tc.body + strings.Repeat(" ", int(tc.limit)-len(tc.body)+extra) + err := tc.call(c, t.Context()) + if extra == 0 && err != nil { + t.Fatalf("body at cap rejected: %v", err) + } + if extra == 1 && (!errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed)) { + t.Fatalf("body above cap accepted: %v", err) + } + if f.count(tc.key) != 1 || len(*waits) != 0 { + t.Fatalf("unexpected retries: %v", f.counts()) + } + }) + } + } +} + +func TestDownload(t *testing.T) { + for _, tc := range []struct { + name string + body string + expected int64 + chunked int64 + partial bool + want error + status int + }{ + {name: "exact limit", body: "body", expected: 4}, + {name: "content-length oversize", body: "large", expected: 5, want: errTooLarge}, + {name: "chunked oversize", body: "body", expected: 4, chunked: 5, want: errTooLarge}, + { + name: "partial content", body: "body", expected: 4, partial: true, + want: datasource.ErrFetchFailed, status: 206, + }, + {name: "source changed", body: "body", expected: 5, want: errSourceChanged}, + {name: "empty", expected: 0, want: errEmptyFile}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, waits := testClient(t) + f.addFile(testRepoID, "/file", []byte(tc.body), 1) + f.chunkedOversize["/file"] = tc.chunked + f.partialContent["/file"] = tc.partial + link, _, err := c.downloadLink(t.Context(), testRepoID, "/file") + if err != nil { + t.Fatal(err) + } + body, err := c.download(t.Context(), link, tc.expected, 4) + if !errors.Is(err, tc.want) || statusOf(err) != tc.status { + t.Fatalf("download = %v, want %v", err, tc.want) + } + if err == nil && string(body) != tc.body { + t.Fatalf("body = %q", body) + } + if err != nil && (strings.Contains(err.Error(), link) || strings.Contains(err.Error(), testToken)) { + t.Fatalf("download error leaked the link or token: %v", err) + } + if f.count("download:/file") != 1 || len(*waits) != 0 { + t.Fatalf("unexpected retries: %v", f.counts()) + } + assertNoCredentials(t, f.requests("download:/file")) + }) + } +} + +func TestDownloadRetries(t *testing.T) { + f, c, waits := testClient(t) + f.addFile(testRepoID, "/file", []byte("body"), 1) + f.fail("download:/file", 503, 2) + link, _, err := c.downloadLink(t.Context(), testRepoID, "/file") + if err != nil { + t.Fatal(err) + } + body, err := c.download(t.Context(), link, 4, 4) + if err != nil || string(body) != "body" || f.count("download:/file") != 3 || + !slices.Equal(*waits, []time.Duration{time.Second, 2 * time.Second}) { + t.Fatalf("download retries = %v, counts = %v, waits = %v", err, f.counts(), *waits) + } + assertNoCredentials(t, f.requests("download:/file")) +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestDownloadSSRFBlocked(t *testing.T) { + _, c, waits := testClient(t) + calls := 0 + c.files.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) { + calls++ + return nil, errors.New("unexpected request") + }) + link := "http://169.254.169.254/x" + _, err := c.download(t.Context(), link, 1, 4) + if !errors.Is(err, errSSRFBlocked) || !errors.Is(err, datasource.ErrFetchFailed) || calls != 0 || len(*waits) != 0 { + t.Fatalf("download = %v, calls = %d", err, calls) + } + if strings.Contains(err.Error(), link) { + t.Fatalf("blocked download leaked the URL: %v", err) + } +} + +func TestDownloadRejectsUserinfo(t *testing.T) { + _, c, waits := testClient(t) + calls := 0 + c.files.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) { + calls++ + return nil, errors.New("unexpected request") + }) + _, err := c.download(t.Context(), "http://user:secret@localhost/files/x", 1, 4) + if !errors.Is(err, errInvalidResponse) || calls != 0 || len(*waits) != 0 { + t.Fatalf("download = %v, calls = %d", err, calls) + } + if strings.Contains(err.Error(), "secret") { + t.Fatalf("download error leaked userinfo: %v", err) + } +} + +func TestNetworkRetries(t *testing.T) { + for _, tc := range []struct { + name string + failure error + failures int + attempts int + }{ + {"dial recovered", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New(testToken)}, 2, 3}, + {"dial exhausted", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New(testToken)}, 3, 3}, + {"timeout recovered", &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}, 2, 3}, + {"other error", errors.New(testToken), 3, 1}, + {"SSRF redirect", utils.ErrSSRFRedirectBlocked, 3, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + _, c, waits := testClient(t) + base := c.api.Transport + attempts := 0 + c.api.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + attempts++ + if attempts <= tc.failures { + return nil, tc.failure + } + return base.RoundTrip(r) + }) + err := c.ping(t.Context()) + if (err == nil) != (tc.failures < tc.attempts) || attempts != tc.attempts || len(*waits) != tc.attempts-1 { + t.Fatalf("ping = %v, attempts = %d, waits = %v", err, attempts, *waits) + } + if err != nil && strings.Contains(err.Error(), testToken) { + t.Fatalf("transport error leaked the token: %v", err) + } + if err != nil && !errors.Is(err, datasource.ErrFetchFailed) { + t.Fatalf("transport error must wrap ErrFetchFailed: %v", err) + } + }) + } +} + +func TestCanceledContext(t *testing.T) { + f, c, waits := testClient(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err := c.ping(ctx) + if !errors.Is(err, context.Canceled) || f.count("ping") != 0 || len(*waits) != 0 { + t.Fatalf("canceled ping = %v, counts = %v", err, f.counts()) + } + if err := sleepCtx(ctx, time.Hour); !errors.Is(err, context.Canceled) { + t.Fatalf("sleepCtx ignored cancellation: %v", err) + } +} + +func TestRedirectPolicy(t *testing.T) { + t.Run("download redirected to private address", func(t *testing.T) { + f, c, waits := testClient(t) + f.addFile(testRepoID, "/file", []byte("body"), 1) + f.redirects["download:/file"] = "http://169.254.169.254/private-signed-link" + link, _, err := c.downloadLink(t.Context(), testRepoID, "/file") + if err != nil { + t.Fatal(err) + } + _, err = c.download(t.Context(), link, 4, 4) + if !errors.Is(err, errSSRFBlocked) || f.count("download:/file") != 1 || len(*waits) != 0 { + t.Fatalf("redirect = %v, counts = %v", err, f.counts()) + } + if strings.Contains(err.Error(), "private-signed-link") { + t.Fatalf("redirect error leaked the target: %v", err) + } + }) + t.Run("api redirected to private address", func(t *testing.T) { + f, c, _ := testClient(t) + f.redirects["repos"] = "http://169.254.169.254/" + _, err := c.listRepos(t.Context()) + if !errors.Is(err, datasource.ErrFetchFailed) || errors.Is(err, datasource.ErrInvalidCredentials) { + t.Fatalf("listRepos = %v", err) + } + }) + t.Run("cross-origin hop strips the token", func(t *testing.T) { + f, c, _ := testClient(t) + f.addFile(testRepoID, "/pong", []byte(`"pong"`), 1) + link, _, err := c.downloadLink(t.Context(), testRepoID, "/pong") + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.redirects["ping"] = link + f.mu.Unlock() + if err := c.ping(t.Context()); err != nil { + t.Fatal(err) + } + requests := f.requests("download:/pong") + if len(requests) != 1 { + t.Fatalf("download requests = %d", len(requests)) + } + assertNoCredentials(t, requests) + }) +} diff --git a/internal/datasource/connector/seafile/connector.go b/internal/datasource/connector/seafile/connector.go new file mode 100644 index 00000000..d1967c9b --- /dev/null +++ b/internal/datasource/connector/seafile/connector.go @@ -0,0 +1,246 @@ +package seafile + +import ( + "context" + "fmt" + "net/http" + "path" + "sort" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" +) + +var ( + _ datasource.Connector = (*Connector)(nil) + _ datasource.StreamingConnector = (*Connector)(nil) + _ datasource.FullStreamingConnector = (*Connector)(nil) +) + +// Connector is stateless: every data source carries its own server URL and +// API token in its encrypted credentials. +type Connector struct{} + +// NewConnector creates the Seafile connector registered in the container. +func NewConnector() *Connector { return &Connector{} } + +// Type returns the connector type key stored on data sources. +func (*Connector) Type() string { return types.ConnectorTypeSeafile } + +// Validate checks the selection locally, pings Seafile with the token and, +// when resources are selected, confirms they belong to one existing, +// unencrypted library; it never lists directories. +func (*Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error { + cfg, err := parseConfig(ds) + if err != nil { + return err + } + var repoID string + if len(ds.ResourceIDs) > 0 { + if repoID, _, err = collapseRoots(ds.ResourceIDs); err != nil { + return err + } + } + client := newClient(cfg) + if err := client.ping(ctx); err != nil { + return err + } + if repoID == "" { + return nil + } + repos, err := client.listRepos(ctx) + if err != nil { + return err + } + _, err = selectedRepo(repos, repoID) + return err +} + +func selectedRepo(repos []repoInfo, repoID string) (repoInfo, error) { + for _, repo := range repos { + if repo.ID != repoID { + continue + } + if repo.Encrypted { + return repoInfo{}, fmt.Errorf("%w: encrypted Seafile libraries are not supported", + datasource.ErrInvalidConfig) + } + return repo, nil + } + return repoInfo{}, fmt.Errorf("%w: Seafile library %s", datasource.ErrResourceNotFound, repoID) +} + +// ListResources returns the unencrypted libraries for an empty parent and one +// directory level otherwise. Files with unsupported extensions are omitted so +// the picker only offers what a sync would import. Entries the sync would +// reject are skipped here rather than failing the whole level: the picker +// stays browsable and the sync reports the strict failure on its own. +func (*Connector) ListResources( + ctx context.Context, ds *types.DataSourceConfig, parentID string, +) ([]types.Resource, error) { + cfg, err := parseConfig(ds) + if err != nil { + return nil, err + } + client := newClient(cfg) + var out []types.Resource + if parentID == "" { + out, err = listLibraries(ctx, client) + } else { + out, err = listDirectory(ctx, client, parentID) + } + if err != nil { + return nil, err + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Name != out[j].Name { + return out[i].Name < out[j].Name + } + return out[i].ExternalID < out[j].ExternalID + }) + return out, nil +} + +func listLibraries(ctx context.Context, client *client) ([]types.Resource, error) { + repos, err := client.listRepos(ctx) + if err != nil { + return nil, err + } + out := make([]types.Resource, 0, len(repos)) + for _, repo := range repos { + if repo.Encrypted { + continue + } + out = append(out, types.Resource{ + ExternalID: encodeResourceID(repo.ID, "/"), + Name: repo.Name, + Type: "library", + Description: repo.Type, + HasChildren: true, + }) + } + return out, nil +} + +func listDirectory(ctx context.Context, client *client, parentID string) ([]types.Resource, error) { + repoID, dir, err := parseResourceID(parentID) + if err != nil { + return nil, err + } + entries, err := client.listDir(ctx, repoID, dir) + if err != nil { + return nil, mapDirError(err, dir) + } + out := make([]types.Resource, 0, len(entries)) + for _, e := range entries { + if !validEntryName(e.Name) { + continue + } + var kind string + switch e.Type { + case "dir": + kind = "directory" + case "file": + if !utils.IsSupportedImportExtension(path.Ext(e.Name)) { + continue + } + kind = "file" + default: + continue + } + out = append(out, types.Resource{ + ExternalID: encodeResourceID(repoID, path.Join(dir, e.Name)), + Name: e.Name, + Type: kind, + ParentID: parentID, + HasChildren: e.Type == "dir", + ModifiedAt: time.Unix(e.Mtime, 0).UTC(), + }) + } + return out, nil +} + +// mapDirError classifies a directory listing failure: 404 means the resource +// is gone, 403 is a permission scoping problem rather than a bad token. The +// 403 message carries the reason code so the sync log names the cause the +// same way error items do. +func mapDirError(err error, p string) error { + switch statusOf(err) { + case http.StatusNotFound: + return fmt.Errorf("%w: Seafile path %s", datasource.ErrResourceNotFound, p) + case http.StatusForbidden: + return fmt.Errorf("%w: %s: Seafile path %s", datasource.ErrFetchFailed, reasonPermissionDenied, p) + default: + return err + } +} + +// ResolveResourceAncestors derives ancestors from the IDs alone; no request +// is made and unparsable IDs contribute nothing. +func (*Connector) ResolveResourceAncestors( + _ context.Context, _ *types.DataSourceConfig, ids []string, +) ([]string, error) { + seen := make(map[string]bool) + out := make([]string, 0) + for _, id := range ids { + for _, ancestor := range ancestorIDs(id) { + if !seen[ancestor] { + seen[ancestor] = true + out = append(out, ancestor) + } + } + } + sort.Strings(out) + return out, nil +} + +// collector adapts the streaming engine to the collecting Connector methods. +type collector struct{ items []types.FetchedItem } + +func (h *collector) Emit(_ context.Context, item types.FetchedItem) error { + h.items = append(h.items, item) + return nil +} + +func (*collector) Checkpoint(context.Context, *types.SyncCursor) error { return nil } + +// FetchAll collects a fresh sync of the given resources without a cursor. +func (c *Connector) FetchAll( + ctx context.Context, ds *types.DataSourceConfig, resourceIDs []string, +) ([]types.FetchedItem, error) { + if ds == nil { + return nil, datasource.ErrInvalidConfig + } + dsCopy := *ds + dsCopy.ResourceIDs = resourceIDs + items, _, err := c.FetchIncremental(ctx, &dsCopy, nil) + return items, err +} + +// FetchIncremental collects one streaming run into memory. +func (c *Connector) FetchIncremental( + ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, +) ([]types.FetchedItem, *types.SyncCursor, error) { + h := &collector{} + next, err := c.FetchStream(ctx, ds, old, h) + return h.items, next, err +} + +// FetchStream is the production sync path: it scans the selected scope, +// emits changed files as they are downloaded and checkpoints the cursor so +// an interrupted run resumes instead of restarting. +func (c *Connector) FetchStream( + ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler, +) (*types.SyncCursor, error) { + return c.runSync(ctx, ds, old, h, false) +} + +// FetchFullStream re-downloads every file while keeping the old cursor as a +// deletion baseline until the run completes. +func (c *Connector) FetchFullStream( + ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler, +) (*types.SyncCursor, error) { + return c.runSync(ctx, ds, old, h, true) +} diff --git a/internal/datasource/connector/seafile/connector_test.go b/internal/datasource/connector/seafile/connector_test.go new file mode 100644 index 00000000..416d40de --- /dev/null +++ b/internal/datasource/connector/seafile/connector_test.go @@ -0,0 +1,163 @@ +package seafile + +import ( + "errors" + "net/url" + "slices" + "testing" + + "github.com/Tencent/WeKnora/internal/datasource" +) + +func TestConnectorResources(t *testing.T) { + noWait(t) + f := newFakeSeafile(t) + f.addRepo(testRepoID, "Zulu", "repo", false) + f.addRepo(otherRepoID, "Alpha", "srepo", false) + f.addRepo("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Hidden", "repo", true) + cfg := syncConfig(f) + c := NewConnector() + if c.Type() != "seafile" { + t.Fatalf("Type = %q", c.Type()) + } + got, err := c.ListResources(t.Context(), cfg, "") + if err != nil || len(got) != 2 { + t.Fatalf("libraries = %+v, %v", got, err) + } + for i, want := range []struct{ id, name, typ string }{ + {otherRepoID, "Alpha", "srepo"}, {testRepoID, "Zulu", "repo"}, + } { + r := got[i] + if r.ExternalID != want.id+":/" || r.Name != want.name || + r.Type != "library" || r.Description != want.typ || !r.HasChildren { + t.Fatalf("library[%d] = %+v", i, r) + } + } + p := "/产品/100% 文档" + f.addDir(testRepoID, p+"/子目录") + f.addFile(testRepoID, p+"/说明.pdf", []byte("pdf"), 1) + f.addFile(testRepoID, p+"/archive.zip", []byte("zip"), 1) + f.addFile(testRepoID, p+"/page.mdx", []byte("mdx"), 1) + parent := testRepoID + ":" + p + got, err = c.ListResources(t.Context(), cfg, parent) + if err != nil || len(got) != 2 { + t.Fatalf("children = %+v, %v", got, err) + } + wantTypes := map[string]string{"子目录": "directory", "说明.pdf": "file"} + for _, r := range got { + typ, ok := wantTypes[r.Name] + if !ok || r.Type != typ || r.HasChildren != (typ == "directory") || + r.ParentID != parent || r.ExternalID != parent+"/"+r.Name { + t.Fatalf("child = %+v", r) + } + delete(wantTypes, r.Name) + } + reqs := f.requests("dir:" + p) + if len(reqs) != 1 || reqs[0].RawQuery != (url.Values{"p": {p}}).Encode() { + t.Fatalf("directory query was not encoded exactly once: %+v", reqs) + } + _, err = c.ListResources(t.Context(), cfg, testRepoID+":/missing") + if !errors.Is(err, datasource.ErrResourceNotFound) { + t.Fatalf("missing directory = %v", err) + } + f.fail("repos", 403, -1) + _, err = c.ListResources(t.Context(), cfg, "") + if !errors.Is(err, datasource.ErrInvalidCredentials) { + t.Fatalf("forbidden libraries = %v", err) + } +} + +func TestConnectorAncestors(t *testing.T) { + noWait(t) + f := newFakeSeafile(t) + c := NewConnector() + cfg := syncConfig(f) + got, err := c.ResolveResourceAncestors(t.Context(), cfg, []string{ + testRepoID + ":/a/b/c/d.pdf", testRepoID + ":/a/b/e.pdf", + testRepoID + ":/a/b/c/d.pdf", testRepoID + ":/", + }) + want := []string{testRepoID + ":/", testRepoID + ":/a", testRepoID + ":/a/b", testRepoID + ":/a/b/c"} + if err != nil || !slices.Equal(got, want) { + t.Fatalf("ancestors = %v, %v; want %v", got, err, want) + } + got, err = c.ResolveResourceAncestors(t.Context(), cfg, []string{testRepoID + ":/"}) + if err != nil || len(got) != 0 || len(f.counts()) != 0 { + t.Fatalf("root ancestors = %v, %v; requests = %v", got, err, f.counts()) + } +} + +func TestConnectorValidate(t *testing.T) { + for _, tc := range []struct { + name string + roots []string + encrypted bool + want error + }{ + {"credentials only", nil, false, nil}, + {"selected directory", []string{"/docs"}, false, nil}, + {"two repositories", []string{"/docs", "other"}, false, datasource.ErrInvalidConfig}, + {"encrypted", []string{"/docs"}, true, datasource.ErrInvalidConfig}, + {"unknown repository", []string{"other"}, false, datasource.ErrResourceNotFound}, + } { + t.Run(tc.name, func(t *testing.T) { + noWait(t) + f := newFakeSeafile(t) + f.addRepo(testRepoID, "Library", "repo", tc.encrypted) + f.addDir(testRepoID, "/docs") + cfg := syncConfig(f, tc.roots...) + for i, p := range tc.roots { + if p == "other" { + cfg.ResourceIDs[i] = otherRepoID + ":/" + } + } + err := NewConnector().Validate(t.Context(), cfg) + if !errors.Is(err, tc.want) { + t.Fatalf("Validate = %v; want %v", err, tc.want) + } + if tc.want == nil && f.count("ping") != 1 { + t.Fatalf("Validate did not ping: %v", f.counts()) + } + if tc.encrypted && f.countPrefix("dir:") != 0 { + t.Fatalf("encrypted repository was traversed: %v", f.counts()) + } + }) + } +} + +func TestConnectorEmptySelection(t *testing.T) { + noWait(t) + f := newFakeSeafile(t) + h := &recorder{} + _, err := run(t, NewConnector(), syncConfig(f), nil, h, false) + if !errors.Is(err, datasource.ErrInvalidConfig) || len(f.counts()) != 0 || + len(h.items) != 0 || len(h.checkpoints) != 0 { + t.Fatalf("empty selection = %v; requests = %v; handler = %+v", err, f.counts(), h) + } +} + +func TestConnectorBatchWrappers(t *testing.T) { + noWait(t) + f := newFakeSeafile(t) + f.addRepo(testRepoID, "Library", "repo", false) + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + f.addFile(testRepoID, "/outside/b.pdf", []byte("b"), 1) + c := NewConnector() + cfg := syncConfig(f, "/outside") + items, err := c.FetchAll(t.Context(), cfg, []string{testRepoID + ":/docs"}) + if err != nil { + t.Fatal(err) + } + assertPaths(t, items, "/docs/a.pdf") + cfg = syncConfig(f, "/docs") + items, cur, err := c.FetchIncremental(t.Context(), cfg, nil) + if err != nil { + t.Fatal(err) + } + assertPaths(t, items, "/docs/a.pdf") + f.touch(testRepoID, "/docs/a.pdf") + items, cur, err = c.FetchIncremental(t.Context(), cfg, cur) + if err != nil || len(filesOf(cur)) != 1 { + t.Fatalf("incremental wrapper = %v, cursor = %+v", err, cur) + } + assertPaths(t, items, "/docs/a.pdf") +} diff --git a/internal/datasource/connector/seafile/cursor.go b/internal/datasource/connector/seafile/cursor.go new file mode 100644 index 00000000..3a2fe903 --- /dev/null +++ b/internal/datasource/connector/seafile/cursor.go @@ -0,0 +1,91 @@ +package seafile + +import ( + "encoding/json" + "fmt" + "maps" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +const cursorSchemaVersion = 1 + +// cursor is the connector state persisted between runs. Files maps every +// known path to its fingerprint; an empty fingerprint marks a path whose +// fetch failed and must be retried. FullSync and FullSyncBaseline exist only +// while a forced full run is in progress (same shape as Confluence). +type cursor struct { + SchemaVersion int `json:"schema_version"` + RepoID string `json:"repo_id"` + RepoName string `json:"repo_name"` + Files map[string]string `json:"files"` + FullSync bool `json:"full_sync,omitempty"` + FullSyncBaseline map[string]string `json:"full_sync_baseline,omitempty"` +} + +// decodeCursor accepts a nil or empty cursor as a fresh state; anything else +// must carry the current schema version. +func decodeCursor(old *types.SyncCursor) (cursor, error) { + c := cursor{SchemaVersion: cursorSchemaVersion} + if old != nil && len(old.ConnectorCursor) > 0 { + c.SchemaVersion = 0 + raw, err := json.Marshal(old.ConnectorCursor) + if err == nil { + err = json.Unmarshal(raw, &c) + } + if err != nil { + return cursor{}, fmt.Errorf("%w: invalid Seafile cursor: %w", datasource.ErrInvalidConfig, err) + } + if c.SchemaVersion != cursorSchemaVersion { + return cursor{}, fmt.Errorf("%w: unsupported Seafile cursor schema %d", + datasource.ErrInvalidConfig, c.SchemaVersion) + } + } + if c.Files == nil { + c.Files = make(map[string]string) + } + if c.FullSyncBaseline == nil { + c.FullSyncBaseline = make(map[string]string) + } + return c, nil +} + +// toSyncCursor produces a snapshot independent of the working maps through a +// JSON round trip, so the service can serialize it after the run moves on. +// Neither step can fail: the cursor is plain strings and string maps. +func (c *cursor) toSyncCursor() *types.SyncCursor { + raw, _ := json.Marshal(c) + fields := map[string]interface{}{} + _ = json.Unmarshal(raw, &fields) + return &types.SyncCursor{LastSyncTime: time.Now().UTC(), ConnectorCursor: fields} +} + +// prepareCursor decodes the previous cursor, enforces the library binding and +// switches into full-sync mode when requested. The returned flag reports +// whether the cursor changed and therefore needs saving. +func prepareCursor(old *types.SyncCursor, repoID string, forceFull bool) (cursor, bool, error) { + c, err := decodeCursor(old) + if err != nil { + return cursor{}, false, err + } + if c.RepoID != "" && c.RepoID != repoID { + return cursor{}, false, fmt.Errorf( + "%w: this data source already synced Seafile library %q; restore that library "+ + "or create a new data source instead of switching to %s", + datasource.ErrInvalidConfig, c.RepoName, repoID) + } + changed := false + if c.RepoID == "" { + c.RepoID = repoID + changed = true + } + if forceFull && !c.FullSync { + c.FullSyncBaseline = maps.Clone(c.Files) + c.Files = make(map[string]string) + c.FullSync = true + changed = true + } + return c, changed, nil +} diff --git a/internal/datasource/connector/seafile/cursor_test.go b/internal/datasource/connector/seafile/cursor_test.go new file mode 100644 index 00000000..7e2f5c86 --- /dev/null +++ b/internal/datasource/connector/seafile/cursor_test.go @@ -0,0 +1,114 @@ +package seafile + +import ( + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +func TestCursorRoundTrip(t *testing.T) { + c, _, err := prepareCursor(nil, testRepoID, false) + if err != nil { + t.Fatal(err) + } + c.RepoName = "原资料库" + c.Files = map[string]string{"/ok.pdf": "o:abc|m:1|s:3", "/retry.pdf": ""} + c.FullSync = true + c.FullSyncBaseline = map[string]string{"/gone.pdf": "old", "/pending.pdf": ""} + data, err := json.Marshal(c.toSyncCursor()) + if err != nil { + t.Fatal(err) + } + var wire types.SyncCursor + if err := json.Unmarshal(data, &wire); err != nil { + t.Fatal(err) + } + for _, key := range []string{"schema_version", "repo_id", "repo_name", "files", "full_sync", "full_sync_baseline"} { + if _, ok := wire.ConnectorCursor[key]; !ok { + t.Errorf("cursor missing JSON key %q", key) + } + } + got, err := decodeCursor(&wire) + if err != nil || !reflect.DeepEqual(got, c) { + t.Fatalf("round trip = %+v, %v; want %+v", got, err, c) + } +} + +func TestCursorEmptyAndUnknownVersion(t *testing.T) { + got, err := decodeCursor(nil) + if err != nil || got.Files == nil || len(got.Files) != 0 || len(got.FullSyncBaseline) != 0 { + t.Fatalf("nil cursor = %+v, %v", got, err) + } + old := &types.SyncCursor{ConnectorCursor: map[string]any{"schema_version": 999999}} + if _, err := decodeCursor(old); !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("unknown schema = %v", err) + } + if _, _, err := prepareCursor(old, testRepoID, false); !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("prepare unknown schema = %v", err) + } + // A non-empty cursor from another connector or a truncated write carries + // no usable version and must not be reinterpreted as Seafile state. + for name, foreign := range map[string]map[string]any{ + "missing version": {"files": map[string]any{"/a.pdf": "x"}}, + "null version": {"schema_version": nil, "repo_id": testRepoID}, + "zero version": {"schema_version": 0, "repo_id": testRepoID}, + } { + _, err := decodeCursor(&types.SyncCursor{ConnectorCursor: foreign}) + if !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("%s = %v", name, err) + } + } +} + +func TestPrepareCursorFullSync(t *testing.T) { + old := seededCursor(t, "Library", map[string]string{"/a.pdf": "a", "/pending.pdf": ""}) + before := cursorJSON(t, old) + c, changed, err := prepareCursor(old, testRepoID, true) + if err != nil || !changed || !c.FullSync || len(c.Files) != 0 || + !reflect.DeepEqual(c.FullSyncBaseline, filesOf(old)) { + t.Fatalf("prepare full = %+v, changed=%v, err=%v", c, changed, err) + } + c.FullSyncBaseline["/a.pdf"] = "mutated" + c.Files["/new.pdf"] = "new" + if cursorJSON(t, old) != before { + t.Fatal("full cursor aliases the old cursor") + } + c.FullSyncBaseline["/a.pdf"] = "a" + active := c.toSyncCursor() + before = cursorJSON(t, active) + for _, force := range []bool{false, true} { + resumed, _, err := prepareCursor(active, testRepoID, force) + if err != nil || !resumed.FullSync || !reflect.DeepEqual(resumed.Files, c.Files) || + !reflect.DeepEqual(resumed.FullSyncBaseline, c.FullSyncBaseline) { + t.Fatalf("resume force=%v: %+v, %v", force, resumed, err) + } + } + if cursorJSON(t, active) != before { + t.Fatal("prepare mutated an active full-sync cursor") + } +} + +func TestCursorRepositoryMismatchBeforeHTTP(t *testing.T) { + old := seededCursor(t, "原资料库", map[string]string{"/a.pdf": "saved"}) + before := cursorJSON(t, old) + _, _, err := prepareCursor(old, otherRepoID, false) + if !errors.Is(err, datasource.ErrInvalidConfig) || !strings.Contains(err.Error(), "原资料库") { + t.Fatalf("prepare mismatch = %v", err) + } + f := newFakeSeafile(t) + cfg := syncConfig(f) + cfg.ResourceIDs = []string{otherRepoID + ":/"} + h := &recorder{} + _, err = run(t, NewConnector(), cfg, old, h, false) + if !errors.Is(err, datasource.ErrInvalidConfig) || !strings.Contains(err.Error(), "原资料库") { + t.Fatalf("stream mismatch = %v", err) + } + if len(f.counts()) != 0 || len(h.items) != 0 || len(h.checkpoints) != 0 || cursorJSON(t, old) != before { + t.Fatalf("mismatch had side effects: requests=%v, handler=%+v", f.counts(), h) + } +} diff --git a/internal/datasource/connector/seafile/fake_seafile_test.go b/internal/datasource/connector/seafile/fake_seafile_test.go new file mode 100644 index 00000000..46508a66 --- /dev/null +++ b/internal/datasource/connector/seafile/fake_seafile_test.go @@ -0,0 +1,410 @@ +package seafile + +import ( + "bytes" + "crypto/sha1" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path" + "sort" + "strconv" + "strings" + "sync" + "testing" + + "github.com/Tencent/WeKnora/internal/utils" +) + +// TestMain whitelists loopback for SSRF so the httptest servers are reachable. +// Production keeps the default strict policy. +func TestMain(m *testing.M) { + _ = os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + utils.ResetSSRFWhitelistForTest() + os.Exit(m.Run()) +} + +type fakeNode struct { + Type string + ID string + Mtime int64 + Body []byte +} + +type fakeLocation struct{ repo, path string } + +type fakeRequest struct { + Headers http.Header + RawQuery string +} + +type fakeFailure struct { + status int + remaining int // negative repeats forever + retryAfter string +} + +// fakeSeafile is an in-process stand-in for a Seafile 10.0.1 deployment with +// the API and the fileserver on separate servers. Requests are keyed as +// "ping", "repos", "dir:", "file:" and "download:"; the +// same keys drive failure injection. +type fakeSeafile struct { + api *httptest.Server + fileserver *httptest.Server + // prefix simulates a deployment path such as "/seafile". + prefix string + + mu sync.Mutex + repos []repoInfo + tree map[string]map[string]*fakeNode // repo → path → node + forbidden map[string]bool // directory listings answering 403 + + failures map[string]*fakeFailure + rawBody map[string]string // raw 200 body per key + redirects map[string]string // 302 target per key + linkOID map[string]string // path → oid header override + linkURL map[string]string // path → download link override + chunkedOversize map[string]int64 // path → bytes streamed without Content-Length + partialContent map[string]bool // path → answer 206 + + tokens map[string]fakeLocation + calls map[string]int + seen map[string][]fakeRequest +} + +func newFakeSeafile(t *testing.T) *fakeSeafile { + t.Helper() + f := &fakeSeafile{ + tree: map[string]map[string]*fakeNode{}, + forbidden: map[string]bool{}, + failures: map[string]*fakeFailure{}, + rawBody: map[string]string{}, + redirects: map[string]string{}, + linkOID: map[string]string{}, + linkURL: map[string]string{}, + chunkedOversize: map[string]int64{}, + partialContent: map[string]bool{}, + tokens: map[string]fakeLocation{}, + calls: map[string]int{}, + seen: map[string][]fakeRequest{}, + } + f.fileserver = httptest.NewServer(http.HandlerFunc(f.handleDownload)) + t.Cleanup(f.fileserver.Close) + f.api = httptest.NewServer(http.HandlerFunc(f.handleAPI)) + t.Cleanup(f.api.Close) + return f +} + +func (f *fakeSeafile) baseURL() string { return f.api.URL + f.prefix } + +func (f *fakeSeafile) addRepo(id, name, typ string, encrypted bool) { + f.mu.Lock() + defer f.mu.Unlock() + f.repos = append(f.repos, repoInfo{ID: id, Name: name, Type: typ, Encrypted: encrypted, Permission: "rw"}) + f.addDirLocked(id, "/") +} + +func (f *fakeSeafile) renameRepo(id, name string) { + f.mu.Lock() + defer f.mu.Unlock() + for i := range f.repos { + if f.repos[i].ID == id { + f.repos[i].Name = name + } + } +} + +func (f *fakeSeafile) addDirLocked(repo, p string) { + if f.tree[repo] == nil { + f.tree[repo] = map[string]*fakeNode{} + } + for { + if f.tree[repo][p] == nil { + f.tree[repo][p] = &fakeNode{Type: "dir", ID: "dir-" + p} + } + if p == "/" { + return + } + p = path.Dir(p) + } +} + +func (f *fakeSeafile) addDir(repo, p string) { + f.mu.Lock() + defer f.mu.Unlock() + f.addDirLocked(repo, p) +} + +func (f *fakeSeafile) addFile(repo, p string, body []byte, mtime int64) { + f.mu.Lock() + defer f.mu.Unlock() + f.addDirLocked(repo, path.Dir(p)) + f.tree[repo][p] = &fakeNode{ + Type: "file", ID: fmt.Sprintf("%x", sha1.Sum(body)), Mtime: mtime, Body: bytes.Clone(body), + } +} + +// removePath deletes a file or a directory subtree. +func (f *fakeSeafile) removePath(repo, p string) { + f.mu.Lock() + defer f.mu.Unlock() + for name := range f.tree[repo] { + if name == p || strings.HasPrefix(name, strings.TrimSuffix(p, "/")+"/") { + delete(f.tree[repo], name) + } + } +} + +// movePath renames a file or directory subtree, keeping oids and mtimes. +func (f *fakeSeafile) movePath(repo, from, to string) { + f.mu.Lock() + defer f.mu.Unlock() + moved := map[string]*fakeNode{} + for name, node := range f.tree[repo] { + if name == from || strings.HasPrefix(name, from+"/") { + moved[to+strings.TrimPrefix(name, from)] = node + delete(f.tree[repo], name) + } + } + f.addDirLocked(repo, path.Dir(to)) + for name, node := range moved { + f.tree[repo][name] = node + } +} + +// setBody replaces a file's content, which changes its oid and bumps mtime. +func (f *fakeSeafile) setBody(repo, p string, body []byte) { + f.mu.Lock() + defer f.mu.Unlock() + if node := f.tree[repo][p]; node != nil { + node.Body = bytes.Clone(body) + node.ID = fmt.Sprintf("%x", sha1.Sum(body)) + node.Mtime++ + } +} + +// touch bumps a file's mtime without changing its content or oid. +func (f *fakeSeafile) touch(repo, p string) { + f.mu.Lock() + defer f.mu.Unlock() + if node := f.tree[repo][p]; node != nil { + node.Mtime++ + } +} + +// fail makes the next count requests for key answer status (count < 0: always). +func (f *fakeSeafile) fail(key string, status, count int) { + f.failWithRetryAfter(key, status, count, "") +} + +func (f *fakeSeafile) failWithRetryAfter(key string, status, count int, retryAfter string) { + f.mu.Lock() + defer f.mu.Unlock() + f.failures[key] = &fakeFailure{status: status, remaining: count, retryAfter: retryAfter} +} + +func (f *fakeSeafile) count(key string) int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls[key] +} + +func (f *fakeSeafile) counts() map[string]int { + f.mu.Lock() + defer f.mu.Unlock() + out := make(map[string]int, len(f.calls)) + for key, n := range f.calls { + out[key] = n + } + return out +} + +func (f *fakeSeafile) resetCounts() { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = map[string]int{} + f.seen = map[string][]fakeRequest{} +} + +// countPrefix sums the counters whose key starts with prefix ("dir:", "download:"). +func (f *fakeSeafile) countPrefix(prefix string) int { + f.mu.Lock() + defer f.mu.Unlock() + total := 0 + for key, n := range f.calls { + if strings.HasPrefix(key, prefix) { + total += n + } + } + return total +} + +func (f *fakeSeafile) requests(key string) []fakeRequest { + f.mu.Lock() + defer f.mu.Unlock() + out := make([]fakeRequest, 0, len(f.seen[key])) + for _, req := range f.seen[key] { + out = append(out, fakeRequest{Headers: req.Headers.Clone(), RawQuery: req.RawQuery}) + } + return out +} + +// The handler helpers below run with mu held. + +func (f *fakeSeafile) record(key string, r *http.Request) { + f.calls[key]++ + f.seen[key] = append(f.seen[key], fakeRequest{Headers: r.Header.Clone(), RawQuery: r.URL.RawQuery}) +} + +// injected serves a configured redirect, failure or raw body for key. +func (f *fakeSeafile) injected(w http.ResponseWriter, r *http.Request, key string) bool { + if target, ok := f.redirects[key]; ok { + http.Redirect(w, r, target, http.StatusFound) + return true + } + if failure := f.failures[key]; failure != nil && failure.remaining != 0 { + if failure.remaining > 0 { + failure.remaining-- + } + if failure.retryAfter != "" { + w.Header().Set("Retry-After", failure.retryAfter) + } + w.WriteHeader(failure.status) + _, _ = w.Write([]byte("injected failure")) + return true + } + if body, ok := f.rawBody[key]; ok { + _, _ = w.Write([]byte(body)) + return true + } + return false +} + +func (f *fakeSeafile) handleAPI(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if r.Method != http.MethodGet || !strings.HasPrefix(r.URL.Path, f.prefix+"/api2/") { + http.NotFound(w, r) + return + } + route := strings.TrimPrefix(r.URL.Path, f.prefix) + switch route { + case "/api2/auth/ping/": + f.record("ping", r) + if !f.injected(w, r, "ping") { + _ = json.NewEncoder(w).Encode("pong") + } + return + case "/api2/repos/": + f.record("repos", r) + if !f.injected(w, r, "repos") { + _ = json.NewEncoder(w).Encode(f.repos) + } + return + } + parts := strings.Split(strings.Trim(route, "/"), "/") + if len(parts) != 4 || parts[0] != "api2" || parts[1] != "repos" || (parts[3] != "dir" && parts[3] != "file") { + http.NotFound(w, r) + return + } + repo, op, p := parts[2], parts[3], r.URL.Query().Get("p") + key := op + ":" + p + f.record(key, r) + if f.injected(w, r, key) { + return + } + node := f.tree[repo][p] + if op == "dir" { + if f.forbidden[p] { + w.WriteHeader(http.StatusForbidden) + return + } + if node == nil || node.Type != "dir" { + http.NotFound(w, r) + return + } + f.writeDir(w, repo, p) + return + } + if node == nil || node.Type != "file" { + http.NotFound(w, r) + return + } + if r.URL.Query().Get("reuse") != "1" { + w.WriteHeader(http.StatusBadRequest) + return + } + oid := node.ID + if override, ok := f.linkOID[p]; ok { + oid = override + } + w.Header().Set("oid", oid) + token := fmt.Sprintf("download-token-%d", len(f.tokens)+1) + f.tokens[token] = fakeLocation{repo: repo, path: p} + link := f.fileserver.URL + "/files/" + token + if override, ok := f.linkURL[p]; ok { + link = override + } + _ = json.NewEncoder(w).Encode(link) +} + +// writeDir renders one level like seahub: every entry carries id, name, type, +// mtime and permission; only files carry size. +func (f *fakeSeafile) writeDir(w http.ResponseWriter, repo, dir string) { + entries := make([]map[string]any, 0) + for name, node := range f.tree[repo] { + if name == dir || path.Dir(name) != dir { + continue + } + entry := map[string]any{ + "id": node.ID, "name": path.Base(name), "type": node.Type, + "mtime": node.Mtime, "permission": "rw", + } + if node.Type == "file" { + entry["size"] = len(node.Body) + } + entries = append(entries, entry) + } + sort.Slice(entries, func(i, j int) bool { + return entries[i]["name"].(string) < entries[j]["name"].(string) + }) + _ = json.NewEncoder(w).Encode(entries) +} + +func (f *fakeSeafile) handleDownload(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + location, ok := f.tokens[strings.TrimPrefix(r.URL.Path, "/files/")] + if !ok { + http.NotFound(w, r) + return + } + p := location.path + key := "download:" + p + f.record(key, r) + if f.injected(w, r, key) { + return + } + node := f.tree[location.repo][p] + if node == nil { + http.NotFound(w, r) + return + } + status := http.StatusOK + if f.partialContent[p] { + status = http.StatusPartialContent + } + if n := f.chunkedOversize[p]; n > 0 { + w.WriteHeader(status) + _, _ = w.Write(bytes.Repeat([]byte("x"), int(n-1))) + w.(http.Flusher).Flush() + _, _ = w.Write([]byte("x")) + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(node.Body))) + w.WriteHeader(status) + _, _ = w.Write(node.Body) +} diff --git a/internal/datasource/connector/seafile/filename.go b/internal/datasource/connector/seafile/filename.go new file mode 100644 index 00000000..4da8f8b1 --- /dev/null +++ b/internal/datasource/connector/seafile/filename.go @@ -0,0 +1,39 @@ +package seafile + +import ( + "fmt" + "path" + "strings" + "unicode" + + "github.com/Tencent/WeKnora/internal/datasource" +) + +// knowledgeFileName maps a library file to the knowledge base folder +// convention "/". Every segment is +// sanitized on its own; depth and length limits are applied by the service. +func knowledgeFileName(repoName, filePath string) string { + segments := strings.Split(strings.TrimPrefix(filePath, "/"), "/") + last := len(segments) - 1 + for i := 0; i < last; i++ { + segments[i] = datasource.SanitizeFileName(segments[i]) + } + ext := path.Ext(segments[last]) + segments[last] = datasource.SanitizeFileName(strings.TrimSuffix(segments[last], ext)) + ext + return datasource.SanitizeFileName(repoName) + "/" + strings.Join(segments, "/") +} + +func externalID(repoID, filePath string) string { + return "seafile:" + repoID + ":" + filePath +} + +// fingerprint identifies a file version; three equal parts mean unchanged. +func fingerprint(oid string, mtime, size int64) string { + return fmt.Sprintf("o:%s|m:%d|s:%d", oid, mtime, size) +} + +// validEntryName accepts a single non-empty path segment. +func validEntryName(name string) bool { + return name != "" && name != "." && name != ".." && + !strings.ContainsAny(name, "/\\") && !strings.ContainsFunc(name, unicode.IsControl) +} diff --git a/internal/datasource/connector/seafile/filename_test.go b/internal/datasource/connector/seafile/filename_test.go new file mode 100644 index 00000000..2007a9da --- /dev/null +++ b/internal/datasource/connector/seafile/filename_test.go @@ -0,0 +1,63 @@ +package seafile + +import ( + "strings" + "testing" +) + +func TestKnowledgeFileName(t *testing.T) { + if got := knowledgeFileName("01-机场线", "/产品/产品A/需求: v2.docx"); got != "01-机场线/产品/产品A/需求_ v2.docx" { + t.Fatalf("filename = %q", got) + } + p := "/" + strings.Repeat("层级/", 20) + "说明.pdf" + if got := knowledgeFileName("资料库", p); got != "资料库"+p { + t.Fatalf("deep filename was truncated: %q", got) + } +} + +func TestExternalIDAndFingerprint(t *testing.T) { + if got := externalID(testRepoID, "/产品/a:b.pdf"); got != "seafile:"+testRepoID+":/产品/a:b.pdf" { + t.Fatalf("externalID = %q", got) + } + for _, tc := range []struct { + oid string + mtime, size int64 + want string + }{ + {"abc123", 123, 456, "o:abc123|m:123|s:456"}, + {"", 0, 0, "o:|m:0|s:0"}, + } { + if got := fingerprint(tc.oid, tc.mtime, tc.size); got != tc.want { + t.Fatalf("fingerprint = %q, want %q", got, tc.want) + } + } +} + +func TestValidEntryName(t *testing.T) { + for _, tc := range []struct { + name string + want bool + }{ + {"说明.pdf", true}, + {"需求: v2.docx", true}, + {"a%2Fb.pdf", true}, + {".hidden.pdf", true}, + {" spaced .pdf", true}, + {"", false}, + {".", false}, + {"..", false}, + {"../outside.pdf", false}, + {"/absolute.pdf", false}, + {"a/b.pdf", false}, + {"a\\b.pdf", false}, + {"a\x00b.pdf", false}, + {"a\nb.pdf", false}, + {"a\rb.pdf", false}, + {"a\tb.pdf", false}, + {"a\x7fb.pdf", false}, + } { + if got := validEntryName(tc.name); got != tc.want { + t.Errorf("validEntryName(%q) = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/internal/datasource/connector/seafile/sync.go b/internal/datasource/connector/seafile/sync.go new file mode 100644 index 00000000..bfc3d372 --- /dev/null +++ b/internal/datasource/connector/seafile/sync.go @@ -0,0 +1,458 @@ +package seafile + +import ( + "context" + "errors" + "fmt" + "net/http" + "path" + "sort" + "strconv" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" +) + +// checkpointEvery bounds how many cursor mutations may be lost on a crash. +const checkpointEvery = 50 + +// syncRun holds the state of one FetchStream / FetchFullStream execution. +type syncRun struct { + ctx context.Context + client *client + h datasource.StreamHandler + cur cursor + repoID string + // repoName is frozen in the cursor on the first run so folder names stay + // stable when the library is renamed. + repoName string + limit int64 + // seen records every supported file listed this run; anything known to + // the cursor but not seen is a deletion candidate. + seen map[string]bool + unsaved int +} + +func (c *Connector) runSync( + ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, + h datasource.StreamHandler, forceFull bool, +) (*types.SyncCursor, error) { + cfg, err := parseConfig(ds) + if err != nil { + return nil, err + } + repoID, roots, err := collapseRoots(ds.ResourceIDs) + if err != nil { + return nil, err + } + cur, changed, err := prepareCursor(old, repoID, forceFull) + if err != nil { + return nil, err + } + r := &syncRun{ctx: ctx, client: newClient(cfg), h: h, cur: cur, repoID: repoID, seen: make(map[string]bool)} + if changed { + r.unsaved++ + } + + // Nothing has been fetched yet, so failures here return without saving: + // a cursor must not bind to a library that was never confirmed to exist. + repos, err := r.client.listRepos(ctx) + if err != nil { + return nil, r.canceledOr(err) + } + repo, err := selectedRepo(repos, repoID) + if err != nil { + return nil, err + } + if r.cur.RepoName == "" { + r.cur.RepoName = repo.Name + r.unsaved++ + } + r.repoName = r.cur.RepoName + r.limit = utils.GetMaxFileSize() + + for _, root := range roots { + if err := r.scanRoot(root); err != nil { + return nil, err + } + } + if err := r.reconcile(); err != nil { + return nil, err + } + logger.Infof(ctx, "[Seafile] sync finished: %d files in scope, %d tracked", len(r.seen), len(r.cur.Files)) + return r.cur.toSyncCursor(), nil +} + +// canceledOr reports cancellation as ErrSyncCanceled and passes other errors +// through unchanged. The second branch covers a handler that failed on a +// context of its own; applying it twice is harmless. +func (r *syncRun) canceledOr(err error) error { + if cause := r.ctx.Err(); cause != nil { + return errors.Join(datasource.ErrSyncCanceled, cause) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return errors.Join(datasource.ErrSyncCanceled, err) + } + return err +} + +func (r *syncRun) canceled() error { + if cause := r.ctx.Err(); cause != nil { + return errors.Join(datasource.ErrSyncCanceled, cause) + } + return nil +} + +// abort saves unsaved progress while the context is still valid, then +// returns the source error. Handler errors never come through here. +func (r *syncRun) abort(err error) error { + if canceled := r.canceledOr(err); canceled != err { + return canceled + } + if r.unsaved > 0 { + if checkpointErr := r.checkpoint(); checkpointErr != nil { + return errors.Join(err, checkpointErr) + } + } + return err +} + +func (r *syncRun) checkpoint() error { + if err := r.canceled(); err != nil { + return err + } + if err := r.h.Checkpoint(r.ctx, r.cur.toSyncCursor()); err != nil { + return err + } + r.unsaved = 0 + return nil +} + +func (r *syncRun) mutated() error { + r.unsaved++ + if r.unsaved >= checkpointEvery { + return r.checkpoint() + } + return nil +} + +func (r *syncRun) emit(item types.FetchedItem) error { + if err := r.canceled(); err != nil { + return err + } + if err := r.h.Emit(r.ctx, item); err != nil { + return r.canceledOr(err) + } + return nil +} + +func (r *syncRun) listDir(p string) ([]dirent, error) { + if err := r.canceled(); err != nil { + return nil, err + } + entries, err := r.client.listDir(r.ctx, r.repoID, p) + if err != nil { + return nil, r.canceledOr(err) + } + return entries, nil +} + +// scanRoot classifies a selected root by its current type: a directory is +// traversed, a file listed by its parent is synced alone, anything else is +// gone. +func (r *syncRun) scanRoot(root string) error { + entries, err := r.listDir(root) + if err == nil { + return r.walkDir(root, entries) + } + if statusOf(err) != http.StatusNotFound || root == "/" { + return r.abort(mapDirError(err, root)) + } + parent := parentPath(root) + entries, err = r.listDir(parent) + if err != nil { + return r.abort(mapDirError(err, parent)) + } + if err := validateListing(parent, entries); err != nil { + return r.abort(err) + } + for _, e := range entries { + if e.Name != path.Base(root) || e.Type != "file" { + continue + } + if !utils.IsSupportedImportExtension(path.Ext(e.Name)) { + return nil + } + return r.syncFile(root, e) + } + return r.abort(fmt.Errorf("%w: Seafile path %s", datasource.ErrResourceNotFound, root)) +} + +// validateListing rejects entries the traversal cannot trust; a bad listing +// is a directory failure so the run emits no deletions. +func validateListing(dir string, entries []dirent) error { + names := make(map[string]bool, len(entries)) + for _, e := range entries { + bad := !validEntryName(e.Name) || names[e.Name] || e.Mtime < 0 || + (e.Type != "file" && e.Type != "dir") || + (e.Type == "file" && (e.Size == nil || *e.Size < 0)) + if bad { + return fmt.Errorf("%w: %w: directory listing %s", datasource.ErrFetchFailed, errInvalidResponse, dir) + } + names[e.Name] = true + } + return nil +} + +// walkDir traverses root depth-first with an explicit stack of paths. Each +// level is listed once; files are synced before descending into +// sub-directories, both in name order. +func (r *syncRun) walkDir(root string, rootEntries []dirent) error { + stack := []string{root} + for len(stack) > 0 { + dir := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + entries := rootEntries + if dir != root { + var err error + if entries, err = r.listDir(dir); err != nil { + // A sub-directory that vanished mid-scan is a listing failure, + // not a missing selection: the run stops without deletions and + // the next run sees the new shape. + if statusOf(err) == http.StatusNotFound { + return r.abort(fmt.Errorf("%w: Seafile directory %s disappeared during the scan", + datasource.ErrFetchFailed, dir)) + } + return r.abort(mapDirError(err, dir)) + } + } + if err := validateListing(dir, entries); err != nil { + return r.abort(err) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) + for _, e := range entries { + if e.Type == "file" && utils.IsSupportedImportExtension(path.Ext(e.Name)) { + if err := r.syncFile(path.Join(dir, e.Name), e); err != nil { + return err + } + } + } + for i := len(entries) - 1; i >= 0; i-- { + if entries[i].Type == "dir" { + stack = append(stack, path.Join(dir, entries[i].Name)) + } + } + } + return nil +} + +// syncFile downloads and emits one file unless its fingerprint is unchanged. +// Every caller validated the listing, so e.Size is non-nil. The fingerprint +// is stored only after Emit succeeds. +func (r *syncRun) syncFile(p string, e dirent) error { + if err := r.canceled(); err != nil { + return err + } + if r.seen[p] { + return nil + } + r.seen[p] = true + size := *e.Size + fp := fingerprint(e.ID, e.Mtime, size) + if previous := r.cur.Files[p]; previous != "" && previous == fp { + return nil + } + if size > r.limit { + return r.failFile(p, e, reasonFileTooLarge, 0) + } + + link, oid, err := r.client.downloadLink(r.ctx, r.repoID, p) + if err != nil { + return r.fetchError(p, e, err, linkReason(err)) + } + if oid != "" && e.ID != "" && oid != e.ID { + return r.failFile(p, e, reasonSourceChanged, 0) + } + body, err := r.client.download(r.ctx, link, size, r.limit) + if err != nil { + return r.fetchError(p, e, err, downloadReason(err)) + } + if err := r.emit(r.buildItem(p, e, body)); err != nil { + return err + } + r.cur.Files[p] = fp + return r.mutated() +} + +func linkReason(err error) string { + switch { + case statusOf(err) == http.StatusForbidden: + return reasonPermissionDenied + case statusOf(err) == http.StatusNotFound: + return reasonNotFound + case errors.Is(err, errInvalidResponse): + return reasonInvalidResponse + default: + return reasonFetchFailed + } +} + +func downloadReason(err error) string { + switch { + case errors.Is(err, errSSRFBlocked): + return reasonSSRFBlocked + case errors.Is(err, errTooLarge): + return reasonFileTooLarge + case errors.Is(err, errEmptyFile): + return reasonEmptyFile + case errors.Is(err, errSourceChanged): + return reasonSourceChanged + default: + return reasonFetchFailed + } +} + +// fetchError isolates a per-file failure as an error item, except for +// cancellation and an over-long Retry-After, which end the run. Client +// errors carry only the operation and status, so logging them is safe. +func (r *syncRun) fetchError(p string, e dirent, err error, code string) error { + if canceled := r.canceledOr(err); canceled != err { + return canceled + } + if errors.Is(err, errRetryAfterTooLong) { + return r.abort(err) + } + logger.Warnf(r.ctx, "[Seafile] fetch failed: repo=%s path=%s code=%s: %v", r.repoID, p, code, err) + return r.failFile(p, e, code, statusOf(err)) +} + +func (r *syncRun) failFile(p string, e dirent, code string, status int) error { + if err := r.emit(r.errorItem(p, e, code, status)); err != nil { + return err + } + return r.markFailed(p) +} + +// markFailed keeps a known path alive with an empty fingerprint so it is +// retried next run and still reconciled if it disappears. Paths the cursor +// never knew stay absent. +func (r *syncRun) markFailed(p string) error { + value, known := r.cur.Files[p] + _, inBaseline := r.cur.FullSyncBaseline[p] + if (known && value != "") || (!known && inBaseline) { + r.cur.Files[p] = "" + return r.mutated() + } + return nil +} + +// reconcile emits deletions for every known path not seen this run. It only +// runs after every root enumerated successfully. +func (r *syncRun) reconcile() error { + if err := r.canceled(); err != nil { + return err + } + missing := make(map[string]bool) + for p := range r.cur.Files { + if !r.seen[p] { + missing[p] = true + } + } + if r.cur.FullSync { + for p := range r.cur.FullSyncBaseline { + if !r.seen[p] { + missing[p] = true + } + } + } + paths := make([]string, 0, len(missing)) + for p := range missing { + paths = append(paths, p) + } + sort.Strings(paths) + if len(paths) > 0 && r.unsaved > 0 { + if err := r.checkpoint(); err != nil { + return err + } + } + for _, p := range paths { + if err := r.emit(r.deletedItem(p)); err != nil { + return err + } + delete(r.cur.Files, p) + delete(r.cur.FullSyncBaseline, p) + if err := r.mutated(); err != nil { + return err + } + } + if r.cur.FullSync { + r.cur.FullSync = false + r.cur.FullSyncBaseline = nil + r.unsaved++ + } + if r.unsaved > 0 { + return r.checkpoint() + } + return nil +} + +func (r *syncRun) identity(p string, e dirent) types.FetchedItem { + return types.FetchedItem{ + ExternalID: externalID(r.repoID, p), + Title: r.repoName + "/" + strings.TrimPrefix(p, "/"), + FileName: knowledgeFileName(r.repoName, p), + UpdatedAt: time.Unix(e.Mtime, 0).UTC(), + SourceResourceID: encodeResourceID(r.repoID, "/"), + } +} + +func (r *syncRun) buildItem(p string, e dirent, body []byte) types.FetchedItem { + item := r.identity(p, e) + item.Content = body + item.ContentType = http.DetectContentType(body) + item.Metadata = map[string]string{ + "channel": types.ChannelSeafile, + "source_type": "seafile", + "seafile_repo_id": r.repoID, + "seafile_repo_name": r.repoName, + "seafile_path": p, + "seafile_object_id": e.ID, + "seafile_mtime": strconv.FormatInt(e.Mtime, 10), + "seafile_size": strconv.FormatInt(*e.Size, 10), + } + return item +} + +// errorItem follows the service contract for failed fetches: no content, a +// stable reason code and English fallback text. The text is fixed so +// credentials and signed links never reach sync logs. +func (r *syncRun) errorItem(p string, e dirent, code string, status int) types.FetchedItem { + item := r.identity(p, e) + item.Metadata = map[string]string{ + "channel": types.ChannelSeafile, + "source_type": "seafile", + "seafile_path": p, + "error": errorReason(code), + "error_reason_code": code, + "error_reason": errorReason(code), + } + if status > 0 { + item.Metadata["error_reason_code_value"] = strconv.Itoa(status) + } + return item +} + +func (r *syncRun) deletedItem(p string) types.FetchedItem { + return types.FetchedItem{ + ExternalID: externalID(r.repoID, p), + Title: r.repoName + "/" + strings.TrimPrefix(p, "/"), + IsDeleted: true, + SourceResourceID: encodeResourceID(r.repoID, "/"), + Metadata: map[string]string{"channel": types.ChannelSeafile, "seafile_path": p}, + } +} diff --git a/internal/datasource/connector/seafile/sync_scale_test.go b/internal/datasource/connector/seafile/sync_scale_test.go new file mode 100644 index 00000000..fd55a50c --- /dev/null +++ b/internal/datasource/connector/seafile/sync_scale_test.go @@ -0,0 +1,107 @@ +package seafile + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestSyncScale(t *testing.T) { + f, c, cfg := syncFixture(t, "/") + dirTarget := 300 + if os.Getenv("SEAFILE_SCALE_TEST") == "1" { + dirTarget = 3000 + } + // Each group has one level-one dir, one level-two dir and eight + // level-three dirs. All 300 (or 3000) non-root dirs have ten files. + groups := dirTarget / 10 + for g := 0; g < groups; g++ { + top := fmt.Sprintf("/g%03d", g) + mid := top + "/middle" + dirs := []string{top, mid} + for leaf := 0; leaf < 8; leaf++ { + dirs = append(dirs, fmt.Sprintf("%s/leaf%02d", mid, leaf)) + } + for _, dir := range dirs { + addNumberedFiles(f, dir, 10) + } + } + directoryCount := 0 + f.mu.Lock() + for _, node := range f.tree[testRepoID] { + if node.Type == "dir" { + directoryCount++ + } + } + f.mu.Unlock() + if directoryCount != dirTarget+1 { + t.Fatalf("fixture has %d directories, want %d", directoryCount, dirTarget+1) + } + fileCount := dirTarget * 10 + full := compactRecorder() + cur, err := run(t, c, cfg, nil, full, true) + if err != nil { + t.Fatal(err) + } + if len(full.contentItems()) != fileCount || len(full.items) != fileCount || len(filesOf(cur)) != fileCount { + t.Fatalf("full items=%d, total=%d, cursor=%d", len(full.contentItems()), len(full.items), len(filesOf(cur))) + } + h := compactRecorder() + retain := h.onCheckpoint + h.onCheckpoint = func(cp map[string]any) { + retain(cp) + if len(filesOf(&types.SyncCursor{ConnectorCursor: cp})) >= fileCount/2 { + h.cancel() + } + } + _, err = run(t, c, cfg, cur, h, true) + if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 { + t.Fatalf("midpoint cancel = %v, late checkpoints=%d", err, h.checkpointsAfterStop) + } + saved := checkpointCursor(t, h) + savedFiles := filesOf(saved) + // Checkpoints land every 50 mutations, and the full-sync switch is one of + // them, so the saved batch ends within one batch of the midpoint. + if len(savedFiles) < fileCount/2 || len(savedFiles) >= fileCount/2+checkpointEvery || + !mustCursor(t, saved).FullSync { + t.Fatalf("midpoint saved %d/%d files", len(savedFiles), fileCount) + } + f.resetCounts() + resumed := compactRecorder() + cur, err = run(t, c, cfg, saved, resumed, false) + if err != nil { + t.Fatal(err) + } + if len(resumed.contentItems()) != fileCount-len(savedFiles) || len(filesOf(cur)) != fileCount || + len(resumed.deletedItems()) != 0 || len(resumed.errorItems()) != 0 { + t.Fatalf("resume content=%d, cursor=%d, deleted=%d, errors=%d", + len(resumed.contentItems()), len(filesOf(cur)), len(resumed.deletedItems()), len(resumed.errorItems())) + } + for p := range savedFiles { + if f.count("download:"+p) != 0 { + t.Fatalf("resume downloaded saved file %s", p) + } + } + f.resetCounts() + cur, unchanged := mustRun(t, c, cfg, cur, false) + if len(unchanged.items) != 0 || f.countPrefix("download:") != 0 || + f.countPrefix("dir:") != directoryCount || f.count("repos") != 1 || len(unchanged.checkpoints) > 1 { + t.Fatalf("unchanged: items=%d, downloads=%d, dirs=%d/%d, repos=%d, checkpoints=%d", + len(unchanged.items), f.countPrefix("download:"), f.countPrefix("dir:"), directoryCount, + f.count("repos"), len(unchanged.checkpoints)) + } + if os.Getenv("SEAFILE_SCALE_TEST") == "1" { + data, err := json.Marshal(cur.ConnectorCursor) + if err != nil { + t.Fatal(err) + } + t.Logf("files=%d cursor_bytes=%d checkpoints: full=%d interrupted=%d resumed=%d unchanged=%d", + fileCount, len(data), full.checkpointCalls, h.checkpointCalls, resumed.checkpointCalls, + unchanged.checkpointCalls) + } +} diff --git a/internal/datasource/connector/seafile/sync_test.go b/internal/datasource/connector/seafile/sync_test.go new file mode 100644 index 00000000..1015397a --- /dev/null +++ b/internal/datasource/connector/seafile/sync_test.go @@ -0,0 +1,989 @@ +package seafile + +import ( + "context" + "crypto/sha1" + "encoding/json" + "errors" + "fmt" + "reflect" + "slices" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +var errRecordedEmit = errors.New("recorder emit failed") + +type recorder struct { + items []types.FetchedItem + checkpoints []map[string]any + failEmitAfter int + cancelAfter int + cancel context.CancelFunc + checkpointErr error + + onEmit func(types.FetchedItem) + onCheckpoint func(map[string]any) + checkpointCalls int + checkpointsAfterStop int + stopped bool +} + +var _ datasource.StreamHandler = (*recorder)(nil) + +func (h *recorder) Emit(_ context.Context, item types.FetchedItem) error { + h.items = append(h.items, item) + if h.onEmit != nil { + h.onEmit(item) + } + if h.failEmitAfter > 0 && len(h.items) >= h.failEmitAfter { + h.stopped = true + return errRecordedEmit + } + if h.cancelAfter > 0 && len(h.items) >= h.cancelAfter { + h.stopped = true + h.cancel() + } + return nil +} + +func (h *recorder) Checkpoint(ctx context.Context, cur *types.SyncCursor) error { + h.checkpointCalls++ + if h.stopped || ctx.Err() != nil { + h.checkpointsAfterStop++ + } + snapshot := cloneConnectorCursor(cur.ConnectorCursor) + h.checkpoints = append(h.checkpoints, snapshot) + if h.checkpointErr != nil { + h.stopped = true + return h.checkpointErr + } + if h.onCheckpoint != nil { + h.onCheckpoint(snapshot) + } + return nil +} + +func (h *recorder) contentItems() []types.FetchedItem { + var out []types.FetchedItem + for _, item := range h.items { + if !item.IsDeleted && item.Content != nil && item.Metadata["error"] == "" { + out = append(out, item) + } + } + return out +} + +func (h *recorder) errorItems() []types.FetchedItem { + var out []types.FetchedItem + for _, item := range h.items { + if item.Metadata["error"] != "" { + out = append(out, item) + } + } + return out +} + +func (h *recorder) deletedItems() []types.FetchedItem { + var out []types.FetchedItem + for _, item := range h.items { + if item.IsDeleted { + out = append(out, item) + } + } + return out +} + +func (h *recorder) paths() []string { + out := make([]string, 0, len(h.items)) + for _, item := range h.items { + out = append(out, item.Metadata["seafile_path"]) + } + slices.Sort(out) + return out +} + +func run( + t *testing.T, c *Connector, cfg *types.DataSourceConfig, old *types.SyncCursor, h *recorder, full bool, +) (*types.SyncCursor, error) { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + h.cancel = cancel + if full { + return c.FetchFullStream(ctx, cfg, old, h) + } + return c.FetchStream(ctx, cfg, old, h) +} + +func cloneConnectorCursor(m map[string]any) map[string]any { + b, err := json.Marshal(m) + if err != nil { + panic(err) + } + var out map[string]any + if err := json.Unmarshal(b, &out); err != nil { + panic(err) + } + return out +} + +func filesOf(cur *types.SyncCursor) map[string]string { + if cur == nil { + return nil + } + b, err := json.Marshal(cur.ConnectorCursor["files"]) + if err != nil { + panic(err) + } + var files map[string]string + if err := json.Unmarshal(b, &files); err != nil { + panic(err) + } + return files +} + +func syncConfig(f *fakeSeafile, roots ...string) *types.DataSourceConfig { + cfg := &types.DataSourceConfig{Credentials: map[string]any{ + "base_url": f.baseURL(), "api_token": testToken, + }} + for _, p := range roots { + cfg.ResourceIDs = append(cfg.ResourceIDs, testRepoID+":"+p) + } + return cfg +} + +func syncFixture(t *testing.T, roots ...string) (*fakeSeafile, *Connector, *types.DataSourceConfig) { + t.Helper() + noWait(t) + f := newFakeSeafile(t) + f.addRepo(testRepoID, "Library", "repo", false) + return f, NewConnector(), syncConfig(f, roots...) +} + +func seededCursor(t *testing.T, name string, files map[string]string) *types.SyncCursor { + t.Helper() + c, _, err := prepareCursor(nil, testRepoID, false) + if err != nil { + t.Fatal(err) + } + c.RepoName = name + c.Files = files + return c.toSyncCursor() +} + +func cursorJSON(t *testing.T, c *types.SyncCursor) string { + t.Helper() + b, err := json.Marshal(c) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func mustCursor(t *testing.T, cur *types.SyncCursor) cursor { + t.Helper() + if cur == nil { + t.Fatal("missing cursor") + } + c, err := decodeCursor(cur) + if err != nil { + t.Fatal(err) + } + return c +} + +func checkpointCursor(t *testing.T, h *recorder) *types.SyncCursor { + t.Helper() + if len(h.checkpoints) == 0 { + t.Fatal("missing checkpoint") + } + return &types.SyncCursor{ConnectorCursor: cloneConnectorCursor(h.checkpoints[len(h.checkpoints)-1])} +} + +func mustRun( + t *testing.T, c *Connector, cfg *types.DataSourceConfig, old *types.SyncCursor, full bool, +) (*types.SyncCursor, *recorder) { + t.Helper() + h := &recorder{} + cur, err := run(t, c, cfg, old, h, full) + if err != nil { + t.Fatal(err) + } + if cur == nil { + t.Fatal("successful run returned no cursor") + } + return cur, h +} + +func assertPaths(t *testing.T, items []types.FetchedItem, want ...string) { + t.Helper() + h := &recorder{items: items} + got := h.paths() + want = slices.Clone(want) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } + for _, item := range items { + p := item.Metadata["seafile_path"] + if item.ExternalID != "seafile:"+testRepoID+":"+p || item.SourceResourceID != testRepoID+":/" { + t.Fatalf("item identity = %+v", item) + } + } +} + +func addNumberedFiles(f *fakeSeafile, dir string, n int) { + for i := 0; i < n; i++ { + f.addFile(testRepoID, fmt.Sprintf("%s/%03d.pdf", dir, i), []byte("x"), 1) + } +} + +// assertFullSyncCleared checks that a completed full run dropped both the +// flag and the baseline from the persisted cursor. +func assertFullSyncCleared(t *testing.T, cur *types.SyncCursor) { + t.Helper() + if cur == nil { + t.Fatal("missing cursor") + } + _, flag := cur.ConnectorCursor["full_sync"] + _, baseline := cur.ConnectorCursor["full_sync_baseline"] + if flag || baseline { + t.Fatalf("completed full sync kept its state: %v", cur.ConnectorCursor) + } +} + +func assertPending(t *testing.T, cur *types.SyncCursor, p string) { + t.Helper() + if fp, ok := filesOf(cur)[p]; !ok || fp != "" { + t.Fatalf("%s should be retained with empty fingerprint: %v", p, filesOf(cur)) + } +} + +func TestSyncRecursiveScopeAndMetadata(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs", "/docs/产品") + f.addFile(testRepoID, "/docs/产品/需求: v2.docx", []byte("body"), 7) + f.addFile(testRepoID, "/docs/map.xmind", []byte("map"), 1) + f.addFile(testRepoID, "/docs/skip.zip", []byte("zip"), 1) + f.addFile(testRepoID, "/docs/skip.mdx", []byte("mdx"), 1) + f.addFile(testRepoID, "/docs-sibling/secret.pdf", []byte("secret"), 1) + cur, h := mustRun(t, c, cfg, nil, false) + assertPaths(t, h.contentItems(), "/docs/产品/需求: v2.docx", "/docs/map.xmind") + if len(h.errorItems()) != 0 || len(filesOf(cur)) != 2 || f.count("dir:/docs/产品") != 1 || + f.count("dir:/docs-sibling") != 0 || f.count("file:/docs/skip.zip") != 0 || + f.count("file:/docs/skip.mdx") != 0 { + t.Fatalf("scope traversal: counts=%v, files=%v", f.counts(), filesOf(cur)) + } + for _, item := range h.contentItems() { + p := item.Metadata["seafile_path"] + if item.FileName != knowledgeFileName("Library", p) || item.Title != "Library"+p { + t.Fatalf("display names = %+v", item) + } + if item.Metadata["channel"] != "seafile" || item.Metadata["source_type"] == "" || + item.Metadata["seafile_repo_id"] != testRepoID || item.Metadata["seafile_repo_name"] != "Library" { + t.Fatalf("metadata = %v", item.Metadata) + } + if strings.HasSuffix(p, ".docx") { + oid := fmt.Sprintf("%x", sha1.Sum([]byte("body"))) + if string(item.Content) != "body" || item.Metadata["seafile_object_id"] != oid || + item.Metadata["seafile_mtime"] != "7" || item.Metadata["seafile_size"] != "4" { + t.Fatalf("content metadata = %+v", item) + } + } + } + f.addFile(testRepoID, "/docs/new/deep/new.pdf", []byte("new"), 2) + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems(), "/docs/new/deep/new.pdf") + if len(filesOf(cur)) != 3 { + t.Fatalf("descendant missing from cursor: %v", filesOf(cur)) + } +} + +func TestSyncSingleFileAndDisappearance(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs/a.pdf") + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + f.addFile(testRepoID, "/docs/b.pdf", []byte("b"), 1) + f.addFile(testRepoID, "/docs/sub/c.pdf", []byte("c"), 1) + old, h := mustRun(t, c, cfg, nil, false) + assertPaths(t, h.contentItems(), "/docs/a.pdf") + // The root is probed once as a directory (404), then its parent is listed once. + if f.count("dir:/docs") != 1 || f.count("dir:/docs/a.pdf") != 1 || f.countPrefix("dir:") != 2 || + f.countPrefix("download:") != 1 { + t.Fatalf("single-file selection requests = %v", f.counts()) + } + before := cursorJSON(t, old) + f.removePath(testRepoID, "/docs/a.pdf") + h = &recorder{} + cur, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, datasource.ErrResourceNotFound) || len(h.deletedItems()) != 0 { + t.Fatalf("selected file disappeared: %v, items=%+v", err, h.items) + } + if cursorJSON(t, old) != before { + t.Fatal("failed run mutated the old cursor") + } + if cur != nil { + if _, ok := filesOf(cur)["/docs/a.pdf"]; !ok { + t.Fatal("returned cursor forgot the selected file") + } + } + for _, cp := range h.checkpoints { + if _, ok := filesOf(&types.SyncCursor{ConnectorCursor: cp})["/docs/a.pdf"]; !ok { + t.Fatal("checkpoint forgot the selected file") + } + } +} + +func TestSyncUnsupportedFileRootIsSkipped(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs/archive.zip", "/docs/sub") + f.addFile(testRepoID, "/docs/archive.zip", []byte("zip"), 1) + f.addFile(testRepoID, "/docs/sub/a.pdf", []byte("a"), 1) + cur, h := mustRun(t, c, cfg, nil, false) + assertPaths(t, h.contentItems(), "/docs/sub/a.pdf") + if len(h.errorItems()) != 0 || f.count("file:/docs/archive.zip") != 0 || len(filesOf(cur)) != 1 { + t.Fatalf("unsupported file root: items=%+v, counts=%v, files=%v", h.items, f.counts(), filesOf(cur)) + } + // A selected directory replaced by an extensionless file loses its + // children through reconciliation instead of importing the replacement. + f.removePath(testRepoID, "/docs/sub") + f.addFile(testRepoID, "/docs/sub", []byte("blob"), 2) + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems()) + assertPaths(t, h.deletedItems(), "/docs/sub/a.pdf") + if f.count("file:/docs/sub") != 0 || len(filesOf(cur)) != 0 { + t.Fatalf("directory replaced by unsupported file: counts=%v, files=%v", f.counts(), filesOf(cur)) + } +} + +func TestSyncFileReplacedByDirectory(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/docs/a.pdf") + f.addFile(testRepoID, "/docs/a.pdf/child.pdf", []byte("child"), 2) + cur, h := mustRun(t, c, cfg, old, false) + assertPaths(t, h.contentItems(), "/docs/a.pdf/child.pdf") + assertPaths(t, h.deletedItems(), "/docs/a.pdf") + if len(filesOf(cur)) != 1 || f.count("dir:/docs/a.pdf") != 1 { + t.Fatalf("directory without size not traversed: %v, %v", filesOf(cur), f.counts()) + } +} + +func TestSyncNoChangeAndMtimeOnly(t *testing.T) { + f, c, cfg := syncFixture(t, "/") + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + f.addFile(testRepoID, "/docs/sub/b.pdf", []byte("b"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.resetCounts() + cur, h := mustRun(t, c, cfg, old, false) + if len(h.items) != 0 || f.countPrefix("download:") != 0 || f.countPrefix("dir:") != 3 || + f.count("repos") != 1 || len(h.checkpoints) > 1 { + t.Fatalf("unchanged run: counts=%v, items=%d, checkpoints=%d", f.counts(), len(h.items), len(h.checkpoints)) + } + f.touch(testRepoID, "/docs/a.pdf") + f.resetCounts() + next, h := mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems(), "/docs/a.pdf") + if f.count("download:/docs/a.pdf") != 1 || filesOf(next)["/docs/a.pdf"] == filesOf(cur)["/docs/a.pdf"] { + t.Fatal("mtime-only change did not re-download and update the fingerprint") + } +} + +func TestSyncFileFailures(t *testing.T) { + cases := []struct { + name, code string + status int + inject func(*fakeSeafile, string) + }{ + {"forbidden", "seafile_permission_denied", 403, func(f *fakeSeafile, p string) { f.fail("file:"+p, 403, -1) }}, + {"missing", "seafile_not_found", 404, func(f *fakeSeafile, p string) { f.fail("file:"+p, 404, -1) }}, + {"server error", "seafile_fetch_failed", 500, func(f *fakeSeafile, p string) { f.fail("file:"+p, 500, -1) }}, + {"empty", "seafile_empty_file", 0, func(f *fakeSeafile, p string) { f.setBody(testRepoID, p, nil) }}, + {"listed oversize", "seafile_file_too_large", 0, func(f *fakeSeafile, p string) { + f.setBody(testRepoID, p, []byte(strings.Repeat("x", (1<<20)+1))) + }}, + {"chunked oversize", "seafile_file_too_large", 0, func(f *fakeSeafile, p string) { + f.chunkedOversize[p] = (1 << 20) + 1 + }}, + {"changed object", "seafile_source_changed", 0, func(f *fakeSeafile, p string) { + f.linkOID[p] = "different-object" + }}, + {"malformed link", "seafile_invalid_response", 0, func(f *fakeSeafile, p string) { + f.rawBody["file:"+p] = "{" + }}, + {"SSRF", "seafile_ssrf_blocked", 0, func(f *fakeSeafile, p string) { + f.linkURL[p] = "http://169.254.169.254/blocked" + }}, + } + for _, tc := range cases { + for _, known := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/known=%v", tc.name, known), func(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + // GetMaxFileSize reads this environment variable without caching. + t.Setenv("MAX_FILE_SIZE_MB", "1") + p := "/docs/a.pdf" + f.addFile(testRepoID, p, []byte("body"), 1) + var old *types.SyncCursor + if known { + old, _ = mustRun(t, c, cfg, nil, false) + f.touch(testRepoID, p) + } + tc.inject(f, p) + cur, h := mustRun(t, c, cfg, old, false) + assertPaths(t, h.errorItems(), p) + if len(h.items) != 1 { + t.Fatalf("failure emitted extra items: %+v", h.items) + } + item := h.errorItems()[0] + if item.Content != nil || item.IsDeleted || item.Metadata["error_reason_code"] != tc.code || + item.Metadata["error_reason"] == "" { + t.Fatalf("error item = %+v", item) + } + if value := item.Metadata["error_reason_code_value"]; tc.status != 0 && value != fmt.Sprint(tc.status) { + t.Fatalf("HTTP reason value = %q, status=%d", value, tc.status) + } + if known { + assertPending(t, cur, p) + } else if _, ok := filesOf(cur)[p]; ok { + t.Fatalf("unknown failure entered cursor: %v", filesOf(cur)) + } + f.mu.Lock() + delete(f.failures, "file:"+p) + delete(f.chunkedOversize, p) + delete(f.linkOID, p) + delete(f.linkURL, p) + delete(f.rawBody, "file:"+p) + f.mu.Unlock() + f.setBody(testRepoID, p, []byte("recovered")) + f.resetCounts() + next, retry := mustRun(t, c, cfg, cur, false) + assertPaths(t, retry.contentItems(), p) + if filesOf(next)[p] == "" || f.count("download:"+p) != 1 { + t.Fatalf("pending file not retried: %v, %v", filesOf(next), f.counts()) + } + }) + } + } +} + +func TestSyncExactSizeLimit(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + t.Setenv("MAX_FILE_SIZE_MB", "1") + body := []byte(strings.Repeat("x", 1<<20)) + f.addFile(testRepoID, "/docs/exact.pdf", body, 1) + _, h := mustRun(t, c, cfg, nil, false) + assertPaths(t, h.contentItems(), "/docs/exact.pdf") + if len(h.contentItems()[0].Content) != len(body) || len(h.errorItems()) != 0 { + t.Fatal("file exactly at limit was not accepted") + } +} + +func TestSyncCheckpointCadenceAndResume(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + addNumberedFiles(f, "/docs", 120) + cur, h := mustRun(t, c, cfg, nil, false) + if len(h.contentItems()) != 120 || len(h.checkpoints) < 3 { + t.Fatalf("items=%d, checkpoints=%d", len(h.contentItems()), len(h.checkpoints)) + } + previous := 0 + for _, cp := range h.checkpoints { + n := len(filesOf(&types.SyncCursor{ConnectorCursor: cp})) + if n < previous || n-previous > 50 { + t.Fatalf("checkpoint sizes: previous=%d, current=%d", previous, n) + } + previous = n + } + if previous != 120 || len(filesOf(cur)) != 120 { + t.Fatalf("final checkpoint=%d, files=%d", previous, len(filesOf(cur))) + } + // From an initialized cursor every mutation is a file, so the first + // checkpoint lands exactly on the 50th file. + h = &recorder{} + h.onCheckpoint = func(cp map[string]any) { + if len(filesOf(&types.SyncCursor{ConnectorCursor: cp})) >= 50 { + h.cancel() + } + } + _, err := run(t, c, cfg, seededCursor(t, "Library", map[string]string{}), h, false) + if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 { + t.Fatalf("checkpoint cancellation = %v; late checkpoints=%d", err, h.checkpointsAfterStop) + } + saved := checkpointCursor(t, h) + savedFiles := filesOf(saved) + if len(savedFiles) != 50 { + t.Fatalf("first progress checkpoint saved %d files", len(savedFiles)) + } + f.resetCounts() + cur, resumed := mustRun(t, c, cfg, saved, false) + if len(resumed.contentItems()) != 70 || len(filesOf(cur)) != 120 { + t.Fatalf("resume items=%d, files=%d", len(resumed.contentItems()), len(filesOf(cur))) + } + for p := range savedFiles { + if f.count("download:"+p) != 0 { + t.Fatalf("saved file downloaded again: %s", p) + } + } +} + +// Known-file failures flip fingerprints to empty; those mutations must +// respect the same 50-change checkpoint bound as successful downloads. +func TestSyncKnownFailuresCheckpointCadence(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + addNumberedFiles(f, "/docs", 120) + old, _ := mustRun(t, c, cfg, nil, false) + for i := 0; i < 120; i++ { + p := fmt.Sprintf("/docs/%03d.pdf", i) + f.touch(testRepoID, p) + f.fail("file:"+p, 500, -1) + } + pending := func(cp map[string]any) int { + n := 0 + for _, fp := range filesOf(&types.SyncCursor{ConnectorCursor: cp}) { + if fp == "" { + n++ + } + } + return n + } + h := &recorder{} + h.onCheckpoint = func(cp map[string]any) { + if pending(cp) >= 50 { + h.cancel() + } + } + _, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 { + t.Fatalf("failure cadence = %v; late checkpoints=%d", err, h.checkpointsAfterStop) + } + if got := pending(h.checkpoints[len(h.checkpoints)-1]); got != 50 || len(h.errorItems()) != 50 { + t.Fatalf("first failure checkpoint saved %d pending paths after %d error items", got, len(h.errorItems())) + } + + h = &recorder{checkpointErr: errors.New("checkpoint unavailable")} + if _, err := run(t, c, cfg, old, h, false); !errors.Is(err, h.checkpointErr) || len(h.errorItems()) != 50 { + t.Fatalf("checkpoint failure on the failure path = %v after %d error items", err, len(h.errorItems())) + } +} + +func TestSyncHandlerFailuresStopImmediately(t *testing.T) { + checkpointFailure := errors.New("checkpoint unavailable") + for _, tc := range []struct { + name string + handler *recorder + want error + emits, checkpoints int + }{ + {"early cancel", &recorder{cancelAfter: 1}, context.Canceled, 1, 0}, + {"cancel after progress", &recorder{cancelAfter: 51}, context.Canceled, 51, 1}, + {"emit failure", &recorder{failEmitAfter: 51}, errRecordedEmit, 51, 1}, + {"checkpoint failure", &recorder{checkpointErr: checkpointFailure}, checkpointFailure, 50, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + addNumberedFiles(f, "/docs", 120) + _, err := run(t, c, cfg, seededCursor(t, "Library", map[string]string{}), tc.handler, false) + h := tc.handler + if !errors.Is(err, tc.want) || len(h.items) != tc.emits || len(h.checkpoints) != tc.checkpoints || + h.checkpointsAfterStop != 0 || f.countPrefix("download:") != tc.emits || + f.countPrefix("file:") != tc.emits { + t.Fatalf("err=%v, emits=%d, checkpoints=%d, late=%d, counts=%v", + err, len(h.items), len(h.checkpoints), h.checkpointsAfterStop, f.counts()) + } + }) + } +} + +func TestSyncDeletionAndCheckpointBeforeDeletion(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/gone.pdf", []byte("gone"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/docs/gone.pdf") + f.addFile(testRepoID, "/docs/new.pdf", []byte("new"), 1) + h := &recorder{} + h.onEmit = func(item types.FetchedItem) { + if item.IsDeleted { + saved := filesOf(checkpointCursor(t, h)) + if saved["/docs/new.pdf"] == "" || saved["/docs/gone.pdf"] == "" { + t.Fatalf("pre-deletion checkpoint lost progress/baseline: %v", saved) + } + } + } + cur, err := run(t, c, cfg, old, h, false) + if err != nil { + t.Fatal(err) + } + assertPaths(t, h.deletedItems(), "/docs/gone.pdf") + assertPaths(t, h.contentItems(), "/docs/new.pdf") + if len(filesOf(cur)) != 1 { + t.Fatalf("deletion not reflected in cursor: %v", filesOf(cur)) + } + _, again := mustRun(t, c, cfg, cur, false) + assertPaths(t, again.deletedItems()) +} + +// Cancellation raised inside a handler callback during reconciliation must stop +// the connector itself: no further deletion is emitted and nothing is saved. +func TestSyncCancelDuringReconciliationStopsImmediately(t *testing.T) { + for _, tc := range []struct { + name string + wire func(h *recorder) + emits int + }{ + {"pre-deletion checkpoint", func(h *recorder) { + h.onCheckpoint = func(map[string]any) { h.cancel() } + }, 1}, + {"first deletion", func(h *recorder) { + h.onEmit = func(item types.FetchedItem) { + if item.IsDeleted { + h.cancel() + } + } + }, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/gone-a.pdf", []byte("a"), 1) + f.addFile(testRepoID, "/docs/gone-b.pdf", []byte("b"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/docs/gone-a.pdf") + f.removePath(testRepoID, "/docs/gone-b.pdf") + f.addFile(testRepoID, "/docs/new.pdf", []byte("new"), 1) + h := &recorder{} + tc.wire(h) + _, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, context.Canceled) || len(h.items) != tc.emits || len(h.checkpoints) != 1 { + t.Fatalf("cancel in %s = %v, items=%d, checkpoints=%d", tc.name, err, len(h.items), len(h.checkpoints)) + } + }) + } +} + +func TestSyncDirectoryFailuresKeepProgressAndSuppressDeletion(t *testing.T) { + for _, tc := range []struct { + name string + inject func(*fakeSeafile) + want error + reason string + }{ + {"500", func(f *fakeSeafile) { f.fail("dir:/z", 500, -1) }, datasource.ErrFetchFailed, ""}, + {"503 exhausted", func(f *fakeSeafile) { f.fail("dir:/z", 503, -1) }, datasource.ErrFetchFailed, ""}, + {"subdir forbidden", func(f *fakeSeafile) { + f.addDir(testRepoID, "/z/private") + f.forbidden["/z/private"] = true + }, datasource.ErrFetchFailed, "seafile_permission_denied"}, + {"malformed entry", func(f *fakeSeafile) { + f.rawBody["dir:/z"] = `[{"id":"bad","name":"../outside.pdf","type":"file","size":1,"mtime":1}]` + }, datasource.ErrFetchFailed, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + f, c, cfg := syncFixture(t, "/a", "/z") + f.addFile(testRepoID, "/a/gone.pdf", []byte("gone"), 1) + f.addFile(testRepoID, "/z/keep.pdf", []byte("keep"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/a/gone.pdf") + f.addFile(testRepoID, "/a/new.pdf", []byte("new"), 1) + tc.inject(f) + h := &recorder{} + _, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, tc.want) || (tc.reason != "" && !strings.Contains(err.Error(), tc.reason)) { + t.Fatalf("directory failure = %v, want %v / %s", err, tc.want, tc.reason) + } + assertPaths(t, h.deletedItems()) + assertPaths(t, h.contentItems(), "/a/new.pdf") + saved := filesOf(checkpointCursor(t, h)) + for _, p := range []string{"/a/gone.pdf", "/a/new.pdf", "/z/keep.pdf"} { + if saved[p] == "" { + t.Fatalf("directory failure lost %s: %v", p, saved) + } + } + }) + } +} + +func TestSyncFileFailureDoesNotSuppressOtherDeletions(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/fail.pdf", []byte("fail"), 1) + f.addFile(testRepoID, "/docs/gone.pdf", []byte("gone"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.touch(testRepoID, "/docs/fail.pdf") + f.fail("file:/docs/fail.pdf", 500, -1) + f.removePath(testRepoID, "/docs/gone.pdf") + cur, h := mustRun(t, c, cfg, old, false) + assertPaths(t, h.errorItems(), "/docs/fail.pdf") + assertPaths(t, h.deletedItems(), "/docs/gone.pdf") + assertPending(t, cur, "/docs/fail.pdf") + if len(filesOf(cur)) != 1 { + t.Fatalf("cursor = %v", filesOf(cur)) + } +} + +func TestSyncLongRetryAfterAborts(t *testing.T) { + f, c, cfg := syncFixture(t, "/a", "/b", "/z") + f.addFile(testRepoID, "/a/gone.pdf", []byte("gone"), 1) + f.addDir(testRepoID, "/b") + f.addFile(testRepoID, "/z/later.pdf", []byte("later"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/a/gone.pdf") + f.addFile(testRepoID, "/a/progress.pdf", []byte("progress"), 1) + f.addFile(testRepoID, "/b/stop.pdf", []byte("stop"), 1) + f.addFile(testRepoID, "/b/zz-later.pdf", []byte("later"), 1) + f.failWithRetryAfter("file:/b/stop.pdf", 429, -1, "120") + f.resetCounts() + h := &recorder{} + var atAbort map[string]int + h.onCheckpoint = func(map[string]any) { atAbort = f.counts() } + _, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, datasource.ErrFetchFailed) || f.count("file:/b/stop.pdf") != 1 || + f.count("download:/b/stop.pdf") != 0 || f.count("dir:/z") != 0 || + f.countPrefix("file:") != 2 || f.countPrefix("download:") != 1 { + t.Fatalf("Retry-After abort = %v, counts=%v", err, f.counts()) + } + assertPaths(t, h.deletedItems()) + saved := filesOf(checkpointCursor(t, h)) + if saved["/a/progress.pdf"] == "" || saved["/a/gone.pdf"] == "" || + !reflect.DeepEqual(atAbort, f.counts()) { + t.Fatalf("abort checkpoint or subsequent requests: saved=%v, before=%v, after=%v", saved, atAbort, f.counts()) + } +} + +func TestSyncMoveDuringScan(t *testing.T) { + f, c, cfg := syncFixture(t, "/A", "/B") + f.addFile(testRepoID, "/A/first.pdf", []byte("first"), 1) + f.addFile(testRepoID, "/B/moving.pdf", []byte("moving"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.touch(testRepoID, "/A/first.pdf") + f.resetCounts() + h := &recorder{} + moved := false + h.onEmit = func(item types.FetchedItem) { + if item.Metadata["seafile_path"] == "/A/first.pdf" && item.Content != nil { + if f.count("dir:/B") != 0 { + t.Fatal("B was listed before the move") + } + f.movePath(testRepoID, "/B/moving.pdf", "/A/moving.pdf") + moved = true + } + } + cur, err := run(t, c, cfg, old, h, false) + if err != nil || !moved { + t.Fatalf("move during scan = %v, moved=%v", err, moved) + } + assertPaths(t, h.contentItems(), "/A/first.pdf") + assertPaths(t, h.deletedItems(), "/B/moving.pdf") + _, next := mustRun(t, c, cfg, cur, false) + assertPaths(t, next.contentItems(), "/A/moving.pdf") + assertPaths(t, next.deletedItems()) +} + +func TestSyncRenameAndMoveOutOfScope(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/old.pdf", []byte("body"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.movePath(testRepoID, "/docs/old.pdf", "/docs/new.pdf") + cur, h := mustRun(t, c, cfg, old, false) + assertPaths(t, h.contentItems(), "/docs/new.pdf") + assertPaths(t, h.deletedItems(), "/docs/old.pdf") + f.movePath(testRepoID, "/docs/new.pdf", "/elsewhere/new.pdf") + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems()) + assertPaths(t, h.deletedItems(), "/docs/new.pdf") + if len(filesOf(cur)) != 0 || f.count("dir:/elsewhere") != 0 { + t.Fatalf("move out of scope: files=%v, counts=%v", filesOf(cur), f.counts()) + } +} + +func TestSyncScopeShrinkAndExpand(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/a/one.pdf", []byte("one"), 1) + f.addFile(testRepoID, "/docs/b/two.pdf", []byte("two"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + cfg.ResourceIDs = []string{testRepoID + ":/docs/a"} + cur, h := mustRun(t, c, cfg, old, false) + assertPaths(t, h.deletedItems(), "/docs/b/two.pdf") + assertPaths(t, h.contentItems()) + cfg.ResourceIDs = []string{testRepoID + ":/docs"} + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems(), "/docs/b/two.pdf") + assertPaths(t, h.deletedItems()) + if len(filesOf(cur)) != 2 { + t.Fatalf("expanded cursor = %v", filesOf(cur)) + } +} + +func TestSyncSelectedDirectoryDisappears(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/docs") + h := &recorder{} + cur, err := run(t, c, cfg, old, h, false) + if !errors.Is(err, datasource.ErrResourceNotFound) { + t.Fatalf("missing selected directory = %v", err) + } + assertPaths(t, h.deletedItems()) + if filesOf(old)["/docs/a.pdf"] == "" { + t.Fatal("lost the old directory's file") + } + if cur != nil && filesOf(cur)["/docs/a.pdf"] == "" { + t.Fatal("returned cursor lost the old directory's file") + } + for _, cp := range h.checkpoints { + if filesOf(&types.SyncCursor{ConnectorCursor: cp})["/docs/a.pdf"] == "" { + t.Fatal("checkpoint lost the old directory's file") + } + } +} + +func TestSyncForcedFullCancelResumeAndUnionDeletions(t *testing.T) { + for _, addedThenRemoved := range []bool{false, true} { + t.Run(fmt.Sprintf("added-then-removed=%v", addedThenRemoved), func(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + addNumberedFiles(f, "/docs", 65) + f.addFile(testRepoID, "/docs/vanished.pdf", []byte("gone"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + before := cursorJSON(t, old) + f.removePath(testRepoID, "/docs/vanished.pdf") + if addedThenRemoved { + f.addFile(testRepoID, "/docs/000-new.pdf", []byte("new"), 1) + } + f.resetCounts() + h := &recorder{} + h.onCheckpoint = func(map[string]any) { h.cancel() } + _, err := run(t, c, cfg, old, h, true) + if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 { + t.Fatalf("full cancel = %v, late checkpoints=%d", err, h.checkpointsAfterStop) + } + saved := checkpointCursor(t, h) + active := mustCursor(t, saved) + // Switching into full sync is itself a mutation, so the first batch + // holds 49 files. + batch := len(active.Files) + if !active.FullSync || !reflect.DeepEqual(active.FullSyncBaseline, filesOf(old)) || + batch != 49 || len(h.contentItems()) != batch || f.countPrefix("download:") != batch { + t.Fatalf("full checkpoint files=%d downloads=%d", batch, f.countPrefix("download:")) + } + if cursorJSON(t, old) != before { + t.Fatal("forced full mutated its input baseline") + } + wantDeleted := []string{"/docs/vanished.pdf"} + if addedThenRemoved { + if active.Files["/docs/000-new.pdf"] == "" { + t.Fatal("new file was not saved before cancellation") + } + f.removePath(testRepoID, "/docs/000-new.pdf") + wantDeleted = append(wantDeleted, "/docs/000-new.pdf") + } + f.resetCounts() + cur, resumed := mustRun(t, c, cfg, saved, false) + assertPaths(t, resumed.deletedItems(), wantDeleted...) + expectedRemaining := 65 - len(active.Files) + if addedThenRemoved { + expectedRemaining++ + } + if len(resumed.contentItems()) != expectedRemaining { + t.Fatalf("resume content=%d, want %d", len(resumed.contentItems()), expectedRemaining) + } + for p := range active.Files { + if f.count("download:"+p) != 0 { + t.Fatalf("full resume downloaded saved file %s", p) + } + } + assertFullSyncCleared(t, cur) + if len(filesOf(cur)) != 65 { + t.Fatalf("full completion files = %d", len(filesOf(cur))) + } + _, next := mustRun(t, c, cfg, cur, false) + assertPaths(t, next.items) + }) + } +} + +func TestSyncFullDirectoryFailureResumesIncrementally(t *testing.T) { + f, c, cfg := syncFixture(t, "/a", "/z") + f.addFile(testRepoID, "/a/one.pdf", []byte("one"), 1) + f.addFile(testRepoID, "/z/two.pdf", []byte("two"), 1) + f.addFile(testRepoID, "/z/gone.pdf", []byte("gone"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.removePath(testRepoID, "/z/gone.pdf") + f.fail("dir:/z", 500, -1) + h := &recorder{} + _, err := run(t, c, cfg, old, h, true) + if !errors.Is(err, datasource.ErrFetchFailed) { + t.Fatalf("full directory failure = %v", err) + } + assertPaths(t, h.contentItems(), "/a/one.pdf") + assertPaths(t, h.deletedItems()) + saved := checkpointCursor(t, h) + active := mustCursor(t, saved) + if !active.FullSync || !reflect.DeepEqual(active.FullSyncBaseline, filesOf(old)) || + active.Files["/a/one.pdf"] == "" { + t.Fatalf("interrupted full cursor = %+v", active) + } + f.fail("dir:/z", 500, 0) + f.resetCounts() + cur, resumed := mustRun(t, c, cfg, saved, false) + assertPaths(t, resumed.contentItems(), "/z/two.pdf") + assertPaths(t, resumed.deletedItems(), "/z/gone.pdf") + assertFullSyncCleared(t, cur) + if f.count("download:/a/one.pdf") != 0 || len(filesOf(cur)) != 2 { + t.Fatalf("completed cursor=%v, requests=%v", filesOf(cur), f.counts()) + } +} + +func TestSyncLibraryRenameKeepsFolderName(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.renameRepo(testRepoID, "Renamed library") + f.resetCounts() + cur, h := mustRun(t, c, cfg, old, false) + if len(h.items) != 0 || f.countPrefix("download:") != 0 || mustCursor(t, cur).RepoName != "Library" { + t.Fatalf("library rename caused churn: items=%+v, counts=%v, cursor=%+v", h.items, f.counts(), cur) + } + f.addFile(testRepoID, "/docs/b.pdf", []byte("b"), 1) + _, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.contentItems(), "/docs/b.pdf") + if h.contentItems()[0].FileName != "Library/docs/b.pdf" { + t.Fatalf("renamed library changed destination folder: %q", h.contentItems()[0].FileName) + } +} + +func TestSyncFullFailureRetainsPendingThenRetriesAndDeletes(t *testing.T) { + f, c, cfg := syncFixture(t, "/docs") + p := "/docs/a.pdf" + f.addFile(testRepoID, p, []byte("body"), 1) + old, _ := mustRun(t, c, cfg, nil, false) + f.fail("file:"+p, 500, -1) + cur, h := mustRun(t, c, cfg, old, true) + assertPaths(t, h.errorItems(), p) + assertPaths(t, h.deletedItems()) + assertPending(t, cur, p) + assertFullSyncCleared(t, cur) + f.resetCounts() + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.errorItems(), p) + assertPending(t, cur, p) + if f.count("file:"+p) == 0 { + t.Fatal("incremental did not retry the empty fingerprint") + } + f.removePath(testRepoID, p) + cur, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.deletedItems(), p) + if len(filesOf(cur)) != 0 { + t.Fatalf("deleted pending path remains: %v", filesOf(cur)) + } + _, h = mustRun(t, c, cfg, cur, false) + assertPaths(t, h.deletedItems()) +} + +func compactRecorder() *recorder { + h := &recorder{} + // Scale runs need the latest resume point, not hundreds of full maps. + // Each callback still receives a JSON-deep-copied snapshot. + h.onCheckpoint = func(cp map[string]any) { + h.checkpoints = []map[string]any{cp} + } + return h +} diff --git a/internal/datasource/connector/seafile/types.go b/internal/datasource/connector/seafile/types.go new file mode 100644 index 00000000..4565f320 --- /dev/null +++ b/internal/datasource/connector/seafile/types.go @@ -0,0 +1,235 @@ +// Package seafile implements the WeKnora data source connector for Seafile +// Server (community edition 10.0.1, api2). A data source selects nodes of a +// single library; the connector scans the selected scope one directory level +// at a time, downloads files through the two-step link + fileserver flow and +// reconciles deletions against a per-file fingerprint cursor. +package seafile + +import ( + "fmt" + "net/url" + "regexp" + "sort" + "strings" + "unicode" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +// config is the parsed credential set. The selection lives entirely in +// resource_ids, so Settings carry no Seafile-specific keys and are ignored; +// a stale key left over from another connector type does no harm. +type config struct { + baseURL string + token string +} + +func parseConfig(ds *types.DataSourceConfig) (config, error) { + if ds == nil { + return config{}, fmt.Errorf("%w: seafile config is nil", datasource.ErrInvalidConfig) + } + rawBase, _ := ds.Credentials["base_url"].(string) + rawToken, _ := ds.Credentials["api_token"].(string) + + token := strings.TrimSpace(rawToken) + if token == "" || strings.ContainsFunc(token, func(r rune) bool { + return unicode.IsSpace(r) || unicode.IsControl(r) + }) { + return config{}, fmt.Errorf("%w: api_token is required and must not contain whitespace", + datasource.ErrInvalidConfig) + } + + baseURL, err := normalizeBaseURL(rawBase) + if err != nil { + return config{}, err + } + return config{baseURL: baseURL, token: token}, nil +} + +// normalizeBaseURL trims the URL, defaults the scheme to https, drops the +// trailing slash and keeps any deployment path prefix. +func normalizeBaseURL(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", fmt.Errorf("%w: base_url is required", datasource.ErrInvalidConfig) + } + if !strings.Contains(raw, "://") { + raw = "https://" + raw + } + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || + u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return "", fmt.Errorf("%w: base_url must be an http(s) URL without credentials, query or fragment", + datasource.ErrInvalidConfig) + } + base := strings.TrimRight(u.String(), "/") + if err := datasource.ValidateConnectorBaseURL(base); err != nil { + return "", fmt.Errorf("%w: %v", datasource.ErrInvalidConfig, err) + } + return base, nil +} + +// Resource IDs are ":"; the library root is +// ":/". The split happens at the first colon so paths may contain +// colons. IDs are never URL-decoded. + +var repoIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) + +func parseResourceID(id string) (repoID, path string, err error) { + repoID, rawPath, ok := strings.Cut(id, ":") + if !ok || !repoIDPattern.MatchString(repoID) { + return "", "", fmt.Errorf("%w: seafile resource id must be :", + datasource.ErrInvalidConfig) + } + path, err = normalizePath(rawPath) + if err != nil { + return "", "", err + } + return repoID, path, nil +} + +func encodeResourceID(repoID, path string) string { + return repoID + ":" + path +} + +// normalizePath collapses repeated slashes, strips the trailing slash (except +// for the root) and rejects dot segments, backslashes and control characters. +func normalizePath(p string) (string, error) { + if !strings.HasPrefix(p, "/") || strings.Contains(p, "\\") || strings.ContainsFunc(p, unicode.IsControl) { + return "", fmt.Errorf("%w: seafile path must be absolute without backslashes or control characters", + datasource.ErrInvalidConfig) + } + segments := make([]string, 0, 8) + for _, segment := range strings.Split(p, "/") { + switch segment { + case "": + continue + case ".", "..": + return "", fmt.Errorf("%w: seafile path must not contain dot segments", datasource.ErrInvalidConfig) + } + segments = append(segments, segment) + } + return "/" + strings.Join(segments, "/"), nil +} + +// collapseRoots dedupes and sorts the selection, requires a single library +// and drops every path whose ancestor directory is also selected. "/a" does +// not cover "/ab". +func collapseRoots(ids []string) (repoID string, roots []string, err error) { + if len(ids) == 0 { + return "", nil, fmt.Errorf("%w: seafile requires at least one selected resource", datasource.ErrInvalidConfig) + } + selected := make(map[string]bool, len(ids)) + for _, id := range ids { + repo, p, err := parseResourceID(id) + if err != nil { + return "", nil, err + } + if repoID != "" && repo != repoID { + return "", nil, fmt.Errorf("%w: seafile selections must belong to one library", datasource.ErrInvalidConfig) + } + repoID = repo + selected[p] = true + } + sorted := make([]string, 0, len(selected)) + for p := range selected { + sorted = append(sorted, p) + } + sort.Strings(sorted) + for _, p := range sorted { + if !hasSelectedAncestor(p, selected) { + roots = append(roots, p) + } + } + return repoID, roots, nil +} + +func hasSelectedAncestor(p string, selected map[string]bool) bool { + for p != "/" { + p = parentPath(p) + if selected[p] { + return true + } + } + return false +} + +// parentPath returns the parent of a normalized absolute path ("/" for +// top-level entries). +func parentPath(p string) string { + if i := strings.LastIndex(p, "/"); i > 0 { + return p[:i] + } + return "/" +} + +// ancestorIDs lists the resource IDs a lazy picker must expand to reveal id: +// ":/a/b/c" yields ":/", ":/a", ":/a/b". Unparsable +// IDs and the root yield nothing. +func ancestorIDs(id string) []string { + repoID, p, err := parseResourceID(id) + if err != nil || p == "/" { + return nil + } + out := []string{encodeResourceID(repoID, "/")} + for i := 1; i < len(p); i++ { + if p[i] == '/' { + out = append(out, encodeResourceID(repoID, p[:i])) + } + } + return out +} + +// repoInfo is one row of GET /api2/repos/. seahub 10.0.1 exposes no reliable +// "virtual" marker, so it is deliberately not decoded. +type repoInfo struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Encrypted bool `json:"encrypted"` + Permission string `json:"permission"` +} + +// dirent is one entry of GET /api2/repos/{id}/dir/. Only file entries carry +// a size key. +type dirent struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Mtime int64 `json:"mtime"` + Size *int64 `json:"size,omitempty"` + Permission string `json:"permission"` +} + +// Error reason codes surfaced on error items; the frontend localises them via +// datasource.syncError.. +const ( + reasonPermissionDenied = "seafile_permission_denied" + reasonNotFound = "seafile_not_found" + reasonFileTooLarge = "seafile_file_too_large" + reasonEmptyFile = "seafile_empty_file" + reasonSourceChanged = "seafile_source_changed" + reasonInvalidResponse = "seafile_invalid_response" + reasonSSRFBlocked = "seafile_ssrf_blocked" + reasonFetchFailed = "seafile_fetch_failed" +) + +var reasonText = map[string]string{ + reasonPermissionDenied: "Permission to access the Seafile resource was denied", + reasonNotFound: "The Seafile resource was not found", + reasonFileTooLarge: "The Seafile file exceeds the configured size limit", + reasonEmptyFile: "The Seafile file is empty", + reasonSourceChanged: "The Seafile file changed while it was being fetched", + reasonInvalidResponse: "Seafile returned an unexpected response", + reasonSSRFBlocked: "The Seafile download URL was blocked by the SSRF policy", + reasonFetchFailed: "Failed to fetch the file from Seafile", +} + +// errorReason returns the English fallback text for a reason code. +func errorReason(code string) string { + if text, ok := reasonText[code]; ok { + return text + } + return reasonText[reasonFetchFailed] +} diff --git a/internal/datasource/connector/seafile/types_test.go b/internal/datasource/connector/seafile/types_test.go new file mode 100644 index 00000000..d9e40bc4 --- /dev/null +++ b/internal/datasource/connector/seafile/types_test.go @@ -0,0 +1,169 @@ +package seafile + +import ( + "errors" + "slices" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +const ( + testRepoID = "01234567-89ab-cdef-0123-456789abcdef" + otherRepoID = "fedcba98-7654-3210-fedc-ba9876543210" + testToken = "seafile-secret-token-do-not-echo" +) + +func TestParseResourceID(t *testing.T) { + for _, tc := range []struct{ input, want string }{ + {"/", "/"}, + {"////", "/"}, + {"//a///b/", "/a/b"}, + {"/a:b/c:d", "/a:b/c:d"}, + {"/产品/说明.pdf", "/产品/说明.pdf"}, + {"/%2e%2e/a%2Fb", "/%2e%2e/a%2Fb"}, + {"/ spaced /file ", "/ spaced /file "}, + } { + t.Run(tc.input, func(t *testing.T) { + repo, p, err := parseResourceID(testRepoID + ":" + tc.input) + if err != nil || repo != testRepoID || p != tc.want { + t.Fatalf("parse = (%q, %q, %v), want path %q", repo, p, err, tc.want) + } + againRepo, againPath, err := parseResourceID(encodeResourceID(repo, p)) + if err != nil || againRepo != repo || againPath != p { + t.Fatalf("round trip = (%q, %q, %v)", againRepo, againPath, err) + } + }) + } + for _, id := range []string{ + "", testRepoID, testRepoID + ":", testRepoID + ":relative", + testRepoID + ":/a/../b", testRepoID + ":/./a", testRepoID + ":/a/..", + testRepoID + ":/a\\b", testRepoID + ":/a\nb", testRepoID + ":/a\x00b", + strings.ToUpper(testRepoID) + ":/", "123:/", testRepoID + "0:/", + } { + t.Run("invalid "+id, func(t *testing.T) { + if _, _, err := parseResourceID(id); !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("expected ErrInvalidConfig, got %v", err) + } + }) + } +} + +func TestCollapseRoots(t *testing.T) { + input := []string{ + testRepoID + ":/ab", testRepoID + ":/a/c", testRepoID + ":/a-b", + testRepoID + ":/a/", testRepoID + ":/a", testRepoID + ":/z/deep", + } + want := []string{"/a", "/a-b", "/ab", "/z/deep"} + for i := 0; i < len(input); i++ { + repo, roots, err := collapseRoots(input) + if err != nil || repo != testRepoID || !slices.Equal(roots, want) { + t.Fatalf("collapse(%v) = (%q, %v, %v)", input, repo, roots, err) + } + input = append(input[1:], input[0]) + } + _, roots, err := collapseRoots(append(input, testRepoID+":/")) + if err != nil || !slices.Equal(roots, []string{"/"}) { + t.Fatalf("root collapse = (%v, %v)", roots, err) + } + for _, ids := range [][]string{ + nil, + {}, + {testRepoID + ":/", otherRepoID + ":/a"}, + {testRepoID + ":/", "invalid"}, + {testRepoID + ":/a", testRepoID + ":/../b"}, + } { + if _, _, err := collapseRoots(ids); !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("collapse(%v): expected ErrInvalidConfig, got %v", ids, err) + } + } +} + +func TestParseConfig(t *testing.T) { + for _, settings := range []map[string]any{nil, {}, {"edition": "server"}} { + cfg, err := parseConfig(&types.DataSourceConfig{ + Credentials: map[string]any{"base_url": " localhost/seafile/// ", "api_token": " " + testToken + " "}, + Settings: settings, + }) + if err != nil || cfg.baseURL != "https://localhost/seafile" || cfg.token != testToken { + t.Fatalf("parseConfig = (%+v, %v)", cfg, err) + } + } + for _, token := range []any{"", " ", "a b", "a\tb", "a\nb", "a\x00b", 123, nil} { + _, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]any{ + "base_url": "http://localhost", "api_token": token, + }}) + if !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("token %q accepted: %v", token, err) + } + } + for _, base := range []any{ + "", 123, "ftp://localhost", "https://", "http://169.254.169.254", + "http://user:" + testToken + "@localhost", "http://localhost/?token=" + testToken, + "http://localhost/#fragment", + } { + _, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]any{ + "base_url": base, "api_token": testToken, + }}) + if !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("base_url %q accepted: %v", base, err) + } + if strings.Contains(err.Error(), testToken) { + t.Fatalf("config error leaked the token: %v", err) + } + } + for _, ds := range []*types.DataSourceConfig{nil, {}} { + if _, err := parseConfig(ds); !errors.Is(err, datasource.ErrInvalidConfig) { + t.Fatalf("empty config accepted: %v", err) + } + } +} + +func TestAncestorIDs(t *testing.T) { + for _, tc := range []struct { + id string + want []string + }{ + {testRepoID + ":/a/b/c", []string{testRepoID + ":/", testRepoID + ":/a", testRepoID + ":/a/b"}}, + {testRepoID + ":/a:b/c", []string{testRepoID + ":/", testRepoID + ":/a:b"}}, + {testRepoID + ":/", nil}, + {testRepoID + ":/../a", nil}, + {"invalid", nil}, + } { + if got := ancestorIDs(tc.id); !slices.Equal(got, tc.want) { + t.Fatalf("ancestorIDs(%q) = %v, want %v", tc.id, got, tc.want) + } + } +} + +func TestErrorReason(t *testing.T) { + for _, code := range []string{ + reasonPermissionDenied, reasonNotFound, reasonFileTooLarge, reasonEmptyFile, + reasonSourceChanged, reasonInvalidResponse, reasonSSRFBlocked, reasonFetchFailed, + } { + if errorReason(code) == "" { + t.Fatalf("no fallback text for %s", code) + } + } + if errorReason("unknown") != errorReason(reasonFetchFailed) { + t.Fatal("unknown code should fall back to the generic text") + } +} + +func FuzzResourceID(f *testing.F) { + for _, id := range []string{testRepoID + ":/", testRepoID + ":/a:b//产品/", testRepoID + ":/../a", ""} { + f.Add(id) + } + f.Fuzz(func(t *testing.T, id string) { + repo, p, err := parseResourceID(id) + if err != nil { + return + } + againRepo, againPath, err := parseResourceID(encodeResourceID(repo, p)) + if err != nil || againRepo != repo || againPath != p { + t.Fatalf("unstable resource id %q", id) + } + }) +} diff --git a/internal/handler/dto/datasource.go b/internal/handler/dto/datasource.go index a3e4f520..9d4a2c0e 100644 --- a/internal/handler/dto/datasource.go +++ b/internal/handler/dto/datasource.go @@ -122,10 +122,19 @@ func enrichRSSFeedURLsInSettings(dsType string, parsed *types.DataSourceConfig, cfgDTO.Settings["feed_urls"] = feedURLs } +// NewDataSourceResponses converts a list of entities for the list endpoint. +// The sync cursor is stripped from every element: the settings page polls +// the list every few seconds during a sync, cursors can grow to megabytes, +// and no list consumer reads them. Detail, create and update responses +// still carry the cursor through NewDataSourceResponse. func NewDataSourceResponses(dss []*types.DataSource) []*DataSourceResponse { out := make([]*DataSourceResponse, 0, len(dss)) for _, d := range dss { - out = append(out, NewDataSourceResponse(d)) + resp := NewDataSourceResponse(d) + if resp != nil { + resp.LastSyncCursor = nil + } + out = append(out, resp) } return out } diff --git a/internal/handler/dto/datasource_test.go b/internal/handler/dto/datasource_test.go index 7456ef1e..79edcc27 100644 --- a/internal/handler/dto/datasource_test.go +++ b/internal/handler/dto/datasource_test.go @@ -48,6 +48,33 @@ func TestDataSourceResponse_OmitsCredentials(t *testing.T) { assert.Contains(t, s, "main") } +func TestDataSourceResponses_OmitsLastSyncCursor(t *testing.T) { + ds := &types.DataSource{ + ID: "ds-1", + Name: "github-prod", + Type: "github", + LastSyncCursor: types.JSON(`{"page":42}`), + LastSyncResult: types.JSON(`{"total":10}`), + } + + list := NewDataSourceResponses([]*types.DataSource{ds}) + assert.Len(t, list, 1) + got := list[0] + assert.Empty(t, got.LastSyncCursor) + + body, err := json.Marshal(got) + assert.NoError(t, err) + var raw map[string]json.RawMessage + assert.NoError(t, json.Unmarshal(body, &raw)) + assert.NotContains(t, raw, "last_sync_cursor") + + // Every other field must match the single-entity conversion. + want := NewDataSourceResponse(ds) + assert.Equal(t, json.RawMessage(`{"page":42}`), want.LastSyncCursor) + want.LastSyncCursor = nil + assert.Equal(t, want, got) +} + func TestDataSourceResponse_NilSafe(t *testing.T) { assert.Nil(t, NewDataSourceResponse(nil)) assert.Equal(t, []*DataSourceResponse{}, NewDataSourceResponses(nil)) diff --git a/internal/types/datasource.go b/internal/types/datasource.go index 5130b931..814b7408 100644 --- a/internal/types/datasource.go +++ b/internal/types/datasource.go @@ -38,6 +38,7 @@ const ( ConnectorTypeRSS = "rss" ConnectorTypeGitLab = "gitlab" ConnectorTypeIMA = "ima" + ConnectorTypeSeafile = "seafile" // Sync modes SyncModeIncremental = "incremental" diff --git a/internal/types/knowledge.go b/internal/types/knowledge.go index 176b53d9..50b27c12 100644 --- a/internal/types/knowledge.go +++ b/internal/types/knowledge.go @@ -37,6 +37,7 @@ const ( ChannelYuque = "yuque" // Yuque (语雀) ChannelRSS = "rss" // RSS / Atom feed ChannelIMA = "ima" // Tencent IMA (ima.qq.com) + ChannelSeafile = "seafile" // Seafile ) // Knowledge parse status constants diff --git a/internal/utils/import_filetypes.go b/internal/utils/import_filetypes.go new file mode 100644 index 00000000..c196d66a --- /dev/null +++ b/internal/utils/import_filetypes.go @@ -0,0 +1,47 @@ +package utils + +import ( + "sort" + "strings" +) + +// supportedImportFileExtensions is the single source of truth for extensions +// accepted by every knowledge import path: direct upload, file-URL download, +// the worker's post-download re-check and data source connectors. Keeping one +// set avoids the drift that let direct upload accept xlsx while URL import +// rejected it (#2447). +var supportedImportFileExtensions = map[string]struct{}{ + "pdf": {}, "txt": {}, "docx": {}, "doc": {}, "epub": {}, + "html": {}, "htm": {}, "mhtml": {}, "md": {}, "markdown": {}, + "xmind": {}, + "png": {}, "jpg": {}, "jpeg": {}, "gif": {}, + "csv": {}, "xlsx": {}, "xls": {}, "pptx": {}, "ppt": {}, "json": {}, + "mp3": {}, "wav": {}, "m4a": {}, "flac": {}, "ogg": {}, +} + +// NormalizeImportExtension lowercases an extension and strips surrounding +// whitespace and one leading dot, so callers can pass "xlsx", ".XLSX" or a +// raw user-supplied file_type. +func NormalizeImportExtension(ext string) string { + return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(ext), ".")) +} + +// IsSupportedImportExtension reports whether a bare extension can be imported. +func IsSupportedImportExtension(ext string) bool { + ext = NormalizeImportExtension(ext) + if ext == "" { + return false + } + _, ok := supportedImportFileExtensions[ext] + return ok +} + +// SupportedImportExtensions returns a sorted copy of the supported extensions. +func SupportedImportExtensions() []string { + out := make([]string, 0, len(supportedImportFileExtensions)) + for ext := range supportedImportFileExtensions { + out = append(out, ext) + } + sort.Strings(out) + return out +} diff --git a/internal/utils/import_filetypes_test.go b/internal/utils/import_filetypes_test.go new file mode 100644 index 00000000..e87654df --- /dev/null +++ b/internal/utils/import_filetypes_test.go @@ -0,0 +1,59 @@ +package utils + +import ( + "sort" + "testing" +) + +func TestNormalizeImportExtension(t *testing.T) { + tests := []struct { + ext string + want string + }{ + {"pdf", "pdf"}, + {".PDF", "pdf"}, + {" .XLSX ", "xlsx"}, + {".", ""}, + {"", ""}, + } + for _, tt := range tests { + if got := NormalizeImportExtension(tt.ext); got != tt.want { + t.Errorf("NormalizeImportExtension(%q) = %q, want %q", tt.ext, got, tt.want) + } + } +} + +func TestIsSupportedImportExtension(t *testing.T) { + tests := []struct { + ext string + want bool + }{ + {"pdf", true}, + {" .XLSX ", true}, + {"XMIND", true}, + {"exe", false}, + {"mp4", false}, + {"unknown", false}, + {"", false}, + } + for _, tt := range tests { + if got := IsSupportedImportExtension(tt.ext); got != tt.want { + t.Errorf("IsSupportedImportExtension(%q) = %v, want %v", tt.ext, got, tt.want) + } + } +} + +func TestSupportedImportExtensions(t *testing.T) { + exts := SupportedImportExtensions() + if len(exts) != len(supportedImportFileExtensions) { + t.Fatalf("SupportedImportExtensions() has %d entries, want %d", len(exts), len(supportedImportFileExtensions)) + } + if !sort.StringsAreSorted(exts) { + t.Errorf("SupportedImportExtensions() is not sorted: %v", exts) + } + for _, ext := range exts { + if !IsSupportedImportExtension(ext) { + t.Errorf("SupportedImportExtensions() contains unsupported extension %q", ext) + } + } +} diff --git a/website-docs/03-features/10-datasource.md b/website-docs/03-features/10-datasource.md index 5734f77e..54aff677 100644 --- a/website-docs/03-features/10-datasource.md +++ b/website-docs/03-features/10-datasource.md @@ -34,6 +34,7 @@ | 钉钉文档 | `dingtalk` | 知识库、文件夹与在线文档 | | 腾讯 IMA | `ima` | 知识库中的文件与笔记 | | GitLab | `gitlab` | 仓库指定分支/标签下的目录 | +| Seafile | `seafile` | 资料库中的目录与文件 | | RSS / Atom | `rss` | 订阅源文章 | 各连接器支持的格式、认证与删除检测见参考部分。 @@ -91,6 +92,19 @@ {"credentials":{"base_url":"https://gitlab.example.com","access_token":""},"settings":{"projects":[{"project_id":"123","ref":"main","paths":["docs"]}]}} ``` +#### Seafile(`connector/seafile/`) + +1. 获取 Seafile 账号的用户 API Token,确认该账号对目标资料库有读取权限。 +2. 添加「Seafile」数据源,填写 Seafile 地址(支持部署路径前缀)和 API Token。私网部署或独立 fileserver 地址需先加入 `SSRF_WHITELIST`。 +3. 测试连接后,在资源树中勾选同一资料库内的根目录、目录或文件;加密资料库和不支持的文件格式不会出现在选择器中。 +4. 发起首次同步;文件按 `<资料库名>/<资料库内路径>` 进入知识库,来源显示为「Seafile」。 + +连接器支持定时、增量、流式检查点及同步删除。同步逐层扫描目录,以「对象 ID + 修改时间 + 大小」比较文件指纹,只下载需要更新的文件;下载经过 API 获取链接、fileserver 获取内容两步,fileserver 请求不携带令牌。每 50 次游标变更保存检查点,中断后从检查点继续。 + +单文件获取失败不阻断其他文件,已知路径保留待重试状态;目录扫描失败或 `Retry-After` 超过 60 秒时停止本轮并暂停删除对账。删除知识条目受「同步删除」开关控制,单文件大小沿用 `MAX_FILE_SIZE_MB`。已同步的数据源不能改绑其他资料库,需新建数据源。 + +配置、格式限制、失败恢复与删除边界见 [Seafile 接入](25-seafile.md)。 + #### 腾讯 IMA(`connector/ima/`) 填写 credentials.client_id 和 api_key;base_url 可选,默认 `https://ima.qq.com`。资源列表是该凭据可见的 IMA 知识库(扁平列表,不展开目录),选择结果保存为 config.resource_ids;同步时递归遍历所选知识库中的全部子文件夹。源端授权失败或资源不可见时,先检查 IMA 凭据及知识库访问权。 @@ -392,9 +406,10 @@ registry.Register(dingtalkConnector.NewConnector()) // dingtalk registry.Register(imaConnector.NewConnector()) // ima registry.Register(rssConnector.NewConnector()) // rss registry.Register(gitlabConnector.NewConnector()) // gitlab +registry.Register(seafileConnector.NewConnector()) // seafile ``` -> 注意:`connector.go` 中的 `ConnectorMetadataRegistry` 仍包含尚未实现的连接器(GitHub、Google Drive、OneDrive、Web Crawler、Slack、IMAP 等)。当前实际注册可用的类型为:`feishu`、`lark`、`feishu_drive`、`lark_drive`、`notion`、`confluence`、`yuque`、`dingtalk`、`ima`、`rss`、`gitlab`。未注册类型在创建数据源时会被 `connectorRegistry.Get()` 以 `ErrConnectorNotFound` 拒绝。 +> 注意:`connector.go` 中的 `ConnectorMetadataRegistry` 仍包含尚未实现的连接器(GitHub、Google Drive、OneDrive、Web Crawler、Slack、IMAP 等)。当前实际注册可用的类型为:`feishu`、`lark`、`feishu_drive`、`lark_drive`、`notion`、`confluence`、`yuque`、`dingtalk`、`ima`、`rss`、`gitlab`、`seafile`。未注册类型在创建数据源时会被 `connectorRegistry.Get()` 以 `ErrConnectorNotFound` 拒绝。 ### 数据模型(internal/types/datasource.go) diff --git a/website-docs/03-features/25-seafile.md b/website-docs/03-features/25-seafile.md new file mode 100644 index 00000000..e0615af2 --- /dev/null +++ b/website-docs/03-features/25-seafile.md @@ -0,0 +1,97 @@ +# Seafile 接入 + +`seafile` 将一个 Seafile 资料库中勾选的目录和文件同步到知识库,支持定时、增量、断点续传和源端删除对账。兼容基线为 Seafile 社区版 Server 10.0.1(api2 接口)。通用同步流程见[数据源同步](10-datasource.md)。 + +## 账号与 API Token + +使用一个能登录 Seafile、对目标资料库至少有只读权限的账号;同步范围以该账号的权限为准。凭据是该账号的用户 API Token,连接器只保存和使用 Token,不处理账号密码、SSO 登录或资料库专用令牌。 + +Seafile 10.0.1 个人设置页的「Web API Auth Token」默认不显示,需要管理员在 `seahub_settings.py` 中设置 `ENABLE_GET_AUTH_TOKEN_BY_SESSION = True` 并重启 Seahub。也可以用账号密码调用 `POST /api2/auth-token/` 获取;启用双因素认证时,按响应中的 `X-Seafile-OTP` 要求补交验证码。 + +WeKnora 内的连接测试调用 `/api2/auth/ping/` 验证 Token;资料库和目录是否可见要到加载资源树时才会验证。 + +## 在知识库中配置 + +1. 知识库设置 → 数据源 → 新建,选择「Seafile」。 +2. 填写 Seafile 地址和 API Token,执行连接测试。地址可以带部署路径前缀,如 `https://example.com/seafile`。 +3. 在资源树中勾选资料库根目录、任意目录或单个文件。顶层只列出该账号可访问的未加密资料库,目录逐级展开;一个数据源只能选同一个资料库,勾选第二个资料库会被拒绝。 +4. 选择全量/增量、同步计划、冲突策略与同步删除;保存后先手动同步少量文件,检查日志和解析结果。 + +勾选目录表示递归同步,之后新增的文件和子目录自动纳入;勾选单个文件只同步该文件;子项被父目录覆盖时只保留父目录。选择器只列出 WeKnora 支持导入的扩展名,`.zip` 等不支持的文件不出现,也不会同步。 + +## 网络与 SSRF + +| 请求 | 目标 | 携带 Token | +| --- | --- | --- | +| API(`/api2/…`) | 配置的 Seafile 地址 | 是,`Authorization: Token` | +| 文件下载 | Seafile 返回的 fileserver 链接,通常是同域名下的 `/seafhttp/…`,也可能是独立域名 | 否 | + +两类地址都经过 SSRF 校验。Seafile 部署在私网或使用独立 fileserver 域名时,把对应主机加入 `.env` 的 `SSRF_WHITELIST`,否则保存凭据时报「base_url SSRF validation failed」,或同步日志出现 `seafile_ssrf_blocked`。 + +## 目录、格式与大小 + +同步进来的文件按 `<资料库名>/<资料库内路径>` 落到知识库目录,来源标签显示为「Seafile」。资料库名在首次同步时写入游标并固定,之后在 Seafile 改名不会改变知识库目录,也不会触发重新下载。目录名和文件名逐段清理非法字符。 + +格式范围与知识库上传一致(PDF、Office、Markdown、HTML、常见图片、音频等),以 `internal/utils/import_filetypes.go` 为准。图片需要知识库配置 VLM,音频需要配置 ASR;未配置时条目在同步日志中记为入库失败,不影响其他文件。 + +单文件上限沿用 `MAX_FILE_SIZE_MB`(默认 50 MiB):目录列表中超限的文件直接记为 `seafile_file_too_large` 且不下载,下载中实际字节数超限同样拒绝,不会截断入库。调大该值时须同步调整 DocReader 的 `DOCREADER_GRPC_MAX_FILE_SIZE_MB` 并重启 app、docreader、frontend,否则文件能下载但解析阶段被 gRPC 拒绝。 + +## 同步行为 + +每个文件以「对象 ID + 修改时间 + 大小」组成指纹保存在游标中,三者都相同则跳过下载;指纹变化时重新下载并覆盖旧条目(先删后建,解析期间该文档短暂不可用)。无变化的一轮只做目录扫描,请求数等于目录数。 + +| 源端操作 | 行为 | +| --- | --- | +| 新增文件或子目录 | 下次同步纳入 | +| 修改内容 | 重新下载并更新 | +| 删除文件 | 开启「同步删除」时删除对应知识条目,否则仅从游标移除 | +| 重命名、移动或移出范围 | 新路径按新文件导入,旧路径按删除处理;不保留知识条目 ID | +| 勾选的目录或文件被删除、改名 | 本轮报错停止,不产生任何删除;需重新选择范围 | +| 资料库改名 | 无变化,目录名沿用首次同步时的名字 | + +失败处理: + +| 情况 | 行为 | +| --- | --- | +| 单文件 403 / 404 / 5xx、网络错误、超限、空文件、下载中变化 | 记为失败条目,其余文件继续;该路径留在游标中,下次同步重试 | +| 目录列表 403 / 404 / 5xx 或响应畸形 | 保存已完成的进度后停止,本轮不产生任何删除 | +| 429 / 502 / 503 / 504 或临时网络错误 | 同一请求最多 3 次尝试,退避 1s、2s;`Retry-After` 不超过 60s 时取其值,超过则停止本轮 | +| Token 失效(401 / 403) | 凭据错误,数据源进入错误状态 | + +每 50 次游标变更、发出删除前和结束时保存检查点;任务超时或中断后,下次从最后一个检查点继续,已保存的文件不重复下载。首次同步数万文件的大资料库可能跨多次任务执行才完成。强制全量同步会重新下载全部文件,同时保留旧游标作为删除对账基线。 + +「连接器获取重试」与「入库解析恢复」是两回事:前者指下载失败的文件在下次同步重新下载;后者指文件已提交入库但解析、索引失败,由知识库侧的重试机制处理,同步日志中显示为入库失败。 + +同步日志错误码: + +| 错误码 | 含义 | +| --- | --- | +| `seafile_permission_denied` | Token 所属账号无权访问该文件或目录 | +| `seafile_not_found` | 文件在扫描后消失;下次同步重试,已从资料库消失则按「同步删除」开关对账 | +| `seafile_file_too_large` | 超过 `MAX_FILE_SIZE_MB` | +| `seafile_empty_file` | 文件为空,跳过 | +| `seafile_source_changed` | 下载过程中文件被修改,下次同步重试 | +| `seafile_invalid_response` | Seafile 返回无法解析的响应,多为版本或反向代理问题 | +| `seafile_ssrf_blocked` | 下载地址被 SSRF 策略拦截 | +| `seafile_fetch_failed` | 其他获取失败,下次同步重试 | + +## 注意事项 + +- 已同步的数据源不能改绑其他资料库:改选后下一次同步会以「该数据源已同步资料库 <旧名>」失败且游标不变,需新建数据源。保存前先取消已选项即可换库。 +- 删除对账不保证补删:目录扫描失败的那一轮不产生删除;「同步删除」关闭期间发生的删除,重新开启后不会追溯。 +- 删除或重建数据源不会清理已导入的知识条目,遗留内容需在知识库中单独清理。 +- 加密资料库不出现在选择器中,也不支持同步;SeaDoc 在线文档、自定义属性和双向同步不在支持范围内。 + +## 常见问题 + +| 现象 | 处理 | +| --- | --- | +| 保存凭据时报 SSRF 校验失败 | Seafile 地址是私网或被拦截端口,加入 `SSRF_WHITELIST` | +| 「Seafile library … not found」 | Token 所属账号看不到该资料库,或资料库已删除 | +| 「encrypted Seafile libraries are not supported」 | 选中的资料库是加密库 | +| 同步日志大量 `seafile_ssrf_blocked` | fileserver 域名与 API 域名不同且未加白 | +| 同步日志 `seafile_file_too_large` | 调大 `MAX_FILE_SIZE_MB` 与 `DOCREADER_GRPC_MAX_FILE_SIZE_MB` 后重启 | +| 文件已下载但知识条目解析失败 | 属入库解析问题,检查 VLM / ASR 配置和 DocReader 日志 | +| 「this data source already synced Seafile library …」 | 改绑了资料库,恢复原资料库或新建数据源 | + +实现参考:`internal/datasource/connector/seafile/` 和 `internal/application/service/datasource_service.go`。 diff --git a/website-docs/06-development/03-extension-points.md b/website-docs/06-development/03-extension-points.md index 88d8ca30..22954c9d 100644 --- a/website-docs/06-development/03-extension-points.md +++ b/website-docs/06-development/03-extension-points.md @@ -496,6 +496,7 @@ type StreamingConnector interface { | `ima` | `internal/datasource/connector/ima/` | 腾讯 ima 知识库 | | `rss` | `internal/datasource/connector/rss/` | RSS 订阅 | | `gitlab` | `internal/datasource/connector/gitlab/` | GitLab 仓库 | +| `seafile` | `internal/datasource/connector/seafile/` | 资料库目录与文件 | `internal/types/datasource.go` 中还有 `github`、`google_drive` 等尚未注册实现的类型常量。