Files
SakuraHub/sakura_admin_web/src/views/app/UserListPage.vue
T
2026-11-16 20:45:22 +08:00

415 lines
14 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<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>