Files
Omnibox/sidebar.ts

1089 lines
40 KiB
TypeScript
Raw Permalink Normal View History

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<string> = 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<void> {
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<string, TreeNode>();
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<string> {
const folderPath = this.plugin.settings.syncFolder || 'OmniBox';
const files = this.app.vault.getFiles();
const downloaded = new Set<string>();
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<void> {
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<OmniBoxResource[]> {
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<boolean> {
// 1. 下载文档内容(保留 attachments/<attachmentId> 原始引用)
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<string, string>();
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/<id> 替换为本地路径
await this.saveToVault(resource.name, content, resource.id, attachmentMap);
this.updateCachedResourceTime(resource.id);
return true;
}
/** 递归创建目录(已存在则忽略) */
private async ensureFolder(folderPath: string): Promise<void> {
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<string, string>) {
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/<attachmentId>,
// 官方的 attachment.name 常常全是 "Image",按文件名匹配永远对不上,必须按 ID 替换。
if (attachmentMap && attachmentMap.size > 0) {
let replaced = 0;
for (const [attId, relPath] of attachmentMap) {
const idEsc = attId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// 兼容:相对路径 attachments/<id>、以及被旧版本改写过的完整网页 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() {}
}