Files
Mebbling/lib/memos.ts
T

52 lines
4.4 KiB
TypeScript

export type MemosMemo = { name: string; content: string; visibility: string; createTime?: string; updateTime?: string; tags?: string[]; attachments?: { type?: string }[]; resources?: { type?: string }[] };
export type MemosIdentity = { name: string; username?: string; nickname?: string; avatarUrl?: string; avatar?: string };
export type MemosSyncRules = { tags?: string[]; from?: string | null; to?: string | null; attachmentMode?: "all" | "images" | "none" };
const base = (url: string) => url.replace(/\/+$/, "") + "/api/v1";
async function request(url: string, token: string, init?: RequestInit) {
const res = await fetch(url, { ...init, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", ...(init?.headers || {}) }, cache: "no-store" });
if (!res.ok) throw new Error(`Memos API ${res.status}: ${await res.text()}`); return res;
}
export async function verifyMemos(baseUrl: string, token: string) { await request(`${base(baseUrl)}/memos?pageSize=1`, token); }
export async function getMemosIdentity(baseUrl: string, token: string) {
const user = await (await request(`${base(baseUrl)}/auth/status`, token, { method: "POST", body: "{}" })).json() as MemosIdentity;
if (!user.name) throw new Error("Memos did not return an account identity");
return user;
}
export function memoUrl(baseUrl: string, memoName: string) { const id = memoName.split("/").at(-1); return id ? `${baseUrl.replace(/\/$/, "")}/m/${encodeURIComponent(id)}` : null; }
export async function listMemos(baseUrl: string, token: string, rules: MemosSyncRules = {}) {
const all: MemosMemo[] = []; let pageToken = "";
do { const res = await request(`${base(baseUrl)}/memos?pageSize=100${pageToken ? `&pageToken=${encodeURIComponent(pageToken)}` : ""}`, token); const data = await res.json(); all.push(...(data.memos || [])); pageToken = data.nextPageToken || ""; } while (pageToken);
const tags = rules.tags?.filter(Boolean) || []; const mode = rules.attachmentMode || "all";
return all.filter((memo) => {
if (memo.visibility !== "PUBLIC") return false;
if (tags.length && !tags.every((tag) => memo.tags?.includes(tag))) return false;
const created = memo.createTime?.slice(0, 10); if (rules.from && (!created || created < rules.from)) return false; if (rules.to && (!created || created > rules.to)) return false;
return true;
}).map((memo) => {
if (mode === "all") return memo;
const onlyImages = <T extends { type?: string }>(items: T[] | undefined) => mode === "none" ? [] : (items || []).filter((item) => item.type?.startsWith("image/"));
return { ...memo, attachments: onlyImages(memo.attachments), resources: onlyImages(memo.resources) };
});
}
export async function createMemo(baseUrl: string, token: string, memo: Pick<MemosMemo, "content" | "visibility"> & { attachments?: unknown[]; resources?: unknown[] }) {
return (await request(`${base(baseUrl)}/memos`, token, { method: "POST", body: JSON.stringify({ state: "NORMAL", ...memo }) })).json() as Promise<MemosMemo>;
}
export async function createAttachment(baseUrl: string, token: string, attachment: { filename: string; content: string; type: string }) {
return (await request(`${base(baseUrl)}/attachments`, token, { method: "POST", body: JSON.stringify(attachment) })).json() as Promise<{ name: string; filename: string; type: string }>;
}
export async function setMemoAttachments(baseUrl: string, token: string, memoName: string, attachments: unknown[]) {
const memoId = memoName.split("/").at(-1);
if (!memoId) throw new Error("Invalid Memos memo name");
await request(`${base(baseUrl)}/memos/${encodeURIComponent(memoId)}/attachments`, token, { method: "PATCH", body: JSON.stringify({ name: memoName, attachments }) });
}
export async function createResource(baseUrl: string, token: string, resource: { filename: string; content: string; type: string; size: string }) {
return (await request(`${base(baseUrl)}/resources`, token, { method: "POST", body: JSON.stringify(resource) })).json() as Promise<{ name: string; filename: string; type: string; size: string }>;
}
export async function createRemoteFile(baseUrl: string, token: string, file: { filename: string; content: string; type: string; size: string }) {
try { return { kind: "attachment" as const, value: await createAttachment(baseUrl, token, file) }; }
catch (error) {
if (!(error instanceof Error) || !error.message.startsWith("Memos API 404")) throw error;
return { kind: "resource" as const, value: await createResource(baseUrl, token, file) };
}
}