This commit is contained in:
2026-02-26 11:07:10 +08:00
parent 85edf0d847
commit eb68553baf
9 changed files with 329 additions and 168 deletions
BIN
View File
Binary file not shown.
-7
View File
@@ -22,13 +22,6 @@ export async function POST(req: Request) {
} }
const initToken = process.env.INIT_SETUP_TOKEN; const initToken = process.env.INIT_SETUP_TOKEN;
const isProduction = process.env.NODE_ENV === "production";
if (isProduction && !initToken) {
return NextResponse.json(
{ error: "Server misconfigured: INIT_SETUP_TOKEN is required in production." },
{ status: 500 }
);
}
if (initToken) { if (initToken) {
const providedToken = req.headers.get("x-init-token"); const providedToken = req.headers.get("x-init-token");
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
export async function GET() {
try {
const settings = await prisma.globalSettings.findUnique({
where: { id: "default" },
select: { id: true },
});
return NextResponse.json({ initialized: Boolean(settings) });
} catch {
return NextResponse.json({ initialized: false, error: "Failed to check settings status" }, { status: 500 });
}
}
+122 -12
View File
@@ -1,19 +1,42 @@
"use client"; "use client";
import { useState } from "react"; import { useEffect, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Lock, Sparkles } from "lucide-react"; import { Lock, Sparkles } from "lucide-react";
export default function LoginPage() { export default function LoginPage() {
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [initPassword, setInitPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState(""); const [error, setError] = useState("");
const [isInitialized, setIsInitialized] = useState<boolean | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [rememberMe, setRememberMe] = useState(false); const [rememberMe, setRememberMe] = useState(false);
const [duration, setDuration] = useState("1"); const [duration, setDuration] = useState("1");
const router = useRouter(); const router = useRouter();
useEffect(() => {
const loadStatus = async () => {
try {
const res = await fetch("/api/settings/status", { cache: "no-store" });
if (!res.ok) {
setIsInitialized(true);
return;
}
const data = await res.json();
setIsInitialized(Boolean(data.initialized));
} catch {
setIsInitialized(true);
}
};
loadStatus();
}, []);
const handleLogin = async (e: React.FormEvent) => { const handleLogin = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (isSubmitting) return;
setError(""); setError("");
setIsSubmitting(true);
try { try {
const res = await fetch("/api/auth/login", { const res = await fetch("/api/auth/login", {
@@ -34,9 +57,72 @@ export default function LoginPage() {
} }
} catch { } catch {
setError("发生错误,请重试"); setError("发生错误,请重试");
} finally {
setIsSubmitting(false);
} }
}; };
const handleInitialize = async (e: React.FormEvent) => {
e.preventDefault();
if (isSubmitting) return;
setError("");
if (initPassword.length < 6) {
setError("密码至少 6 位");
return;
}
if (initPassword !== confirmPassword) {
setError("两次输入的密码不一致");
return;
}
setIsSubmitting(true);
try {
const initRes = await fetch("/api/settings/init", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: initPassword }),
});
const initData = await initRes.json().catch(() => ({}));
if (!initRes.ok) {
setError(initData.error || "初始化失败");
return;
}
const loginRes = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
password: initPassword,
rememberMe: false,
durationDays: 1,
}),
});
const loginData = await loginRes.json().catch(() => ({}));
if (!loginRes.ok) {
setError(loginData.error || "初始化成功,但自动登录失败,请手动登录");
setIsInitialized(true);
setPassword(initPassword);
return;
}
router.push("/");
} catch {
setError("初始化失败,请重试");
} finally {
setIsSubmitting(false);
}
};
if (isInitialized === null) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="ui-card ui-enter w-full max-w-md p-8 text-center text-muted-foreground">...</div>
</div>
);
}
return ( return (
<div className="min-h-screen flex items-center justify-center bg-background p-4"> <div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="ui-card ui-enter w-full max-w-md space-y-8 p-8 shadow-xl"> <div className="ui-card ui-enter w-full max-w-md space-y-8 p-8 shadow-xl">
@@ -44,12 +130,13 @@ export default function LoginPage() {
<div className="ui-float inline-flex items-center justify-center w-16 h-16 bg-primary rounded-2xl text-primary-foreground mb-4 shadow-sm"> <div className="ui-float inline-flex items-center justify-center w-16 h-16 bg-primary rounded-2xl text-primary-foreground mb-4 shadow-sm">
<Sparkles size={32} /> <Sparkles size={32} />
</div> </div>
<h1 className="text-3xl font-bold tracking-tight"></h1> <h1 className="text-3xl font-bold tracking-tight">{isInitialized ? "欢迎回来" : "首次初始化"}</h1>
<p className="text-muted-foreground">访</p> <p className="text-muted-foreground">{isInitialized ? "请输入访问密码以继续。" : "请先设置访问密码,完成后将自动登录。"}</p>
</div> </div>
<form onSubmit={handleLogin} className="space-y-4"> <form onSubmit={isInitialized ? handleLogin : handleInitialize} className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
{isInitialized ? (
<div className="relative"> <div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} /> <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
<input <input
@@ -61,9 +148,36 @@ export default function LoginPage() {
required required
/> />
</div> </div>
) : (
<>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
<input
type="password"
placeholder="设置访问密码(至少6位)"
value={initPassword}
onChange={(e) => setInitPassword(e.target.value)}
className="ui-input pl-10 pr-4 py-3"
required
/>
</div>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
<input
type="password"
placeholder="确认访问密码"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="ui-input pl-10 pr-4 py-3"
required
/>
</div>
</>
)}
{error && <p className="text-sm text-destructive font-medium">{error}</p>} {error && <p className="text-sm text-destructive font-medium">{error}</p>}
</div> </div>
{isInitialized && (
<div className="flex items-center justify-between text-sm px-1"> <div className="flex items-center justify-between text-sm px-1">
<label className="flex items-center gap-2 cursor-pointer text-muted-foreground hover:text-foreground transition-colors select-none"> <label className="flex items-center gap-2 cursor-pointer text-muted-foreground hover:text-foreground transition-colors select-none">
<input <input
@@ -87,18 +201,14 @@ export default function LoginPage() {
</select> </select>
)} )}
</div> </div>
)}
<button <button type="submit" disabled={isSubmitting} className="ui-btn-primary w-full py-3 font-semibold shadow-md">
type="submit" {isSubmitting ? "处理中..." : isInitialized ? "登录" : "完成初始化"}
className="ui-btn-primary w-full py-3 font-semibold shadow-md"
>
</button> </button>
</form> </form>
<div className="text-center text-xs text-muted-foreground"> <div className="text-center text-xs text-muted-foreground">NoteAI - </div>
NoteAI -
</div>
</div> </div>
</div> </div>
); );
+30 -19
View File
@@ -293,53 +293,63 @@ export default function Home() {
editable={!activePage.isLocked} editable={!activePage.isLocked}
/> />
<section className="ui-enter mt-6 space-y-3 md:mt-8 md:space-y-4"> <section className="ui-enter mt-6 space-y-3 md:mt-7">
<div className="ui-card p-3 md:p-4"> <div className="grid gap-2 md:grid-cols-3">
<div className="ui-card p-2.5 md:p-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-foreground"></h3> <h3 className="text-sm font-semibold text-foreground"></h3>
<p className="mt-1 text-xs text-muted-foreground">使 `[[页面名]]` `Ctrl/Cmd + 点击` </p> <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{outgoingLinks.length}</span>
<div className="mt-3 flex flex-wrap gap-2"> </div>
<p className="mt-1 text-[11px] text-muted-foreground"> `[[页面名]]` </p>
<div className="mt-2 flex flex-wrap gap-1.5">
{outgoingLinks.length > 0 ? ( {outgoingLinks.length > 0 ? (
outgoingLinks.map((item) => ( outgoingLinks.map((item) => (
<button <button
key={item.id} key={item.id}
onClick={() => setActivePageId(item.id)} onClick={() => setActivePageId(item.id)}
className="rounded-md border border-border/70 bg-muted/40 px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-accent" className="rounded-md border border-border/70 bg-muted/40 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent"
> >
{item.icon ? `${item.icon} ` : ""} {item.icon ? `${item.icon} ` : ""}
{item.title} {item.title}
</button> </button>
)) ))
) : ( ) : (
<span className="text-xs text-muted-foreground"></span> <span className="text-[11px] text-muted-foreground"></span>
)} )}
</div> </div>
</div> </div>
<div className="ui-card p-3 md:p-4"> <div className="ui-card p-2.5 md:p-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-foreground"></h3> <h3 className="text-sm font-semibold text-foreground"></h3>
<p className="mt-1 text-xs text-muted-foreground"></p> <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{backlinks.length}</span>
<div className="mt-3 flex flex-wrap gap-2"> </div>
<p className="mt-1 text-[11px] text-muted-foreground"></p>
<div className="mt-2 flex flex-wrap gap-1.5">
{backlinks.length > 0 ? ( {backlinks.length > 0 ? (
backlinks.map((item) => ( backlinks.map((item) => (
<button <button
key={item.id} key={item.id}
onClick={() => setActivePageId(item.id)} onClick={() => setActivePageId(item.id)}
className="rounded-md border border-border/70 bg-muted/40 px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-accent" className="rounded-md border border-border/70 bg-muted/40 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent"
> >
{item.icon ? `${item.icon} ` : ""} {item.icon ? `${item.icon} ` : ""}
{item.title} {item.title}
</button> </button>
)) ))
) : ( ) : (
<span className="text-xs text-muted-foreground"></span> <span className="text-[11px] text-muted-foreground"></span>
)} )}
</div> </div>
</div> </div>
<div className="ui-card p-3 md:p-4"> <div className="ui-card p-2.5 md:p-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-foreground"></h3> <h3 className="text-sm font-semibold text-foreground"></h3>
<p className="mt-1 text-xs text-muted-foreground"> `[[页面名]]` </p> <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{unresolvedLinks.length}</span>
<div className="mt-3 flex flex-wrap gap-2"> </div>
<p className="mt-1 text-[11px] text-muted-foreground"></p>
<div className="mt-2 flex flex-wrap gap-1.5">
{unresolvedLinks.length > 0 ? ( {unresolvedLinks.length > 0 ? (
unresolvedLinks.map((title) => ( unresolvedLinks.map((title) => (
<button <button
@@ -347,19 +357,20 @@ export default function Home() {
onClick={async () => { onClick={async () => {
await addPage(null, "file", { title, content: "" }); await addPage(null, "file", { title, content: "" });
}} }}
className="rounded-md border border-dashed border-border bg-muted/30 px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-accent" className="rounded-md border border-dashed border-border bg-muted/30 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent"
title={`创建页面:${title}`} title={`创建页面:${title}`}
> >
+ {title} + {title}
</button> </button>
)) ))
) : ( ) : (
<span className="text-xs text-muted-foreground"></span> <span className="text-[11px] text-muted-foreground"></span>
)} )}
</div> </div>
</div> </div>
</div>
<div className="ui-card p-3 md:p-4"> <div className="ui-card p-2.5 md:p-3">
<button <button
onClick={() => setIsHistoryOpen((v) => !v)} onClick={() => setIsHistoryOpen((v) => !v)}
className="flex w-full items-center justify-between rounded-md px-1 py-1 text-left transition-colors hover:bg-muted/45" className="flex w-full items-center justify-between rounded-md px-1 py-1 text-left transition-colors hover:bg-muted/45"
@@ -373,9 +384,9 @@ export default function Home() {
</div> </div>
<ChevronDown size={15} className={cn("text-muted-foreground transition-transform", isHistoryOpen && "rotate-180")} /> <ChevronDown size={15} className={cn("text-muted-foreground transition-transform", isHistoryOpen && "rotate-180")} />
</button> </button>
<p className="mt-1 text-xs text-muted-foreground"></p> <p className="mt-1 text-[11px] text-muted-foreground"></p>
{isHistoryOpen && ( {isHistoryOpen && (
<div className="mt-3 space-y-3"> <div className="mt-2 space-y-2.5">
{localHistory.length > 0 ? ( {localHistory.length > 0 ? (
<> <>
<div className="rounded-lg border border-border/60 bg-muted/20 p-2"> <div className="rounded-lg border border-border/60 bg-muted/20 p-2">
+6 -11
View File
@@ -27,8 +27,6 @@ import { SlashCommand, getSuggestionItems, renderSuggestionItems } from "./edito
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight"; import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
import { lowlight } from "lowlight"; import { lowlight } from "lowlight";
import { CodeBlockComponent } from "./editor/code-block"; import { CodeBlockComponent } from "./editor/code-block";
import Link from "@tiptap/extension-link";
import Underline from "@tiptap/extension-underline";
import Subscript from "@tiptap/extension-subscript"; import Subscript from "@tiptap/extension-subscript";
import Superscript from "@tiptap/extension-superscript"; import Superscript from "@tiptap/extension-superscript";
import Highlight from "@tiptap/extension-highlight"; import Highlight from "@tiptap/extension-highlight";
@@ -45,7 +43,6 @@ import TableHeader from "@tiptap/extension-table-header";
import Image from "@tiptap/extension-image"; import Image from "@tiptap/extension-image";
import Youtube from "@tiptap/extension-youtube"; import Youtube from "@tiptap/extension-youtube";
import TextAlign from "@tiptap/extension-text-align"; import TextAlign from "@tiptap/extension-text-align";
import Gapcursor from "@tiptap/extension-gapcursor";
import { Markdown } from "tiptap-markdown"; import { Markdown } from "tiptap-markdown";
import { Fragment, type Node as ProseMirrorNode, type Schema } from "@tiptap/pm/model"; import { Fragment, type Node as ProseMirrorNode, type Schema } from "@tiptap/pm/model";
import { TextSelection } from "@tiptap/pm/state"; import { TextSelection } from "@tiptap/pm/state";
@@ -624,11 +621,16 @@ export function Editor({ content, onChange, onEditorReady, onToggleAI, onExport,
const editor = useEditor({ const editor = useEditor({
extensions: [ extensions: [
Gapcursor,
StarterKit.configure({ StarterKit.configure({
heading: { heading: {
levels: [1, 2, 3], levels: [1, 2, 3],
}, },
link: {
openOnClick: false,
HTMLAttributes: {
class: "cursor-pointer text-blue-600 dark:text-blue-400 hover:underline hover:text-blue-800 dark:hover:text-blue-300 transition-colors",
},
},
codeBlock: false, codeBlock: false,
bulletList: { bulletList: {
keepMarks: true, keepMarks: true,
@@ -650,13 +652,6 @@ export function Editor({ content, onChange, onEditorReady, onToggleAI, onExport,
return ReactNodeViewRenderer(CodeBlockComponent); return ReactNodeViewRenderer(CodeBlockComponent);
}, },
}).configure({ lowlight, defaultLanguage: "plaintext" }), }).configure({ lowlight, defaultLanguage: "plaintext" }),
Link.configure({
openOnClick: false,
HTMLAttributes: {
class: "cursor-pointer text-blue-600 dark:text-blue-400 hover:underline hover:text-blue-800 dark:hover:text-blue-300 transition-colors",
},
}),
Underline,
Subscript, Subscript,
Superscript, Superscript,
Highlight.configure({ Highlight.configure({
+113 -76
View File
@@ -1,4 +1,4 @@
"use client"; "use client";
import React, { createContext, useContext, useRef, useState, useCallback } from "react"; import React, { createContext, useContext, useRef, useState, useCallback } from "react";
import { useEditorStore } from "@/lib/store"; import { useEditorStore } from "@/lib/store";
@@ -10,6 +10,17 @@ interface ImportContextType {
isImporting: boolean; isImporting: boolean;
} }
class ImportApiError extends Error {
status: number;
detail: string;
constructor(message: string, status: number, detail: string) {
super(message);
this.status = status;
this.detail = detail;
}
}
const ImportContext = createContext<ImportContextType | undefined>(undefined); const ImportContext = createContext<ImportContextType | undefined>(undefined);
export function ImportProvider({ children }: { children: React.ReactNode }) { export function ImportProvider({ children }: { children: React.ReactNode }) {
@@ -18,10 +29,43 @@ export function ImportProvider({ children }: { children: React.ReactNode }) {
const targetParentIdRef = useRef<string | null>(null); const targetParentIdRef = useRef<string | null>(null);
const { fetchPages } = useEditorStore(); const { fetchPages } = useEditorStore();
const postPage = useCallback(
async (
payload: {
title: string;
content?: string;
parentId?: string | null;
type: "file" | "folder";
},
contextLabel: string
) => {
const res = await fetch("/api/pages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
credentials: "same-origin",
});
if (!res.ok) {
let detail = "";
try {
const data = await res.json();
detail = typeof data?.error === "string" ? data.error : JSON.stringify(data);
} catch {
detail = await res.text();
}
throw new ImportApiError(`${contextLabel}失败(${res.status}${detail ? `: ${detail}` : ""}`, res.status, detail);
}
return res.json();
},
[]
);
const triggerImport = useCallback((parentId: string | null = null) => { const triggerImport = useCallback((parentId: string | null = null) => {
targetParentIdRef.current = parentId; targetParentIdRef.current = parentId;
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ''; // Reset fileInputRef.current.value = "";
fileInputRef.current.click(); fileInputRef.current.click();
} }
}, []); }, []);
@@ -32,14 +76,15 @@ export function ImportProvider({ children }: { children: React.ReactNode }) {
setIsImporting(true); setIsImporting(true);
try { try {
if (file.name.toLowerCase().endsWith('.zip')) { if (file.name.toLowerCase().endsWith(".zip")) {
await handleZipImport(file); await handleZipImport(file);
} else { } else {
await handleSingleFileImport(file); await handleSingleFileImport(file);
} }
} catch (error) { } catch (error) {
console.error("Import failed", error); console.error("Import failed", error);
alert("导入失败,请检查文件"); const message = error instanceof Error ? error.message : "导入失败,请检查文件";
alert(message);
} finally { } finally {
setIsImporting(false); setIsImporting(false);
fetchPages(); fetchPages();
@@ -48,131 +93,123 @@ export function ImportProvider({ children }: { children: React.ReactNode }) {
const handleSingleFileImport = async (file: File) => { const handleSingleFileImport = async (file: File) => {
const text = await file.text(); const text = await file.text();
const title = file.name.replace(/\.md$/i, ''); const title = file.name.replace(/\.md$/i, "");
const html = await marked.parse(text); const html = await marked.parse(text);
await fetch('/api/pages', { await postPage(
method: 'POST', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title, title,
content: html, content: html,
parentId: targetParentIdRef.current, parentId: targetParentIdRef.current,
type: 'file' type: "file",
}), },
}); "创建导入文件"
);
}; };
const handleZipImport = async (file: File) => { const handleZipImport = async (file: File) => {
const zip = await JSZip.loadAsync(file); const zip = await JSZip.loadAsync(file);
// Create root folder based on zip name const rootName = file.name.replace(/(\.md)?\.zip$/i, "");
// Remove .md.zip or .zip let rootFolder: { id: string };
const rootName = file.name.replace(/(\.md)?\.zip$/i, '');
const rootRes = await fetch('/api/pages', { try {
method: 'POST', rootFolder = await postPage(
headers: { 'Content-Type': 'application/json' }, {
body: JSON.stringify({
title: rootName, title: rootName,
parentId: targetParentIdRef.current, parentId: targetParentIdRef.current,
type: 'folder' type: "folder",
}), },
}); "创建导入根目录"
);
} catch (error) {
const invalidParent =
error instanceof ImportApiError && error.status === 400 && /Parent folder not found/i.test(error.detail);
if (!invalidParent || !targetParentIdRef.current) {
throw error;
}
// Parent folder may have been deleted; fallback to root level and continue import.
rootFolder = await postPage(
{
title: rootName,
parentId: null,
type: "folder",
},
"创建导入根目录"
);
}
if (!rootRes.ok) throw new Error("Failed to create root folder");
const rootFolder = await rootRes.json();
const rootId = rootFolder.id; const rootId = rootFolder.id;
// Collect all file entries and infer folder structure const fileEntries: { path: string; file: JSZip.JSZipObject }[] = [];
const fileEntries: { path: string, file: JSZip.JSZipObject }[] = [];
const folderPaths = new Set<string>(); const folderPaths = new Set<string>();
zip.forEach((relativePath, zipEntry) => { zip.forEach((relativePath, zipEntry) => {
if (relativePath.startsWith('__MACOSX') || relativePath.includes('/.') || relativePath.startsWith('.')) return; // Skip hidden/mac files if (relativePath.startsWith("__MACOSX") || relativePath.includes("/.") || relativePath.startsWith(".")) return;
if (zipEntry.dir) { if (zipEntry.dir) {
// Remove trailing slash const cleanPath = relativePath.endsWith("/") ? relativePath.slice(0, -1) : relativePath;
const cleanPath = relativePath.endsWith('/') ? relativePath.slice(0, -1) : relativePath;
if (cleanPath) folderPaths.add(cleanPath); if (cleanPath) folderPaths.add(cleanPath);
} else { } else {
fileEntries.push({ path: relativePath, file: zipEntry }); fileEntries.push({ path: relativePath, file: zipEntry });
// Also infer parent folders for files const parts = relativePath.split("/");
const parts = relativePath.split('/'); let currentPath = "";
let currentPath = ''; for (let i = 0; i < parts.length - 1; i += 1) {
for (let i = 0; i < parts.length - 1; i++) {
currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i]; currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i];
folderPaths.add(currentPath); folderPaths.add(currentPath);
} }
} }
}); });
// Map path (e.g. "folder/sub") to database ID. Empty key '' maps to rootId.
const pathMap = new Map<string, string>(); const pathMap = new Map<string, string>();
pathMap.set('', rootId); pathMap.set("", rootId);
// Sort folders by depth (length of path splits) to create parents before children const sortedFolders = Array.from(folderPaths).sort((a, b) => a.split("/").length - b.split("/").length);
const sortedFolders = Array.from(folderPaths).sort((a, b) => {
return a.split('/').length - b.split('/').length;
});
// Create folders sequentially
for (const folderPath of sortedFolders) { for (const folderPath of sortedFolders) {
const parts = folderPath.split('/'); const parts = folderPath.split("/");
const name = parts[parts.length - 1]; const name = parts[parts.length - 1];
const parentPath = parts.slice(0, -1).join('/'); const parentPath = parts.slice(0, -1).join("/");
const parentId = pathMap.get(parentPath); // Should exist because we sorted by depth const parentId = pathMap.get(parentPath);
if (!parentId) { if (!parentId) {
console.warn(`Parent not found for ${folderPath}, skipping`); console.warn(`Parent not found for ${folderPath}, skipping`);
continue; continue;
} }
// Check if we need to create it (users might have zip with folder/ and folder/file, avoiding dups) const folder = await postPage(
// But we didn't check if it existed on server. We assume new import. {
// Actually, we are just building map here.
const res = await fetch('/api/pages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: name, title: name,
parentId: parentId, parentId,
type: 'folder' type: "folder",
}), },
}); `创建目录 ${folderPath}`
);
if (res.ok) {
const folder = await res.json();
pathMap.set(folderPath, folder.id); pathMap.set(folderPath, folder.id);
} }
}
// Create files parallel-ish or sequential? Sequential is safer for order but parallel faster. for (const { path, file: zipFile } of fileEntries) {
// Let's do batch sequential to avoid overwhelming server if huge const parts = path.split("/");
for (const { path, file } of fileEntries) {
const parts = path.split('/');
const fileName = parts.pop() || ""; const fileName = parts.pop() || "";
const parentPath = parts.join('/'); const parentPath = parts.join("/");
const parentId = pathMap.get(parentPath); const parentId = pathMap.get(parentPath);
if (!parentId) continue; if (!parentId) continue;
if (!fileName.endsWith('.md') && !fileName.endsWith('.txt')) continue; // Verify extension again if (!fileName.endsWith(".md") && !fileName.endsWith(".txt")) continue;
const contentMsg = await file.async('string'); const markdown = await zipFile.async("string");
const title = fileName.replace(/\.md$/i, '').replace(/\.txt$/i, ''); const title = fileName.replace(/\.md$/i, "").replace(/\.txt$/i, "");
const html = await marked.parse(contentMsg); const html = await marked.parse(markdown);
await fetch('/api/pages', { await postPage(
method: 'POST', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title, title,
content: html, content: html,
parentId: parentId, parentId,
type: 'file' type: "file",
}), },
}); `创建文件 ${path}`
);
} }
}; };
+1 -1
View File
@@ -5,7 +5,7 @@ const globalForPrisma = global as unknown as { prisma: PrismaClient };
export const prisma = export const prisma =
globalForPrisma.prisma || globalForPrisma.prisma ||
new PrismaClient({ new PrismaClient({
log: ['query'], log: process.env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
}); });
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma; if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
+1 -1
View File
@@ -3,7 +3,7 @@ import type { NextRequest } from 'next/server';
import { getSessionCookieName, verifySessionToken } from '@/lib/session'; import { getSessionCookieName, verifySessionToken } from '@/lib/session';
const PUBLIC_PATHS = new Set(['/login']); const PUBLIC_PATHS = new Set(['/login']);
const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/settings/init']); const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/settings/init', '/api/settings/status']);
export default async function proxy(request: NextRequest) { export default async function proxy(request: NextRequest) {
const authCookie = request.cookies.get(getSessionCookieName()); const authCookie = request.cookies.get(getSessionCookieName());