feat: export posts and sources

This commit is contained in:
2026-07-19 05:36:52 +08:00
parent 05ddafb0d9
commit 591981b7c8
8 changed files with 50 additions and 7 deletions
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
function markdown(post: any) {
const tags = (() => { try { return JSON.parse(post.tags_json || "[]"); } catch { return []; } })();
const attachments = (() => { try { return JSON.parse(post.attachments_json || "[]"); } catch { return []; } })();
const quote = (value: unknown) => JSON.stringify(value ?? "");
const attachmentList = attachments.length ? `\n\n## Attachments\n${attachments.map((item: any) => `- [${item.filename || item.name || "attachment"}](${item.url || item.externalLink || ""})`).join("\n")}` : "";
return `---\nid: ${post.id}\norigin: ${quote(post.origin)}\nvisibility: ${quote(post.visibility)}\npublished_at: ${quote(post.remote_created_at || post.created_at)}\ntags: ${JSON.stringify(tags)}\nremote_url: ${quote(post.remote_url)}\n---\n\n${post.content}${attachmentList}\n`;
}
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
const user = await requireUser(); const { id: rawId } = await params; const post = db.prepare("SELECT p.*,s.name AS source_name FROM posts p LEFT JOIN sources s ON s.id=p.source_id WHERE p.id=?").get(Number(rawId)) as any;
if (!post) return NextResponse.json({ error: "Not found" }, { status: 404 });
const permitted = post.author_id === user.id || (post.source_id && db.prepare("SELECT 1 FROM source_members WHERE source_id=? AND user_id=?").get(post.source_id, user.id));
if (!permitted) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const format = new URL(request.url).searchParams.get("format") === "markdown" ? "markdown" : "json";
const body = format === "markdown" ? markdown(post) : JSON.stringify({ version: 1, exportedAt: new Date().toISOString(), post: { ...post, tags: JSON.parse(post.tags_json || "[]"), attachments: JSON.parse(post.attachments_json || "[]") } }, null, 2);
return new NextResponse(body, { headers: { "Content-Type": format === "markdown" ? "text/markdown; charset=utf-8" : "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="mebbling-post-${post.id}.${format === "markdown" ? "md" : "json"}"` } });
}