import { App, Component, ItemView, MarkdownRenderer, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, RequestUrlParam, Setting, WorkspaceLeaf, getIcon, requestUrl, setIcon, } from 'obsidian'; // ============================================================ // 常量 // ============================================================ const VIEW_TYPE_MEMOS = 'memos-sidebar-view'; const DRAFT_KEY = 'memos-plugin-draft'; const DRAFT_REFS_KEY = 'memos-plugin-draft-refs'; const MAX_COMPOSER_HEIGHT = 240; // ============================================================ // 类型 // ============================================================ type MemoVisibility = 'PRIVATE' | 'PUBLIC' | 'PROTECTED'; interface MemosPluginSettings { serverUrl: string; apiToken: string; pageSize: number; defaultVisibility: MemoVisibility; showImages: boolean; autoLoadMore: boolean; showTags: boolean; debug: boolean; } interface MemoResource { id?: number | string; filename?: string; externalLink?: string; type?: string; size?: number; } /** Memos 的 MemoRelation:网页端那条「🔗 #612 正文」的小卡片就是它渲染的 */ interface MemoRelation { memoId?: number | string; relatedMemoId?: number | string; type?: string; } interface Memo { id: number | string; content: string; visibility?: MemoVisibility; pinned?: boolean; // v0.18.x createdTs?: number; updatedTs?: number; displayTs?: number; resourceList?: MemoResource[]; relationList?: MemoRelation[]; // 旧版 / 新版服务端字段 createTime?: string; updateTime?: string; displayTime?: string; } interface MemoListPage { memos: Memo[]; nextPageToken?: string; hasMore: boolean; } interface StatusResponse { profile?: { version?: string; mode?: string }; host?: { username?: string }; } interface MeResponse { nickname?: string; username?: string; avatarUrl?: string; } const DEFAULT_SETTINGS: MemosPluginSettings = { serverUrl: 'https://me.sangushui.com', apiToken: '', pageSize: 20, defaultVisibility: 'PUBLIC', showImages: true, autoLoadMore: true, showTags: true, debug: false, }; // ============================================================ // 工具函数 // ============================================================ function pad2(n: number): string { return n < 10 ? '0' + n : String(n); } /** 取 Memo 的显示时间戳(秒) */ function memoTime(memo: Memo): number { if (typeof memo.displayTs === 'number' && memo.displayTs > 0) return memo.displayTs; if (typeof memo.createdTs === 'number' && memo.createdTs > 0) return memo.createdTs; const iso = memo.createTime || memo.displayTime; if (iso) { const t = Date.parse(iso); if (!isNaN(t)) return Math.floor(t / 1000); } return 0; } /** 是否被编辑过(更新晚于创建 1 分钟以上) */ function isEdited(memo: Memo): boolean { const created = memo.createdTs || 0; const updated = memo.updatedTs || 0; return updated > 0 && created > 0 && updated - created > 60; } function formatAbsolute(seconds: number): string { if (!seconds) return '未知时间'; const d = new Date(seconds * 1000); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; } function formatRelative(seconds: number): string { if (!seconds) return '未知时间'; const now = Date.now() / 1000; const diff = now - seconds; if (diff < 60) return '刚刚'; if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`; if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`; const d = new Date(seconds * 1000); const nowDate = new Date(); const sameYear = d.getFullYear() === nowDate.getFullYear(); const yesterday = new Date(nowDate.getTime() - 86400000); if (d.getFullYear() === yesterday.getFullYear() && d.getMonth() === yesterday.getMonth() && d.getDate() === yesterday.getDate()) { return `昨天 ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; } if (sameYear) { return `${d.getMonth() + 1}月${d.getDate()}日 ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; } return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; } /** 提取正文中的 #标签 */ function extractTags(content: string): string[] { const out: string[] = []; const re = /(^|[\s((])#([^\s#()(),,。;;::!!??]+)/g; let m: RegExpExecArray | null; while ((m = re.exec(content || '')) !== null) { const tag = m[2]; if (tag && out.indexOf(tag) === -1) out.push(tag); } return out; } /** 排序:置顶优先,其次按时间倒序 */ function sortMemos(list: Memo[]): Memo[] { return list.slice().sort((a, b) => { const pa = a.pinned ? 1 : 0; const pb = b.pinned ? 1 : 0; if (pa !== pb) return pb - pa; return memoTime(b) - memoTime(a); }); } function mergeUnique(base: Memo[], incoming: Memo[]): Memo[] { const seen: Record = {}; const out: Memo[] = []; const push = (m: Memo) => { const key = String(m.id); if (seen[key]) return; seen[key] = true; out.push(m); }; base.forEach(push); incoming.forEach(push); return out; } /** 把 Memos 的 HTML 片段 / 相对资源路径整理成 Obsidian 可渲染的 Markdown */ function normalizeContent(content: string, serverUrl: string): string { let out = content || ''; // 相对资源路径补全为绝对地址(v0.18 的 /o/r/、/assets/) const base = serverUrl.replace(/\/+$/, ''); out = out.replace(/\]\((\/(?:o\/r|assets)\/[^)\s]+)\)/g, (_m, p: string) => `](${base}${p})`); // -> Markdown out = out.replace(/]*>/gi, (tag) => { const srcMatch = tag.match(/src=["']([^"']+)["']/i); if (!srcMatch) return ''; const altMatch = tag.match(/alt=["']([^"']*)["']/i); const alt = altMatch ? altMatch[1] : '图片'; return `![${alt}](${srcMatch[1]})`; }); out = out.replace(//gi, '\n'); out = out.replace(/ /g, ' '); out = out.replace(/

