Files
SakuraHub/sakura_cloud/main.py
T

410 lines
15 KiB
Python
Raw Normal View History

2026-11-16 20:45:22 +08:00
from __future__ import annotations
import asyncio
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from sakura_cloud.api.middleware import security_headers_middleware, trace_logging_middleware
from sakura_cloud.api.v1.router import api_router
from sakura_cloud.core.config import settings
from sakura_cloud.core.logging import configure_logging, logger
from sakura_cloud.db.session import SessionLocal
from sakura_cloud.services.migrations import upgrade_database_to_head
from sakura_cloud.services.reminders import run_daily_reminder_digest
from sakura_cloud.services.storage import cleanup_stale_uploads
def _admin_frontend_dist() -> Path:
base_dir = Path(__file__).resolve().parent
candidates = [
base_dir.parent / "sakura_admin_web" / "dist",
base_dir / "sakura_admin_web" / "dist",
]
for candidate in candidates:
if (candidate / "index.html").is_file():
return candidate
return candidates[0]
def _cloud_public_dir() -> Path:
return Path(__file__).resolve().parent / "public"
def _online_search_page() -> HTMLResponse:
return HTMLResponse(
"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sakura Cloud 在线搜索</title>
<style>
* { box-sizing: border-box; }
:root {
font-family: "Microsoft YaHei", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #243142;
background: #fff7fb;
color-scheme: light;
}
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(circle at 16% -8%, rgba(255, 208, 225, .6), transparent 28%),
linear-gradient(180deg, #fff7fb, #f7fbff);
}
main { width: min(1100px, calc(100% - 32px)); margin: 0 auto; padding: 28px 0 44px; }
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 16px;
align-items: end;
margin-bottom: 18px;
}
h1 { margin: 0 0 8px; font-size: clamp(26px, 5vw, 38px); font-weight: 750; letter-spacing: 0; }
p { margin: 0; color: #728094; line-height: 1.7; }
.badge {
display: inline-flex;
align-items: center;
min-height: 36px;
padding: 0 14px;
border-radius: 999px;
background: #ffe8f0;
color: #bd4f7c;
font-weight: 700;
white-space: nowrap;
}
.panel {
margin-top: 18px;
padding: 18px;
border: 1px solid #ead7df;
border-radius: 14px;
background: rgba(255, 255, 255, .92);
box-shadow: 0 18px 48px rgba(171, 92, 126, .10);
}
.toolbar { display: grid; grid-template-columns: 150px 190px minmax(220px, 1fr); gap: 10px; align-items: center; }
.searchbar { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; margin-top: 12px; }
.source-tools { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; margin-top: 12px; }
input, select, textarea, button {
min-height: 44px;
border: 1px solid #ead7df;
border-radius: 10px;
font: inherit;
max-width: 100%;
}
input, select, textarea { width: 100%; padding: 0 13px; background: #fff; color: #243142; }
textarea {
width: 100%;
min-height: 132px;
margin-top: 10px;
padding: 12px 13px;
resize: vertical;
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
font-size: 13px;
line-height: 1.5;
}
button {
padding: 0 18px;
cursor: pointer;
background: #fff;
color: #243142;
font-weight: 700;
white-space: nowrap;
}
button.primary { border: 0; background: #d65f8f; color: #fff; box-shadow: 0 10px 24px rgba(214, 95, 143, .25); }
button.ghost { color: #bd4f7c; }
.muted { color: #728094; }
.error { color: #b7465c; }
.status-line { min-height: 28px; margin-top: 12px; }
.results { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; margin-top: 14px; }
.card {
display: grid;
grid-template-columns: 70px minmax(0,1fr);
gap: 12px;
padding: 12px;
border: 1px solid #ead7df;
border-radius: 12px;
background: #fffafd;
min-width: 0;
}
.cover {
width: 70px;
aspect-ratio: 3/4;
display: grid;
place-items: center;
overflow: hidden;
border-radius: 10px;
background: #ffe8f0;
color: #cf5f8b;
font-weight: 800;
}
.cover img { width: 100%; height: 100%; object-fit: cover; }
.card strong, .card span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card strong { font-size: 16px; line-height: 1.45; }
.card a {
display: block;
margin-top: 8px;
color: #a63f6a;
text-decoration: none;
overflow-wrap: anywhere;
line-height: 1.45;
}
@media (max-width: 760px) {
main { width: min(100% - 24px, 560px); padding: 20px 0 32px; }
.hero { grid-template-columns: 1fr; align-items: start; }
.badge { width: fit-content; }
.panel { padding: 14px; border-radius: 18px; }
.toolbar, .searchbar, .source-tools { grid-template-columns: 1fr; }
button { width: 100%; min-height: 48px; }
textarea { min-height: 108px; }
.results { grid-template-columns: 1fr; }
.card { grid-template-columns: 62px minmax(0, 1fr); padding: 10px; }
.cover { width: 62px; }
}
</style>
</head>
<body>
<main>
<header class="hero">
<div>
<h1>Sakura 在线搜索</h1>
<p>搜索漫画和小说,可使用云端内置 JSON 源,也可以粘贴自己的 Legado 书源/漫画源 JSON。</p>
</div>
<span class="badge">手机端已适配</span>
</header>
<section class="panel">
<div class="toolbar">
<select id="mode">
<option value="novel">小说</option>
<option value="manga">漫画</option>
</select>
<select id="preset"></select>
<input id="token" type="password" placeholder="Bearer Token,可从网页登录后复制" autocomplete="off">
</div>
<div class="searchbar">
<input id="query" type="search" placeholder="输入关键词">
<button class="primary" id="search">在线搜索</button>
</div>
<div class="source-tools">
<p class="muted">默认使用内置精选源。需要临时测试时,可以展开并粘贴 JSON。</p>
<button class="ghost" id="toggleSources" type="button">展开源 JSON</button>
</div>
<textarea id="sources" placeholder="书源/漫画源 JSON" hidden></textarea>
<p id="status" class="muted status-line"></p>
<div id="results" class="results"></div>
</section>
</main>
<script>
const presets = [
{ name: "精选50书源", url: "/sources/精选50书源.json", mode: "novel" },
{ name: "精选50漫画源", url: "/sources/精选50漫画源.json", mode: "manga" }
];
const presetEl = document.querySelector("#preset");
const modeEl = document.querySelector("#mode");
const tokenEl = document.querySelector("#token");
const queryEl = document.querySelector("#query");
const sourcesEl = document.querySelector("#sources");
const statusEl = document.querySelector("#status");
const resultsEl = document.querySelector("#results");
tokenEl.value = localStorage.getItem("sakura-online-token") || "";
presets.forEach((item, index) => {
const option = document.createElement("option");
option.value = String(index);
option.textContent = item.name;
presetEl.appendChild(option);
});
async function loadPreset() {
const item = presets[Number(presetEl.value || 0)];
modeEl.value = item.mode;
statusEl.textContent = "正在加载内置源...";
sourcesEl.value = await fetch(item.url).then(r => r.text());
statusEl.textContent = "内置源已加载。";
}
presetEl.addEventListener("change", loadPreset);
loadPreset().catch(err => statusEl.textContent = err.message || "内置源加载失败");
document.querySelector("#toggleSources").addEventListener("click", event => {
const visible = sourcesEl.hasAttribute("hidden");
sourcesEl.toggleAttribute("hidden", !visible);
event.currentTarget.textContent = visible ? "收起源 JSON" : "展开源 JSON";
});
queryEl.addEventListener("keydown", event => {
if (event.key === "Enter") document.querySelector("#search").click();
});
document.querySelector("#search").addEventListener("click", async () => {
resultsEl.innerHTML = "";
statusEl.textContent = "";
statusEl.className = "muted";
const token = tokenEl.value.trim().replace(/^Bearer\\s+/i, "");
localStorage.setItem("sakura-online-token", token);
let parsed;
try { parsed = JSON.parse(sourcesEl.value); } catch { statusEl.textContent = "JSON 格式不正确"; statusEl.className = "error"; return; }
try {
statusEl.textContent = "搜索中...";
const res = await fetch(`/api/v1/online-search?mode=${encodeURIComponent(modeEl.value)}`, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` },
body: JSON.stringify({ query: queryEl.value.trim(), sources: parsed, limit_sources: 50, per_source_limit: 20 })
});
const body = await res.json();
if (!res.ok) throw new Error(body.detail || body.message || `HTTP ${res.status}`);
const rows = body.data || [];
statusEl.textContent = `找到 ${rows.length} 条结果`;
resultsEl.innerHTML = rows.map(item => `
<article class="card">
<div class="cover">${item.cover_url ? `<img src="${item.cover_url}" alt="">` : (item.kind === "manga" ? "漫" : "文")}</div>
<div>
<strong>${escapeHtml(item.title || "未命名")}</strong>
<span class="muted">${escapeHtml([item.author, item.source_name].filter(Boolean).join(" · "))}</span>
<a href="${item.detail_url}" target="_blank" rel="noreferrer">${item.detail_url}</a>
</div>
</article>`).join("");
} catch (err) {
statusEl.textContent = err.message || "搜索失败";
statusEl.className = "error";
}
});
function escapeHtml(value) {
return String(value || "").replace(/[&<>"']/g, ch => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[ch]));
}
</script>
</body>
</html>""",
headers={
"Content-Security-Policy": (
"default-src 'self'; base-uri 'self'; object-src 'none'; "
"frame-ancestors 'none'; img-src 'self' data: blob: https: http:; "
"style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; "
"connect-src 'self'"
)
},
)
def _admin_placeholder() -> HTMLResponse:
return HTMLResponse(
"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sakura Cloud Admin</title>
</head>
<body>
<main>
<h1>Sakura Cloud Admin</h1>
<p>Frontend not built. Run: cd sakura_admin_web && npm run build</p>
</main>
</body>
</html>"""
)
def _spa_index(frontend_dist: Path) -> FileResponse | HTMLResponse:
index_path = frontend_dist / "index.html"
if index_path.is_file():
return FileResponse(index_path)
return _admin_placeholder()
async def cleanup_uploads_loop() -> None:
while True:
await asyncio.sleep(3600)
db = SessionLocal()
try:
cleanup_stale_uploads(db)
except Exception:
logger.exception("Cleanup stale uploads failed")
finally:
db.close()
async def reminder_digest_loop() -> None:
while True:
await asyncio.sleep(300)
db = SessionLocal()
try:
run_daily_reminder_digest(db)
except Exception:
logger.exception("Reminder digest loop failed")
finally:
db.close()
def create_app() -> FastAPI:
configure_logging()
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
openapi_url=f"{settings.api_prefix}/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.middleware("http")(security_headers_middleware)
app.middleware("http")(trace_logging_middleware)
app.include_router(api_router, prefix=settings.api_prefix)
frontend_dist = _admin_frontend_dist()
public_dir = _cloud_public_dir()
assets_dir = frontend_dist / "assets"
if settings.admin_frontend_enabled and assets_dir.is_dir():
app.mount("/assets", StaticFiles(directory=assets_dir), name="admin_assets")
sources_dir = public_dir / "sources"
if sources_dir.is_dir():
app.mount("/sources", StaticFiles(directory=sources_dir), name="source_json")
@app.get("/online-search", response_model=None)
def online_search_console() -> HTMLResponse:
return _online_search_page()
@app.get("/search", response_model=None)
def search_console() -> HTMLResponse:
return _online_search_page()
@app.get("/admin", response_model=None)
def admin_console() -> FileResponse | HTMLResponse:
if not settings.admin_frontend_enabled:
return HTMLResponse("<h1>Admin console disabled</h1>", status_code=404)
return _spa_index(frontend_dist)
@app.get("/{full_path:path}", include_in_schema=False, response_model=None)
def spa_fallback(full_path: str) -> FileResponse | HTMLResponse:
api_prefix = settings.api_prefix.strip("/")
if full_path == api_prefix or full_path.startswith(api_prefix + "/"):
raise HTTPException(status_code=404, detail="API route not found")
if not settings.admin_frontend_enabled:
raise HTTPException(status_code=404, detail="Frontend disabled")
return _spa_index(frontend_dist)
@app.on_event("startup")
async def _start_background_tasks() -> None:
if settings.auto_migrate_on_startup:
logger.info("Auto migration enabled, upgrading database to head")
upgrade_database_to_head()
else:
logger.info("Auto migration disabled, skipping database upgrade on startup")
db = SessionLocal()
try:
cleanup_stale_uploads(db)
try:
run_daily_reminder_digest(db)
except Exception:
logger.exception("Initial reminder digest failed during startup")
finally:
db.close()
logger.info("Startup tasks completed")
asyncio.create_task(cleanup_uploads_loop())
asyncio.create_task(reminder_digest_loop())
return app
app = create_app()