first commit

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
kunkunxiaomaoandClaude committed 2026-11-16 20:45:22 +08:00
commit 9c5fef1a4d
412 files changed
+94582

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="referrer" content="no-referrer" />
<title>Sakura Cloud</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
server {
listen 80;
server_name _;
root /var/www/sakura_admin_web/dist;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+1833
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "sakura-admin-web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview --host 0.0.0.0"
},
"dependencies": {
"@vitejs/plugin-vue": "^5.2.4",
"axios": "^1.7.9",
"vite": "^6.0.7",
"vue": "^3.5.13",
"vue-router": "^4.5.0"
},
"devDependencies": {
"typescript": "^5.7.2",
"vue-tsc": "^2.2.0"
}
}
+3
View File
@@ -0,0 +1,3 @@
<template>
<RouterView />
</template>
+53
View File
@@ -0,0 +1,53 @@
import axios, { type AxiosError } from "axios";
import { authState, clearSession, saveSession } from "../stores/session";
const API_BASE = import.meta.env.VITE_API_BASE_URL || "/api/v1";
export const http = axios.create({
baseURL: API_BASE,
timeout: 15000,
withCredentials: false
});
let refreshing: Promise<void> | null = null;
http.interceptors.request.use((config) => {
if (authState.accessToken) {
config.headers.Authorization = `Bearer ${authState.accessToken}`;
}
return config;
});
http.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const original = error.config;
if (!original || error.response?.status !== 401 || !authState.refreshToken || original.headers?.["X-Retry"]) {
throw error;
}
refreshing ||= http
.post("/auth/refresh", { refresh_token: authState.refreshToken }, { headers: { "X-Retry": "1" } })
.then((response) => {
const tokens = response.data?.data;
saveSession(tokens.access_token, tokens.refresh_token);
})
.catch((refreshError) => {
clearSession();
throw refreshError;
})
.finally(() => {
refreshing = null;
});
await refreshing;
original.headers = {
...(original.headers as Record<string, string>),
Authorization: `Bearer ${authState.accessToken}`,
"X-Retry": "1"
} as any;
return http(original);
}
);
export function apiData<T>(response: { data: { data: T } }): T {
return response.data.data;
}
+6
View File
@@ -0,0 +1,6 @@
import { createApp } from "vue";
import App from "./App.vue";
import { router } from "./router";
import "./styles.css";
createApp(App).use(router).mount("#app");
+95
View File
@@ -0,0 +1,95 @@
import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
import { authState, isAdmin, loadMe } from "../stores/auth";
import LoginPage from "../views/public/LoginPage.vue";
import RegisterPage from "../views/public/RegisterPage.vue";
import ForgotPasswordPage from "../views/public/ForgotPasswordPage.vue";
import ForbiddenPage from "../views/public/ForbiddenPage.vue";
import NotFoundPage from "../views/public/NotFoundPage.vue";
import AppLayout from "../views/app/AppLayout.vue";
import UserDashboard from "../views/app/UserDashboard.vue";
import UserListPage from "../views/app/UserListPage.vue";
import UserDetailPage from "../views/app/UserDetailPage.vue";
import UserChapterListPage from "../views/app/UserChapterListPage.vue";
import UserOnlineSearchPage from "../views/app/UserOnlineSearchPage.vue";
import AdminLayout from "../views/admin/AdminLayout.vue";
import AdminDashboard from "../views/admin/AdminDashboard.vue";
import AdminTablePage from "../views/admin/AdminTablePage.vue";
import AdminUserDetail from "../views/admin/AdminUserDetail.vue";
const routes: RouteRecordRaw[] = [
{ path: "/", redirect: "/app" },
{ path: "/login", component: LoginPage },
{ path: "/register", component: RegisterPage },
{ path: "/forgot-password", component: ForgotPasswordPage },
{ path: "/403", component: ForbiddenPage },
{
path: "/app",
component: AppLayout,
meta: { requiresAuth: true },
children: [
{ path: "", component: UserDashboard },
{ path: "gallery", component: UserListPage, props: { kind: "gallery" } },
{ path: "gallery/:id", component: UserDetailPage, props: (route) => ({ kind: "gallery", id: route.params.id }) },
// 漫画三级结构
{ path: "manga", component: UserListPage, props: { kind: "manga" } },
{ path: "manga/series/:seriesKey", component: UserChapterListPage, props: (route) => ({ kind: "manga", seriesKey: route.params.seriesKey }) },
{ path: "manga/read/:id", component: UserDetailPage, props: (route) => ({ kind: "manga", id: route.params.id }) },
// 小说三级结构
{ path: "novels", component: UserListPage, props: { kind: "novels" } },
{ path: "novels/series/:seriesId", component: UserChapterListPage, props: (route) => ({ kind: "novels", seriesId: route.params.seriesId }) },
{ path: "novels/read/:id", component: UserDetailPage, props: (route) => ({ kind: "novels", id: route.params.id }) },
// 旧路由重定向(兼容书签/旧链接)
{ path: "manga/:id", redirect: (to) => `/app/manga/read/${to.params.id}` },
{ path: "novels/:id", redirect: (to) => `/app/novels/read/${to.params.id}` },
{ path: "search", component: UserOnlineSearchPage },
{ path: "alerts", component: UserListPage, props: { kind: "alerts" } },
{ path: "profile", component: UserDetailPage, props: { kind: "profile" } }
]
},
{
path: "/admin",
component: AdminLayout,
meta: { requiresAuth: true, requiresAdmin: true },
children: [
{ path: "", component: AdminDashboard },
{ path: "users", component: AdminTablePage, props: { resource: "users" } },
{ path: "users/:id", component: AdminUserDetail },
{ path: "files", component: AdminTablePage, props: { resource: "files" } },
{ path: "gallery", component: AdminTablePage, props: { resource: "gallery" } },
{ path: "novels", component: AdminTablePage, props: { resource: "novels" } },
{ path: "ocr", component: AdminTablePage, props: { resource: "ocr/tasks" } },
{ path: "push", component: AdminTablePage, props: { resource: "push/devices" } },
{ path: "alerts", component: AdminTablePage, props: { resource: "alerts" } },
{ path: "audit-logs", component: AdminTablePage, props: { resource: "audit-logs" } },
{ path: "system", component: AdminTablePage, props: { resource: "system/health" } }
]
},
{ path: "/404", component: NotFoundPage },
{ path: "/:pathMatch(.*)*", redirect: "/404" }
];
export const router = createRouter({
history: createWebHistory(),
routes
});
const PUBLIC_PATHS = new Set(["/login", "/register", "/forgot-password", "/403", "/404"]);
function isPublicPath(path: string) {
return PUBLIC_PATHS.has(path);
}
router.beforeEach(async (to) => {
if (isPublicPath(to.path)) {
if ((to.path === "/login" || to.path === "/register") && authState.accessToken) {
const user = await loadMe().catch(() => null);
if (user) return isAdmin(user.role) ? "/admin" : "/app";
}
return true;
}
if (!to.meta.requiresAuth) return true;
const user = await loadMe().catch(() => null);
if (!user) return { path: "/login", query: { redirect: to.fullPath } };
if (to.meta.requiresAdmin && !isAdmin(authState.user?.role)) return "/403";
return true;
});
+42
View File
@@ -0,0 +1,42 @@
import { apiData, http } from "../api/http";
import { authState, clearSession, saveSession, type CurrentUser, type Role } from "./session";
export { authState, clearSession, saveSession };
export async function login(usernameOrEmail: string, password: string, admin = false) {
const path = admin ? "/admin/login" : "/auth/login";
const response = await http.post(path, { username_or_email: usernameOrEmail, password });
const tokens = apiData<{ access_token: string; refresh_token: string }>(response);
saveSession(tokens.access_token, tokens.refresh_token);
await loadMe();
}
export async function register(username: string, email: string, password: string) {
await http.post("/auth/register", { username, email, password });
await login(username, password);
}
export async function loadMe(force = false) {
if (authState.user && !force) return authState.user;
if (!authState.accessToken) return null;
authState.loading = true;
try {
const response = await http.get("/me");
authState.user = apiData<CurrentUser>(response);
return authState.user;
} finally {
authState.loading = false;
}
}
export async function logout() {
try {
await http.post("/auth/logout");
} finally {
clearSession();
}
}
export function isAdmin(role?: Role | null) {
return role === "admin" || role === "super_admin";
}
@@ -0,0 +1,87 @@
import { reactive } from "vue";
export interface MangaChapterCacheEntry {
id: string;
title: string;
order: number;
page_count: number;
thumbnail_url: string;
updated_at: string;
}
export interface MangaSeriesCacheEntry {
seriesKey: string;
seriesTitle: string;
coverUrl: string;
author: string;
chapters: MangaChapterCacheEntry[];
}
type MangaRow = Record<string, any>;
export const mangaSeriesCache = reactive<Record<string, MangaSeriesCacheEntry>>({});
function cleanText(value: unknown) {
return String(value || "").trim();
}
function resolveDisplayImage(value: unknown) {
const text = cleanText(value);
return text;
}
export function mangaSeriesKey(item: MangaRow) {
const metadata = item.artwork_metadata || {};
const seriesId = cleanText(metadata.series_id);
if (seriesId) return `manga-${seriesId}`;
const fallbackTitle = cleanText(metadata.series_title) || cleanText(item.title) || cleanText(item.source_id) || cleanText(item.id);
return `manga-title-${fallbackTitle}`;
}
export function normalizeMangaChapter(item: MangaRow): MangaChapterCacheEntry {
const metadata = item.artwork_metadata || {};
return {
id: String(item.id),
title: cleanText(item.title) || cleanText(metadata.chapter_title) || "未命名章节",
order: Number(metadata.chapter_order || 0),
page_count: Number(item.page_count || 1),
thumbnail_url: cleanText(item.thumbnail_url),
updated_at: cleanText(item.updated_at),
};
}
export function buildMangaSeriesGroups(rows: MangaRow[]) {
const groups = new Map<string, MangaRow[]>();
for (const row of rows) {
const key = mangaSeriesKey(row);
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(row);
}
return Array.from(groups.entries()).map(([seriesKey, pages]) => {
const sorted = [...pages].sort((a, b) => normalizeMangaChapter(a).order - normalizeMangaChapter(b).order);
const latest = [...pages].sort((a, b) => Date.parse(String(b.updated_at || "")) - Date.parse(String(a.updated_at || "")))[0] || pages[0];
const first = sorted[0] || latest;
const metadata = first?.artwork_metadata || {};
const chapters = sorted.map(normalizeMangaChapter);
const entry: MangaSeriesCacheEntry = {
seriesKey,
seriesTitle: cleanText(metadata.series_title) || cleanText(first?.title) || "未命名漫画",
coverUrl: resolveDisplayImage(first?.thumbnail_url || first?.image_url || first?.thumbnail_path || first?.file_path),
author: cleanText(first?.author),
chapters,
};
mangaSeriesCache[seriesKey] = entry;
return {
entry,
first,
latest,
pageTotal: pages.reduce((total, item) => total + Number(item.page_count || 1), 0),
tags: Array.isArray(first?.tags) ? first.tags : [],
};
});
}
export function clearMangaCache() {
Object.keys(mangaSeriesCache).forEach((key) => delete mangaSeriesCache[key]);
}
+38
View File
@@ -0,0 +1,38 @@
import { reactive } from "vue";
export type Role = "user" | "admin" | "super_admin";
export interface CurrentUser {
id: string;
username: string;
email: string;
role: Role;
is_active: boolean;
storage_used: number;
storage_limit: number;
}
const ACCESS_KEY = "sakura_access_token";
const REFRESH_KEY = "sakura_refresh_token";
export const authState = reactive({
accessToken: sessionStorage.getItem(ACCESS_KEY) || "",
refreshToken: sessionStorage.getItem(REFRESH_KEY) || "",
user: null as CurrentUser | null,
loading: false
});
export function saveSession(accessToken: string, refreshToken: string) {
authState.accessToken = accessToken;
authState.refreshToken = refreshToken;
sessionStorage.setItem(ACCESS_KEY, accessToken);
sessionStorage.setItem(REFRESH_KEY, refreshToken);
}
export function clearSession() {
authState.accessToken = "";
authState.refreshToken = "";
authState.user = null;
sessionStorage.removeItem(ACCESS_KEY);
sessionStorage.removeItem(REFRESH_KEY);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,42 @@
<template>
<main class="content">
<header class="page-head">
<div>
<p class="eyebrow">安全后台</p>
<h1>Dashboard</h1>
</div>
</header>
<section class="metric-grid">
<article v-for="(value, key) in stats" :key="key" class="metric">
<span>{{ labels[key] || key }}</span>
<strong>{{ value }}</strong>
</article>
</section>
</main>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { apiData, http } from "../../api/http";
const stats = ref<Record<string, number>>({});
const labels: Record<string, string> = {
users: "用户",
active_users: "活跃用户",
artworks: "作品",
novels: "小说",
files: "文件",
storage_used: "存储",
uploads_pending: "上传任务",
ocr_pending: "OCR 待处理",
ocr_failed: "OCR 失败",
push_devices: "推送设备",
follows: "关注",
alerts: "提醒"
};
onMounted(async () => {
const response = await http.get("/admin/dashboard");
stats.value = apiData<Record<string, number>>(response);
});
</script>
@@ -0,0 +1,19 @@
<template>
<div class="shell admin-shell">
<aside class="sidebar admin-sidebar">
<strong>Admin</strong>
<RouterLink to="/admin">Dashboard</RouterLink>
<RouterLink to="/admin/users">用户</RouterLink>
<RouterLink to="/admin/files">文件</RouterLink>
<RouterLink to="/admin/gallery">图库</RouterLink>
<RouterLink to="/admin/novels">小说</RouterLink>
<RouterLink to="/admin/ocr">OCR</RouterLink>
<RouterLink to="/admin/push">推送</RouterLink>
<RouterLink to="/admin/alerts">提醒</RouterLink>
<RouterLink to="/admin/audit-logs">审计</RouterLink>
<RouterLink to="/admin/system">系统</RouterLink>
<RouterLink to="/app">用户端</RouterLink>
</aside>
<RouterView />
</div>
</template>
@@ -0,0 +1,74 @@
<template>
<main class="content">
<header class="page-head">
<div>
<p class="eyebrow">管理</p>
<h1>{{ resourceTitle }}</h1>
</div>
<div class="toolbar">
<input v-if="canSearch" v-model.trim="q" placeholder="搜索" @keyup.enter="load" />
<button class="primary" @click="load">刷新</button>
</div>
</header>
<section class="panel">
<p v-if="loading" class="muted">加载中...</p>
<pre v-else-if="resource === 'system/health'">{{ single }}</pre>
<table v-else>
<thead>
<tr>
<th v-for="key in columns" :key="key">{{ key }}</th>
<th v-if="resource === 'users'">操作</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td v-for="key in columns" :key="key">{{ row[key] }}</td>
<td v-if="resource === 'users'" class="actions">
<RouterLink class="small-link" :to="`/admin/users/${row.id}`">详情</RouterLink>
<button class="danger" @click="toggleUser(row)">{{ row.is_active ? "禁用" : "启用" }}</button>
</td>
</tr>
</tbody>
</table>
<p v-if="!loading && rows.length === 0 && resource !== 'system/health'" class="muted">暂无数据。</p>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { apiData, http } from "../../api/http";
const props = defineProps<{ resource: string }>();
const loading = ref(false);
const q = ref("");
const rows = ref<Array<Record<string, any>>>([]);
const single = ref("");
const resourceTitle = computed(() => props.resource.replace("/", " / "));
const canSearch = computed(() => ["users", "gallery", "novels"].includes(props.resource));
const columns = computed(() => Object.keys(rows.value[0] || {}).filter((key) => !["password_hash", "fcm_token"].includes(key)).slice(0, 8));
async function load() {
loading.value = true;
try {
const response = await http.get(`/admin/${props.resource}`, { params: q.value ? { q: q.value } : {} });
const data = apiData<any>(response);
if (props.resource === "system/health") {
single.value = JSON.stringify(data, null, 2);
rows.value = [];
} else {
rows.value = Array.isArray(data) ? data : data.items || [];
}
} finally {
loading.value = false;
}
}
async function toggleUser(row: Record<string, any>) {
await http.patch(`/admin/users/${row.id}/status`, { is_active: !row.is_active, reason: row.is_active ? "Disabled from web admin" : null });
await load();
}
watch(() => props.resource, load);
onMounted(load);
</script>
@@ -0,0 +1,58 @@
<template>
<main class="content">
<header class="page-head">
<div>
<p class="eyebrow">用户详情</p>
<h1>{{ user?.username || "用户" }}</h1>
</div>
</header>
<section class="panel" v-if="user">
<div class="detail-grid">
<label>角色
<select v-model="role">
<option value="user">user</option>
<option value="admin">admin</option>
<option value="super_admin">super_admin</option>
</select>
</label>
<label>新密码
<input v-model="newPassword" type="password" minlength="8" placeholder="至少 8 位" />
</label>
</div>
<div class="action-row">
<button class="primary" @click="saveRole">保存角色</button>
<button class="danger" :disabled="newPassword.length < 8" @click="resetPassword">重置密码</button>
</div>
<pre>{{ user }}</pre>
</section>
</main>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { apiData, http } from "../../api/http";
const route = useRoute();
const user = ref<Record<string, any> | null>(null);
const role = ref("user");
const newPassword = ref("");
async function load() {
const response = await http.get(`/admin/users/${route.params.id}`);
user.value = apiData<Record<string, any>>(response);
role.value = user.value.role;
}
async function saveRole() {
await http.patch(`/admin/users/${route.params.id}/role`, { role: role.value });
await load();
}
async function resetPassword() {
await http.post(`/admin/users/${route.params.id}/reset-password`, { new_password: newPassword.value });
newPassword.value = "";
}
onMounted(load);
</script>
@@ -0,0 +1,28 @@
<template>
<div class="shell">
<aside class="sidebar">
<strong>Sakura</strong>
<RouterLink to="/app">概览</RouterLink>
<RouterLink to="/app/gallery">图片</RouterLink>
<RouterLink to="/app/manga">漫画</RouterLink>
<RouterLink to="/app/novels">小说</RouterLink>
<RouterLink to="/app/search">在线搜索</RouterLink>
<RouterLink to="/app/alerts">提醒</RouterLink>
<RouterLink to="/app/profile">我的</RouterLink>
<RouterLink v-if="isAdmin(authState.user?.role)" to="/admin">管理后台</RouterLink>
<button class="ghost" @click="doLogout">退出</button>
</aside>
<RouterView />
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
import { authState, isAdmin, logout } from "../../stores/auth";
const router = useRouter();
async function doLogout() {
await logout();
await router.push("/login");
}
</script>
@@ -0,0 +1,207 @@
<template>
<main class="content">
<header class="page-head">
<div>
<nav class="breadcrumb">
<RouterLink :to="`/app/${kind}`">{{ kindLabel }}</RouterLink>
<span>/</span>
<span class="current">{{ seriesTitle || (loading ? "加载中..." : "章节列表") }}</span>
</nav>
</div>
<button class="ghost" @click="goBack">← 返回</button>
</header>
<section v-if="loading" class="panel">
<p class="muted">{{ loadingMessage }}</p>
</section>
<section v-else-if="error" class="panel">
<p class="error">{{ error }}</p>
<button class="ghost" @click="load">重试</button>
</section>
<template v-else>
<div v-if="seriesTitle" class="series-header">
<div class="series-cover" :class="{ placeholder: !coverUrl }">
<img v-if="coverUrl" :src="coverUrl" alt="" loading="lazy" />
<span v-else>{{ kind === "novels" ? "文" : "漫" }}</span>
</div>
<div class="series-info">
<h2>{{ seriesTitle }}</h2>
<p v-if="author" class="muted">{{ author }}</p>
<p class="muted">共 {{ chapters.length }} {{ kind === "novels" ? "章" : "话" }}</p>
</div>
</div>
<section v-if="chapters.length" class="panel chapter-list">
<RouterLink
v-for="(chapter, idx) in chapters"
:key="chapter.id"
class="chapter-row"
:to="chapterReadUrl(chapter.id)"
>
<span class="chapter-index">{{ idx + 1 }}</span>
<div class="chapter-info">
<strong>{{ chapter.title || `第 ${idx + 1} ${kind === "novels" ? "章" : "话"}` }}</strong>
<span v-if="chapter.page_count" class="muted">{{ chapter.page_count }} 页</span>
<span v-if="chapter.updated_at" class="muted">{{ formatDate(chapter.updated_at) }}</span>
</div>
<span class="muted">→</span>
</RouterLink>
</section>
<section v-else class="panel">
<p class="muted">暂无章节</p>
</section>
</template>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { apiData, http } from "../../api/http";
import { buildMangaSeriesGroups, mangaSeriesCache, type MangaChapterCacheEntry } from "../../stores/seriesCache";
const props = defineProps<{
kind: "novels" | "manga";
seriesId?: string;
seriesKey?: string;
}>();
const router = useRouter();
interface ChapterEntry {
id: string;
title: string;
order: number;
page_count?: number;
thumbnail_url?: string;
updated_at?: string;
}
const loading = ref(false);
const reloadingFromApi = ref(false);
const error = ref("");
const seriesTitle = ref("");
const coverUrl = ref("");
const author = ref("");
const chapters = ref<ChapterEntry[]>([]);
const kindLabel = computed(() => (props.kind === "novels" ? "小说" : "漫画"));
const seriesRef = computed(() => (props.kind === "novels" ? String(props.seriesId || "") : String(props.seriesKey || "")));
const encodedSeriesRef = computed(() => encodeURIComponent(seriesRef.value));
const loadingMessage = computed(() => (reloadingFromApi.value ? "正在重新加载..." : "正在加载章节..."));
function normalizeNovelChapter(item: Record<string, any>): ChapterEntry {
return {
id: String(item.id),
title: String(item.chapter_title || item.title || "未命名章节").trim(),
order: Number(item.chapter_order || 0),
updated_at: item.updated_at || "",
};
}
function fromMangaChapter(chapter: MangaChapterCacheEntry): ChapterEntry {
return {
id: chapter.id,
title: chapter.title,
order: chapter.order,
page_count: chapter.page_count,
thumbnail_url: chapter.thumbnail_url,
updated_at: chapter.updated_at,
};
}
function formatDate(value: unknown) {
if (!value) return "";
const date = new Date(String(value));
if (Number.isNaN(date.getTime())) return "";
return `${date.getMonth() + 1}月${date.getDate()}日`;
}
function resolveCoverUrl(value: unknown) {
const text = typeof value === "string" ? value.trim() : "";
return text.startsWith("http") ? text : "";
}
function resetState() {
error.value = "";
seriesTitle.value = "";
coverUrl.value = "";
author.value = "";
chapters.value = [];
}
function goBack() {
router.back();
}
function chapterReadUrl(id: string) {
return `/app/${props.kind}/read/${id}?fromSeries=${encodedSeriesRef.value}`;
}
async function loadNovelSeries() {
const id = String(props.seriesId || "");
if (!id) {
error.value = "缺少系列 ID";
return;
}
const response = await http.get(`/novels/series/${id}`);
const data = apiData<any>(response);
seriesTitle.value = data.series_title || "未命名系列";
author.value = data.author || "";
coverUrl.value = resolveCoverUrl(data.cover_path);
chapters.value = (data.chapters || []).map(normalizeNovelChapter).sort((a: ChapterEntry, b: ChapterEntry) => a.order - b.order);
}
function applyMangaCache(seriesKey: string) {
const cached = mangaSeriesCache[seriesKey];
if (!cached || cached.chapters.length === 0) return false;
seriesTitle.value = cached.seriesTitle;
author.value = cached.author;
coverUrl.value = resolveCoverUrl(cached.coverUrl);
chapters.value = cached.chapters.map(fromMangaChapter);
return true;
}
async function loadMangaSeries() {
const key = String(props.seriesKey || "");
if (!key) {
error.value = "缺少系列标识";
return;
}
if (applyMangaCache(key)) return;
reloadingFromApi.value = true;
const response = await http.get("/me/gallery", {
params: { content_type: "manga", limit: 200, sort: "updated" },
});
const data = apiData<any>(response);
const rows: any[] = Array.isArray(data) ? data : data.items || [];
buildMangaSeriesGroups(rows);
if (!applyMangaCache(key)) {
error.value = "未找到该系列的章节";
}
}
async function load() {
resetState();
loading.value = true;
reloadingFromApi.value = false;
try {
if (props.kind === "novels") await loadNovelSeries();
else await loadMangaSeries();
} catch (err: any) {
error.value = err?.response?.data?.message || err?.response?.data?.detail || "加载章节列表失败";
} finally {
loading.value = false;
reloadingFromApi.value = false;
}
}
onMounted(load);
watch(() => [props.kind, props.seriesId, props.seriesKey], () => load());
</script>
@@ -0,0 +1,207 @@
<template>
<main class="content content-hub">
<header class="reader-hero">
<div>
<p class="eyebrow">Sakura Cloud</p>
<h1>我的内容合集</h1>
<p>插画、视频、漫画和小说都在这里继续看。</p>
</div>
<div class="hero-actions">
<RouterLink class="button-like primary" to="/app/search">在线搜索</RouterLink>
<RouterLink class="button-like" to="/app/alerts">提醒中心</RouterLink>
</div>
</header>
<section class="metric-grid">
<article class="metric"><span>用户</span><strong>{{ authState.user?.username || "Sakura" }}</strong></article>
<article class="metric"><span>空间</span><strong>{{ storageText }}</strong></article>
<article class="metric"><span>视频额度</span><strong>30 GB</strong></article>
<article class="metric"><span>最近内容</span><strong>{{ totalVisible }}</strong></article>
</section>
<section class="hub-section video-section">
<div class="section-head">
<div>
<h2>视频</h2>
<p>来自 X、小红书、抖音的同步视频会优先出现在这里。</p>
</div>
<RouterLink class="button-like" to="/app/gallery">全部内容</RouterLink>
</div>
<div v-if="videos.length" class="video-grid">
<RouterLink v-for="item in videos" :key="item.id" class="video-card" :to="`/app/gallery/${item.id}`">
<div class="video-frame">
<img v-if="displayUrl(item.id, displayImage(item))" :src="displayUrl(item.id, displayImage(item))" :alt="item.title" loading="lazy" />
<span class="play-mark">▶</span>
</div>
<strong>{{ item.title || "未命名视频" }}</strong>
<span>{{ item.author || item.source_platform || "视频" }} · {{ formatBytes(item.file_size) }}</span>
</RouterLink>
</div>
<p v-else class="empty-inline">还没有同步视频,采集后会自动出现在这里。</p>
</section>
<section class="hub-section">
<div class="section-head">
<div>
<h2>插画缩略图</h2>
<p>适合快速浏览和挑选收藏。</p>
</div>
<RouterLink class="button-like" to="/app/gallery">进入图库</RouterLink>
</div>
<div v-if="illusts.length" class="illust-grid compact">
<RouterLink v-for="item in illusts" :key="item.id" class="illust-tile" :to="`/app/gallery/${item.id}`">
<div class="illust-thumb">
<img v-if="displayUrl(item.id, displayImage(item))" :src="displayUrl(item.id, displayImage(item))" :alt="item.title" loading="lazy" />
<span v-else>IMG</span>
</div>
<strong>{{ item.title || "未命名插画" }}</strong>
<span>{{ item.author || item.source_platform }}</span>
</RouterLink>
</div>
<p v-else class="empty-inline">插画缩略图还在等待同步。</p>
</section>
<section class="hub-two-col">
<div class="hub-section">
<div class="section-head">
<div>
<h2>漫画</h2>
<p>按作品聚合,不再把每页拆成一堆入口。</p>
</div>
<RouterLink class="button-like" to="/app/manga">漫画书架</RouterLink>
</div>
<div v-if="mangas.length" class="reading-list">
<RouterLink v-for="item in mangas" :key="item.id" class="reading-row" :to="`/app/manga/${item.id}`">
<div class="reading-cover"><img v-if="displayUrl(item.id, displayImage(item))" :src="displayUrl(item.id, displayImage(item))" loading="lazy" /></div>
<div>
<strong>{{ item.title || "未命名漫画" }}</strong>
<span>{{ item.author || item.source_platform }} · {{ item.page_count || 1 }} 页</span>
</div>
</RouterLink>
</div>
<p v-else class="empty-inline">漫画同步后会以书架形式展示。</p>
</div>
<div class="hub-section">
<div class="section-head">
<div>
<h2>小说</h2>
<p>更接近阅读站的作品列表,适合继续阅读。</p>
</div>
<RouterLink class="button-like" to="/app/novels">小说书架</RouterLink>
</div>
<div v-if="novels.length" class="reading-list">
<RouterLink v-for="item in novels" :key="item.series_id || item.id" class="reading-row" :to="novelUrl(item)">
<div class="reading-cover"><img v-if="displayUrl(item.series_id || item.id, displayImage(item))" :src="displayUrl(item.series_id || item.id, displayImage(item))" loading="lazy" /></div>
<div>
<strong>{{ item.series_title || item.title || "未命名小说" }}</strong>
<span>{{ item.author || "未知作者" }} · {{ item.chapter_count || 0 }} 章</span>
</div>
</RouterLink>
</div>
<p v-else class="empty-inline">小说书架还是空的,可以先去在线搜索。</p>
</div>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { apiData, http } from "../../api/http";
import { authState } from "../../stores/auth";
type Row = Record<string, any>;
const illusts = ref<Row[]>([]);
const videos = ref<Row[]>([]);
const mangas = ref<Row[]>([]);
const novels = ref<Row[]>([]);
const protectedImageUrls = ref<Record<string, string>>({});
const storageText = computed(() => {
const used = authState.user?.storage_used || 0;
const limit = authState.user?.storage_limit || 0;
return `${(used / 1024 / 1024).toFixed(1)} MB / ${(limit / 1024 / 1024).toFixed(0)} MB`;
});
const totalVisible = computed(() => illusts.value.length + videos.value.length + mangas.value.length + novels.value.length);
onMounted(async () => {
await Promise.all([loadGallery("illust", illusts), loadGallery("video", videos), loadGallery("manga", mangas), loadNovels()]);
await loadProtectedImages();
});
async function loadGallery(contentType: string, target: typeof illusts) {
const response = await http.get("/me/gallery", {
params: { content_type: contentType, sort: "updated", page: 1, limit: contentType === "illust" ? 12 : 6, include_total: false },
});
const data = apiData<any>(response);
target.value = Array.isArray(data) ? data : data.items || [];
}
async function loadNovels() {
const response = await http.get("/novels/series", { params: { include_chapters: false } });
const data = apiData<any>(response);
novels.value = (Array.isArray(data) ? data : data.items || []).slice(0, 6);
}
function displayImage(item: Row) {
const value = String(item.thumbnail_url || item.image_url || item.thumbnail_path || item.cover_path || "");
return value.trim();
}
function displayUrl(id: unknown, raw: unknown) {
const text = String(raw || "").trim();
if (!text) return "";
if (text.startsWith("http") || text.startsWith("blob:")) return text;
return protectedImageUrls.value[String(id)] || "";
}
function protectedRequestPath(path: string) {
if (path.startsWith("/api/v1")) return path.slice("/api/v1".length);
if (path.startsWith("/api/")) return path;
return "";
}
function revokeProtectedImages() {
Object.values(protectedImageUrls.value).forEach((url) => URL.revokeObjectURL(url));
protectedImageUrls.value = {};
}
async function loadProtectedImages() {
revokeProtectedImages();
const rows = [...illusts.value, ...videos.value, ...mangas.value, ...novels.value];
const targets = rows
.map((item) => ({ id: String(item.series_id || item.id), path: displayImage(item) }))
.filter((item) => item.path && !item.path.startsWith("http"));
await Promise.all(targets.slice(0, 80).map(async (target) => {
const requestPath = protectedRequestPath(target.path);
if (!requestPath) return;
try {
const response = await http.get(requestPath, { responseType: "blob" });
protectedImageUrls.value[target.id] = URL.createObjectURL(response.data);
} catch {
// Keep placeholder visible when the thumbnail cannot be fetched.
}
}));
}
onUnmounted(revokeProtectedImages);
function novelUrl(item: Row) {
const id = item.series_id || item.id;
return id ? `/app/novels/series/${encodeURIComponent(String(id))}` : "/app/novels";
}
function formatBytes(value: unknown) {
let size = Number(value || 0);
if (!Number.isFinite(size) || size <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
let index = 0;
while (size >= 1024 && index < units.length - 1) {
size /= 1024;
index += 1;
}
return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
}
</script>
@@ -0,0 +1,203 @@
<template>
<main class="content">
<header class="page-head">
<div>
<nav v-if="kind === 'novels' || kind === 'manga'" class="breadcrumb">
<RouterLink :to="`/app/${kind}`">{{ kind === "novels" ? "小说" : "漫画" }}</RouterLink>
<span>/</span>
<RouterLink v-if="fromSeries" :to="backToListRoute">章节列表</RouterLink>
<span v-if="fromSeries">/</span>
<span class="current">{{ displayTitle }}</span>
</nav>
<p class="eyebrow">详情</p>
<h1>{{ title }}</h1>
</div>
<button v-if="kind === 'novels' || kind === 'manga'" class="ghost" @click="$router.back()">← 返回</button>
</header>
<section class="panel">
<p v-if="loading" class="muted">正在加载...</p>
<p v-else-if="error" class="muted">{{ error }}</p>
<div v-else-if="kind === 'profile'" class="detail-grid">
<div><span>用户名</span><strong>{{ authState.user?.username || "-" }}</strong></div>
<div><span>邮箱</span><strong>{{ authState.user?.email || "-" }}</strong></div>
<div><span>角色</span><strong>{{ authState.user?.role || "user" }}</strong></div>
<div><span>空间占用</span><strong>{{ authState.user?.storage_used || 0 }}</strong></div>
</div>
<article v-else-if="detail" class="detail-card">
<img v-if="displayImageUrl" :src="displayImageUrl" alt="" class="detail-cover" />
<div v-else-if="kind !== 'novels'" class="detail-cover placeholder">No Image</div>
<div class="detail-body">
<p class="eyebrow">{{ kind === "novels" ? "小说" : kind === "manga" ? "漫画" : "图片" }}</p>
<h2>{{ displayTitle }}</h2>
<p class="muted">{{ displayMeta }}</p>
<div v-if="kind === 'novels' || kind === 'manga'" class="reader-nav-row">
<RouterLink v-if="prevChapter" class="button-like" :to="chapterUrl(prevChapter.id)">上一章</RouterLink>
<RouterLink class="button-like" :to="backToListRoute">目录</RouterLink>
<RouterLink v-if="nextChapter" class="button-like primary" :to="chapterUrl(nextChapter.id)">下一章</RouterLink>
</div>
<p v-if="detail.summary || detail.description">{{ detail.summary || detail.description }}</p>
<div v-if="tags.length" class="tags">
<span v-for="tag in tags" :key="tag">{{ tag }}</span>
</div>
<section v-if="kind === 'novels'" class="reader-panel">
<p v-if="contentLoading" class="muted">正文加载中...</p>
<p v-else-if="novelContent" class="novel-text">{{ novelContent }}</p>
<p v-else class="muted">暂时没有正文内容。</p>
</section>
</div>
</article>
<p v-else class="muted">没有找到这条内容。</p>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { apiData, http } from "../../api/http";
import { authState } from "../../stores/auth";
import { buildMangaSeriesGroups, mangaSeriesCache } from "../../stores/seriesCache";
const props = defineProps<{
kind: "gallery" | "manga" | "novels" | "profile";
id?: string;
}>();
const route = useRoute();
const fromSeries = computed(() => String(route.query.fromSeries || ""));
const backToListRoute = computed(() => {
if (fromSeries.value) {
return `/app/${props.kind}/series/${encodeURIComponent(fromSeries.value)}`;
}
return `/app/${props.kind}`;
});
const loading = ref(false);
const contentLoading = ref(false);
const error = ref("");
const detail = ref<Record<string, any> | null>(null);
const imageObjectUrl = ref("");
const novelContent = ref("");
const prevChapter = ref<Record<string, any> | null>(null);
const nextChapter = ref<Record<string, any> | null>(null);
const title = computed(() => {
if (props.kind === "profile") return "我的资料";
if (props.kind === "manga") return "漫画详情";
if (props.kind === "novels") return "小说阅读";
return "作品详情";
});
const displayTitle = computed(() => detail.value?.title || detail.value?.original_name || "未命名");
const displayMeta = computed(() => {
const item = detail.value;
if (!item) return "";
return [item.author, item.source_platform, item.updated_at || item.created_at].filter(Boolean).join(" · ");
});
const tags = computed(() => {
const raw = detail.value?.tags;
return Array.isArray(raw) ? raw.map((item) => String(item)).filter(Boolean) : [];
});
const displayImageUrl = computed(() => imageObjectUrl.value || directImageUrl.value);
const directImageUrl = computed(() => {
const path = detail.value?.thumbnail_url || detail.value?.image_url;
return typeof path === "string" && path.startsWith("http") ? path : "";
});
async function loadDetail() {
revokeImageUrl();
error.value = "";
detail.value = null;
novelContent.value = "";
prevChapter.value = null;
nextChapter.value = null;
if (props.kind === "profile") return;
if (!props.id) {
error.value = "缺少内容 ID。";
return;
}
loading.value = true;
try {
const endpoint = props.kind === "novels" ? `/novels/${props.id}` : `/gallery/${props.id}`;
const response = await http.get(endpoint);
detail.value = apiData<Record<string, any>>(response);
loading.value = false;
void loadProtectedImage();
void loadNovelContent();
void loadChapterNavigation();
} catch (err: any) {
error.value = err?.response?.data?.message || err?.response?.data?.detail || "详情加载失败,请稍后再试。";
loading.value = false;
}
}
async function loadProtectedImage() {
if (props.kind === "novels") return;
const path = detail.value?.thumbnail_url || detail.value?.image_url;
if (typeof path !== "string" || !path.startsWith("/api/")) return;
const requestPath = path.startsWith("/api/v1") ? path.slice("/api/v1".length) : path;
const response = await http.get(requestPath, { responseType: "blob" });
imageObjectUrl.value = URL.createObjectURL(response.data);
}
async function loadNovelContent() {
if (props.kind !== "novels" || !props.id) return;
contentLoading.value = true;
try {
const response = await http.get(`/novels/${props.id}/content`, { responseType: "text" });
novelContent.value = String(response.data || "").trim();
} catch {
novelContent.value = "";
} finally {
contentLoading.value = false;
}
}
function chapterUrl(id: unknown) {
return `/app/${props.kind}/read/${id}?fromSeries=${encodeURIComponent(fromSeries.value)}`;
}
function normalizeChapter(item: Record<string, any>) {
return {
id: String(item.id),
order: Number(item.chapter_order ?? item.order ?? 0),
updated_at: String(item.updated_at || ""),
};
}
async function loadChapterNavigation() {
if ((props.kind !== "novels" && props.kind !== "manga") || !props.id || !fromSeries.value) return;
let chapters: Array<Record<string, any>> = [];
if (props.kind === "novels") {
const response = await http.get(`/novels/series/${fromSeries.value}`);
const data = apiData<any>(response);
chapters = (data.chapters || []).map(normalizeChapter);
} else {
if (!mangaSeriesCache[fromSeries.value]) {
const response = await http.get("/me/gallery", {
params: { content_type: "manga", limit: 200, sort: "updated", include_total: false },
});
const data = apiData<any>(response);
buildMangaSeriesGroups(Array.isArray(data) ? data : data.items || []);
}
chapters = (mangaSeriesCache[fromSeries.value]?.chapters || []).map(normalizeChapter);
}
chapters.sort((a, b) => Number(a.order || 0) - Number(b.order || 0));
const index = chapters.findIndex((item) => String(item.id) === String(props.id));
if (index < 0) return;
prevChapter.value = index > 0 ? chapters[index - 1] : null;
nextChapter.value = index < chapters.length - 1 ? chapters[index + 1] : null;
}
function revokeImageUrl() {
if (imageObjectUrl.value) {
URL.revokeObjectURL(imageObjectUrl.value);
imageObjectUrl.value = "";
}
}
watch(() => [props.kind, props.id], loadDetail);
onMounted(loadDetail);
onUnmounted(revokeImageUrl);
</script>
@@ -0,0 +1,414 @@
<template>
<main class="content">
<header class="page-head">
<div>
<p class="eyebrow">我的内容</p>
<h1>{{ title }}</h1>
</div>
<form v-if="kind !== 'alerts'" class="search-form" @submit.prevent="searchNow">
<input v-model.trim="search" placeholder="搜索作品、作者或章节" @input="debounceSearch" />
<button type="submit">搜索</button>
</form>
</header>
<section class="panel">
<div v-if="kind === 'manga' || kind === 'novels'" class="online-search-box">
<div class="online-search-head">
<div>
<strong>在线搜索</strong>
<p class="muted">导入 Legado 书源/漫画源 JSON 后,可按 App 端同类规则搜索。</p>
</div>
<label class="button-like">
导入 JSON
<input class="hidden-input" type="file" accept=".json,application/json,text/plain" @change="importSourceFile" />
</label>
</div>
<div class="online-source-row">
<input v-model.trim="onlineQuery" :placeholder="kind === 'manga' ? '搜索在线漫画' : '搜索在线小说'" @keydown.enter.prevent="runOnlineSearch" />
<button class="primary" :disabled="onlineLoading || !onlineQuery || !onlineSourcesText" @click="runOnlineSearch">
{{ onlineLoading ? "搜索中..." : "在线搜索" }}
</button>
</div>
<textarea v-model="onlineSourcesText" class="source-json-input" placeholder="也可以粘贴书源/漫画源 JSON,支持数组或 { sources: [...] }"></textarea>
<p v-if="onlineError" class="error">{{ onlineError }}</p>
<div v-if="onlineResults.length" class="online-result-list">
<a v-for="item in onlineResults" :key="`${item.source_name}-${item.detail_url}`" class="online-result-row" :href="item.detail_url" target="_blank" rel="noreferrer">
<div class="online-cover" :class="{ placeholder: !item.cover_url }">
<img v-if="item.cover_url" :src="item.cover_url" alt="" loading="lazy" />
<span v-else>{{ kind === "manga" ? "漫" : "文" }}</span>
</div>
<div>
<strong>{{ item.title }}</strong>
<p>{{ [item.author, item.source_name].filter(Boolean).join(" · ") || "在线来源" }}</p>
</div>
</a>
</div>
</div>
<p v-if="loading" class="muted">正在加载...</p>
<p v-else-if="items.length === 0" class="muted">这里暂时空空的,同步后会开出第一朵小花。</p>
<div v-else-if="usesWorkCards" class="work-list">
<RouterLink v-for="group in displayGroups" :key="group.id" class="work-card" :to="detailUrl(group)">
<div class="work-cover" :class="{ placeholder: !group.coverUrl }">
<img v-if="displayUrl(group.id, group.coverUrl)" :src="displayUrl(group.id, group.coverUrl)" alt="" loading="lazy" />
<span v-else>{{ kind === "novels" ? "文" : "漫" }}</span>
</div>
<div class="work-main">
<div class="work-title-row">
<strong>{{ group.title }}</strong>
<span class="work-badge">{{ group.badge }}</span>
</div>
<p class="work-meta">{{ group.meta || "暂无作者信息" }}</p>
<p v-if="group.latest" class="work-latest">最新:{{ group.latest }}</p>
<p v-if="group.summary" class="work-summary">{{ group.summary }}</p>
<div v-if="group.previewChapters.length" class="chapter-strip">
<span v-for="chapter in group.previewChapters" :key="chapter.id">{{ chapter.label }}</span>
</div>
</div>
</RouterLink>
</div>
<div v-else-if="kind === 'gallery'" class="illust-grid">
<RouterLink v-for="item in items" :key="item.id" class="illust-tile" :to="detailUrlById(item.id)">
<div class="illust-thumb" :class="{ placeholder: !displayUrl(item.id, galleryImage(item)) }">
<img v-if="displayUrl(item.id, galleryImage(item))" :src="displayUrl(item.id, galleryImage(item))" alt="" loading="lazy" />
<span v-else>插画</span>
</div>
<strong>{{ item.title || "未命名" }}</strong>
<span>{{ item.author || item.source_platform || "图片" }}</span>
</RouterLink>
</div>
<div v-else class="list">
<RouterLink v-for="item in items" :key="item.id" class="list-row" :to="detailUrlById(item.id)">
<strong>{{ item.title || item.platform || item.original_name || "未命名" }}</strong>
<span>{{ item.author || item.content_type || item.created_at || item.updated_at }}</span>
</RouterLink>
</div>
<footer v-if="supportsPagination" class="pager">
<button :disabled="loading || page <= 1" @click="previousPage">上一页</button>
<span>第 {{ page }} 页</span>
<button :disabled="loading || !hasNext" @click="nextPage">下一页</button>
</footer>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { apiData, http } from "../../api/http";
import { buildMangaSeriesGroups } from "../../stores/seriesCache";
type ListKind = "gallery" | "manga" | "novels" | "alerts";
type Row = Record<string, any>;
type WorkGroup = {
id: string;
targetId: string;
title: string;
coverUrl: string;
badge: string;
meta: string;
latest: string;
summary: string;
previewChapters: Array<{ id: string; label: string }>;
seriesKey?: string; // manga: 用于路由和缓存的唯一标识
seriesId?: string; // novels: 后端 series_id
};
const props = defineProps<{ kind: ListKind }>();
const loading = ref(false);
const search = ref("");
const items = ref<Row[]>([]);
const protectedImageUrls = ref<Record<string, string>>({});
const page = ref(1);
const onlineQuery = ref("");
const onlineSourcesText = ref("");
const onlineResults = ref<Row[]>([]);
const onlineLoading = ref(false);
const onlineError = ref("");
const pageLimit = computed(() => (props.kind === "manga" || props.kind === "novels" ? 80 : 20));
const hasNext = ref(false);
let searchTimer: ReturnType<typeof setTimeout> | null = null;
const title = computed(
() =>
({
gallery: "图片",
manga: "漫画",
novels: "小说",
alerts: "提醒中心",
})[props.kind],
);
const usesWorkCards = computed(() => props.kind === "manga" || props.kind === "novels");
const supportsPagination = computed(() => props.kind !== "alerts" && props.kind !== "novels");
const displayGroups = computed<WorkGroup[]>(() => {
if (props.kind === "novels") return groupNovels(items.value);
if (props.kind === "manga") return groupManga(items.value);
return [];
});
function detailUrl(group: WorkGroup): string {
if (props.kind === "alerts") return "/app/alerts";
if (props.kind === "novels" && group.seriesId) {
return `/app/novels/series/${group.seriesId}`;
}
if (props.kind === "manga" && group.seriesKey) {
return `/app/manga/series/${encodeURIComponent(group.seriesKey)}`;
}
return `/app/${props.kind}/${group.targetId}`;
}
function detailUrlById(id: string): string {
if (props.kind === "alerts") return "/app/alerts";
return `/app/${props.kind}/${id}`;
}
function endpoint() {
if (props.kind === "manga") return "/me/gallery";
if (props.kind === "novels") return "/novels/series";
return `/me/${props.kind}`;
}
function params() {
if (props.kind === "alerts") return {};
if (props.kind === "novels") {
return { include_chapters: false };
}
return {
page: page.value,
limit: pageLimit.value,
search: search.value || undefined,
include_total: false,
sort: props.kind === "gallery" || props.kind === "manga" ? "updated" : undefined,
content_type: props.kind === "manga" ? "manga" : props.kind === "gallery" ? "illust" : undefined,
};
}
async function load() {
loading.value = true;
try {
const response = await http.get(endpoint(), { params: params() });
const data = apiData<any>(response);
const rows = Array.isArray(data) ? data : data.items || [];
items.value = rows;
hasNext.value = supportsPagination.value && rows.length >= pageLimit.value;
await loadProtectedImages();
} finally {
loading.value = false;
}
}
function groupNovels(rows: Row[]): WorkGroup[] {
// rows 来自 /novels/series (include_chapters=false),已经是系列数据
const q = search.value.trim().toLowerCase();
return rows
.filter((series) => {
if (!q) return true;
const title = String(series.series_title || "").toLowerCase();
const author = String(series.author || "").toLowerCase();
return title.includes(q) || author.includes(q);
})
.map((series) => {
const seriesId = String(series.series_id || "");
return {
id: `novel-${seriesId}`,
targetId: "",
seriesId,
title: series.series_title || "未命名小说",
coverUrl: resolveDisplayImage(series.cover_path),
badge: `${series.chapter_count || 0} 章`,
meta: [series.author, formatDate(series.last_viewed_at || series.last_read_at || series.updated_at)].filter(Boolean).join(" · "),
latest: "",
summary: "",
previewChapters: [],
};
});
}
function groupManga(rows: Row[]): WorkGroup[] {
return buildMangaSeriesGroups(rows).map(({ entry, first, latest, pageTotal, tags }) => ({
id: entry.seriesKey,
targetId: String(first?.id || ""),
seriesKey: entry.seriesKey,
title: entry.seriesTitle,
coverUrl: entry.coverUrl,
badge: `${pageTotal} 页`,
meta: [entry.author, first?.source_platform, formatDate(latest?.updated_at)].filter(Boolean).join(" · "),
latest: "",
summary: tags.slice(0, 5).join(" / "),
previewChapters: entry.chapters.slice(0, 4).map((chapter, index) => ({
id: chapter.id,
label: chapter.title || `第 ${index + 1} 话`,
})),
}));
}
function resolveDisplayImage(value: unknown) {
const text = typeof value === "string" ? value.trim() : "";
return text;
}
function galleryImage(item: Row) {
return resolveDisplayImage(item.thumbnail_url || item.image_url || item.thumbnail_path || item.file_path);
}
function displayUrl(id: unknown, raw: unknown) {
const text = resolveDisplayImage(raw);
if (!text) return "";
if (text.startsWith("http") || text.startsWith("blob:")) return text;
return protectedImageUrls.value[String(id)] || "";
}
function protectedRequestPath(path: string) {
if (path.startsWith("/api/v1")) return path.slice("/api/v1".length);
if (path.startsWith("/api/")) return path;
return "";
}
function revokeProtectedImages() {
Object.values(protectedImageUrls.value).forEach((url) => URL.revokeObjectURL(url));
protectedImageUrls.value = {};
}
async function loadProtectedImages() {
revokeProtectedImages();
const targets: Array<{ id: string; path: string }> = [];
if (props.kind === "gallery") {
for (const item of items.value) {
const path = galleryImage(item);
if (path && !path.startsWith("http")) targets.push({ id: String(item.id), path });
}
}
if (props.kind === "manga" || props.kind === "novels") {
for (const group of displayGroups.value) {
if (group.coverUrl && !group.coverUrl.startsWith("http")) {
targets.push({ id: group.id, path: group.coverUrl });
}
}
}
await Promise.all(targets.slice(0, 80).map(async (target) => {
const requestPath = protectedRequestPath(target.path);
if (!requestPath) return;
try {
const response = await http.get(requestPath, { responseType: "blob" });
protectedImageUrls.value[target.id] = URL.createObjectURL(response.data);
} catch {
// Thumbnail loading is best-effort; the card fallback stays visible.
}
}));
}
function timeOf(value: unknown) {
const time = Date.parse(String(value || ""));
return Number.isFinite(time) ? time : 0;
}
function formatDate(value: unknown) {
if (!value) return "";
const date = new Date(String(value));
if (Number.isNaN(date.getTime())) return "";
return `${date.getMonth() + 1}月${date.getDate()}日`;
}
function searchNow() {
if (searchTimer) {
clearTimeout(searchTimer);
searchTimer = null;
}
page.value = 1;
load();
}
function debounceSearch() {
if (searchTimer) {
clearTimeout(searchTimer);
}
searchTimer = setTimeout(() => {
searchNow();
}, 400);
}
function onlineStorageKey() {
return `sakura-online-sources:${props.kind}`;
}
function loadOnlineSources() {
if (props.kind !== "manga" && props.kind !== "novels") return;
onlineSourcesText.value = localStorage.getItem(onlineStorageKey()) || "";
}
function saveOnlineSources() {
if (props.kind !== "manga" && props.kind !== "novels") return;
localStorage.setItem(onlineStorageKey(), onlineSourcesText.value);
}
async function importSourceFile(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
onlineSourcesText.value = await file.text();
saveOnlineSources();
input.value = "";
}
async function runOnlineSearch() {
onlineError.value = "";
onlineResults.value = [];
if (!onlineQuery.value || !onlineSourcesText.value) return;
onlineLoading.value = true;
saveOnlineSources();
try {
const parsedSources = JSON.parse(onlineSourcesText.value);
const response = await http.post("/online-search", {
query: onlineQuery.value,
sources: parsedSources,
limit_sources: 40,
per_source_limit: 20,
}, {
params: { mode: props.kind === "manga" ? "manga" : "novel" },
timeout: 30000,
});
onlineResults.value = apiData<Row[]>(response);
} catch (err: any) {
onlineError.value = err?.response?.data?.detail || err?.message || "在线搜索失败,请检查 JSON 或源站状态。";
} finally {
onlineLoading.value = false;
}
}
function previousPage() {
if (page.value <= 1) return;
page.value -= 1;
load();
}
function nextPage() {
if (!hasNext.value) return;
page.value += 1;
load();
}
watch(
() => props.kind,
() => {
page.value = 1;
search.value = "";
onlineResults.value = [];
onlineError.value = "";
loadOnlineSources();
load();
},
);
onMounted(() => {
loadOnlineSources();
load();
});
onUnmounted(() => {
if (searchTimer) {
clearTimeout(searchTimer);
}
revokeProtectedImages();
});
</script>
@@ -0,0 +1,231 @@
<template>
<main class="content">
<header class="page-head">
<div>
<p class="eyebrow">在线内容</p>
<h1>在线搜索</h1>
<p class="muted">使用云端内置书源/漫画源,或导入自己的 Legado JSON 源。</p>
</div>
</header>
<section class="panel online-page-panel">
<div class="online-mode-row">
<button :class="{ primary: mode === 'novel' }" type="button" @click="setMode('novel')">小说</button>
<button :class="{ primary: mode === 'manga' }" type="button" @click="setMode('manga')">漫画</button>
</div>
<div class="online-page-controls">
<select v-model="selectedSourceUrl" @change="loadSelectedSource">
<option value="">选择云端内置源</option>
<option v-for="source in filteredPresetSources" :key="source.url" :value="source.url">
{{ source.name }}
</option>
</select>
<label class="button-like">
导入 JSON
<input class="hidden-input" type="file" accept=".json,application/json,text/plain" @change="importSourceFile" />
</label>
</div>
<form class="online-page-search" @submit.prevent="runSearch">
<input v-model.trim="query" :placeholder="mode === 'manga' ? '搜索在线漫画' : '搜索在线小说'" />
<button class="primary" type="submit" :disabled="loading || !query || !sourcesText">
{{ loading ? "搜索中..." : "搜索" }}
</button>
</form>
<div class="online-json-actions">
<p class="muted">{{ sourceHint }}</p>
<button type="button" class="ghost" @click="showSources = !showSources">
{{ showSources ? "收起源 JSON" : "展开源 JSON" }}
</button>
</div>
<textarea
v-if="showSources"
v-model="sourcesText"
class="source-json-input large"
placeholder="粘贴书源/漫画源 JSON,支持数组或 { sources: [...] }"
@blur="saveSources"
></textarea>
<p v-if="error" class="error">{{ error }}</p>
<p v-else class="muted">{{ statusText }}</p>
<div v-if="results.length" class="online-page-results">
<a
v-for="item in results"
:key="`${item.source_name}-${item.detail_url}`"
class="online-page-card"
:href="item.detail_url"
target="_blank"
rel="noreferrer"
>
<div class="online-page-cover" :class="{ placeholder: !item.cover_url }">
<img v-if="item.cover_url" :src="item.cover_url" alt="" loading="lazy" />
<span v-else>{{ mode === "manga" ? "漫" : "文" }}</span>
</div>
<div class="online-page-main">
<strong>{{ item.title || "未命名" }}</strong>
<p>{{ [item.author, item.source_name].filter(Boolean).join(" · ") || "在线来源" }}</p>
<span>{{ item.detail_url }}</span>
</div>
</a>
</div>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { apiData, http } from "../../api/http";
type SearchMode = "novel" | "manga";
type PresetSource = {
name: string;
mode: SearchMode;
url: string;
};
type OnlineResult = {
source_name: string;
source_url: string;
title: string;
author?: string | null;
cover_url?: string | null;
detail_url: string;
kind: string;
};
const mode = ref<SearchMode>("novel");
const query = ref("");
const sourcesText = ref("");
const selectedSourceUrl = ref("");
const presetSources = ref<PresetSource[]>([]);
const results = ref<OnlineResult[]>([]);
const loading = ref(false);
const error = ref("");
const showSources = ref(false);
const loadedSourceName = ref("");
const filteredPresetSources = computed(() => presetSources.value.filter((source) => source.mode === mode.value));
const sourceHint = computed(() => {
if (loadedSourceName.value) return `当前源:${loadedSourceName.value}`;
if (sourcesText.value.trim()) return "已导入自定义 JSON 源。";
return "请选择云端内置源,或导入/粘贴 JSON 源。";
});
const statusText = computed(() => {
if (loading.value) return "正在搜索,请稍候...";
if (results.value.length) return `找到 ${results.value.length} 条结果。`;
return mode.value === "manga" ? "输入关键词后搜索在线漫画。" : "输入关键词后搜索在线小说。";
});
function storageKey() {
return `sakura-online-page-sources:${mode.value}`;
}
function setMode(nextMode: SearchMode) {
if (mode.value === nextMode) return;
mode.value = nextMode;
}
function saveSources() {
localStorage.setItem(storageKey(), sourcesText.value);
}
function loadStoredSources() {
sourcesText.value = localStorage.getItem(storageKey()) || "";
loadedSourceName.value = sourcesText.value.trim() ? "本地保存源" : "";
}
async function loadPresetIndex() {
try {
const response = await fetch("/sources/source-index.json");
if (!response.ok) return;
const rows = await response.json();
presetSources.value = Array.isArray(rows) ? rows.filter(isPresetSource) : [];
if (!sourcesText.value.trim() && filteredPresetSources.value[0]) {
selectedSourceUrl.value = filteredPresetSources.value[0].url;
await loadSelectedSource();
}
} catch {
// 内置源索引不可用时,页面仍允许手动导入 JSON。
}
}
function isPresetSource(value: unknown): value is PresetSource {
const source = value as PresetSource;
return Boolean(source?.name && source?.url && (source.mode === "novel" || source.mode === "manga"));
}
async function loadSelectedSource() {
error.value = "";
const source = presetSources.value.find((item) => item.url === selectedSourceUrl.value);
if (!source) return;
try {
const response = await fetch(source.url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
sourcesText.value = await response.text();
loadedSourceName.value = source.name;
saveSources();
} catch (err: any) {
error.value = err?.message || "内置源加载失败。";
}
}
async function importSourceFile(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
sourcesText.value = await file.text();
selectedSourceUrl.value = "";
loadedSourceName.value = file.name;
saveSources();
input.value = "";
}
async function runSearch() {
error.value = "";
results.value = [];
if (!query.value || !sourcesText.value.trim()) return;
loading.value = true;
saveSources();
try {
const parsedSources = JSON.parse(sourcesText.value);
const response = await http.post(
"/online-search",
{
query: query.value,
sources: parsedSources,
limit_sources: 80,
per_source_limit: 20,
},
{
params: { mode: mode.value },
timeout: 45000,
},
);
results.value = apiData<OnlineResult[]>(response);
} catch (err: any) {
error.value = err?.response?.data?.detail || err?.message || "在线搜索失败,请检查 JSON 或源站状态。";
} finally {
loading.value = false;
}
}
watch(mode, async () => {
query.value = "";
results.value = [];
error.value = "";
selectedSourceUrl.value = "";
loadStoredSources();
const preset = filteredPresetSources.value[0];
if (!sourcesText.value.trim() && preset) {
selectedSourceUrl.value = preset.url;
await loadSelectedSource();
}
});
onMounted(async () => {
loadStoredSources();
await loadPresetIndex();
});
</script>
@@ -0,0 +1,7 @@
<template>
<main class="empty-page">
<h1>403</h1>
<p>你没有访问这个页面的权限。</p>
<RouterLink class="button-like" to="/app">返回首页</RouterLink>
</main>
</template>
@@ -0,0 +1,10 @@
<template>
<main class="auth-shell">
<section class="auth-panel">
<p class="eyebrow">Sakura Cloud</p>
<h1>找回密码</h1>
<p class="muted">当前版本请联系管理员重置密码。管理员重置后,旧 token 会立即失效。</p>
<RouterLink class="button-like" to="/login">返回登录</RouterLink>
</section>
</main>
</template>
@@ -0,0 +1,54 @@
<template>
<main class="auth-shell">
<section class="auth-panel">
<p class="eyebrow">Sakura Cloud</p>
<h1>登录</h1>
<form @submit.prevent="submit">
<label>
账号或邮箱
<input v-model.trim="form.username" autocomplete="username" required />
</label>
<label>
密码
<input v-model="form.password" type="password" autocomplete="current-password" required />
</label>
<label class="row small">
<input v-model="form.admin" type="checkbox" />
管理员登录
</label>
<button class="primary" :disabled="loading">{{ loading ? "登录中..." : "登录" }}</button>
</form>
<p v-if="error" class="error">{{ error }}</p>
<nav class="auth-links">
<RouterLink to="/register">注册账号</RouterLink>
<RouterLink to="/forgot-password">忘记密码</RouterLink>
</nav>
</section>
</main>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { authState, isAdmin, login } from "../../stores/auth";
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const error = ref("");
const form = reactive({ username: "", password: "", admin: false });
async function submit() {
error.value = "";
loading.value = true;
try {
await login(form.username, form.password, form.admin);
const redirect = String(route.query.redirect || "");
await router.push(redirect || (isAdmin(authState.user?.role) ? "/admin" : "/app"));
} catch {
error.value = "账号、密码或权限不正确";
} finally {
loading.value = false;
}
}
</script>
@@ -0,0 +1,7 @@
<template>
<main class="empty-page">
<h1>404</h1>
<p>页面不存在。</p>
<RouterLink class="button-like" to="/app">返回首页</RouterLink>
</main>
</template>
@@ -0,0 +1,40 @@
<template>
<main class="auth-shell">
<section class="auth-panel">
<p class="eyebrow">Sakura Cloud</p>
<h1>注册</h1>
<form @submit.prevent="submit">
<label>用户名<input v-model.trim="form.username" minlength="3" maxlength="50" required /></label>
<label>邮箱<input v-model.trim="form.email" type="email" required /></label>
<label>密码<input v-model="form.password" type="password" minlength="8" maxlength="128" required /></label>
<button class="primary" :disabled="loading">{{ loading ? "创建中..." : "创建账号" }}</button>
</form>
<p v-if="error" class="error">{{ error }}</p>
<nav class="auth-links"><RouterLink to="/login">已有账号,去登录</RouterLink></nav>
</section>
</main>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { register } from "../../stores/auth";
const router = useRouter();
const loading = ref(false);
const error = ref("");
const form = reactive({ username: "", email: "", password: "" });
async function submit() {
error.value = "";
loading.value = true;
try {
await register(form.username, form.email, form.password);
await router.push("/app");
} catch {
error.value = "注册失败,请检查用户名或邮箱是否已被使用";
} finally {
loading.value = false;
}
}
</script>
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
server: {
port: 5174,
proxy: {
"/api": {
target: "http://127.0.0.1:8000",
changeOrigin: true
}
}
}
});