e00cab2f70
用户对 系统设置 → 数据源配置 的四条要求: ① 这里不要做文件格式筛选(格式归目录级标注决定); ② 列出我账号下能看到的知识库;③ 列出钉盘能看到哪些;④ 勾选那些作为来源。 ① 来源卡片不再渲染 FilenameFilterEditor(目录级筛选仍在「来源与目录」里,按目录就近覆盖)。 ②③ 新端点 GET /api/v1/dingtalk-spaces/available(管理员,只读):用 dws 列举 - 知识库:wiki +space-list --type orgWikiSpace/myWikiSpace(实测 17 + 1 个) - 钉盘:wiki space list --type mySpace/orgSpace(实测 我的文件 + 6 个组织空间) 实测约束写进命令形态:--limit 上限是 50;翻页必须 --page-all(--max-items 兜底), 否则超过一页的知识库会被静默截断(被截断时页面显示"可能不全"而不是假装列全)。 列不出来 ≠ 空列表:dws 未登录/权限不足 → 503 + 原因;某一类失败只丢那一类。 ④ 面板勾选后走既有登记路径(/api/v1/dingtalk-spaces),首次目录扫描自动排队; 已登记的按空间名标「已是来源」并禁用勾选;扫码会话失效时直接弹二维码,扫完自动重试。 基础设施:api 与 worker 共享同一份 dws 状态(bind mount 同一份,refresh token 是轮换制, 不能各留一份)。子进程 HOME 必须指向 DWS_HOME —— 这条是实测踩出来的:漏了会报"未登录", 已有回归测试钉住。dws 子进程沿用白名单环境,库口令等变量不进子进程。 测试:新包 internal/dingtalkdiscovery(fixture 用真实 dws 输出形状):paging 约束、 截断提示、一类失败不连带、全部失败→ErrUnavailable、子进程环境;httpapi 侧 401/501/503/500 与不泄漏内部错误;OpenAPI 契约(400/503 组件)通过。前端 189 条 + tsc 干净。 面板实测:知识库(18)/钉盘(7)都列出来,已有三条钉钉来源自动标「已是来源」; 勾选「视觉文档」→ 加入为来源 → 新来源 sc-8a4be5b8293d1c9a048c3c7e9b194155(dingtalk,enabled) + source.catalog.refresh 已完成。
234 lines
8.5 KiB
Go
234 lines
8.5 KiB
Go
// Package dingtalkdiscovery 用 dws CLI 枚举「我账号下能看到的数据源」:
|
||
// 钉钉知识库(组织知识库 + 我的知识库)与钉盘空间(我的文件 / 组织空间)。
|
||
//
|
||
// 只读:本包只运行 dws 的列举命令并解析 JSON,不写任何远端对象,也不碰凭据值。
|
||
//
|
||
// 两条实测约束决定了命令形态:--limit 只能是 1-50;翻页必须靠 --page-all(带 --max-items
|
||
// 兜底),否则超过一页的知识库会被静默截断。
|
||
//
|
||
// dws 的令牌是轮换制,因此运行它的进程必须与 worker 共享同一份状态目录(见 compose.yaml),
|
||
// 且子进程的 HOME 必须指向 DWS_HOME(文件型 keychain 在 $HOME/.local/share/dws-cli)。
|
||
package dingtalkdiscovery
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||
type KnowledgeBase struct {
|
||
Name string `json:"name"`
|
||
SpaceID string `json:"space_id"`
|
||
SpaceType string `json:"space_type"`
|
||
URL string `json:"url"`
|
||
Description string `json:"description,omitempty"`
|
||
}
|
||
|
||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||
type DriveSpace struct {
|
||
Name string `json:"name"`
|
||
SpaceID string `json:"space_id"`
|
||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||
SpaceType string `json:"space_type"`
|
||
}
|
||
|
||
// Result 是一次发现的结果。
|
||
type Result struct {
|
||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||
// 列不出某一类是常见状态(租户权限差异),页面照常显示能列出来的那部分,只在这里给原因。
|
||
KnowledgeNotice string `json:"knowledge_notice,omitempty"`
|
||
DriveNotice string `json:"drive_notice,omitempty"`
|
||
FetchedAt time.Time `json:"fetched_at"`
|
||
}
|
||
|
||
// Runner 执行一条 dws 命令并返回 stdout。实现要求:非零退出码也要把 stdout 交回
|
||
// (dws 把错误 JSON 写在那里),并且超时即失败,绝不返回半截 JSON。
|
||
type Runner interface {
|
||
RunDWS(ctx context.Context, args ...string) ([]byte, error)
|
||
}
|
||
|
||
// ErrUnavailable 表示 dws 不可用(二进制缺失、未登录、权限不足、输出不可解析):
|
||
// 调用方应把它映射成「探测不可用」而不是 500 —— 这是环境问题,不是平台缺陷。
|
||
var ErrUnavailable = errors.New("dws unavailable")
|
||
|
||
// knowledgeSpaceTypes 是知识库的两个范围:组织知识库与我的知识库。
|
||
var knowledgeSpaceTypes = []string{"orgWikiSpace", "myWikiSpace"}
|
||
|
||
// SpaceListArgs 是知识库列举的固定命令形态:一次取完,最多 200 条(4 页 × 50)。
|
||
func SpaceListArgs(spaceType string) []string {
|
||
return []string{"wiki", "+space-list", "--type", spaceType, "--page-all", "--max-items", "200", "--page-limit", "4", "--limit", "50"}
|
||
}
|
||
|
||
// Discover 枚举知识库与钉盘空间。
|
||
//
|
||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||
func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||
result := Result{FetchedAt: time.Now().UTC()}
|
||
|
||
failures := make([]string, 0, len(knowledgeSpaceTypes))
|
||
seenKnowledge := map[string]bool{}
|
||
for _, spaceType := range knowledgeSpaceTypes {
|
||
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
|
||
if err != nil {
|
||
failures = append(failures, describe(spaceType, err))
|
||
continue
|
||
}
|
||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||
if err != nil {
|
||
failures = append(failures, describe(spaceType, err))
|
||
continue
|
||
}
|
||
if notice != "" {
|
||
result.KnowledgeNotice = notice
|
||
}
|
||
for _, base := range bases {
|
||
if seenKnowledge[base.SpaceID] {
|
||
continue
|
||
}
|
||
seenKnowledge[base.SpaceID] = true
|
||
result.KnowledgeBases = append(result.KnowledgeBases, base)
|
||
}
|
||
}
|
||
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
|
||
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
|
||
}
|
||
if len(failures) > 0 {
|
||
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
|
||
}
|
||
|
||
seenDrive := map[string]bool{}
|
||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||
if err != nil {
|
||
result.DriveNotice = err.Error()
|
||
continue
|
||
}
|
||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||
if err != nil {
|
||
result.DriveNotice = err.Error()
|
||
continue
|
||
}
|
||
for _, space := range spaces {
|
||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||
continue
|
||
}
|
||
seenDrive[space.SpaceType+":"+space.SpaceID] = true
|
||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||
}
|
||
}
|
||
return result, nil
|
||
}
|
||
|
||
func describe(scope string, err error) string {
|
||
return scope + ":" + err.Error()
|
||
}
|
||
|
||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||
// {"ok":true,"data":{"count":17,"hasMore":false,"autoPageComplete":true,"spaces":[{name,url,workspaceId}]}}
|
||
// 第二个返回值是「结果不完整」的说明(被 --max-items 截断)。
|
||
func parseKnowledgeBases(raw []byte, spaceType string) ([]KnowledgeBase, string, error) {
|
||
var payload struct {
|
||
OK bool `json:"ok"`
|
||
Data struct {
|
||
Count int `json:"count"`
|
||
HasMore bool `json:"hasMore"`
|
||
AutoPageComplete bool `json:"autoPageComplete"`
|
||
Spaces []struct {
|
||
Name string `json:"name"`
|
||
URL string `json:"url"`
|
||
WorkspaceID string `json:"workspaceId"`
|
||
Description string `json:"description"`
|
||
} `json:"spaces"`
|
||
} `json:"data"`
|
||
Error *struct {
|
||
Message string `json:"message"`
|
||
Type string `json:"type"`
|
||
} `json:"error"`
|
||
}
|
||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||
return nil, "", fmt.Errorf("parse knowledge base list: %w", err)
|
||
}
|
||
if !payload.OK {
|
||
message := "dws reported failure"
|
||
if payload.Error != nil && payload.Error.Message != "" {
|
||
message = payload.Error.Message
|
||
}
|
||
return nil, "", errors.New(message)
|
||
}
|
||
out := make([]KnowledgeBase, 0, len(payload.Data.Spaces))
|
||
for _, space := range payload.Data.Spaces {
|
||
name := strings.TrimSpace(space.Name)
|
||
id := strings.TrimSpace(space.WorkspaceID)
|
||
if name == "" || id == "" {
|
||
continue
|
||
}
|
||
url := strings.TrimSpace(space.URL)
|
||
if url == "" {
|
||
url = SpaceURL(id)
|
||
}
|
||
out = append(out, KnowledgeBase{Name: name, SpaceID: id, SpaceType: spaceType, URL: url, Description: strings.TrimSpace(space.Description)})
|
||
}
|
||
notice := ""
|
||
if payload.Data.HasMore && !payload.Data.AutoPageComplete {
|
||
notice = fmt.Sprintf("%s 结果超过上限,只列出前 %d 个知识库。", spaceType, len(out))
|
||
}
|
||
return out, notice, nil
|
||
}
|
||
|
||
// parseDriveSpaces 解析 `dws wiki space list --type …`:
|
||
// {"success":true,"result":{"items":[{spaceId,spaceName,spaceType,rootFolderId}]}}
|
||
func parseDriveSpaces(raw []byte, spaceType string) ([]DriveSpace, error) {
|
||
var payload struct {
|
||
Success bool `json:"success"`
|
||
ErrorMsg string `json:"errorMsg"`
|
||
ErrorCode string `json:"errorCode"`
|
||
Result struct {
|
||
Items []struct {
|
||
SpaceID json.Number `json:"spaceId"`
|
||
SpaceName string `json:"spaceName"`
|
||
SpaceType string `json:"spaceType"`
|
||
RootFolderID string `json:"rootFolderId"`
|
||
} `json:"items"`
|
||
} `json:"result"`
|
||
}
|
||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||
return nil, fmt.Errorf("parse drive space list: %w", err)
|
||
}
|
||
if !payload.Success {
|
||
message := strings.TrimSpace(payload.ErrorMsg)
|
||
if message == "" {
|
||
message = strings.TrimSpace(payload.ErrorCode)
|
||
}
|
||
if message == "" {
|
||
message = "dws reported failure"
|
||
}
|
||
return nil, errors.New(message)
|
||
}
|
||
out := make([]DriveSpace, 0, len(payload.Result.Items))
|
||
for _, item := range payload.Result.Items {
|
||
name := strings.TrimSpace(item.SpaceName)
|
||
id := strings.TrimSpace(item.SpaceID.String())
|
||
if name == "" || id == "" {
|
||
continue
|
||
}
|
||
kind := strings.TrimSpace(item.SpaceType)
|
||
if kind == "" {
|
||
kind = spaceType
|
||
}
|
||
out = append(out, DriveSpace{Name: name, SpaceID: id, SpaceType: kind, RootFolderID: strings.TrimSpace(item.RootFolderID)})
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// SpaceURL 由空间 id 拼出 alidocs 链接:登记来源走的就是这个形态。
|
||
func SpaceURL(spaceID string) string {
|
||
return "https://alidocs.dingtalk.com/i/spaces/" + spaceID + "/overview"
|
||
}
|