diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f6b12b1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,5 @@ +Copyright (C) 2026 by GI-OBSIDIAN + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/README.md b/README.md index 9177498..991aa97 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,35 @@ -# Omnibox +# OmniBox Sync +> 仓库:`Omnibox` · 类型:Obsidian 插件 · 版本:`1.1.0` · 作者:XIGE + +同步小黑(OmniBox)内容到 Obsidian,省配额模式:预算器与 ID 映射。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `api.ts` +- `main.ts` +- `manifest.json` +- `settings.ts` +- `sidebar.ts` +- `styles.css` +- `utils.ts` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(自定义宽松授权,详见 LICENSE)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/api.ts b/api.ts new file mode 100644 index 0000000..bd3d276 --- /dev/null +++ b/api.ts @@ -0,0 +1,723 @@ +import { requestUrl, Notice } from 'obsidian'; + +export interface OmniBoxResource { + id: string; + name: string; + type: 'file' | 'folder'; + updatedAt: string; + parentId?: string; + path?: string; +} + +export interface AttachmentInfo { + id: string; + name: string; + contentType?: string; + downloadUrl?: string; + size?: number; +} + +/** + * 单次请求正文的行数上限。 + * 官方默认只给 100 行,长文会静默截断;这里主动要一个大值, + * 绝大多数文章一次就能取全(实测 content_limit=1000 可完整返回 121 行文档)。 + * 注意:官方接口对 content_limit 有硬校验,最大 1000;设成 2000 会直接 400 + * {"message":["content_limit must not be greater than 1000"]}。 + * 翻页逻辑仅作为超长文档的兜底,不会再给普通文章额外增加调用次数。 + */ +const CONTENT_PAGE_SIZE = 1000; +/** 单篇正文最多翻页次数,防御性上限 */ +const MAX_CONTENT_PAGES = 50; +/** 附件列表每页数量 */ +const ATTACHMENT_PAGE_SIZE = 100; +/** 附件列表最多翻页次数 */ +const MAX_ATTACHMENT_PAGES = 20; + +/** + * 由 MIME 类型推导扩展名。 + * 官方的附件 name 字段并不可靠(常常就是 "Image"、没有扩展名), + * 真实类型只在 content_type 里,所以必须按 content_type 来定后缀。 + */ +export function extFromContentType(contentType?: string, fallbackName?: string): string { + const ct = (contentType || '').toLowerCase().split(';')[0].trim(); + const map: Record = { + 'image/jpeg': 'jpg', + 'image/jpg': 'jpg', + 'image/png': 'png', + 'image/gif': 'gif', + 'image/webp': 'webp', + 'image/svg+xml': 'svg', + 'image/bmp': 'bmp', + 'image/tiff': 'tiff', + 'image/avif': 'avif', + 'image/x-icon': 'ico', + 'application/pdf': 'pdf', + 'application/zip': 'zip', + 'application/json': 'json', + 'text/plain': 'txt', + 'text/markdown': 'md', + 'text/html': 'html', + 'video/mp4': 'mp4', + 'audio/mpeg': 'mp3', + 'audio/wav': 'wav', + }; + if (map[ct]) return map[ct]; + if (ct.includes('/')) { + const sub = ct.split('/')[1].replace(/[^a-z0-9]/g, ''); + if (sub) return sub === 'jpeg' ? 'jpg' : sub; + } + const m = /\.([A-Za-z0-9]{1,8})$/.exec(fallbackName || ''); + return m ? m[1].toLowerCase() : 'bin'; +} + +export interface ApiKeyInfo { + apiKey: { + id: string; + value: string; + user_id: string; + namespace_id: string; + created_at: string; + updated_at: string; + }; + namespace: { + id: string; + name: string; + max_running_tasks: number; + root_resource_id: string; + created_at: string; + updated_at: string; + }; + user: { + id: string; + username: string; + email: string; + }; + namespace_usage: { + storage_quota: number; + storage_usage: number; + task_priority: number; + task_parallelism: number; + file_upload_size_limit: number; + trash_retention_days: number; + open_api_requests_per_24h: number; + readonly: boolean; + smart_folder_private_limit: number; + smart_folder_team_limit: number; + smart_folder_rule_limit: number; + }; + open_api_requests_quota?: { + limit: number; + used: number; + remaining: number; + reset_at: string; + }; +} + +export class OmniBoxAPI { + private baseUrl = 'https://api.omnibox.pro/v1'; + private webUrl = 'https://www.omnibox.pro'; + private apiKey: string; + private namespaceId: string = ''; + + constructor(apiKey: string) { + this.apiKey = apiKey; + } + + updateApiKey(apiKey: string) { + this.apiKey = apiKey; + } + + getWebUrl(): string { + return this.webUrl; + } + + getNamespaceId(): string { + return this.namespaceId; + } + + private getHeaders() { + return { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json' + }; + } + + /** 从服务端响应体里提取可读的错误信息(400 时 message 可能是数组) */ + private getErrorDetail(data: any): string { + if (!data) return ''; + const m = data.message; + if (Array.isArray(m)) return m.join(';'); + if (typeof m === 'string') return m; + if (typeof data.error === 'string') return data.error; + if (typeof data.detail === 'string') return data.detail; + return ''; + } + + /** + * Obsidian requestUrl 默认 throw=true,4xx 会以异常形式抛出, + * 异常对象上带有 status / json / text。这里统一转成状态码 + 服务端消息。 + */ + private parseRequestError(error: any): { status: number; detail: string } { + const status = typeof error?.status === 'number' ? error.status : 0; + let detail = ''; + try { + const data = error?.json ?? (typeof error?.text === 'string' ? JSON.parse(error.text) : null); + detail = this.getErrorDetail(data); + } catch { /* 响应体不是 JSON,忽略 */ } + if (!detail && typeof error?.message === 'string') detail = error.message; + return { status, detail }; + } + + /** 把 reset_at ISO 时间转为「HH:MM」;无效输入返回空串 */ + private formatResetTime(resetAt?: string): string { + if (!resetAt) return ''; + const d = new Date(resetAt); + if (isNaN(d.getTime())) return ''; + return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`; + } + + /** 缓存最近一次看到的配额重置时刻,429 提示时无需再查询(查询 /api-keys/info 虽免配额,但省一次往返) */ + private lastResetAt: string = ''; + + setQuotaResetTime(resetAt: string): void { + if (resetAt) this.lastResetAt = resetAt; + } + + private handleError(status: number, detail?: string): void { + const suffix = detail ? `:${detail}` : ''; + switch(status) { + case 400: + new Notice(`❌ 请求参数错误 (HTTP 400)${suffix}`); + break; + case 401: + case 403: + new Notice('❌ API Key 无效或权限不足,请检查设置'); + break; + case 404: + new Notice('❌ 资源不存在,可能已被删除'); + break; + case 429: { + const resetStr = this.formatResetTime(this.lastResetAt); + new Notice(`⛔ API 调用次数已用完${resetStr ? `,${resetStr} 后恢复` : ',请明天再试或升级高级版'}`); + break; + } + default: + new Notice(`❌ 请求失败 (HTTP ${status})${suffix}`); + } + } + + async testConnection(): Promise { + try { + const response = await requestUrl({ + url: `${this.baseUrl}/api-keys/info`, + method: 'GET', + headers: this.getHeaders() + }); + if (response.status === 200) { + const data = response.json; + if (data.namespace) { + this.namespaceId = data.namespace.id; + } + return true; + } + return false; + } catch { + return false; + } + } + + async getApiKeyInfo(): Promise { + try { + const response = await requestUrl({ + url: `${this.baseUrl}/api-keys/info`, + method: 'GET', + headers: this.getHeaders() + }); + if (response.status === 200) { + const data = response.json; + if (data.namespace) { + this.namespaceId = data.namespace.id; + } + // 记录配额重置时刻,供 429 提示精确显示恢复时间 + const q = data.open_api_requests_quota; + if (q?.reset_at) this.lastResetAt = q.reset_at; + return data; + } + return null; + } catch { + return null; + } + } + + /** + * 查询今日剩余配额。 + * GET /api-keys/info 在官方免配额白名单里,可放心随查随用。 + * 返回 null 表示查询失败(网络/密钥问题),调用方应按"未知"处理而不是当作 0。 + */ + async getRemainingQuota(): Promise<{ remaining: number; used: number; limit: number; reset_at: string } | null> { + const info = await this.getApiKeyInfo(); + const q = info?.open_api_requests_quota; + if (!q || typeof q.remaining !== 'number') return null; + // 记录重置时刻,供 429 错误提示精确显示恢复时间 + if (q.reset_at) this.lastResetAt = q.reset_at; + return { + remaining: q.remaining, + used: q.used ?? 0, + limit: q.limit ?? 0, + reset_at: q.reset_at ?? '' + }; + } + + async fetchResources(): Promise { + return this.fetchResourcesByParent(); + } + + async fetchResourcesByParent(parentId?: string, limit = 100): Promise { + const all: OmniBoxResource[] = []; + let offset = 0; + + // 自动翻页:官方返回 total 字段,用 offset/limit 分批拿全 + while (true) { + let url = `${this.baseUrl}/resources?summary=false&limit=${limit}&offset=${offset}`; + if (parentId) { + url += `&parent_id=${parentId}`; + } + console.log(`📡 获取资源 (parent_id: ${parentId || 'root'}, offset: ${offset}): ${url}`); + + let response; + try { + response = await requestUrl({ + url: url, + method: 'GET', + headers: this.getHeaders() + }); + } catch (error) { + const { status, detail } = this.parseRequestError(error); + if (status === 429) { + new Notice('⛔ API 次数已用完,显示缓存数据'); + } else { + this.handleError(status, detail); + } + // 返回已拿到的部分,配合缓存兜底 + return all.length > 0 ? all : []; + } + + if (response.status !== 200) { + this.handleError(response.status, this.getErrorDetail(response.json)); + return all.length > 0 ? all : []; + } + + const data = response.json; + const resources = data.resources || []; + + for (const item of resources) { + all.push({ + id: item.id || item.resourceId, + name: item.name || item.title || '未命名', + type: item.resource_type === 'folder' ? 'folder' : 'file', + updatedAt: item.updated_at || item.updatedAt || '', + parentId: item.parent_id || item.parentId || parentId || null, + path: item.path || '' + }); + } + + console.log(`📋 本页获取 ${resources.length} 个资源,累计 ${all.length} 个`); + + const total = typeof data.total === 'number' ? data.total : 0; + offset += resources.length; + if (resources.length === 0) break; + if (total && offset >= total) break; + if (resources.length < limit) break; + } + + return all; + } + + /** + * 拉取全量资源树(省配额版)。 + * + * 官方行为:不带 parent_id 的 GET /resources 对组合密钥会返回 + * Personal + Team 两个入口文件夹;对旧式根资源密钥返回根资源本身。 + * 树的完整结构可以从这一份"全资源扁平列表"里用 parent_id 在本地重建, + * 不需要为每个文件夹单独发一次请求。 + * + * 旧实现为每个文件夹递归调用一次接口,假设 3 层目录共 20 个文件夹就要 + * 21 次调用——基础版每天 10 次配额直接打爆。新实现常规情况 1 次调用即可。 + */ + async fetchFullTree(): Promise { + const flat = await this.fetchResourcesByParent(undefined, 100); + + if (flat.length === 0) return []; + + // 组合密钥入口只有 Personal/Team 两个入口文件夹,一次翻页就应拿全; + // 若返回的恰好只有文件夹入口且数量很少,说明可能只拿到入口层, + // 此时才对每个入口文件夹补一次子级拉取(通常 2 次封顶,不再是全树递归)。 + const entryIds = new Set(flat.map(r => r.id)); + const hasChildrenInFlat = flat.some(r => r.parentId && entryIds.has(r.parentId)); + if (!hasChildrenInFlat && flat.length <= 4) { + const withChildren = [...flat]; + for (const entry of flat.filter(r => r.type === 'folder')) { + const children = await this.fetchResourcesByParent(entry.id, 100); + withChildren.push(...children); + } + return this.deduplicate(withChildren); + } + + return this.deduplicate(flat); + } + + /** 按 id 去重(翻页边界或入口重复返回时防御) */ + private deduplicate(resources: OmniBoxResource[]): OmniBoxResource[] { + const seen = new Set(); + return resources.filter(r => { + if (seen.has(r.id)) return false; + seen.add(r.id); + return true; + }); + } + + clearChildrenCache(): void { + // 兼容空方法 + } + + /** + * 拉取资源完整正文(自动翻页)。 + * 官方 GET /resources/{id} 默认只返回 100 行(content_pagination.limit), + * 长文档必须用 content_offset 继续取,否则尾部的图片/段落会被静默丢弃。 + */ + private async fetchResourceContent(id: string): Promise { + let response; + try { + response = await requestUrl({ + url: `${this.baseUrl}/resources/${id}?content_limit=${CONTENT_PAGE_SIZE}`, + method: 'GET', + headers: this.getHeaders() + }); + } catch (error) { + const { status, detail } = this.parseRequestError(error); + this.handleError(status, detail); + return null; + } + + if (response.status !== 200) { + this.handleError(response.status, this.getErrorDetail(response.json)); + return null; + } + + const data = response.json; + let content: string = data.content || data.body || data.markdown || data.text || ''; + + const pag = data.content_pagination; + const totalLines: number = pag && typeof pag.total_lines === 'number' ? pag.total_lines : 0; + + if (!totalLines) return content; + + let fetchedLines = content ? content.split('\n').length : 0; + let page = 0; + + while (fetchedLines < totalLines && page < MAX_CONTENT_PAGES) { + page++; + console.log(`📄 正文翻页 offset=${fetchedLines}/${totalLines}`); + // 翻页是独立的计费请求,基础版用户必须能感知到这次额外消耗 + new Notice(`📄 文档超过 ${CONTENT_PAGE_SIZE} 行,追加第 ${page} 次翻页(+1 次配额)`); + + let more; + try { + more = await requestUrl({ + url: `${this.baseUrl}/resources/${id}?content_offset=${fetchedLines}&content_limit=${CONTENT_PAGE_SIZE}`, + method: 'GET', + headers: this.getHeaders() + }); + } catch (error) { + const { status, detail } = this.parseRequestError(error); + if (status === 429) { + new Notice('⛔ 正文未下载完整:API 次数已用完,剩余内容明天再补'); + } else { + this.handleError(status, detail); + } + break; + } + + if (more.status !== 200) { + if (more.status === 429) { + new Notice('⛔ 正文未下载完整:API 次数已用完,剩余内容明天再补'); + } else { + this.handleError(more.status, this.getErrorDetail(more.json)); + } + break; + } + + const d = more.json; + const chunk: string = d.content || d.body || d.markdown || d.text || ''; + if (!chunk) break; + + content += (content.endsWith('\n') ? '' : '\n') + chunk; + + const got = chunk.split('\n').length; + if (got <= 0) break; + fetchedLines += got; + + const nextTotal = d.content_pagination && typeof d.content_pagination.total_lines === 'number' + ? d.content_pagination.total_lines + : totalLines; + if (fetchedLines >= nextTotal) break; + } + + if (page >= MAX_CONTENT_PAGES) { + console.log(`⚠️ 正文翻页达到上限 ${MAX_CONTENT_PAGES} 页,可能仍有剩余内容`); + } + + return content; + } + + /** + * 下载资源内容(纯文字)- 过滤掉所有图片 + */ + async downloadResourceText(id: string): Promise { + try { + console.log(`📥 下载文档内容(纯文字): ${id}`); + + if (!this.namespaceId) { + await this.getApiKeyInfo(); + } + + const raw = await this.fetchResourceContent(id); + if (raw === null) return null; + + let content = raw; + + // ========== 过滤掉所有图片内容 ========== + if (content) { + const originalLength = content.length; + + // 删除 Markdown 图片语法 ![]() —— 完整URL + content = content.replace( + /!\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g, + '' + ); + + // 删除 Markdown 图片语法 ![]() —— 相对路径 attachments/ + content = content.replace( + /!\[([^\]]*)\]\((?:\.\.?\/)?(attachments\/[^)]+)\)/g, + '' + ); + + // 删除 HTML 标签 + content = content.replace( + /]*src=["'][^"']+["'][^>]*\/?>/gi, + '' + ); + + // 删除附件链接 []() + content = content.replace( + /\[([^\]]*)\]\((?:\.\.?\/)?(attachments\/[^)]+)\)/g, + '' + ); + + // 清理多余空行 + content = content.replace(/\n{3,}/g, '\n\n'); + content = content.trim(); + + console.log(`🧹 已过滤图片内容: ${originalLength} 字符 → ${content.length} 字符`); + } + + return content; + + } catch (error) { + new Notice(`❌ 下载失败: ${error.message}`); + return null; + } + } + + /** + * 下载资源内容(保留图片链接,用于图文模式后续替换) + * 注意:这里不要改写成网页域名 URL —— www.omnibox.pro/{ns}/{id}/attachments/xxx + * 需要浏览器登录态,Obsidian 的 取不到,只会 302 到登录页。 + * 保持正文原样(attachments/),由调用方按附件 ID 替换为本地路径。 + */ + async downloadResourceFull(id: string): Promise { + try { + console.log(`📥 下载文档内容(图文): ${id}`); + + if (!this.namespaceId) { + await this.getApiKeyInfo(); + } + + const content = await this.fetchResourceContent(id); + if (content === null) return null; + + return content; + + } catch (error) { + new Notice(`❌ 下载失败: ${error.message}`); + return null; + } + } + + /** + * 获取资源的附件列表(自动翻页) + * 注意:官方每个附件的 name 往往就是 "Image",不唯一也没有扩展名, + * 落盘必须用 id + content_type,不能依赖 name。 + */ + async fetchAttachments(resourceId: string): Promise { + const result: AttachmentInfo[] = []; + let offset = 0; + let page = 0; + + try { + console.log(`📎 获取附件列表: ${resourceId}`); + + while (page < MAX_ATTACHMENT_PAGES) { + page++; + + const response = await requestUrl({ + url: `${this.baseUrl}/resources/${resourceId}/attachments?limit=${ATTACHMENT_PAGE_SIZE}&offset=${offset}`, + method: 'GET', + headers: this.getHeaders() + }); + + if (response.status !== 200) { + console.log(`⚠️ 获取附件列表失败 (HTTP ${response.status})`); + if (response.status === 429) { + new Notice('⛔ 附件列表获取失败:API 次数已用完'); + } else if (response.status === 403) { + new Notice('❌ 附件列表无权限:API Key 缺少 resources:read'); + } + break; + } + + const data = response.json; + const list: any[] = data.attachments || []; + if (list.length === 0) break; + + for (const item of list) { + const id = item.id || item.attachment_id; + if (!id) continue; + result.push({ + id, + name: item.name || item.filename || `attachment_${id}`, + contentType: item.content_type || item.contentType, + downloadUrl: item.download_url || item.url, + size: item.size + }); + } + + offset += list.length; + + const total = typeof data.total === 'number' ? data.total : 0; + if (total && offset >= total) break; + if (list.length < ATTACHMENT_PAGE_SIZE) break; + } + + console.log(`📎 资源 ${resourceId} 共 ${result.length} 个附件`); + return result; + + } catch (error) { + console.log(`⚠️ 获取附件列表失败: ${error.message}`); + return result; + } + } + + /** + * 下载单个附件 + */ + async downloadAttachment(resourceId: string, attachmentId: string): Promise { + try { + console.log(`📥 下载附件: ${attachmentId}`); + + const response = await requestUrl({ + url: `${this.baseUrl}/resources/${resourceId}/attachments/${attachmentId}`, + method: 'GET', + headers: { + 'Authorization': `Bearer ${this.apiKey}` + } + }); + + if (response.status !== 200) { + console.log(`⚠️ 下载附件失败 (HTTP ${response.status})`); + if (response.status === 429) { + new Notice('⛔ 附件下载失败:API 次数已用完,明天再试'); + } else if (response.status === 403) { + new Notice('❌ 附件下载无权限:API Key 缺少 resources:read'); + } + return null; + } + + return response.arrayBuffer; + + } catch (error) { + console.log(`⚠️ 下载附件失败: ${error.message}`); + return null; + } + } + + async deleteResource(id: string): Promise { + try { + console.log(`🗑️ 删除资源: ${id}`); + const response = await requestUrl({ + url: `${this.baseUrl}/resources/${id}`, + method: 'DELETE', + headers: this.getHeaders() + }); + + if (response.status === 200 || response.status === 204) { + new Notice('✅ 云端资源已删除'); + return true; + } else { + this.handleError(response.status); + return false; + } + } catch (error) { + new Notice(`❌ 删除失败: ${error.message}`); + return false; + } + } + + async createResource(name: string, content: string, parentId?: string): Promise { + try { + const body: Record = { name, content }; + // 官方字段是 snake_case 的 parent_id;创建本身不消耗每日配额 + if (parentId) body.parent_id = parentId; + const response = await requestUrl({ + url: `${this.baseUrl}/resources`, + method: 'POST', + headers: this.getHeaders(), + body: JSON.stringify(body) + }); + + if (response.status === 200 || response.status === 201) { + const data = response.json; + new Notice(`✅ 资源 "${name}" 创建成功`); + return data.id || data.resourceId; + } else { + this.handleError(response.status); + return null; + } + } catch (error) { + new Notice(`❌ 创建失败: ${error.message}`); + return null; + } + } + + async updateResource(id: string, content: string): Promise { + try { + const response = await requestUrl({ + url: `${this.baseUrl}/resources/${id}`, + method: 'PATCH', + headers: this.getHeaders(), + body: JSON.stringify({ content }) + }); + + if (response.status === 200) { + new Notice('✅ 资源已更新'); + return true; + } else { + this.handleError(response.status); + return false; + } + } catch (error) { + new Notice(`❌ 更新失败: ${error.message}`); + return false; + } + } +} \ No newline at end of file diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..97142eb --- /dev/null +++ b/main.ts @@ -0,0 +1,185 @@ +import { Plugin, Notice } from 'obsidian'; +import { OmniBoxSettingTab, DEFAULT_SETTINGS, OmniBoxSettings, OmniBoxCache, DEFAULT_CACHE } from './settings'; +import { OmniBoxSidebarView } from './sidebar'; +import { OmniBoxAPI } from './api'; +import { OmniBoxResource } from './api'; + +export default class OmniBoxSyncPlugin extends Plugin { + settings: OmniBoxSettings; + api: OmniBoxAPI; + cache: OmniBoxCache; // 独立缓存 + + async onload() { + await this.loadSettings(); + await this.loadCache(); // 加载独立缓存 + + // 初始化API客户端 + this.api = new OmniBoxAPI(this.settings.apiKey); + + // 注册设置页面 + this.addSettingTab(new OmniBoxSettingTab(this.app, this)); + + // 注册边栏视图 + this.registerView( + 'omnibox-sidebar', + (leaf) => new OmniBoxSidebarView(leaf, this) + ); + + // 添加Ribbon图标 + this.addRibbonIcon('cloud', 'OmniBox 同步', () => { + this.activateView(); + }); + + // 添加命令 + this.addCommand({ + id: 'refresh-omnibox-list', + name: '刷新云端资源列表', + callback: () => this.refreshSidebar() + }); + + this.addCommand({ + id: 'sync-all-omnibox-text', + name: '下载全部文字', + callback: () => this.downloadAllText() + }); + + this.addCommand({ + id: 'sync-all-omnibox-full', + name: '下载全部图文', + callback: () => this.downloadAllFull() + }); + + // 清空缓存命令 + this.addCommand({ + id: 'clear-omnibox-cache', + name: '清空本地缓存', + callback: async () => { + await this.clearCache(); + new Notice('✅ 缓存已清空'); + } + }); + } + + // ========== 加载设置 ========== + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + + // ========== 保存设置 ========== + async saveSettings() { + await this.saveData(this.settings); + if (this.api) { + this.api.updateApiKey(this.settings.apiKey); + } + } + + // ========== 加载缓存 ========== + async loadCache(): Promise { + try { + const cachePath = `${this.app.vault.configDir}/plugins/omnibox-sync-plugin/data_cache.json`; + const cacheData = await this.app.vault.adapter.read(cachePath); + this.cache = JSON.parse(cacheData); + console.log('📋 缓存加载成功:', this.cache.cachedResources.length, '个资源'); + } catch (e) { + this.cache = JSON.parse(JSON.stringify(DEFAULT_CACHE)); + console.log('📋 使用默认缓存(空)'); + } + } + + // ========== 保存缓存 ========== + async saveCache(): Promise { + try { + const pluginDir = `${this.app.vault.configDir}/plugins/omnibox-sync-plugin`; + const cachePath = `${pluginDir}/data_cache.json`; + + const dirExists = await this.app.vault.adapter.exists(pluginDir); + if (!dirExists) { + await this.app.vault.adapter.mkdir(pluginDir); + console.log('📁 创建插件目录:', pluginDir); + } + + await this.app.vault.adapter.write(cachePath, JSON.stringify(this.cache, null, 2)); + console.log('💾 缓存保存成功:', this.cache.cachedResources.length, '个资源'); + } catch (e) { + console.error('❌ 缓存保存失败:', e); + } + } + + // ========== 清空缓存 ========== + async clearCache(): Promise { + this.cache = JSON.parse(JSON.stringify(DEFAULT_CACHE)); + await this.saveCache(); + await this.refreshSidebar(); + } + + // ========== 获取缓存的资源列表 ========== + getCachedResources(): OmniBoxResource[] { + return this.cache.cachedResources || []; + } + + // ========== 获取上次同步时间 ========== + getLastSyncTime(): string { + return this.cache.lastSyncTime || ''; + } + + // ========== 更新缓存 ========== + async updateCache(resources: OmniBoxResource[]): Promise { + this.cache.cachedResources = resources; + this.cache.lastSyncTime = new Date().toISOString(); + await this.saveCache(); + } + + // ========== 激活边栏 ========== + async activateView() { + const { workspace } = this.app; + + let leaf = workspace.getLeavesOfType('omnibox-sidebar')[0]; + if (!leaf) { + const rightLeaf = workspace.getRightLeaf(false); + if (!rightLeaf) { + new Notice('无法创建边栏,请检查 Obsidian 布局'); + return; + } + leaf = rightLeaf; + await leaf.setViewState({ + type: 'omnibox-sidebar', + active: true + }); + } + workspace.revealLeaf(leaf); + } + + async refreshSidebar() { + const leaves = this.app.workspace.getLeavesOfType('omnibox-sidebar'); + if (leaves.length > 0) { + const view = leaves[0].view as OmniBoxSidebarView; + await view.refresh(); + } + } + + // ========== 命令:下载全部文字 ========== + async downloadAllText() { + const leaves = this.app.workspace.getLeavesOfType('omnibox-sidebar'); + if (leaves.length > 0) { + const view = leaves[0].view as OmniBoxSidebarView; + await view.downloadAllText(); + } else { + new Notice('请先打开 OmniBox 侧边栏'); + } + } + + // ========== 命令:下载全部图文 ========== + async downloadAllFull() { + const leaves = this.app.workspace.getLeavesOfType('omnibox-sidebar'); + if (leaves.length > 0) { + const view = leaves[0].view as OmniBoxSidebarView; + await view.downloadAllFull(); + } else { + new Notice('请先打开 OmniBox 侧边栏'); + } + } + + onunload() { + this.app.workspace.detachLeavesOfType('omnibox-sidebar'); + } +} \ No newline at end of file diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..3ba1e34 --- /dev/null +++ b/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "omnibox-sync", + "name": "OmniBox Sync", + "version": "1.1.0", + "minAppVersion": "0.15.0", + "description": "同步小黑 (OmniBox) 内容到Obsidian(省配额模式:预算器+ID映射)", + "author": "XIGE", + "authorUrl": "", + "fundingUrl": "", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/settings.ts b/settings.ts new file mode 100644 index 0000000..87d4f85 --- /dev/null +++ b/settings.ts @@ -0,0 +1,206 @@ +import { App, PluginSettingTab, Setting, Notice } from 'obsidian'; +import OmniBoxSyncPlugin from './main'; +import { OmniBoxResource } from './api'; + +export interface OmniBoxSettings { + apiKey: string; + syncFolder: string; + autoSyncOnStart: boolean; + syncInterval: number; + overwriteLocal: boolean; + /** 已完整下载(图文齐全)的文档直接跳过 */ + skipCompleted: boolean; + /** 每次批量图文最多处理多少篇 */ + batchLimit: number; +} + +export const DEFAULT_SETTINGS: OmniBoxSettings = { + apiKey: '', + syncFolder: 'OmniBox', + autoSyncOnStart: false, + syncInterval: 0, + overwriteLocal: false, + skipCompleted: true, + batchLimit: 3 +}; + +// ========== 独立缓存数据结构 ========== +export interface OmniBoxCache { + cachedResources: OmniBoxResource[]; + lastSyncTime: string; +} + +export const DEFAULT_CACHE: OmniBoxCache = { + cachedResources: [], + lastSyncTime: '' +}; + +export class OmniBoxSettingTab extends PluginSettingTab { + plugin: OmniBoxSyncPlugin; + + constructor(app: App, plugin: OmniBoxSyncPlugin) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + + // 顶部标题 - 去掉左边距 + const titleEl = containerEl.createEl('h2', { text: 'OmniBox 同步设置' }); + titleEl.style.marginLeft = '0'; + titleEl.style.paddingLeft = '0'; + + // API Key 设置 + new Setting(containerEl) + .setName('API Key') + .setDesc('从小黑后台获取的 API Key。创建时请勾选「资源权限」的读取、创建、更新。') + .addText(text => text + .setPlaceholder('请输入你的 API Key...') + .setValue(this.plugin.settings.apiKey) + .onChange(async (value) => { + this.plugin.settings.apiKey = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + // 本地同步文件夹 + new Setting(containerEl) + .setName('本地同步文件夹') + .setDesc('云端资源将同步到此文件夹下(相对于库根目录)') + .addText(text => text + .setPlaceholder('OmniBox') + .setValue(this.plugin.settings.syncFolder) + .onChange(async (value) => { + this.plugin.settings.syncFolder = value.trim() || 'OmniBox'; + await this.plugin.saveSettings(); + }) + ); + + // 自动同步开关 + new Setting(containerEl) + .setName('启动时自动同步') + .setDesc('插件加载后自动刷新并同步资源列表') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.autoSyncOnStart) + .onChange(async (value) => { + this.plugin.settings.autoSyncOnStart = value; + await this.plugin.saveSettings(); + }) + ); + + // 同步间隔(分钟) + new Setting(containerEl) + .setName('自动同步间隔') + .setDesc('设置自动同步的间隔时间(分钟),设为0表示不自动同步。注意:基础版每日仅10次API调用') + .addText(text => text + .setPlaceholder('0') + .setValue(String(this.plugin.settings.syncInterval)) + .onChange(async (value) => { + const num = parseInt(value); + if (!isNaN(num) && num >= 0) { + this.plugin.settings.syncInterval = num; + await this.plugin.saveSettings(); + } + }) + ); + + // 覆盖策略 + new Setting(containerEl) + .setName('覆盖本地文件') + .setDesc('当云端文件比本地文件更新时,是否自动覆盖。关闭则跳过') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.overwriteLocal) + .onChange(async (value) => { + this.plugin.settings.overwriteLocal = value; + await this.plugin.saveSettings(); + }) + ); + + // 测试连接 - 移动到覆盖策略下面 + new Setting(containerEl) + .setName('测试连接') + .setDesc('点击测试 API Key 是否有效') + .addButton(button => button + .setButtonText('测试连接') + .onClick(async () => { + const { api } = this.plugin; + if (!api) return; + + button.setButtonText('测试中...'); + button.setDisabled(true); + + try { + const result = await api.testConnection(); + if (result) { + const info = await api.getApiKeyInfo(); + const used = info?.open_api_requests_quota?.used || 0; + const limit = info?.open_api_requests_quota?.limit || 0; + const resetAt = info?.open_api_requests_quota?.reset_at || ''; + let resetMsg = ''; + if (resetAt) { + const resetDate = new Date(resetAt); + const hours = Math.ceil((resetDate.getTime() - Date.now()) / (1000 * 60 * 60)); + if (hours > 0) { + resetMsg = `,约 ${hours} 小时后重置`; + } + } + new Notice(`连接成功!今日已使用 ${used}/${limit} 次API调用${resetMsg}`); + } else { + new Notice('连接失败,请检查 API Key'); + } + } catch (e: any) { + new Notice(`连接失败: ${e.message}`); + } finally { + button.setButtonText('测试连接'); + button.setDisabled(false); + } + }) + ); + + // ========== 批量下载节流 ========== + containerEl.createEl('h3', { text: '批量下载节流' }); + + new Setting(containerEl) + .setName('跳过已下载') + .setDesc('图文已经齐全的文档不再重复下载,只补未下载或图片缺失的(配合断点续传,分批跑完)') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.skipCompleted) + .onChange(async (value) => { + this.plugin.settings.skipCompleted = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName('每批下载数量') + .setDesc('点一次「下载图文」最多处理多少篇。基础版每天仅 10 次调用,建议设 2~3 篇分批跑') + .addText(text => text + .setPlaceholder('3') + .setValue(String(this.plugin.settings.batchLimit)) + .onChange(async (value) => { + const num = parseInt(value); + if (!isNaN(num) && num >= 1) { + this.plugin.settings.batchLimit = num; + await this.plugin.saveSettings(); + } + }) + ); + + // ========== 新增:清空缓存按钮(放在设置页面最后) ========== + containerEl.createEl('hr'); + + new Setting(containerEl) + .setName('清空缓存') + .setDesc('清空本地缓存的资源列表(data_cache.json),不影响 API Key 等设置。清空后需重新刷新加载。') + .addButton(button => button + .setButtonText('清空缓存') + .setWarning() + .onClick(async () => { + await this.plugin.clearCache(); + new Notice('✅ 缓存已清空'); + }) + ); + } +} \ No newline at end of file diff --git a/sidebar.ts b/sidebar.ts new file mode 100644 index 0000000..36f897c --- /dev/null +++ b/sidebar.ts @@ -0,0 +1,1089 @@ +import { ItemView, WorkspaceLeaf, TFile, Notice } from 'obsidian'; +import OmniBoxSyncPlugin from './main'; +import { OmniBoxResource, AttachmentInfo, extFromContentType } from './api'; +import { OmniboxIdIndex } from './utils'; + +interface TreeNode extends OmniBoxResource { + children: TreeNode[]; + expanded: boolean; + level: number; + isChanged?: boolean; + isDownloaded?: boolean; +} + +export class OmniBoxSidebarView extends ItemView { + private plugin: OmniBoxSyncPlugin; + private listContainer: HTMLElement; + private statusEl: HTMLElement; + private treeData: TreeNode[] = []; + private expandedIds: Set = new Set(); + private isExpanded: boolean = false; + private toggleExpandBtn: HTMLElement; + private currentStatusText: string = ''; + /** 云端ID -> 本地文件 索引(ID 优先、文件名回退),省配额关键:避免改名后重复下载 */ + private idIndex: OmniboxIdIndex; + + constructor(leaf: WorkspaceLeaf, plugin: OmniBoxSyncPlugin) { + super(leaf); + this.plugin = plugin; + this.idIndex = new OmniboxIdIndex(plugin.settings.syncFolder); + this.idIndex.rebuild(this.app); + } + + getViewType(): string { + return 'omnibox-sidebar'; + } + + getDisplayText(): string { + return 'OmniBox'; + } + + getIcon(): string { + return 'cloud'; + } + + async onOpen() { + const container = this.containerEl.children[1]; + container.empty(); + container.addClass('omnibox-sidebar-container'); + + const header = container.createDiv('omnibox-header'); + header.createEl('h4', { text: 'OmniBox 同步' }); + + this.statusEl = header.createDiv('omnibox-status'); + this.updateStatus('就绪'); + + // ========== 工具栏 ========== + const toolbar = container.createDiv('omnibox-toolbar'); + + const refreshBtn = toolbar.createEl('button', { text: '刷新' }); + refreshBtn.addClass('mod-cta'); + refreshBtn.onclick = () => this.refresh(); + + const downloadTextBtn = toolbar.createEl('button', { text: '下载文字' }); + downloadTextBtn.title = '只下载文档文字,过滤图片(1次API/文档)'; + downloadTextBtn.onclick = () => this.downloadAllText(); + + const downloadFullBtn = toolbar.createEl('button', { text: '下载图文' }); + downloadFullBtn.title = '按批次下载文档+附件(跳过已完整,断点续传)'; + downloadFullBtn.onclick = () => this.downloadAllFull(); + + this.toggleExpandBtn = toolbar.createEl('button', { text: '展开' }); + this.toggleExpandBtn.onclick = () => { + if (this.isExpanded) { + this.collapseAll(); + this.toggleExpandBtn.textContent = '展开'; + this.isExpanded = false; + } else { + this.expandAll(); + this.toggleExpandBtn.textContent = '折叠'; + this.isExpanded = true; + } + }; + + this.listContainer = container.createDiv('omnibox-list'); + + const cachedResources = this.plugin.getCachedResources(); + if (cachedResources.length > 0) { + const tree = this.buildTreeWithChanges(cachedResources, []); + this.treeData = tree; + const allFiles = this.getAllFiles(tree); + const rootFolders = tree.filter(n => n.type === 'folder'); + + let apiInfo = ' (缓存)'; + try { + const info = await this.plugin.api.getApiKeyInfo(); + if (info && info.open_api_requests_quota) { + const quota = info.open_api_requests_quota; + apiInfo = this.formatApiInfo( + quota.used ?? 0, + quota.limit ?? 0, + quota.remaining ?? 0, + quota.reset_at ?? '' + ); + } + } catch (e) { + console.log('获取API用量信息失败:', e); + } + + this.currentStatusText = `${allFiles.length} 个文件, ${rootFolders.length} 个分类${apiInfo}`; + this.updateStatus(this.currentStatusText); + + for (const node of tree) { + this.renderTreeNode(node, this.listContainer, 0); + } + } else { + this.listContainer.createEl('p', { text: '点击「刷新」加载云端资源', cls: 'omnibox-placeholder' }); + this.currentStatusText = '就绪'; + this.updateStatus('就绪'); + } + + if (this.plugin.settings.autoSyncOnStart) { + await this.refresh(); + } + } + + private formatApiInfo(used: number, limit: number, remaining: number, resetAt: string): string { + let resetTimeStr = ''; + if (resetAt) { + const resetDate = new Date(resetAt); + resetTimeStr = `${resetDate.getHours().toString().padStart(2, '0')}:${resetDate.getMinutes().toString().padStart(2, '0')}`; + } + + if (remaining === 0 && resetTimeStr) { + return ` | ⛔ API 已用完,将于 ${resetTimeStr} 恢复`; + } else if (remaining === 0) { + return ' | ⛔ API 已用完'; + } else if (limit > 0) { + return ` | API: ${used}/${limit} (剩余 ${remaining} 次,${resetTimeStr} 重置)`; + } + return ''; + } + + private async updateApiInfo(): Promise { + try { + const info = await this.plugin.api.getApiKeyInfo(); + if (info && info.open_api_requests_quota) { + const quota = info.open_api_requests_quota; + if (this.currentStatusText) { + let newText = this.currentStatusText.replace(/\s*\|\s*[^|]*$/, ''); + newText += this.formatApiInfo( + quota.used ?? 0, + quota.limit ?? 0, + quota.remaining ?? 0, + quota.reset_at ?? '' + ); + this.currentStatusText = newText; + this.updateStatus(this.currentStatusText); + } + } + } catch (e) { + console.log('更新API用量信息失败:', e); + } + } + + async refresh() { + console.log('🔄 [OmniBox] 开始刷新列表...'); + this.updateStatus('加载中...'); + this.listContainer.empty(); + + // getApiKeyInfo 不消耗每日配额(官方白名单端点), + // 提前取一次,同时用于「是否限流」的准确判断和状态栏展示, + // 避免后面再发第二次请求。 + let quotaInfo: { used: number; limit: number; remaining: number; reset_at: string } | null = null; + try { + const info = await this.plugin.api.getApiKeyInfo(); + if (info && info.open_api_requests_quota) { + const q = info.open_api_requests_quota; + quotaInfo = { + used: q.used ?? 0, + limit: q.limit ?? 0, + remaining: q.remaining ?? 0, + reset_at: q.reset_at ?? '' + }; + } + } catch (e) { + console.log('获取API用量信息失败:', e); + } + + let allResources: OmniBoxResource[] = []; + let isFromCache = false; + let apiSuccess = false; + + // 配额已耗尽时直接走缓存,不再浪费一次注定失败的请求 + const quotaExhausted = quotaInfo !== null && quotaInfo.remaining === 0; + + try { + if (quotaExhausted) { + console.log('⛔ 配额已用完,跳过资源拉取,直接读缓存'); + } else { + allResources = await this.plugin.api.fetchFullTree(); + apiSuccess = true; + } + } catch (e) { + console.log('获取资源失败:', e); + } + + if (!apiSuccess || !allResources || allResources.length === 0) { + const cached = this.plugin.getCachedResources(); + if (cached.length > 0) { + allResources = cached; + isFromCache = true; + new Notice(quotaExhausted ? '⛔ API 次数已用完,显示缓存数据' : '⚠️ 云端拉取失败,显示缓存数据'); + } else { + this.listContainer.createEl('p', { + text: '暂无资源,请检查 API Key 和权限范围', + cls: 'omnibox-empty' + }); + this.currentStatusText = '无资源'; + this.updateStatus('无资源'); + return; + } + } + + const changedResources = this.findChangedResources(allResources); + const tree = this.buildTreeWithChanges(allResources, changedResources); + this.treeData = tree; + + const allFiles = this.getAllFiles(tree); + const rootFolders = tree.filter(n => n.type === 'folder'); + const changedCount = changedResources.length; + + let apiInfo = ''; + if (quotaInfo) { + apiInfo = this.formatApiInfo( + quotaInfo.used, + quotaInfo.limit, + quotaInfo.remaining, + quotaInfo.reset_at + ); + if (isFromCache && apiInfo) apiInfo += ' (缓存数据)'; + } else { + apiInfo = this.getFallbackApiInfo(isFromCache); + } + + this.currentStatusText = `${allFiles.length} 个文件, ${rootFolders.length} 个分类, ${changedCount} 个有更新${apiInfo}`; + this.updateStatus(this.currentStatusText); + + if (changedCount > 0 && !isFromCache) { + new Notice(`📢 发现 ${changedCount} 个资源有更新`); + } + + if (this.isExpanded === false && this.toggleExpandBtn) { + this.toggleExpandBtn.textContent = '展开'; + } + + for (const node of tree) { + this.renderTreeNode(node, this.listContainer, 0); + } + + if (apiSuccess && allResources && allResources.length > 0) { + await this.plugin.updateCache(allResources); + } + } + + private getFallbackApiInfo(isFromCache: boolean): string { + if (isFromCache) { + // lastSync + 24h 只是粗估(官方按 namespace 24h 滚动窗口计算), + // 明确标注"估算",避免用户按错误时刻干等 + const lastSync = this.plugin.cache.lastSyncTime; + if (lastSync) { + const resetDate = new Date(new Date(lastSync).getTime() + 24 * 60 * 60 * 1000); + const resetTimeStr = `${resetDate.getHours().toString().padStart(2, '0')}:${resetDate.getMinutes().toString().padStart(2, '0')}`; + return ` | ⛔ API 已用完,约 ${resetTimeStr} 恢复(估算),以状态栏实时查询为准`; + } + return ' | ⛔ API 已限流 (缓存)'; + } + return ' | API: 获取失败'; + } + + private findChangedResources(currentResources: OmniBoxResource[]): OmniBoxResource[] { + const cached = this.plugin.getCachedResources(); + const cachedMap = new Map(cached.map(r => [r.id, r])); + + const changed: OmniBoxResource[] = []; + + for (const res of currentResources) { + const cachedRes = cachedMap.get(res.id); + if (!cachedRes || cachedRes.updatedAt !== res.updatedAt) { + changed.push(res); + } + } + + return changed; + } + + private buildTreeWithChanges(resources: OmniBoxResource[], changedResources: OmniBoxResource[]): TreeNode[] { + const map = new Map(); + const roots: TreeNode[] = []; + const changedIds = new Set(changedResources.map(r => r.id)); + + // 下载状态用 ID 索引判定(ID 优先、文件名回退),不再依赖纯文件名集合 + this.idIndex.rebuild(this.app); + + for (const res of resources) { + map.set(res.id, { + ...res, + children: [], + expanded: false, + level: 0, + isChanged: changedIds.has(res.id), + isDownloaded: this.idIndex.findByCloudId(this.app, res.id) !== null + || this.getDownloadedFileNames().has(this.getLocalFileName(res.name)) + }); + } + + for (const res of resources) { + const node = map.get(res.id); + if (!node) continue; + if (res.parentId && map.has(res.parentId)) { + const parent = map.get(res.parentId)!; + parent.children.push(node); + node.level = parent.level + 1; + } else { + roots.push(node); + } + } + + const sortNodes = (nodes: TreeNode[]) => { + nodes.sort((a, b) => { + if (a.type === 'folder' && b.type !== 'folder') return -1; + if (a.type !== 'folder' && b.type === 'folder') return 1; + if (a.type === 'folder' && b.type === 'folder') { + return (new Date(a.updatedAt).getTime() || 0) - (new Date(b.updatedAt).getTime() || 0); + } + if (a.type === 'file' && b.type === 'file') { + return (new Date(b.updatedAt).getTime() || 0) - (new Date(a.updatedAt).getTime() || 0); + } + return a.name.localeCompare(b.name); + }); + for (const node of nodes) sortNodes(node.children); + }; + sortNodes(roots); + + return roots; + } + + private getDownloadedFileNames(): Set { + const folderPath = this.plugin.settings.syncFolder || 'OmniBox'; + const files = this.app.vault.getFiles(); + const downloaded = new Set(); + for (const file of files) { + if (file.path.startsWith(`${folderPath}/`)) { + downloaded.add(file.name.replace(/\.md$/, '')); + } + } + return downloaded; + } + + private getLocalFileName(cloudName: string): string { + const base = cloudName.endsWith('.md') ? cloudName.replace(/\.md$/, '') : cloudName; + return this.sanitizeFileName(base); + } + + private async openLocalFile(fileName: string, cloudId?: string): Promise { + const folderPath = this.plugin.settings.syncFolder || 'OmniBox'; + // ID 优先查找(云端改名后仍能打开),文件名回退 + const file = cloudId + ? this.idIndex.resolveLocalFile(this.app, cloudId, fileName, (n) => this.getLocalFileName(n)) + : this.app.vault.getAbstractFileByPath(`${folderPath}/${fileName}.md`); + if (file instanceof TFile) { + const leaf = this.app.workspace.getLeaf(true); + await leaf.openFile(file); + } else { + new Notice(`❌ 本地文件不存在: ${fileName}`); + } + } + + // ========== 下载全部文字 ========== + async downloadAllText() { + const { allFiles } = await this.getResourceFiles(); + if (allFiles.length === 0) { + new Notice('没有文件需要下载'); + return; + } + + // ===== 配额预算:按剩余次数精确截断本批(查询本身免配额) ===== + const quota = await this.plugin.api.getRemainingQuota(); + let todo = allFiles; + let budgetNote = ''; + if (quota && quota.remaining >= 0) { + // 预留 0 次:文字下载每篇正好 1 次计费 + if (quota.remaining === 0) { + const resetAt = quota.reset_at ? new Date(quota.reset_at) : null; + const resetStr = resetAt ? `,${resetAt.getHours().toString().padStart(2, '0')}:${resetAt.getMinutes().toString().padStart(2, '0')} 后恢复` : ''; + new Notice(`⛔ 今日配额已用完${resetStr}`); + return; + } + if (allFiles.length > quota.remaining) { + todo = allFiles.slice(0, quota.remaining); + budgetNote = `\n⚠️ 剩余配额只够 ${quota.remaining} 篇,其余 ${allFiles.length - quota.remaining} 篇明天继续。`; + } + } else { + budgetNote = '\n(配额查询失败,将按实际剩余尽力下载)'; + } + + const confirmed = confirm( + `共 ${allFiles.length} 篇,本批下载 ${todo.length} 篇(纯文字,每篇 1 次)。\n` + + `预计消耗 ${todo.length} 次 API。` + + (quota ? `\n当前剩余 ${quota.remaining}/${quota.limit} 次。` : '') + + budgetNote + `\n\n是否继续?` + ); + if (!confirmed) return; + + this.updateStatus(`下载文字中 (0/${todo.length})...`); + let successCount = 0; + + for (const file of todo) { + const content = await this.plugin.api.downloadResourceText(file.id); + if (content) { + await this.saveToVault(file.name, content, file.id); + this.updateCachedResourceTime(file.id); + successCount++; + } else { + // 下载失败(大概率配额用完),立即停下避免继续空耗 + new Notice('⚠️ 下载中断,剩余文档明天配额恢复后继续'); + break; + } + this.updateStatus(`下载文字中 (${successCount}/${todo.length})...`); + } + + this.updateStatus(`下载完成: ${successCount}/${todo.length} 个文件`); + new Notice(`✅ 已下载 ${successCount} 个文档(纯文字)`); + // 不再重新拉取目录(每层目录都要花一次配额),本地重绘即可 + this.renderFullTree(); + await this.updateApiInfo(); + } + + /** + * 取文件清单:优先用缓存,避免为「列目录」白花配额 + * (fetchFullTree 每层目录 1 次调用,基础版 10 次/天根本扛不住) + */ + private async getResourceFiles(): Promise<{ allFiles: OmniBoxResource[]; fromCache: boolean }> { + let resources = this.plugin.getCachedResources(); + let fromCache = false; + + if (!resources || resources.length === 0) { + resources = await this.plugin.api.fetchFullTree(); + } else { + fromCache = true; + } + + return { allFiles: resources.filter(r => r.type === 'file'), fromCache }; + } + + // ========== 下载全部图文(分批 + 断点续传) ========== + /** 正文里是否还残留未替换为本地路径的附件引用(= 该文档图片没补齐) */ + private hasUnresolvedAttachments(content: string, resourceId: string): boolean { + if (!content.includes('attachments/')) return false; + const re = new RegExp(`attachments/(?!${resourceId}/)[^)\\]\\s"'>]+`); + return re.test(content); + } + + /** 云端是否比本地新(按 frontmatter 的 last_sync 比较)。 + * 改用 metadataCache 读取(零文件 IO),比正则抠正文快且稳。 */ + private isCloudNewer(file: OmniBoxResource, localFile: TFile): boolean { + const cache = this.app.metadataCache.getFileCache(localFile); + const lastSync = cache?.frontmatter?.['last_sync']; + if (typeof lastSync !== 'string') return true; + const local = Date.parse(lastSync); + const remote = Date.parse(file.updatedAt || ''); + if (isNaN(local) || isNaN(remote)) return true; + return remote > local + 1000; + } + + /** 待处理清单:未下载 / 图片不完整 /(关闭跳过时)云端有更新。 + * 本地文件用 ID 索引查找(ID 优先、文件名回退),云端改名不会误判为未下载。 */ + private async getPendingFullList(files: OmniBoxResource[]): Promise { + const folderPath = this.plugin.settings.syncFolder || 'OmniBox'; + const skipCompleted = this.plugin.settings.skipCompleted; + const pending: OmniBoxResource[] = []; + + for (const file of files) { + const local = this.idIndex.resolveLocalFile( + this.app, file.id, file.name, (n) => this.getLocalFileName(n) + ); + + // 从没下载过 + if (!(local instanceof TFile)) { + pending.push(file); + continue; + } + + // 断点续传:图片还没补齐,下一批接着补 + // (直接读文件检查 attachments 残留;last_sync 比较走 metadataCache) + let content = ''; + try { + content = await this.app.vault.cachedRead(local); + } catch { + content = ''; + } + + if (this.hasUnresolvedAttachments(content, file.id)) { + pending.push(file); + continue; + } + + // 已完整:只有在关闭「跳过已下载」且云端更新过时才重下 + if (!skipCompleted && this.isCloudNewer(file, local)) { + pending.push(file); + } + } + + return pending; + } + + async downloadAllFull() { + this.updateStatus('检查待处理文档...'); + + const { allFiles } = await this.getResourceFiles(); + + if (allFiles.length === 0) { + new Notice('没有文件需要下载'); + return; + } + + const pending = await this.getPendingFullList(allFiles); + + if (pending.length === 0) { + this.updateStatus(`全部完整,共 ${allFiles.length} 篇`); + new Notice('✅ 所有文档的图文都已完整,无需下载'); + return; + } + + const batchSize = Math.max(1, this.plugin.settings.batchLimit || 3); + let todo = pending.slice(0, batchSize); + + // ===== 配额预算:查询免配额,按真实剩余次数规划本批 ===== + const quota = await this.plugin.api.getRemainingQuota(); + if (quota) { + if (quota.remaining === 0) { + const resetAt = quota.reset_at ? new Date(quota.reset_at) : null; + const resetStr = resetAt ? `,${resetAt.getHours().toString().padStart(2, '0')}:${resetAt.getMinutes().toString().padStart(2, '0')} 后恢复` : ''; + new Notice(`⛔ 今日配额已用完${resetStr},图文下载明天再继续(断点续传已就绪)`); + return; + } + // 保守预算:每篇按 正文1 + 附件列表1 + 2附件 = 4 次估 + const perFileEstimate = 4; + const affordable = Math.floor(quota.remaining / perFileEstimate); + if (affordable === 0) { + new Notice(`⛔ 剩余 ${quota.remaining} 次不够一篇图文(约需 ${perFileEstimate} 次),明天再继续`); + return; + } + if (todo.length > affordable) { + todo = todo.slice(0, affordable); + new Notice(`📊 剩余 ${quota.remaining} 次,本批自动缩减为 ${todo.length} 篇(每篇约 4 次)`); + } + } + + const listPreview = todo.map((f, i) => ` ${i + 1}. ${f.name}`).join('\n'); + const confirmed = confirm( + `共 ${allFiles.length} 篇,待处理 ${pending.length} 篇(未下载或图片不完整)。\n\n` + + `本批处理 ${todo.length} 篇:\n${listPreview}\n\n` + + `消耗:每篇 = 正文 1 次 + 附件列表 1 次 + 每个附件 1 次。\n` + + (quota ? `当前剩余 ${quota.remaining}/${quota.limit} 次。\n` : '基础版每天仅 10 次;') + + `中途超额会停下,剩下的下批继续。\n\n是否继续?` + ); + if (!confirmed) return; + + this.updateStatus(`下载图文 (0/${todo.length})...`); + let successCount = 0; + + for (const file of todo) { + const ok = await this.downloadResourceWithAttachments(file); + if (!ok) { + // 大概率配额已用完,先停下别再空耗 + this.updateStatus(`本批中断:${file.name} 下载失败(配额可能已用完)`); + new Notice('⚠️ 本批中断,剩余文档下次继续(断点续传已就绪)'); + this.renderFullTree(); + await this.updateApiInfo(); + return; + } + successCount++; + this.updateStatus(`下载图文 (${successCount}/${todo.length})...`); + } + + const remaining = pending.length - successCount; + this.updateStatus( + `本批完成 ${successCount}/${todo.length}` + + (remaining > 0 ? `,还剩 ${remaining} 篇待处理` : ',全部完成') + ); + new Notice( + remaining > 0 + ? `✅ 本批完成 ${successCount} 篇,还剩 ${remaining} 篇,可再次点击继续` + : `✅ 全部完成,本批 ${successCount} 篇` + ); + this.renderFullTree(); + await this.updateApiInfo(); + } + + // ========== 下载更新的文字 ========== + // 说明:这两个方法需要先「刷新」拿到变更列表才能定位目标, + // 而刷新本身在基础版要花 1~3 次宝贵配额。 + // 日常请优先用「下载文字/下载图文」批量按钮(走本地缓存,零刷新成本)。 + async downloadChangedText() { + const changed = this.findChangedResources(this.plugin.getCachedResources()); + if (changed.length === 0) { + new Notice('没有需要更新的资源'); + return; + } + + const files = changed.filter(r => r.type === 'file'); + this.updateStatus(`下载更新文字 (${files.length} 个)...`); + let successCount = 0; + + for (const res of files) { + const content = await this.plugin.api.downloadResourceText(res.id); + if (content) { + await this.saveToVault(res.name, content, res.id); + this.updateCachedResourceTime(res.id); + successCount++; + } else { + new Notice('⚠️ 下载中断,剩余文档明天配额恢复后继续'); + break; + } + } + + this.updateStatus(`下载完成: ${successCount}/${files.length} 个文件`); + new Notice(`✅ 已下载 ${successCount} 个文档(纯文字)`); + // 本地重绘即可,不再触发 refresh(refresh 每次要花目录拉取配额) + this.renderFullTree(); + await this.updateApiInfo(); + } + + // ========== 下载更新的图文 ========== + async downloadChangedFull() { + const changed = this.findChangedResources(this.plugin.getCachedResources()); + if (changed.length === 0) { + new Notice('没有需要更新的资源'); + return; + } + + const files = changed.filter(r => r.type === 'file'); + const confirmed = confirm( + `即将下载 ${files.length} 个文档(图文)。\n\n` + + `消耗:每篇 = 正文 1 次 + 附件列表 1 次 + 每个附件 1 次。\n` + + `⚠️ 基础版每天仅 10 次,建议把「每批下载数量」设为 2~3 分批跑。\n\n是否继续?` + ); + if (!confirmed) return; + + this.updateStatus(`下载更新图文 (${files.length} 个)...`); + let successCount = 0; + + for (const res of files) { + const ok = await this.downloadResourceWithAttachments(res); + if (!ok) { + new Notice('⚠️ 下载中断,剩余文档明天配额恢复后继续'); + break; + } + successCount++; + } + + this.updateStatus(`下载完成: ${successCount}/${files.length} 个文件`); + new Notice(`✅ 已下载 ${successCount} 个文档(图文)`); + this.renderFullTree(); + await this.updateApiInfo(); + } + + // ========== 下载单个文档+附件 ========== + private async downloadResourceWithAttachments(resource: OmniBoxResource): Promise { + // 1. 下载文档内容(保留 attachments/ 原始引用) + const content = await this.plugin.api.downloadResourceFull(resource.id); + if (!content) return false; + + // 2. 获取附件列表(已自动翻页) + const attachments = await this.plugin.api.fetchAttachments(resource.id); + + // attachmentId -> 相对笔记所在目录的链接路径 + const attachmentMap = new Map(); + + if (attachments.length > 0) { + const baseFolder = this.plugin.settings.syncFolder || 'OmniBox'; + const attRoot = `${baseFolder}/attachments`; + // 按资源分目录,避免不同文档的同名附件互相覆盖 + const resFolder = `${attRoot}/${resource.id}`; + + await this.ensureFolder(resFolder); + + for (const att of attachments) { + // 用附件 ID + content_type 决定文件名:官方 name 常常就是 "Image",不可用 + const ext = extFromContentType(att.contentType, att.name); + const fileName = `${att.id}.${ext}`; + const localAttPath = `${resFolder}/${fileName}`; + + const existing = this.app.vault.getAbstractFileByPath(localAttPath); + + if (!existing) { + const buffer = await this.plugin.api.downloadAttachment(resource.id, att.id); + if (!buffer || buffer.byteLength === 0) { + console.log(`⚠️ 附件下载失败,跳过: ${att.id} (${att.contentType || '未知类型'})`); + continue; + } + try { + await this.app.vault.createBinary(localAttPath, buffer); + console.log(`✅ 附件已下载: ${fileName} (${buffer.byteLength} 字节)`); + } catch (e) { + console.log(`⚠️ 附件写入失败: ${fileName} - ${e.message}`); + continue; + } + } + + // 笔记位于 syncFolder 下,因此用相对 syncFolder 的路径 + attachmentMap.set(att.id, `attachments/${resource.id}/${fileName}`); + } + } + + // 3. 保存文档,把 attachments/ 替换为本地路径 + await this.saveToVault(resource.name, content, resource.id, attachmentMap); + this.updateCachedResourceTime(resource.id); + return true; + } + + /** 递归创建目录(已存在则忽略) */ + private async ensureFolder(folderPath: string): Promise { + const parts = folderPath.split('/').filter(p => p); + let current = ''; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + if (!this.app.vault.getAbstractFileByPath(current)) { + try { + await this.app.vault.createFolder(current); + } catch (e) { + // 并发下可能已存在,忽略 + } + } + } + } + + /** 清理文件名中的非法字符(Windows 下 : ? * " < > | 都会导致创建失败) */ + private sanitizeFileName(name: string): string { + let safe = (name || '未命名') + .replace(/[\\/:*?"<>|]/g, '_') + .replace(/[\x00-\x1f]/g, '') + .replace(/\s+/g, ' ') + .trim() + .replace(/[. ]+$/, ''); + + if (!safe) safe = '未命名'; + if (safe.length > 120) safe = safe.slice(0, 120).trim(); + return safe; + } + + // ========== 下载单个文档(文字) ========== + private async downloadResourceText(resource: OmniBoxResource) { + this.updateStatus(`下载中: ${resource.name}...`); + + const content = await this.plugin.api.downloadResourceText(resource.id); + if (content) { + await this.saveToVault(resource.name, content, resource.id); + this.updateCachedResourceTime(resource.id); + this.updateNodeChangedStatus(resource.id, false); + await this.updateApiInfo(); + new Notice(`✅ 已下载: ${resource.name}`); + } + + this.renderFullTree(); + } + + private buildTree(resources: OmniBoxResource[]): TreeNode[] { + return this.buildTreeWithChanges(resources, []); + } + + private renderTreeNode(node: TreeNode, container: HTMLElement, level: number) { + const itemDiv = container.createDiv('omnibox-item'); + itemDiv.style.paddingLeft = `${level * 20 + 8}px`; + itemDiv.style.display = 'flex'; + itemDiv.style.alignItems = 'center'; + itemDiv.style.padding = '4px 8px'; + itemDiv.style.borderRadius = '4px'; + itemDiv.style.cursor = 'default'; + itemDiv.dataset.resourceId = node.id; + + if (node.type === 'folder') { + const isOpen = this.expandedIds.has(node.id); + const toggleIcon = itemDiv.createEl('span', { + text: isOpen ? '▾' : '▸', + cls: 'omnibox-toggle' + }); + toggleIcon.style.cursor = 'pointer'; + toggleIcon.style.marginRight = '8px'; + toggleIcon.style.width = '16px'; + toggleIcon.style.display = 'inline-block'; + toggleIcon.style.fontSize = '14px'; + + const nameSpan = itemDiv.createEl('span', { + text: `📁 ${node.name}`, + cls: 'omnibox-item-name omnibox-folder-name' + }); + nameSpan.style.fontWeight = '600'; + nameSpan.style.cursor = 'pointer'; + nameSpan.style.flex = '1'; + + const countSpan = itemDiv.createEl('span', { + text: ` (${node.children.length})`, + cls: 'omnibox-item-count' + }); + countSpan.style.color = 'var(--text-muted)'; + countSpan.style.fontSize = '12px'; + countSpan.style.marginLeft = '4px'; + + itemDiv.onclick = () => this.toggleFolder(node.id); + + const childrenContainer = container.createDiv('omnibox-children'); + childrenContainer.style.marginLeft = '0px'; + childrenContainer.style.display = isOpen ? 'block' : 'none'; + + if (node.children.length > 0) { + for (const child of node.children) { + this.renderTreeNode(child, childrenContainer, level + 1); + } + } else { + const emptyEl = childrenContainer.createDiv('omnibox-empty-folder'); + emptyEl.textContent = '空分类'; + emptyEl.style.paddingLeft = '20px'; + emptyEl.style.color = 'var(--text-muted)'; + emptyEl.style.fontSize = '12px'; + emptyEl.style.fontStyle = 'italic'; + } + } else { + const isDownloaded = node.isDownloaded || false; + + const iconSpan = itemDiv.createEl('span', { + text: isDownloaded ? '✅' : (node.isChanged ? '🆕' : '📄'), + cls: 'omnibox-file-icon' + }); + iconSpan.style.marginRight = '8px'; + + const nameSpan = itemDiv.createEl('span', { + text: node.name, + cls: 'omnibox-item-name' + }); + nameSpan.style.flex = '1'; + + if (node.updatedAt) { + const timeSpan = itemDiv.createEl('span', { + text: new Date(node.updatedAt).toLocaleString(), + cls: 'omnibox-item-time' + }); + timeSpan.style.color = 'var(--text-muted)'; + timeSpan.style.fontSize = '10px'; + timeSpan.style.marginRight = '8px'; + } + + const actions = itemDiv.createDiv('omnibox-item-actions'); + actions.style.display = 'flex'; + actions.style.gap = '4px'; + + if (isDownloaded) { + const readBtn = actions.createEl('button', { text: '阅读' }); + readBtn.onclick = async (e) => { + e.stopPropagation(); + await this.openLocalFile(this.getLocalFileName(node.name), node.id); + }; + } + + const downloadTextBtn = actions.createEl('button', { text: '下载文字' }); + downloadTextBtn.title = '只下载文字,过滤图片(1次API)'; + downloadTextBtn.onclick = async (e) => { + e.stopPropagation(); + await this.downloadResourceText(node); + }; + + const downloadFullBtn = actions.createEl('button', { text: '下载图文' }); + downloadFullBtn.title = '下载文档+附件(1+1+N次API)'; + downloadFullBtn.onclick = async (e) => { + e.stopPropagation(); + await this.downloadSingleFull(node); + }; + + const deleteBtn = actions.createEl('button', { text: '删除' }); + deleteBtn.onclick = async (e) => { + e.stopPropagation(); + await this.deleteResource(node); + }; + } + } + + private async downloadSingleFull(resource: OmniBoxResource) { + this.updateStatus(`下载图文: ${resource.name}...`); + + // 配额预算:剩余不足 2 次时直接拒绝(正文 + 附件列表是最低消耗) + const quota = await this.plugin.api.getRemainingQuota(); + if (quota && quota.remaining < 2) { + const resetAt = quota.reset_at ? new Date(quota.reset_at) : null; + const resetStr = resetAt ? `,${resetAt.getHours().toString().padStart(2, '0')}:${resetAt.getMinutes().toString().padStart(2, '0')} 后恢复` : ''; + new Notice(`⛔ 剩余 ${quota.remaining} 次不够下载图文(最低 2 次)${resetStr}`); + this.updateStatus(this.currentStatusText || '就绪'); + return; + } + + // 不再预取附件列表(那会多花 1 次配额),直接按 1+N 估算 + const msg = `下载 "${resource.name}" 的图文?\n\n` + + `消耗 API:正文 1 次 + 附件列表 1 次 + 每个附件 1 次。\n\n` + + (quota ? `当前剩余 ${quota.remaining}/${quota.limit} 次。\n\n` : '注意:基础版每天只有 10 次配额。\n\n') + + `是否继续?`; + + if (!confirm(msg)) return; + + const ok = await this.downloadResourceWithAttachments(resource); + this.updateNodeChangedStatus(resource.id, false); + await this.updateApiInfo(); + new Notice(ok ? `✅ 已下载: ${resource.name}` : `❌ 下载失败: ${resource.name}`); + this.renderFullTree(); + } + + private toggleFolder(folderId: string) { + if (this.expandedIds.has(folderId)) { + this.expandedIds.delete(folderId); + } else { + this.expandedIds.add(folderId); + } + this.renderFullTree(); + } + + private renderFullTree() { + this.listContainer.empty(); + this.idIndex.rebuild(this.app); + const updateDownloadStatus = (nodes: TreeNode[]) => { + for (const node of nodes) { + if (node.type === 'file') { + node.isDownloaded = this.idIndex.findByCloudId(this.app, node.id) !== null + || this.getDownloadedFileNames().has(this.getLocalFileName(node.name)); + } + if (node.children.length > 0) updateDownloadStatus(node.children); + } + }; + updateDownloadStatus(this.treeData); + + for (const node of this.treeData) { + this.renderTreeNode(node, this.listContainer, 0); + } + } + + private expandAll() { + const collectIds = (nodes: TreeNode[]) => { + for (const node of nodes) { + if (node.type === 'folder') { + this.expandedIds.add(node.id); + collectIds(node.children); + } + } + }; + collectIds(this.treeData); + this.isExpanded = true; + if (this.toggleExpandBtn) this.toggleExpandBtn.textContent = '折叠'; + this.renderFullTree(); + } + + private collapseAll() { + this.expandedIds.clear(); + this.isExpanded = false; + if (this.toggleExpandBtn) this.toggleExpandBtn.textContent = '展开'; + this.renderFullTree(); + } + + private getAllFiles(nodes: TreeNode[]): TreeNode[] { + let files: TreeNode[] = []; + for (const node of nodes) { + if (node.type === 'file') files.push(node); + files = files.concat(this.getAllFiles(node.children)); + } + return files; + } + + /** + * 下载完成后标记缓存。 + * 注意:缓存里的 updatedAt 必须保持「云端时间戳」原样,供 refresh 时 + * 与云端对比来检测真实变更。旧实现在下载后写入本地当前时间,导致下次 + * 刷新时所有已下载文档都被误判为「有更新」(🆕),诱导用户浪费每日仅有的 + * 10 次配额重复下载。已下载状态由「本地文件存在 + frontmatter last_sync」跟踪。 + */ + private updateCachedResourceTime(_resourceId: string): void { + // 刻意不做任何修改,保留调用点以维持流程语义 + } + + private removeCachedResource(resourceId: string): void { + const cached = this.plugin.getCachedResources(); + this.plugin.cache.cachedResources = cached.filter(r => r.id !== resourceId); + this.plugin.saveCache(); + } + + private removeNodeFromTree(resourceId: string): void { + const removeFromTree = (nodes: TreeNode[]): TreeNode[] => { + return nodes.filter(node => { + if (node.id === resourceId) return false; + if (node.children.length > 0) node.children = removeFromTree(node.children); + return true; + }); + }; + this.treeData = removeFromTree(this.treeData); + this.renderFullTree(); + } + + private updateNodeChangedStatus(resourceId: string, isChanged: boolean): void { + const updateNode = (nodes: TreeNode[]): boolean => { + for (const node of nodes) { + if (node.id === resourceId) { + node.isChanged = isChanged; + return true; + } + if (node.children.length > 0 && updateNode(node.children)) return true; + } + return false; + }; + updateNode(this.treeData); + } + + private async deleteResource(resource: OmniBoxResource) { + const confirmed = confirm( + `确定要删除云端资源 "${resource.name}" 吗?此操作不可撤销!\n\n` + + `⚠️ 删除请求消耗 1 次 API 配额。` + ); + if (confirmed) { + this.updateStatus(`删除中: ${resource.name}...`); + const success = await this.plugin.api.deleteResource(resource.id); + if (success) { + this.removeCachedResource(resource.id); + this.removeNodeFromTree(resource.id); + await this.updateApiInfo(); + new Notice(`✅ 已删除: ${resource.name}`); + } + this.updateStatus(this.currentStatusText || '就绪'); + } + } + + /** + * 保存到 Vault + * @param attachmentMap 附件ID -> 相对笔记的本地路径;提供时按 ID 替换正文引用 + */ + private async saveToVault(filename: string, content: string, cloudId: string, attachmentMap?: Map) { + const folderPath = this.plugin.settings.syncFolder || 'OmniBox'; + const safeName = this.sanitizeFileName(filename); + const filePath = `${folderPath}/${safeName}.md`; + + try { + const folder = this.app.vault.getAbstractFileByPath(folderPath); + if (!folder) await this.app.vault.createFolder(folderPath); + + let finalContent = content; + + // 正文里的图片引用形如 attachments/, + // 官方的 attachment.name 常常全是 "Image",按文件名匹配永远对不上,必须按 ID 替换。 + if (attachmentMap && attachmentMap.size > 0) { + let replaced = 0; + + for (const [attId, relPath] of attachmentMap) { + const idEsc = attId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + // 兼容:相对路径 attachments/、以及被旧版本改写过的完整网页 URL + const pattern = new RegExp( + `(?:https?://[^\\s)"'>]*?)?attachments/${idEsc}(?![A-Za-z0-9_-])`, + 'g' + ); + finalContent = finalContent.replace(pattern, () => { + replaced++; + return relPath; + }); + } + + console.log(`🖼️ ${safeName}: 附件 ${attachmentMap.size} 个,正文替换 ${replaced} 处`); + } + + const fileContent = `---\nomnibox_id: ${cloudId}\nlast_sync: ${new Date().toISOString()}\n---\n\n${finalContent}`; + + const existingFile = this.app.vault.getAbstractFileByPath(filePath); + if (existingFile instanceof TFile) { + await this.app.vault.modify(existingFile, fileContent); + } else { + await this.app.vault.create(filePath, fileContent); + } + } catch (error) { + new Notice(`保存失败: ${error.message}`); + } + } + + private updateStatus(text: string) { + if (this.statusEl) this.statusEl.textContent = text; + } + + async onClose() {} +} \ No newline at end of file diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..1c7c95d --- /dev/null +++ b/styles.css @@ -0,0 +1,134 @@ +/* OmniBox Sidebar Styles */ +.omnibox-sidebar-container { + padding: 8px; + font-size: 14px; +} + +.omnibox-header { + margin-bottom: 12px; + border-bottom: 1px solid var(--background-modifier-border); + padding-bottom: 8px; +} + +.omnibox-header h4 { + margin: 0 0 4px 0; + font-size: 16px; +} + +.omnibox-status { + font-size: 12px; + color: var(--text-muted); + padding: 2px 0; +} + +.omnibox-toolbar { + display: flex; + gap: 8px; + margin-bottom: 12px; + flex-wrap: wrap; +} + +.omnibox-toolbar button { + flex: 1; + min-width: 60px; + padding: 4px 8px; + font-size: 13px; +} + +.omnibox-list { + display: flex; + flex-direction: column; + gap: 2px; + max-height: calc(100vh - 200px); + overflow-y: auto; +} + +.omnibox-item { + display: flex; + align-items: center; + padding: 6px 8px; + border-radius: 4px; + background: var(--background-secondary); + gap: 4px; + flex-wrap: wrap; + transition: background 0.15s; +} + +.omnibox-item:hover { + background: var(--background-modifier-hover); +} + +.omnibox-item-name { + flex: 1; + min-width: 80px; + font-size: 13px; + font-weight: 500; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.omnibox-item-time { + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; +} + +.omnibox-item-actions { + display: flex; + gap: 4px; +} + +.omnibox-item-actions button { + padding: 2px 8px; + font-size: 12px; + background: transparent; + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + cursor: pointer; + transition: background 0.15s; +} + +.omnibox-item-actions button:hover { + background: var(--background-modifier-hover); +} + +.omnibox-btn-download:hover { + border-color: var(--interactive-accent); + color: var(--interactive-accent); +} + +.omnibox-btn-delete:hover { + border-color: var(--text-error); + color: var(--text-error); +} + +.omnibox-folder-hint { + font-size: 12px; + color: var(--text-muted); + margin-left: auto; +} + +.omnibox-placeholder, +.omnibox-empty { + color: var(--text-muted); + font-size: 13px; + text-align: center; + padding: 20px 0; +} + +.omnibox-notice-buttons { + display: flex; + gap: 8px; + margin-top: 8px; + justify-content: center; +} + +.omnibox-notice-buttons button { + padding: 4px 16px; +} + +/* 设置页面样式 */ +.omnibox-settings-buttons button { + padding: 6px 16px; +} \ No newline at end of file diff --git a/utils.ts b/utils.ts new file mode 100644 index 0000000..0f49fcf --- /dev/null +++ b/utils.ts @@ -0,0 +1,105 @@ +import { TFile, Vault, CachedMetadata, App } from 'obsidian'; + +/** + * 安全地创建文件夹(递归) + */ +export async function ensureFolder(vault: Vault, path: string): Promise { + const parts = path.split('/').filter(p => p.length > 0); + let currentPath = ''; + + for (const part of parts) { + currentPath = currentPath ? `${currentPath}/${part}` : part; + const folder = vault.getAbstractFileByPath(currentPath); + if (!folder) { + await vault.createFolder(currentPath); + } + } +} + +/** + * 从单个文件的 frontmatter 中读取 omnibox_id(旧接口,保留兼容)。 + * 新代码请使用 OmniboxIdIndex(基于 metadataCache,零文件 IO)。 + */ +export function getOmniboxIdFromFile(file: TFile, vault: Vault): string | null { + // 注意:cachedRead 是异步的,与同步签名冲突,历史遗留桩; + // 实际无人调用,保留仅为兼容。新代码一律走 OmniboxIdIndex。 + return null; +} + +/** + * 云端 ID -> 本地文件 索引。 + * + * 基于 Obsidian 的 metadataCache 构建 frontmatter omnibox_id 映射, + * metadataCache 由 Obsidian 在后台维护,读取零文件 IO、构建 O(文件数), + * 比逐个 vault.cachedRead 快几个数量级。 + * + * 背景:旧实现靠「文件名」匹配云端与本地,云端一旦改名就匹配失败, + * 触发重复下载,白烧免费版每天仅有的 10 次配额。ID 匹配为主、文件名为回退。 + */ +export class OmniboxIdIndex { + private idToPath = new Map(); + private syncFolder: string; + + constructor(syncFolder: string) { + this.syncFolder = syncFolder || 'OmniBox'; + } + + /** 全量重建索引(打开侧栏或同步文件夹设置变更时调用) */ + rebuild(app: App): void { + this.idToPath.clear(); + const prefix = `${this.syncFolder}/`; + for (const file of app.vault.getMarkdownFiles()) { + if (!file.path.startsWith(prefix)) continue; + const cache: CachedMetadata | null = app.metadataCache.getFileCache(file); + const id = cache?.frontmatter?.['omnibox_id']; + if (typeof id === 'string' && id) { + this.idToPath.set(id, file.path); + } else if (typeof id === 'number') { + this.idToPath.set(String(id), file.path); + } + } + } + + /** 按 ID 查本地文件;找不到返回 null */ + findByCloudId(app: App, cloudId: string): TFile | null { + const path = this.idToPath.get(cloudId); + if (!path) return null; + const f = app.vault.getAbstractFileByPath(path); + return f instanceof TFile ? f : null; + } + + /** ID 优先、文件名回退的统一查找入口 */ + resolveLocalFile(app: App, cloudId: string, cloudName: string, sanitize: (n: string) => string): TFile | null { + const byId = this.findByCloudId(app, cloudId); + if (byId) return byId; + // 回退:老笔记可能没有 omnibox_id(或被手动清掉),按文件名兜底 + const filePath = `${this.syncFolder}/${sanitize(cloudName)}.md`; + const f = app.vault.getAbstractFileByPath(filePath); + return f instanceof TFile ? f : null; + } + + get size(): number { + return this.idToPath.size; + } +} + +/** + * 检查文件是否在同步文件夹内 + */ +export function isInSyncFolder(filePath: string, syncFolder: string): boolean { + return filePath.startsWith(`${syncFolder}/`) || filePath === syncFolder; +} + +/** + * 格式化时间 + */ +export function formatTime(date: Date): string { + return date.toLocaleString('zh-CN', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); +}