同步插件源代码并补齐标准项目文件
This commit is contained in:
29
.gitignore
vendored
Normal file
29
.gitignore
vendored
Normal file
@@ -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
|
||||
7
CHANGELOG.md
Normal file
7
CHANGELOG.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# 变更记录
|
||||
|
||||
## 2026-11-26 · 初始同步
|
||||
|
||||
- 同步插件源代码到新 Gitea 仓库。
|
||||
- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。
|
||||
- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。
|
||||
19
CONTRIBUTING.md
Normal file
19
CONTRIBUTING.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# 贡献指南
|
||||
|
||||
欢迎对本插件提出改进建议或提交代码。
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。
|
||||
- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。
|
||||
- 涉及对外服务或凭据的配置不要写入代码或文档。
|
||||
|
||||
## 提交流程
|
||||
|
||||
1. Fork 仓库并创建功能分支。
|
||||
2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
|
||||
3. 重要功能变更请同步更新 `CHANGELOG.md`。
|
||||
|
||||
## 问题反馈
|
||||
|
||||
请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。
|
||||
5
LICENSE
Normal file
5
LICENSE
Normal file
@@ -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.
|
||||
35
README.md
35
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` 及源码目录放入 `<Vault>/.obsidian/plugins/<插件 id>/`。
|
||||
3. 在 Obsidian「设置 → 第三方插件」中启用该插件。
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
|
||||
|
||||
## 授权
|
||||
|
||||
授权条款见 [LICENSE](LICENSE)(自定义宽松授权,详见 LICENSE)。第三方组件版权归各自作者所有。
|
||||
|
||||
## 变更记录
|
||||
|
||||
详见 [CHANGELOG.md](CHANGELOG.md)。
|
||||
|
||||
185
main.ts
Normal file
185
main.ts
Normal file
@@ -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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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');
|
||||
}
|
||||
}
|
||||
11
manifest.json
Normal file
11
manifest.json
Normal file
@@ -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
|
||||
}
|
||||
206
settings.ts
Normal file
206
settings.ts
Normal file
@@ -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('✅ 缓存已清空');
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
1089
sidebar.ts
Normal file
1089
sidebar.ts
Normal file
File diff suppressed because it is too large
Load Diff
134
styles.css
Normal file
134
styles.css
Normal file
@@ -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;
|
||||
}
|
||||
105
utils.ts
Normal file
105
utils.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { TFile, Vault, CachedMetadata, App } from 'obsidian';
|
||||
|
||||
/**
|
||||
* 安全地创建文件夹(递归)
|
||||
*/
|
||||
export async function ensureFolder(vault: Vault, path: string): Promise<void> {
|
||||
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<string, string>();
|
||||
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'
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user