\s*/gi, '').replace(/\s*<\/p>/gi, '\n'); return out.trim(); } /** 纯文本摘要,用于预览列表 */ function stripForPreview(content: string): string { return normalizeContent(content || '', '') .replace(/!\[[^\]]*\]\([^)]*\)/g, '') .replace(/[*_`~>#]/g, '') .replace(/\s+/g, ' ') .trim(); } /** Memo 的网页端链接 */ function memoUrl(memo: Memo, serverUrl: string): string { const base = (serverUrl || '').replace(/\/+$/, ''); return `${base}/m/${memo.id}`; } /** 把 Memo 转成可插入笔记的 Markdown */ function memoToMarkdown(memo: Memo, serverUrl: string): string { const content = normalizeContent(memo.content, serverUrl).trim(); const parts: string[] = []; if (content) parts.push(content); const images = (memo.resourceList || []).filter( (r) => !!r.externalLink && !!r.type && r.type.indexOf('image/') === 0 ); if (images.length) { parts.push(images.map((r) => `![${r.filename || '图片'}](${r.externalLink})`).join('\n')); } const time = formatAbsolute(memoTime(memo)); parts.push(`> 🗒️ 来自 Memos · ${time}`); return parts.join('\n\n') + '\n'; } /** 链接文本里的方括号会截断 Markdown 链接,需要转义 */ function escapeLinkText(text: string): string { return text.replace(/\[/g, '\\[').replace(/\]/g, '\\]'); } /** * 被引用 Memo 的「标题」:网页端 chip 里显示的就是被引用 Memo 的正文, * 这里取纯文本(去掉图片、Markdown 标记),过长截断。 */ function memoReferenceTitle(memo: Memo, max = 90): string { const raw = stripForPreview(memo.content || '').replace(/\s+/g, ' ').trim(); if (!raw) return '(无正文)'; return raw.length > max ? raw.slice(0, max).trimEnd() + '…' : raw; } const REFERENCE_TYPE = 'REFERENCE'; /** * 取出「本条 Memo 引用了谁」——网页端下方那排 chip 的数据源。 * 服务端返回的 relationList 是双向的(别人引用本条也会出现), * 这里只保留 memoId === 本条 id 的出向引用。 */ function outgoingReferenceIds(memo: Memo): string[] { const self = String(memo.id); const out: string[] = []; for (const rel of memo.relationList || []) { if (!rel || rel.type !== REFERENCE_TYPE) continue; if (rel.memoId !== undefined && rel.memoId !== null && String(rel.memoId) !== self) continue; if (rel.relatedMemoId === undefined || rel.relatedMemoId === null) continue; const id = String(rel.relatedMemoId); if (!id || id === '0' || id === self) continue; if (out.indexOf(id) === -1) out.push(id); } return out; } /** * 引用写进笔记时的文本形态(笔记里没有 chip,只能退化成一行链接): * `🔗 [#612 正文摘要](原贴地址)` */ function memoToQuote(memo: Memo, serverUrl: string): string { const title = escapeLinkText(`🔗 #${memo.id} ${memoReferenceTitle(memo)}`); return `[${title}](${memoUrl(memo, serverUrl)})\n`; } /** * 画一个和网页端一样的引用卡片(对应网页端的 * `…#612正文`): * 链接图标 + `#ID` + 正文摘要,可点则整块是 A 标签。 */ function buildRefChip( parent: HTMLElement, opts: { id: string; title: string; href?: string; extraClass?: string; onRemove?: () => void } ): { chip: HTMLElement; titleEl: HTMLElement } { const cls = 'memo-ref' + (opts.extraClass ? ' ' + opts.extraClass : ''); const chip = parent.createEl(opts.href ? 'a' : 'span', { cls }); if (opts.href) { chip.setAttribute('href', opts.href); chip.setAttribute('target', '_blank'); chip.setAttribute('rel', 'noopener'); chip.addEventListener('click', (e) => e.stopPropagation()); } chip.setAttribute('title', opts.title ? `#${opts.id} ${opts.title}` : `#${opts.id}`); const icon = chip.createSpan({ cls: 'memo-ref-icon' }); setIcon(icon, 'link'); chip.createSpan({ cls: 'memo-ref-id', text: `#${opts.id}` }); const titleEl = chip.createSpan({ cls: 'memo-ref-title', text: opts.title || '…' }); if (opts.onRemove) { const remove = chip.createEl('button', { cls: 'memo-ref-remove', attr: { type: 'button', 'aria-label': `取消引用 #${opts.id}` }, }); setIcon(remove, 'x'); remove.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); opts.onRemove?.(); }); } return { chip, titleEl }; } // ============================================================ // 待办事项(Memos 的 - [ ] / - [x] 任务列表) // ============================================================ /** 待办行的前缀:缩进 + 列表符号 + `[ ]` */ const TASK_LINE_RE = /^(\s*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\])/; /** 把第 ordinal 个待办行设成指定状态(与渲染出的顺序一一对应),返回新正文 */ function setTaskLine(content: string, ordinal: number, done: boolean): string | null { const lines = String(content || '').split('\n'); let index = -1; for (let i = 0; i < lines.length; i++) { if (!TASK_LINE_RE.test(lines[i])) continue; index++; if (index !== ordinal) continue; lines[i] = lines[i].replace( TASK_LINE_RE, (_m, head: string, _state: string, tail: string) => `${head}${done ? 'x' : ' '}${tail}` ); return lines.join('\n'); } return null; } /** * 给光标所在行(或选中的每一行)加上待办标记: * 普通文本 → `- [ ] 文本`;普通列表项 → `- [ ] 内容`;空行 → 空待办。 */ function applyTaskPrefix(value: string, start: number, end: number): { value: string; caret: number } { const lineStart = value.lastIndexOf('\n', Math.max(0, start - 1)) + 1; let lineEnd = value.indexOf('\n', end); if (lineEnd === -1) lineEnd = value.length; const block = value.slice(lineStart, lineEnd); const out = block.split('\n').map((line) => { if (TASK_LINE_RE.test(line)) return line; if (!line.trim()) return '- [ ] '; const list = line.match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/); if (list) return `${list[1]}- [ ] ${list[3]}`; return `- [ ] ${line}`; }); const replaced = out.join('\n'); return { value: value.slice(0, lineStart) + replaced + value.slice(lineEnd), caret: lineStart + replaced.length, }; } /** * 找到要插入的笔记。 * 旧实现只看 getActiveViewOfType(MarkdownView),而点边栏按钮时「当前活动视图」 * 是 Memos 边栏本身,于是明明开着笔记也报「请先打开一个笔记」。 * 这里依次回退:活动视图 → 最近使用的 leaf → 任意一个 markdown leaf。 */ function findTargetMarkdownView(app: App): MarkdownView | null { const active = app.workspace.getActiveViewOfType(MarkdownView); if (active) return active; const recent = app.workspace.getMostRecentLeaf(); if (recent && recent.view instanceof MarkdownView) return recent.view; for (const leaf of app.workspace.getLeavesOfType('markdown')) { if (leaf.view instanceof MarkdownView) return leaf.view; } return null; } /** 在目标笔记光标处插入 Markdown;没有笔记时返回 ok:false */ function insertIntoNote(app: App, markdown: string): { ok: boolean; note?: string } { const view = findTargetMarkdownView(app); if (!view) return { ok: false }; const editor = view.editor; const cursor = editor.getCursor(); editor.replaceSelection((cursor.ch > 0 ? '\n\n' : '') + markdown); return { ok: true, note: view.file ? view.file.basename : '当前笔记' }; } function debounce void>(fn: T, wait: number): T { let timer: number | null = null; return function (this: unknown, ...args: never[]) { if (timer !== null) window.clearTimeout(timer); timer = window.setTimeout(() => { timer = null; fn.apply(this, args); }, wait); } as T; } // ============================================================ // 图片附件托盘(粘贴 / 拖拽上传) // ============================================================ class AttachmentTray { resources: MemoResource[] = []; private uploading = 0; private container: HTMLElement; private plugin: MemosPlugin; private onChange: () => void; constructor(container: HTMLElement, plugin: MemosPlugin, onChange: () => void) { this.container = container; this.plugin = plugin; this.onChange = onChange; } /** 已上传成功的资源 id,用于创建 Memo 时的 resourceIdList */ get ids(): number[] { const out: number[] = []; for (const r of this.resources) { if (typeof r.id === 'number') out.push(r.id); } return out; } get busy(): boolean { return this.uploading > 0; } get count(): number { return this.resources.length + this.uploading; } async add(files: File[]): Promise { const images: File[] = []; let skipped = 0; for (const f of files) { if (f.type.indexOf('image/') === 0) images.push(f); else skipped++; } if (skipped) new Notice(`已跳过 ${skipped} 个非图片文件`); if (!images.length) { if (!skipped) new Notice('没有可上传的文件'); return; } // 一次批量上传,3 路并发;上传中的占位块数量 = 剩余未完成任务数 this.uploading += images.length; this.render(); const queue = images.slice(); const worker = async () => { while (queue.length) { const file = queue.shift(); if (!file) break; try { const res = await this.plugin.api.uploadResource(file); this.resources.push(res); } catch (e) { new Notice(`❌ ${file.name || '图片'} 上传失败:` + (e as Error).message, 6000); } finally { this.uploading = Math.max(0, this.uploading - 1); this.render(); } } }; const lanes = Math.min(3, images.length); const tasks: Promise[] = []; for (let i = 0; i < lanes; i++) tasks.push(worker()); await Promise.all(tasks); } remove(index: number) { this.resources.splice(index, 1); this.render(); } clear() { this.resources = []; this.uploading = 0; this.render(); } render() { this.container.empty(); this.container.toggleClass('is-empty', this.count === 0); this.resources.forEach((res, index) => { const box = this.container.createDiv('memo-attach'); if (res.externalLink) { box.createEl('img', { attr: { src: res.externalLink, alt: res.filename || '图片' } }); } const del = box.createEl('button', { cls: 'memo-attach-remove' }); setIcon(del, 'x'); del.setAttribute('aria-label', '移除图片'); del.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); this.remove(index); }); }); for (let i = 0; i < this.uploading; i++) { this.container.createDiv('memo-attach is-uploading').setText('上传中'); } this.onChange(); } } function wireAttachmentDnD(input: HTMLTextAreaElement, dropZone: HTMLElement, tray: AttachmentTray) { input.addEventListener('paste', (evt: ClipboardEvent) => { const data = evt.clipboardData; if (!data) return; const files: File[] = []; for (let i = 0; i < data.items.length; i++) { const item = data.items[i]; if (item.kind !== 'file') continue; const file = item.getAsFile(); if (file && file.type.indexOf('image/') === 0) files.push(file); } if (files.length) { evt.preventDefault(); void tray.add(files); } }); dropZone.addEventListener('dragover', (evt: DragEvent) => { evt.preventDefault(); dropZone.addClass('is-dragover'); }); dropZone.addEventListener('dragleave', () => dropZone.removeClass('is-dragover')); dropZone.addEventListener('drop', (evt: DragEvent) => { evt.preventDefault(); dropZone.removeClass('is-dragover'); if (!evt.dataTransfer) return; const files: File[] = []; for (let i = 0; i < evt.dataTransfer.files.length; i++) { files.push(evt.dataTransfer.files[i]); } if (files.length) void tray.add(files); }); } /** 打开系统文件选择框(支持多选图片),选中后回调 */ function pickImageFiles(onPick: (files: File[]) => void) { const input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*'; input.multiple = true; input.addClass('memos-file-input'); let settled = false; const cleanup = () => { if (settled) return; settled = true; input.remove(); }; input.addEventListener('change', () => { const files: File[] = []; const list = input.files; if (list) { for (let i = 0; i < list.length; i++) { const f = list.item(i); if (f) files.push(f); } } cleanup(); if (files.length) onPick(files); }); // 用户取消选择时不会触发 change,靠 cancel 事件兜底清理 input.addEventListener('cancel', cleanup); document.body.appendChild(input); input.click(); } /** 取第一个当前版本存在的图标,避免 lucide 版本差异导致按钮空白 */ function firstAvailableIcon(...names: string[]): string { for (const name of names) { if (getIcon(name)) return name; } return 'plus'; } // ============================================================ // API 客户端(兼容 Memos v0.18.x 与 v0.22+ 的路径差异) // ============================================================ class MemosApi { private plugin: MemosPlugin; /** true 时优先使用 0.18.x 的 /memo 路径 */ private legacyPaths = true; constructor(plugin: MemosPlugin) { this.plugin = plugin; } resetStyle() { this.legacyPaths = true; } private get baseUrl(): string { return (this.plugin.settings.serverUrl || '').trim().replace(/\/+$/, ''); } private get token(): string { return (this.plugin.settings.apiToken || '').trim(); } private buildHeaders(hasBody: boolean): Record { const headers: Record = { Authorization: `Bearer ${this.token}`, Accept: 'application/json', }; if (hasBody) headers['Content-Type'] = 'application/json'; return headers; } private extractMessage(json: unknown, text?: string): string { if (json && typeof json === 'object') { const obj = json as Record; const msg = obj.message || obj.error || obj.detail; if (typeof msg === 'string' && msg) return msg; } if (text) { try { const parsed = JSON.parse(text) as Record; const msg = parsed.message || parsed.error; if (typeof msg === 'string' && msg) return msg; } catch { const trimmed = text.trim(); if (trimmed && trimmed.length < 200 && trimmed.indexOf('<') !== 0) return trimmed; } } return ''; } private messageForStatus(status: number, serverMessage: string): string { switch (status) { case 400: return serverMessage || '请求参数有误(400)'; case 401: return 'API Token 无效或已过期,请在设置中重新生成'; case 403: return '没有权限执行该操作(403)'; case 404: return '接口不存在(404),请检查服务器地址或 Memos 版本'; case 405: return '接口方法不被支持(405),Memos 版本可能不匹配'; case 413: return '内容过大,服务端拒绝接收(413)'; case 429: return '请求过于频繁(429),请稍后再试'; default: if (status >= 500) return serverMessage || `服务器内部错误(${status})`; return serverMessage || `请求失败(${status})`; } } private makeError(message: string, status?: number): Error { const err = new Error(message); if (typeof status === 'number') (err as Error & { status?: number }).status = status; return err; } private normalizeThrown(e: unknown): Error { const err = e as { status?: number; json?: unknown; text?: string; message?: string }; if (err && typeof err.status === 'number') { return this.makeError( this.messageForStatus(err.status, this.extractMessage(err.json, err.text)), err.status ); } const msg = (err && err.message) || String(e) || ''; if (/net::|failed to fetch|econnrefused|enotfound|network|timeout|timed out|err_name/i.test(msg)) { return this.makeError('无法连接到 Memos 服务器,请检查服务器地址与网络'); } if (/certificate|ssl|tls/i.test(msg)) { return this.makeError('HTTPS 证书校验失败,请检查证书或改用 http'); } return this.makeError(msg || '未知错误'); } private async request(path: string, method: string, body?: unknown): Promise { if (!this.token) throw this.makeError('请先在插件设置中填写 API Token', 401); if (!this.baseUrl) throw this.makeError('请先在插件设置中填写服务器地址'); const url = `${this.baseUrl}/api/v1${path.startsWith('/') ? path : '/' + path}`; const params: RequestUrlParam = { url, method, headers: this.buildHeaders(body !== undefined), throw: false, }; if (body !== undefined) params.body = JSON.stringify(body); this.plugin.log(`[${method}] ${url}`); if (body !== undefined) this.plugin.log('body:', JSON.stringify(body)); let res; try { res = await requestUrl(params); } catch (e) { throw this.normalizeThrown(e); } if (res.status >= 400) { throw this.makeError( this.messageForStatus(res.status, this.extractMessage(undefined, res.text)), res.status ); } const text = res.text; if (!text || !text.trim()) return {} as T; try { return JSON.parse(text) as T; } catch { throw this.makeError('服务端返回了无法解析的数据,请检查服务器地址是否正确'); } } /** 依次尝试新旧两套路径,命中后记住风格 */ private async requestWithFallback( legacyPath: string, modernPath: string, method: string, body?: unknown ): Promise { const order = this.legacyPaths ? [legacyPath, modernPath] : [modernPath, legacyPath]; let firstError: Error | null = null; for (let i = 0; i < order.length; i++) { try { const result = await this.request(order[i], method, body); if (i === 1) this.legacyPaths = !this.legacyPaths; return result; } catch (e) { const err = e instanceof Error ? e : this.makeError(String(e)); const status = (err as Error & { status?: number }).status; if (i === 0) firstError = err; if (status === 404 || status === 405) continue; throw err; } } throw firstError || this.makeError('接口不可用'); } async status(): Promise { return this.request('/status', 'GET'); } async me(): Promise { return this.request('/user/me', 'GET'); } async listTags(): Promise { try { const res = await this.request('/tag', 'GET'); const list: unknown[] = Array.isArray(res) ? res : Array.isArray((res as { data?: unknown[] }).data) ? (res as { data: unknown[] }).data : []; return list.filter((t): t is string => typeof t === 'string'); } catch (e) { this.plugin.log('获取标签失败:', e); return []; } } async listMemos(opts: { limit: number; offset: number; pageToken?: string }): Promise { const query: string[] = [ `limit=${opts.limit}`, `offset=${opts.offset}`, `pageSize=${opts.limit}`, ]; if (opts.pageToken) query.push(`pageToken=${encodeURIComponent(opts.pageToken)}`); const qs = query.join('&'); const raw = await this.requestWithFallback(`/memo?${qs}`, `/memos?${qs}`, 'GET'); let memos: Memo[] = []; let nextPageToken: string | undefined; if (Array.isArray(raw)) { memos = raw as Memo[]; } else if (raw && typeof raw === 'object') { const obj = raw as { memos?: Memo[]; data?: Memo[]; nextPageToken?: string; nextPage?: string }; memos = obj.memos || obj.data || []; nextPageToken = obj.nextPageToken || obj.nextPage; } const hasMore = !!nextPageToken || memos.length >= opts.limit; return { memos, nextPageToken, hasMore }; } /** * 统计服务端全部 Memo 条数。 * v0.18 的列表接口只返回数组、没有总数,所以用「越界 offset 返回空」的特性: * 先按 4 倍步长探测上界,再二分逼近,每步只取 1 条(payload 极小)。 * 失败返回 -1,由调用方保留旧值。 */ async countMemos(): Promise { try { const first = await this.listMemos({ limit: 1, offset: 0 }); if (!first.memos.length) return 0; const anchor = String(first.memos[0].id); const isEmptyAt = async (offset: number): Promise => { const page = await this.listMemos({ limit: 1, offset }); // v0.22+ 的 /memos 用 pageToken,不认 offset:探到同一条就放弃 if (offset > 0 && page.memos.length && String(page.memos[0].id) === anchor) { throw this.makeError('该服务端不支持按 offset 计数'); } return page.memos.length === 0; }; // 找上界:largest offset 有数据 = lo,smallest offset 为空 = hi let lo = 0; let step = 1; let hi = 0; let guard = 0; while (guard++ < 24) { if (await isEmptyAt(step)) { hi = step; break; } lo = step; step *= 4; if (step > 5000000) return -1; } if (!hi) return -1; // 二分:offset 有数据 ⇔ offset < 总数 while (hi - lo > 1) { const mid = Math.floor((lo + hi) / 2); if (await isEmptyAt(mid)) hi = mid; else lo = mid; } return hi; } catch (e) { this.plugin.log('统计总条数失败', e); return -1; } } async createMemo( content: string, visibility: MemoVisibility, resourceIds?: number[], relationIds?: string[] ): Promise { const body: Record = { content: content.trim(), visibility, }; if (resourceIds && resourceIds.length) body.resourceIdList = resourceIds; // 引用走服务端的 MemoRelation(和网页端完全一致),不往正文里塞链接 if (relationIds && relationIds.length) { body.relationList = relationIds .map((id) => Number(id)) .filter((id) => Number.isFinite(id) && id > 0) .map((id) => ({ relatedMemoId: id, type: REFERENCE_TYPE })); } return this.requestWithFallback('/memo', '/memos', 'POST', body); } /** * 上传图片资源。 * Memos 服务端会把它落到「设置 → 存储」里配置的对象存储(S3 / 本地), * 返回的 externalLink 就是该存储的公网地址,与网页端上传完全一致。 */ async uploadResource(file: File): Promise { if (!this.token) throw this.makeError('请先在插件设置中填写 API Token', 401); if (!this.baseUrl) throw this.makeError('请先在插件设置中填写服务器地址'); const boundary = '----ObsidianMemos' + Date.now().toString(16); const filename = (file.name || `pasted-${Date.now()}.png`).replace(/["\r\n]/g, '_'); const mime = file.type || 'application/octet-stream'; const data = new Uint8Array(await file.arrayBuffer()); const encoder = new TextEncoder(); const head = encoder.encode( `--${boundary}\r\n` + `Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` + `Content-Type: ${mime}\r\n\r\n` ); const tail = encoder.encode(`\r\n--${boundary}--\r\n`); const body = new Uint8Array(head.length + data.length + tail.length); body.set(head, 0); body.set(data, head.length); body.set(tail, head.length + data.length); const url = `${this.baseUrl}/api/v1/resource/blob`; this.plugin.log(`[POST] ${url} (${filename}, ${data.length} bytes)`); let res; try { res = await requestUrl({ url, method: 'POST', headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': `multipart/form-data; boundary=${boundary}`, }, body: body.buffer as ArrayBuffer, throw: false, }); } catch (e) { throw this.normalizeThrown(e); } if (res.status >= 400) { throw this.makeError( this.messageForStatus(res.status, this.extractMessage(undefined, res.text)), res.status ); } try { return JSON.parse(res.text) as MemoResource; } catch { throw this.makeError('上传返回的数据无法解析,请检查 Memos 版本'); } } async updateMemo( id: number | string, patch: { content?: string; visibility?: MemoVisibility; pinned?: boolean } ): Promise { return this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'PATCH', patch); } async deleteMemo(id: number | string): Promise { await this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'DELETE'); } /** 按 ID 取单条 Memo(用于「引用已有 Memo」) */ async getMemo(id: number | string): Promise { return this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'GET'); } async setPinned(id: number | string, pinned: boolean): Promise { // v0.18.x:organizer 接口;v0.22+:直接 PATCH memo try { await this.request(`/memo/${id}/organizer`, 'POST', { pinned }); } catch (e) { const status = (e as Error & { status?: number }).status; if (status === 404 || status === 405) { await this.request(`/memos/${id}`, 'PATCH', { pinned }); return; } throw e; } } } // ============================================================ // 插件主体 // ============================================================ export default class MemosPlugin extends Plugin { settings: MemosPluginSettings; api: MemosApi; async onload() { await this.loadSettings(); this.api = new MemosApi(this); this.registerView(VIEW_TYPE_MEMOS, (leaf) => new MemosSidebarView(leaf, this)); this.addRibbonIcon('message-square', 'Memos 管理器', () => { void this.activateView(); }); // 保留原有 command id,避免用户已设置的热键失效 this.addCommand({ id: 'open-memos-sidebar', name: '打开 Memos 边栏', callback: () => void this.activateView(), }); this.addCommand({ id: 'publish-selection-to-memos', name: '发布选中文本到 Memos', editorCallback: (editor) => { const selection = editor.getSelection(); if (!selection.trim()) { new Notice('请先选中要发布的文本'); return; } void this.publishFromCommand(selection); }, }); this.addCommand({ id: 'memos-quick-capture', name: '快速记录一条 Memo', callback: () => { new ComposeMemoModal(this.app, this, '', () => { this.refreshViews(); }).open(); }, }); this.addCommand({ id: 'memos-quote-memo', name: '引用一条 Memo(输入 ID)', callback: () => { new QuoteMemoModal( this.app, this, { toComposer: (memos) => { const view = this.getSidebarView(); return view ? view.insertQuoteIntoComposer(memos) : false; }, toNote: (md) => insertIntoNote(this.app, md), }, 'note' ).open(); }, }); this.addSettingTab(new MemosSettingTab(this.app, this)); } onunload() { this.log('已卸载'); } log(...args: unknown[]) { if (this.settings && this.settings.debug) { console.log('[Memos]', ...args); } } async activateView() { const { workspace } = this.app; let leaf = workspace.getLeavesOfType(VIEW_TYPE_MEMOS)[0]; if (!leaf) { const right = workspace.getRightLeaf(false); if (!right) { new Notice('无法创建边栏'); return; } await right.setViewState({ type: VIEW_TYPE_MEMOS, active: true }); leaf = right; } await workspace.revealLeaf(leaf); } refreshViews() { const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMOS); for (const leaf of leaves) { const view = leaf.view; if (view instanceof MemosSidebarView) void view.refresh(true); } } /** 取已打开的 Memos 边栏视图(用于把引用插回输入框) */ getSidebarView(): MemosSidebarView | null { const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMOS); for (const leaf of leaves) { if (leaf.view instanceof MemosSidebarView) return leaf.view; } return null; } private async publishFromCommand(text: string) { try { await this.api.createMemo( normalizeContent(text, this.settings.serverUrl), this.settings.defaultVisibility ); new Notice('✅ 已发布到 Memos'); this.refreshViews(); } catch (e) { new Notice('❌ 发布失败:' + (e as Error).message, 6000); } } async loadSettings() { const data = (await this.loadData()) || {}; this.settings = Object.assign({}, DEFAULT_SETTINGS, data); // 旧版本字段迁移:limit -> pageSize const legacyLimit = (data as { limit?: number }).limit; if (!(data as { pageSize?: number }).pageSize && typeof legacyLimit === 'number' && legacyLimit > 0) { this.settings.pageSize = legacyLimit; } if (this.settings.pageSize < 1) this.settings.pageSize = DEFAULT_SETTINGS.pageSize; if (this.settings.pageSize > 200) this.settings.pageSize = 200; } async saveSettings() { await this.saveData(this.settings); this.api.resetStyle(); } } // ============================================================ // 自绘下拉 // ============================================================ // // 不用原生