Files
Omnibox/api.ts

723 lines
22 KiB
TypeScript
Raw Normal View History

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<string, string> = {
'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<boolean> {
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<ApiKeyInfo | null> {
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<OmniBoxResource[]> {
return this.fetchResourcesByParent();
}
async fetchResourcesByParent(parentId?: string, limit = 100): Promise<OmniBoxResource[]> {
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<OmniBoxResource[]> {
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<string>();
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<string | null> {
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<string | null> {
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 <img> 标签
content = content.replace(
/<img\s+[^>]*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 的 <img> 取不到,只会 302 到登录页。
* 保持正文原样(attachments/<attachmentId>),由调用方按附件 ID 替换为本地路径。
*/
async downloadResourceFull(id: string): Promise<string | null> {
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<AttachmentInfo[]> {
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<ArrayBuffer | null> {
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<boolean> {
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<string | null> {
try {
const body: Record<string, unknown> = { 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<boolean> {
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;
}
}
}