This commit is contained in:
Vaica committed 2026-06-02 00:23:04 +08:00
1 parent 528104fff0
commit beb498d38b
60 files changed
+3184 -2129

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { hugo } from "@/lib/hugo";
export async function POST() {
try {
hugo.stop();
const result = await hugo.start();
return NextResponse.json({ ok: result.ok });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Failed" },
{ status: 500 }
);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { hugo } from "@/lib/hugo";
import { TG_BOT_TOKEN } from "@/lib/config";
export async function GET() {
const hugoStatus = hugo.status();
return NextResponse.json({
bot: {
enabled: !!TG_BOT_TOKEN,
polling: !!TG_BOT_TOKEN,
},
hugo: hugoStatus,
});
}
+13 -64
View File
@@ -1,39 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { execFile } from "child_process";
import { promisify } from "util";
import { BLOG_ROOT } from "@/lib/config";
const execFileAsync = promisify(execFile);
type GitExecError = Error & {
stdout?: string;
stderr?: string;
code?: number;
};
async function runGit(args: string[], allowFailure = false) {
try {
const { stdout, stderr } = await execFileAsync("git", args, {
cwd: BLOG_ROOT,
windowsHide: true,
maxBuffer: 1024 * 1024,
});
return { stdout, stderr, code: 0 };
} catch (error) {
const err = error as GitExecError;
const result = {
stdout: err.stdout || "",
stderr: err.stderr || err.message,
code: typeof err.code === "number" ? err.code : 1,
};
if (allowFailure) return result;
throw new Error((result.stderr || result.stdout || err.message).trim());
}
}
function isRebaseConflict(message: string) {
return /conflict|CONFLICT|Resolve all conflicts|Automatic merge failed|could not apply|rebase/i.test(message);
}
import { deployQueue } from "@/lib/git";
export async function POST(request: NextRequest) {
try {
@@ -44,40 +10,23 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: "Title is required" }, { status: 400 });
}
let output = "";
const result = await deployQueue.enqueue(`发布: ${title}`);
const addResult = await runGit(["add", "content/post", "static"]);
output += addResult.stdout + addResult.stderr;
const diffResult = await runGit(["diff", "--cached", "--quiet"], true);
if (diffResult.code === 1) {
const commitResult = await runGit(["commit", "-m", `发布: ${title}`]);
output += commitResult.stdout + commitResult.stderr;
} else if (diffResult.code !== 0) {
throw new Error((diffResult.stderr || diffResult.stdout || "检查暂存区失败").trim());
if (result.success) {
return NextResponse.json({ success: true, output: result.output });
}
try {
const pullResult = await runGit(["pull", "--rebase", "--autostash", "origin", "main"]);
output += pullResult.stdout + pullResult.stderr;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (isRebaseConflict(message)) {
return NextResponse.json(
{
error: "远程仓库有新内容,自动合并失败。请在终端解决冲突后执行 git rebase --continue,再重新发布。",
detail: message.slice(0, 1000),
},
{ status: 409 }
);
}
throw error;
if (result.conflict) {
return NextResponse.json(
{
error: result.error,
detail: result.output,
},
{ status: 409 }
);
}
const pushResult = await runGit(["push"]);
output += pushResult.stdout + pushResult.stderr;
return NextResponse.json({ success: true, output: output.slice(0, 1000) });
return NextResponse.json({ error: result.error }, { status: 500 });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Deploy failed" },
+17 -40
View File
@@ -1,50 +1,27 @@
import { NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";
import { BLOG_ROOT, HUGO_PREVIEW } from "@/lib/config";
const execAsync = promisify(exec);
async function isHugoRunning(): Promise<boolean> {
try {
const res = await fetch(HUGO_PREVIEW, { signal: AbortSignal.timeout(1500) });
return res.ok || res.status < 500;
} catch {
return false;
}
}
let starting = false;
import { hugo } from "@/lib/hugo";
import { HUGO_PREVIEW } from "@/lib/config";
export async function GET() {
try {
const running = await isHugoRunning();
if (running) {
const result = await hugo.start();
if (result.alreadyRunning || result.ok) {
return NextResponse.json({ running: true, url: HUGO_PREVIEW });
}
if (starting) {
return NextResponse.json({ running: false, starting: true, url: HUGO_PREVIEW });
}
starting = true;
// Kill existing process on port 1313, then start hugo serve
const killCmd = `for /f "tokens=5" %a in ('netstat -ano ^| findstr :1313 ^| findstr LISTENING') do taskkill /F /PID %a 2>nul`;
const startCmd = `cd "${BLOG_ROOT}" && hugo serve --port 1313 --noHTTPCache`;
try { await execAsync(killCmd); } catch { /* nothing to kill */ }
exec(startCmd, (err) => {
if (err) console.error("Hugo start error:", err.message);
});
// Wait a moment for Hugo to start
await new Promise((r) => setTimeout(r, 2000));
starting = false;
const started = await isHugoRunning();
return NextResponse.json({ running: started, url: HUGO_PREVIEW });
return NextResponse.json({ running: false, url: HUGO_PREVIEW });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Failed" },
{ status: 500 }
);
}
}
export async function DELETE() {
try {
hugo.stop();
return NextResponse.json({ running: false });
} catch (error: unknown) {
starting = false;
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Failed" },
{ status: 500 }
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { useState, useEffect } from "react";
import { Bot, RefreshCw, Server } from "lucide-react";
interface BotStatus {
bot: { enabled: boolean; polling: boolean };
hugo: { running: boolean; starting: boolean };
}
export default function BotPage() {
const [status, setStatus] = useState<BotStatus | null>(null);
const [restarting, setRestarting] = useState(false);
async function fetchStatus() {
try {
const res = await fetch("/api/bot/status");
const data = await res.json();
setStatus(data);
} catch {
setStatus(null);
}
}
async function restartHugo() {
setRestarting(true);
try {
await fetch("/api/bot/restart", { method: "POST" });
} catch { /* ignore */ }
setTimeout(async () => {
await fetchStatus();
setRestarting(false);
}, 3000);
}
useEffect(() => {
fetchStatus();
const timer = setInterval(fetchStatus, 10000);
return () => clearInterval(timer);
}, []);
return (
<div className="p-6 max-w-2xl mx-auto space-y-6">
<h1 className="text-2xl font-bold">Bot 管理</h1>
{/* Bot Status */}
<div className="rounded-lg border border-[var(--border)] p-5 space-y-4">
<h2 className="font-semibold text-lg flex items-center gap-2">
<Bot size={20} /> Telegram Bot
</h2>
<div className="flex items-center gap-3">
<div
className={`w-3 h-3 rounded-full ${
status?.bot.enabled
? "bg-green-500"
: "bg-gray-400"
}`}
/>
<span className="text-sm">
{status?.bot.enabled
? "已配置,随服务自动启动"
: "未配置 TG_BOT_TOKEN"}
</span>
</div>
</div>
{/* Hugo Status */}
<div className="rounded-lg border border-[var(--border)] p-5 space-y-4">
<h2 className="font-semibold text-lg flex items-center gap-2">
<Server size={20} /> Hugo Server
</h2>
<div className="flex items-center gap-3">
<div
className={`w-3 h-3 rounded-full ${
status?.hugo.running
? "bg-green-500"
: status?.hugo.starting
? "bg-yellow-500"
: "bg-gray-400"
}`}
/>
<span className="text-sm">
{status?.hugo.running
? "运行中 — localhost:1313"
: status?.hugo.starting
? "启动中..."
: "已停止"}
</span>
</div>
<button
onClick={restartHugo}
disabled={restarting}
className="px-4 py-2 rounded-md bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
>
<RefreshCw size={14} className={restarting ? "animate-spin" : ""} />
{restarting ? "重启中..." : "重启 Hugo"}
</button>
</div>
</div>
);
}