feat: DramaBox 全量走 App 接口,清单可停止并避免卡死

分类按 App 翻页,精选走推荐接口。清单顶部显示进度,停止后不再拉新剧,已拿到的封面继续加载。列表只绘制可见卡片,避免大量剧目占满主线程。
This commit is contained in:
Nixevol
2026-10-24 03:03:27 +08:00
parent 241762451c
commit cea741eead
25 changed files with 2923 additions and 1070 deletions
+184 -34
View File
@@ -76,11 +76,23 @@ interface ProxySettings {
function emptyProxy(): ProxySettings {
return { mode: "off", scheme: "http", host: "", port: "", username: "", password: "" };
}
function normalizeProxy(value: Partial<ProxySettings> | null | undefined): ProxySettings {
const proxy = { ...emptyProxy(), ...(value || {}) };
if (proxy.mode !== "off" && proxy.mode !== "system" && proxy.mode !== "custom") proxy.mode = "off";
if (proxy.scheme !== "http" && proxy.scheme !== "socks5") proxy.scheme = "http";
proxy.host = String(proxy.host || "");
proxy.port = String(proxy.port || "");
proxy.username = String(proxy.username || "");
proxy.password = String(proxy.password || "");
return proxy;
}
const DEVICE_KEY = "rapt-device-settings";
const SESSION_DEVICE_KEY = "rapt-device";
const ACCOUNTS_KEY = "rapt-accounts";
const PLATFORM_KEY = "rapt-platform";
const DRAMABOX_LANG_KEY = "dramabox-language";
const DRAMABOX_DEVICE_KEY = "dramabox-device";
const themeOverrides: GlobalThemeOverrides = {
Form: {
@@ -108,6 +120,7 @@ const platformLabel = computed(() => {
const dramaboxLang = ref("th");
const dramaboxLangs = ref<{ label: string; value: string }[]>([]);
const accountBusy = ref(false);
const activeProxyUrl = ref("");
const profileError = ref("");
const method = ref<Method>("guest");
const email = ref("");
@@ -120,6 +133,7 @@ const error = ref("");
const token = ref("");
const profile = ref<Profile | null>(null);
const dramaboxLoggedIn = computed(() => profile.value?.has_login === "1");
const dramaboxDeviceReady = computed(() => devices.value.some((item) => item.state === "device"));
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
const playing = ref<{ id: string | number; title: string; image: string } | null>(null);
const progressCount = ref(0);
@@ -150,6 +164,8 @@ const downloadRef = ref<{
loadDirectory: () => Promise<void>;
} | null>(null);
const catalogQuery = ref("");
const catalogMaxPages = ref(300);
let catalogPagesTimer: number | null = null;
const mainMenu = computed(() => [
{ label: "视频清单", key: "download" },
{
@@ -192,7 +208,10 @@ function selectPlatform(key: string) {
platform.value = key;
localStorage.setItem(PLATFORM_KEY, key);
error.value = "";
if (key === "dramabox") void loadDramaboxLanguages();
if (key === "dramabox") {
void loadDramaboxLanguages();
void loadDevices();
}
}
function tokenKey() {
@@ -362,10 +381,7 @@ function loadSettings() {
settings.value.custom = { ...builtinDevice.value, ...data.custom };
}
if (data.proxy && typeof data.proxy === "object") {
const proxy = { ...emptyProxy(), ...data.proxy };
if (proxy.mode !== "off" && proxy.mode !== "system" && proxy.mode !== "custom") proxy.mode = "off";
if (proxy.scheme !== "http" && proxy.scheme !== "socks5") proxy.scheme = "http";
settings.value.proxy = proxy;
settings.value.proxy = normalizeProxy(data.proxy);
}
} catch {
settings.value.custom = { ...builtinDevice.value };
@@ -384,6 +400,50 @@ function normalizeWorkers(value: unknown) {
return count;
}
function normalizeCatalogPages(value: unknown) {
const count = Number(value);
if (!Number.isInteger(count) || count < 1) return 300;
return Math.min(count, 999);
}
async function loadCatalogSettings() {
if (platform.value !== "dramabox") return;
try {
const response = await fetch("/api/dramabox/catalog/settings");
if (!response.ok) return;
const payload = await response.json();
catalogMaxPages.value = normalizeCatalogPages(payload.max_pages);
} catch {
catalogMaxPages.value = 300;
}
}
async function saveCatalogMaxPages(value: number) {
const pages = normalizeCatalogPages(value);
catalogMaxPages.value = pages;
try {
const response = await fetch("/api/dramabox/catalog/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ max_pages: pages }),
});
if (!response.ok) return;
const payload = await response.json();
catalogMaxPages.value = normalizeCatalogPages(payload.max_pages);
} catch {
// 下次刷新会重新读取
}
}
function onCatalogMaxPages(value: number | null) {
if (value === null) return;
catalogMaxPages.value = normalizeCatalogPages(value);
if (catalogPagesTimer) window.clearTimeout(catalogPagesTimer);
catalogPagesTimer = window.setTimeout(() => {
void saveCatalogMaxPages(catalogMaxPages.value);
}, 400);
}
async function loadDownloadSettings() {
const response = await fetch(`${apiBase.value}/downloads/settings`);
if (!response.ok) return;
@@ -408,9 +468,16 @@ async function openSettings() {
watch(page, (value) => {
if (value === "settings") void enterSettings();
if (value === "profile" && platform.value === "dramabox") void loadDevices();
});
watch(
() => platform.value === "dramabox" && !!profile.value,
(ready) => {
if (ready) void loadCatalogSettings();
},
{ immediate: true },
);
// 打开页面时把本机保存的代理推给后端,避免进程重启后丢失。
async function applyProxy(proxy: ProxySettings) {
const response = await fetch("/api/proxy", {
method: "POST",
@@ -421,6 +488,22 @@ async function applyProxy(proxy: ProxySettings) {
if (!response.ok) {
throw new Error(typeof payload.detail === "string" ? payload.detail : "代理设置失败");
}
activeProxyUrl.value = typeof payload.url === "string" ? payload.url : "";
}
// 代理存在后台文件里。页面地址每次启动端口不同,不能只靠浏览器本地存储。
async function loadProxySettings() {
const response = await fetch("/api/proxy");
if (response.ok) {
const payload = await response.json().catch(() => ({}));
const server = normalizeProxy(payload);
if (server.mode !== "off") {
settings.value.proxy = server;
activeProxyUrl.value = typeof payload.url === "string" ? payload.url : "";
return;
}
}
if (settings.value.proxy.mode !== "off") await applyProxy(settings.value.proxy);
}
async function saveSettings() {
@@ -446,14 +529,20 @@ async function saveSettings() {
return;
}
const directory = draft.value.directory.trim();
if (!directory) {
settingsTab.value = "download";
settingsError.value = "请选择下载目录";
return;
}
settingsBusy.value = true;
try {
await applyProxy(proxy);
settings.value.proxy = copySettings(proxy);
localStorage.setItem(DEVICE_KEY, JSON.stringify({
adbMode: settings.value.adbMode,
custom: settings.value.custom,
proxy: settings.value.proxy,
}));
if (!directory) {
settingsTab.value = "download";
settingsError.value = "请选择下载目录";
return;
}
const response = await fetch(`${apiBase.value}/downloads/settings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -595,6 +684,7 @@ function profileText(key: keyof Profile) {
if (kind === "google") return "Google";
if (kind === "facebook") return "Facebook";
if (kind === "apple") return "Apple";
if (kind === "app") return "设备";
return kind ? String(profile.value?.loginType) : "—";
}
const value = profile.value?.[key];
@@ -617,12 +707,21 @@ function deviceLabel(item: Device) {
return `${item.model} · ${item.serial} · ${mark}`;
}
function rememberedSerial() {
try {
return localStorage.getItem(DRAMABOX_DEVICE_KEY) || "";
} catch {
return "";
}
}
function applyDeviceList(list: Device[]) {
devices.value = list;
const stillThere = devices.value.some((item) => item.serial === serial.value && item.state === "device");
if (!stillThere) {
const ready = devices.value.filter((item) => item.state === "device");
serial.value = ready.length === 1 ? ready[0].serial : null;
const remembered = ready.find((item) => item.serial === rememberedSerial());
serial.value = remembered?.serial || (ready.length === 1 ? ready[0].serial : null);
}
}
@@ -694,32 +793,35 @@ async function loginHuangdou() {
}
}
function errorText(exc: unknown, fallback: string) {
if (typeof exc === "string" && exc.trim()) return exc;
if (exc instanceof Error && exc.message) return exc.message;
return fallback;
}
async function loginDramaboxAccount() {
async function loginDramaboxAdb() {
const inside = Boolean(token.value);
error.value = "";
profileError.value = "";
if (inside) accountBusy.value = true;
else busy.value = true;
try {
if (!inTauri()) throw new Error("请在桌面程序里登录");
const { invoke } = await import("@tauri-apps/api/core");
const language = dramaboxLang.value || profile.value?.locale || "th";
const user = await invoke<Record<string, unknown>>("dramabox_login", { language });
localStorage.setItem(DRAMABOX_LANG_KEY, language);
const response = await fetch("/api/dramabox/login/account", {
if (!serial.value) await loadDevices();
if (!serial.value && error.value) throw new Error(error.value);
const ready = devices.value.filter((item) => item.state === "device");
const picked = serial.value || "";
if (!picked) {
throw new Error(
ready.length
? "请选择设备"
: "没有检测到已连接的设备。手机请打开 USB 调试;MuMu 请先点探测。",
);
}
serial.value = picked;
localStorage.setItem(DRAMABOX_DEVICE_KEY, picked);
localStorage.setItem(DRAMABOX_LANG_KEY, dramaboxLang.value);
const response = await fetch("/api/dramabox/login/adb", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ language, user }),
body: JSON.stringify({ serial: picked, language: dramaboxLang.value }),
});
const payload = await response.json();
if (!response.ok) {
throw new Error(typeof payload.detail === "string" ? payload.detail : "登录失败");
throw new Error(typeof payload.detail === "string" ? payload.detail : "读取登录失败");
}
token.value = payload.token;
profile.value = payload.profile;
@@ -729,7 +831,7 @@ async function loginDramaboxAccount() {
startLive();
}
} catch (exc) {
const message = errorText(exc, "登录失败");
const message = exc instanceof Error ? exc.message : "读取登录失败";
if (inside) profileError.value = message;
else error.value = message;
} finally {
@@ -946,13 +1048,16 @@ onMounted(async () => {
await loadDeviceDefaults();
loadSettings();
try {
await applyProxy(settings.value.proxy);
await loadProxySettings();
} catch {
error.value = "代理还没有生效,请重新打开设置并保存";
}
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
if (platform.value === "dramabox") await loadDramaboxLanguages();
if (platform.value === "dramabox") {
await loadDramaboxLanguages();
void loadDevices();
}
let saved = readSavedToken();
if (!saved && isolated.value) {
try {
@@ -1001,6 +1106,27 @@ onUnmounted(stopLive);
:options="mainMenu"
@update:value="page = $event"
/>
<div v-if="platform === 'dramabox' && page === 'download'" class="catalog-limit">
<div class="catalog-limit-label">
最大页数
<n-tooltip>
<template #trigger>
<span class="help-dot" tabindex="0">?</span>
</template>
每个分类最多翻这么多页。精选这类推荐流可能一直有新内容,到上限就会停下。改完后点刷新生效。
</n-tooltip>
</div>
<n-input-number
:value="catalogMaxPages"
class="catalog-limit-input"
size="small"
button-placement="both"
:min="1"
:max="999"
:precision="0"
@update:value="onCatalogMaxPages"
/>
</div>
<div class="user-nav" :class="{ active: page === 'profile' }">
<button type="button" class="user-nav-main" @click="page = 'profile'">
<n-avatar round :size="28" :src="avatarSrc" />
@@ -1107,8 +1233,8 @@ onUnmounted(stopLive);
<div class="profile-block-title">
<span>账号</span>
<span v-if="platform === 'dramabox'" class="profile-title-actions">
<n-tag size="small" :bordered="false" :type="dramaboxLoggedIn ? 'success' : 'default'">{{ dramaboxLoggedIn ? "已登录" : "未登录" }}</n-tag>
<n-button v-if="!dramaboxLoggedIn" size="tiny" secondary :loading="accountBusy" @click="loginDramaboxAccount">登录</n-button>
<n-tag size="small" :bordered="false" :type="dramaboxLoggedIn ? 'success' : 'default'">{{ dramaboxLoggedIn ? "已登录" : "访客" }}</n-tag>
<n-button size="tiny" secondary :loading="accountBusy" :disabled="!dramaboxDeviceReady" @click="loginDramaboxAdb">从设备登录</n-button>
</span>
</div>
<n-alert v-if="profileError" class="hint" type="error" :show-icon="false">{{ profileError }}</n-alert>
@@ -1148,6 +1274,13 @@ onUnmounted(stopLive);
<n-form-item v-if="platform === 'dramabox'" label="地区">
<n-select v-model:value="dramaboxLang" filterable :options="dramaboxLangs" placeholder="选择国家 / 语言" />
</n-form-item>
<n-form-item v-if="platform === 'dramabox'" label="设备">
<div class="device-line">
<n-select v-model:value="serial" :options="deviceOptions" :loading="devicesBusy" placeholder="请选择设备" />
<n-button :loading="devicesBusy" @click="loadDevices">刷新</n-button>
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
</div>
</n-form-item>
<template v-if="platform === 'rapt' && method === 'password'">
<n-form-item v-if="savedAccounts.length" label="已保存">
<div class="device-line">
@@ -1182,13 +1315,15 @@ onUnmounted(stopLive);
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
</div>
</n-form-item>
<n-text v-if="platform === 'dramabox' && !devicesBusy && devices.length === 0" class="hint" depth="3">当前没有可用设备,可先访客进入。</n-text>
<n-text v-if="platform === 'dramabox'" class="hint" depth="3">选好地区后点访客进入即可浏览。解锁内容和下载请先从设备登录。</n-text>
<n-text v-if="platform === 'rapt' && method === 'guest'" class="hint" depth="3">将注册一个新的游客账号,并读取它的个人信息。</n-text>
<n-text v-if="platform === 'rapt' && method === 'adb' && !devicesBusy && devices.length === 0" class="hint" depth="3">没有检测到已连接的设备。</n-text>
<n-text v-if="platform === 'rapt' && method === 'adb'" class="hint" depth="3">从已 root 的设备读取当前登录账号。未 root 的设备无法获取登录信息。默认同时读取这台设备的品牌、型号和系统版本,可在右下角设置里修改。</n-text>
<n-alert v-if="error" class="hint" type="error" :show-icon="false">{{ error }}</n-alert>
<div class="login-actions">
<n-button v-if="platform === 'dramabox'" attr-type="button" :loading="busy" @click="loginDramaboxAccount">登录</n-button>
<n-button type="primary" attr-type="submit" :loading="busy">{{ isolated ? "进入" : "登录" }}</n-button>
<n-button v-if="platform === 'dramabox'" attr-type="button" secondary :loading="busy" :disabled="!dramaboxDeviceReady" @click="loginDramaboxAdb">从设备登录</n-button>
<n-button type="primary" attr-type="submit" :loading="busy">{{ platform === "dramabox" ? "访客进入" : isolated ? "进入" : "登录" }}</n-button>
</div>
</n-form>
</div>
@@ -1284,6 +1419,21 @@ html { color-scheme: dark; }
font-size: 13px;
line-height: 1.2;
}
.catalog-limit {
flex: none;
margin: 12px 4px 0;
padding: 10px 8px 4px;
}
.catalog-limit-label {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
color: rgba(255, 255, 255, 0.72);
font-size: 13px;
}
.catalog-limit-input { width: 100%; }
.catalog-limit-input .n-input__input-el { text-align: center; }
.user-nav {
margin-top: auto;
display: flex;
+1 -1
View File
@@ -45,7 +45,7 @@ async function load() {
episodes.value = Array.isArray(payload.episodes) ? payload.episodes : [];
const first = episodes.value.find((item) => item.playable);
if (!first) {
error.value = "缓存和当前账号都没有可播放的集";
error.value = episodes.value.find((item) => item.locked_reason)?.locked_reason || "没有可播放的集";
return;
}
select(first);
+451 -81
View File
@@ -15,6 +15,24 @@ interface Section {
note: string;
items: Drama[];
loading: boolean;
page: number;
pages: number;
}
interface PageEvent {
key: string;
name: string;
note?: string;
items?: Drama[];
done?: boolean;
page?: number;
pages?: number;
}
interface CardSlot {
id: string;
item: Drama;
style: { width: string; height: string; transform: string };
}
const props = defineProps<{
@@ -25,10 +43,12 @@ const props = defineProps<{
}>();
const apiBase = computed(() => props.apiBase || "/api");
const sections = ref<Section[]>([]);
const sections = shallowRef<Section[]>([]);
const expanded = ref<string[]>([]);
const selected = ref<Set<string>>(new Set());
const selectedInSection = reactive<Record<string, number>>({});
const busy = ref(false);
const stopped = ref(false);
const error = ref("");
const query = ref("");
const searchHint = ref("");
@@ -42,9 +62,29 @@ const flashSerial = ref(0);
const directory = ref("");
const starting = ref(false);
const footError = ref("");
const coverStatus = ref<Record<string, "ready" | "failed">>({});
const coverStatus = reactive<Record<string, "ready" | "failed">>({});
const coverDone = ref(0);
const coverTotal = ref(0);
const scrollTop = ref(0);
const viewHeight = ref(800);
const gridWidth = ref(720);
const gridTops = ref<Record<string, number>>({});
const emit = defineEmits<{ started: []; play: [Drama] }>();
const scrollEl = ref<HTMLElement | null>(null);
const grids = new Map<string, HTMLElement>();
const gridBinders = new Map<string, (el: unknown) => void>();
let resizeObserver: ResizeObserver | null = null;
let measureFrame = 0;
let flushFrame = 0;
let pendingPages: PageEvent[] = [];
let coverQueue: string[] = [];
const coverQueued = new Set<string>();
let coverRunning = 0;
let coverToken = 0;
const COVER_CONCURRENCY = 2;
const GRID_GAP = 12;
const TITLE_HEIGHT = 52;
const MIN_CARD = 148;
function coverOf(image: string) {
if (!image) return "";
@@ -56,14 +96,81 @@ function coverOf(image: string) {
function coverState(image: string): "empty" | "loading" | "ready" | "failed" {
const src = coverOf(image);
if (!src) return "empty";
const status = coverStatus.value[src];
const status = coverStatus[src];
if (status === "ready" || status === "failed") return status;
return "loading";
}
function markCover(src: string, ok: boolean) {
if (!src || coverStatus.value[src]) return;
coverStatus.value = { ...coverStatus.value, [src]: ok ? "ready" : "failed" };
if (!src || coverStatus[src]) return;
coverStatus[src] = ok ? "ready" : "failed";
}
function onCoverError(event: Event, image: string) {
const target = event.target;
if (target instanceof HTMLImageElement && !target.isConnected) return;
markCover(coverOf(image), false);
}
function resetCovers() {
coverToken += 1;
coverQueue = [];
coverQueued.clear();
coverRunning = 0;
coverDone.value = 0;
coverTotal.value = 0;
for (const key of Object.keys(coverStatus)) delete coverStatus[key];
}
function enqueueCovers(items: Drama[]) {
const token = coverToken;
let added = 0;
for (const item of items) {
const src = coverOf(item.image);
if (!src || coverStatus[src] || coverQueued.has(src)) continue;
coverQueued.add(src);
coverQueue.push(src);
added += 1;
}
if (!added) return;
coverTotal.value += added;
pumpCovers(token);
}
function pumpCovers(token: number) {
while (coverRunning < COVER_CONCURRENCY && coverQueue.length) {
const src = coverQueue.shift();
if (!src) break;
coverRunning += 1;
void prefetchCover(src).then(
(ok) => settleCover(token, src, ok),
() => settleCover(token, src, false),
);
}
}
async function prefetchCover(src: string) {
if (src.startsWith("/api/")) {
const response = await fetch(src);
if (!response.ok) return false;
await response.arrayBuffer();
return true;
}
await new Promise<void>((resolve, reject) => {
const image = new Image();
image.onload = () => resolve();
image.onerror = () => reject(new Error("cover"));
image.src = src;
});
return true;
}
function settleCover(token: number, src: string, ok: boolean) {
if (token !== coverToken) return;
coverRunning = Math.max(0, coverRunning - 1);
markCover(src, ok);
coverDone.value += 1;
pumpCovers(token);
}
function isExpanded(key: string) {
@@ -74,10 +181,22 @@ function toggleExpanded(key: string) {
expanded.value = isExpanded(key)
? expanded.value.filter((item) => item !== key)
: [...expanded.value, key];
void nextTick(() => measure());
}
function selectedCount(section: Section) {
return section.items.filter((item) => selected.value.has(dramaKey(item.id))).length;
return selectedInSection[section.key] || 0;
}
function syncSelectedCounts() {
const chosen = selected.value;
for (const section of sections.value) {
let count = 0;
for (const item of section.items) {
if (chosen.has(dramaKey(item.id))) count += 1;
}
selectedInSection[section.key] = count;
}
}
function allChecked(section: Section) {
@@ -99,6 +218,7 @@ function toggleDrama(id: string | number, checked: boolean) {
if (checked) next.add(key);
else next.delete(key);
selected.value = next;
syncSelectedCounts();
}
function toggleSection(section: Section, checked: boolean) {
@@ -109,45 +229,123 @@ function toggleSection(section: Section, checked: boolean) {
else next.delete(key);
}
selected.value = next;
syncSelectedCounts();
}
function clearSelection() {
selected.value = new Set();
syncSelectedCounts();
}
function pruneSelection() {
const ids = new Set(sections.value.flatMap((section) => section.items.map((item) => dramaKey(item.id))));
selected.value = new Set([...selected.value].filter((id) => ids.has(id)));
syncSelectedCounts();
}
function publishSections() {
sections.value = sections.value.slice();
}
function showOutline(list: { key: string; name: string; note?: string; loading?: boolean }[]) {
for (const key of Object.keys(selectedInSection)) delete selectedInSection[key];
sections.value = list.map((item) => ({
key: item.key,
name: item.name,
note: item.note || "",
items: [],
loading: item.loading !== false,
page: 0,
pages: 0,
}));
}
function applyPage(event: { key: string; name: string; note?: string; items?: Drama[]; done?: boolean }) {
function applyPage(event: PageEvent) {
let section = sections.value.find((item) => item.key === event.key);
if (!section) {
section = { key: event.key, name: event.name, note: event.note || "", items: [], loading: !event.done };
section = {
key: event.key,
name: event.name,
note: event.note || "",
items: [],
loading: !event.done,
page: 0,
pages: 0,
};
sections.value.push(section);
}
if (event.note) section.note = event.note;
if (event.items?.length) section.items = section.items.concat(event.items);
if (event.page) section.page = event.page;
if (event.pages) section.pages = event.pages;
if (event.items?.length) {
section.items.push(...event.items);
enqueueCovers(event.items);
}
if (event.done) section.loading = false;
}
function scheduleFlush(generation: number) {
if (flushFrame) return;
flushFrame = requestAnimationFrame(() => {
flushFrame = 0;
if (generation !== catalogGeneration) {
pendingPages = [];
return;
}
const batch = pendingPages.splice(0, 6);
const extra: PageEvent[] = [];
for (const event of batch) {
const items = event.items || [];
const chunk = items.slice(0, 180);
const rest = items.slice(180);
applyPage({ ...event, items: chunk, done: rest.length ? false : event.done });
if (rest.length) extra.push({ ...event, items: rest });
}
if (extra.length) pendingPages.unshift(...extra);
publishSections();
void nextTick(() => measure());
if (pendingPages.length) scheduleFlush(generation);
});
}
function queuePage(event: PageEvent, generation: number) {
if (generation !== catalogGeneration) return;
pendingPages.push(event);
scheduleFlush(generation);
}
function waitFrame() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => resolve());
});
}
function finishSections() {
for (const section of sections.value) section.loading = false;
publishSections();
}
function stopLoad() {
if (!busy.value) return;
stopped.value = true;
catalogAbort?.abort();
finishSections();
busy.value = false;
}
async function reload(refresh = false) {
catalogAbort?.abort();
const current = new AbortController();
catalogAbort = current;
const generation = ++catalogGeneration;
pendingPages = [];
stopped.value = false;
error.value = "";
busy.value = true;
sections.value = [];
grids.clear();
gridBinders.clear();
resetCovers();
try {
const response = await fetch(`${apiBase.value}/catalog`, {
method: "POST",
@@ -155,6 +353,7 @@ async function reload(refresh = false) {
body: JSON.stringify({ token: props.token, device: props.device, refresh }),
signal: current.signal,
});
if (generation !== catalogGeneration) return;
if (!response.ok || !response.body) {
let message = "获取清单失败";
try {
@@ -168,8 +367,10 @@ async function reload(refresh = false) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let queued = 0;
while (true) {
const { done, value } = await reader.read();
if (generation !== catalogGeneration) return;
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
@@ -187,15 +388,27 @@ async function reload(refresh = false) {
continue;
}
if (event.type !== "page") continue;
applyPage(event);
queuePage(event, generation);
queued += 1;
if (queued >= 6) {
queued = 0;
await waitFrame();
if (generation !== catalogGeneration) return;
}
}
}
} catch (exc) {
if (exc instanceof DOMException && exc.name === "AbortError") return;
if (generation !== catalogGeneration) return;
error.value = exc instanceof Error ? exc.message : "获取清单失败";
for (const section of sections.value) section.loading = false;
finishSections();
} finally {
if (generation !== catalogGeneration) return;
let spins = 0;
while (generation === catalogGeneration && (pendingPages.length || flushFrame) && spins < 600) {
spins += 1;
await waitFrame();
}
if (generation === catalogGeneration) busy.value = false;
}
}
@@ -230,45 +443,103 @@ function finishFlash(key: string, serial: number, event: AnimationEvent) {
if (flashKey.value === key && flashSerial.value === serial) flashKey.value = "";
}
function cardInView(node: HTMLElement, scroller: HTMLElement) {
const card = node.getBoundingClientRect();
const view = scroller.getBoundingClientRect();
return card.top >= view.top && card.bottom <= view.bottom;
function layoutOf(section: Section) {
const width = Math.max(MIN_CARD, gridWidth.value);
const cols = Math.max(1, Math.floor((width + GRID_GAP) / (MIN_CARD + GRID_GAP)));
const cardWidth = (width - GRID_GAP * (cols - 1)) / cols;
const cardHeight = cardWidth * 4 / 3 + TITLE_HEIGHT;
const rowHeight = cardHeight + GRID_GAP;
const rows = section.items.length ? Math.ceil(section.items.length / cols) : 0;
const height = rows ? rows * rowHeight - GRID_GAP : 0;
return { cols, cardWidth, cardHeight, rowHeight, height };
}
function scrollCardIntoView(node: HTMLElement) {
function visibleSlots(section: Section): CardSlot[] {
const box = layoutOf(section);
const count = section.items.length;
if (!count) return [];
const gridTop = gridTops.value[section.key] ?? 0;
const top = scrollTop.value;
const bottom = top + Math.max(viewHeight.value, 1);
let startRow = Math.floor((top - gridTop) / box.rowHeight) - 1;
let endRow = Math.ceil((bottom - gridTop) / box.rowHeight) + 1;
const rowCount = Math.ceil(count / box.cols);
if (endRow < 0 || startRow >= rowCount) return [];
startRow = Math.max(0, startRow);
endRow = Math.min(rowCount, Math.max(startRow + 1, endRow));
const start = startRow * box.cols;
const end = Math.min(count, endRow * box.cols);
const slots: CardSlot[] = [];
for (let index = start; index < end; index += 1) {
const item = section.items[index];
const col = index % box.cols;
const row = Math.floor(index / box.cols);
slots.push({
id: dramaKey(item.id),
item,
style: {
width: `${box.cardWidth}px`,
height: `${box.cardHeight}px`,
transform: `translate(${col * (box.cardWidth + GRID_GAP)}px, ${row * box.rowHeight}px)`,
},
});
}
return slots;
}
function bindGrid(key: string, el: unknown) {
if (el instanceof HTMLElement) grids.set(key, el);
else grids.delete(key);
}
function gridBinder(key: string) {
let binder = gridBinders.get(key);
if (!binder) {
binder = (el: unknown) => bindGrid(key, el);
gridBinders.set(key, binder);
}
return binder;
}
function measure() {
const scroller = scrollEl.value;
return new Promise<void>((resolve) => {
if (!scroller) {
resolve();
return;
}
node.scrollIntoView({ block: "center", behavior: "smooth" });
let last = scroller.scrollTop;
let stable = 0;
let moved = false;
const started = performance.now();
const tick = () => {
const current = scroller.scrollTop;
if (Math.abs(current - last) >= 0.5) {
moved = true;
stable = 0;
} else {
stable += 1;
}
last = current;
const arrived = cardInView(node, scroller);
const stopped = moved ? stable >= 4 : stable >= 8;
if ((stopped && arrived) || performance.now() - started > 3000) {
resolve();
return;
}
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
if (!scroller) return;
const nextTop = scroller.scrollTop;
const nextHeight = scroller.clientHeight || viewHeight.value;
let nextWidth = 0;
const tops: Record<string, number> = {};
const scrollRect = scroller.getBoundingClientRect();
for (const [key, el] of grids) {
const rect = el.getBoundingClientRect();
tops[key] = nextTop + rect.top - scrollRect.top;
if (el.clientWidth > 0) nextWidth = el.clientWidth;
}
if (!nextWidth) nextWidth = Math.max(MIN_CARD, scroller.clientWidth - 80);
scrollTop.value = nextTop;
viewHeight.value = nextHeight;
if (nextWidth !== gridWidth.value) gridWidth.value = nextWidth;
gridTops.value = tops;
}
function onScroll() {
if (measureFrame) return;
measureFrame = requestAnimationFrame(() => {
measureFrame = 0;
measure();
});
}
function scrollIndexIntoView(sectionKey: string, index: number) {
const section = sections.value.find((item) => item.key === sectionKey);
const scroller = scrollEl.value;
if (!section || !scroller || index < 0) return;
const box = layoutOf(section);
const row = Math.floor(index / box.cols);
const top = (gridTops.value[sectionKey] ?? 0) + row * box.rowHeight;
scroller.scrollTop = Math.max(0, top - 72);
measure();
}
async function find(keyword = query.value) {
const generation = ++revealGeneration;
const text = keyword.trim();
@@ -303,23 +574,65 @@ async function find(keyword = query.value) {
}
await nextTick();
if (generation !== revealGeneration) return;
const node = scrollEl.value?.querySelector(`[data-card="${key}"]`);
if (node instanceof HTMLElement) await scrollCardIntoView(node);
measure();
const section = sections.value.find((item) => item.key === hit.sectionKey);
const index = section?.items.findIndex((item) => dramaKey(item.id) === dramaKey(hit.id)) ?? -1;
scrollIndexIntoView(hit.sectionKey, index);
await nextTick();
if (generation !== revealGeneration) return;
if (node instanceof HTMLElement && scrollEl.value && !cardInView(node, scrollEl.value)) {
node.scrollIntoView({ block: "center", behavior: "auto" });
}
flashSerial.value += 1;
flashKey.value = "";
await nextTick();
if (generation !== revealGeneration) return;
flashKey.value = key;
}
const loadedCount = computed(() =>
sections.value.reduce((sum, section) => sum + (section.key === "search" ? 0 : section.items.length), 0),
);
const coverPending = computed(() => coverTotal.value > 0 && coverDone.value < coverTotal.value);
const showProgress = computed(() => busy.value || stopped.value || coverPending.value);
const progress = computed(() => {
if (!busy.value && coverPending.value && coverTotal.value) {
return Math.min(100, Math.round((coverDone.value / coverTotal.value) * 100));
}
let got = 0;
let total = 0;
for (const section of sections.value) {
if (!section.pages || section.key === "search") continue;
total += section.pages;
got += section.loading ? Math.min(section.page, section.pages) : section.pages;
}
if (!total) return busy.value ? 0 : 100;
return Math.min(100, Math.round((got / total) * 100));
});
const progressText = computed(() => {
const count = loadedCount.value;
if (busy.value) return `已加载 ${count} 部`;
if (stopped.value && coverPending.value) {
return `已停止,共 ${count} 部,封面 ${coverDone.value}/${coverTotal.value}`;
}
if (stopped.value) return `已停止,共 ${count} 部`;
if (coverPending.value) return `封面 ${coverDone.value}/${coverTotal.value}`;
return "";
});
onMounted(() => {
void reload();
void loadDirectory();
resizeObserver = new ResizeObserver(() => onScroll());
if (scrollEl.value) resizeObserver.observe(scrollEl.value);
measure();
});
defineExpose({ reload, busy, find, searchHint, clearSearch, loadDirectory });
onBeforeUnmount(() => {
catalogGeneration += 1;
coverToken += 1;
pendingPages = [];
catalogAbort?.abort();
resizeObserver?.disconnect();
if (measureFrame) cancelAnimationFrame(measureFrame);
if (flushFrame) cancelAnimationFrame(flushFrame);
});
defineExpose({ reload, busy, stopLoad, showProgress, progress, progressText, find, searchHint, clearSearch, loadDirectory });
async function searchRemote(keyword: string, generation: number) {
searchHint.value = "正在搜索";
@@ -349,9 +662,15 @@ async function searchRemote(keyword: string, generation: number) {
note: items.length ? "" : "没有搜索结果",
items,
loading: false,
page: 0,
pages: 0,
});
}
enqueueCovers(items);
publishSections();
syncSelectedCounts();
if (!isExpanded(key)) expanded.value = [...expanded.value, key];
void nextTick(() => measure());
} catch {
if (generation === revealGeneration) searchHint.value = "搜索失败";
}
@@ -412,8 +731,25 @@ async function startDownload() {
<template>
<div class="download-page">
<div v-if="showProgress" class="load-strip">
<n-progress
class="load-strip-bar"
type="line"
:percentage="progress"
:show-indicator="false"
:processing="busy || coverPending"
:height="8"
/>
<n-text class="load-strip-text" depth="3">{{ progressText }}</n-text>
<n-tooltip v-if="busy">
<template #trigger>
<n-button size="small" secondary @click="stopLoad">停止</n-button>
</template>
停止后不再获取新剧目,已拿到的封面会继续加载
</n-tooltip>
</div>
<div class="download-body">
<div ref="scrollEl" class="download-scroll">
<div ref="scrollEl" class="download-scroll" @scroll="onScroll">
<n-alert v-if="error" class="catalog-error" type="error" :show-icon="false">{{ error }}</n-alert>
<section v-for="section in sections" :key="section.key" class="category">
<div class="category-bar">
@@ -426,49 +762,56 @@ async function startDownload() {
{{ isExpanded(section.key) ? "收起" : "展开" }}
</n-tooltip>
<n-text strong>{{ section.name }}</n-text>
<span v-if="section.loading" class="category-spin" aria-hidden="true"></span>
<n-text depth="3">{{ section.items.length }} 部</n-text>
<n-text depth="3">已选 {{ selectedCount(section) }}</n-text>
<span class="bar-gap"></span>
<span v-if="section.loading" class="category-spin" aria-label="正在加载"></span>
<n-tooltip placement="top">
<template #trigger>
<n-checkbox
:checked="allChecked(section)"
:indeterminate="someChecked(section)"
:disabled="section.items.length === 0"
:disabled="section.loading || section.items.length === 0"
@update:checked="toggleSection(section, $event)"
>
全选
{{ section.loading ? "加载中" : allChecked(section) ? "取消全选" : "全选" }}
</n-checkbox>
</template>
{{ allChecked(section) ? "取消全选" : "全选" }}
{{ section.loading ? "这一栏还在加载" : allChecked(section) ? "取消全选" : "全选" }}
</n-tooltip>
</div>
<div v-if="isExpanded(section.key)" class="category-body">
<n-text v-if="section.note" depth="3">{{ section.note }}</n-text>
<n-text v-else-if="!section.loading && section.items.length === 0" depth="3">暂无剧集</n-text>
<div v-else class="drama-grid">
<div
v-else
class="drama-grid"
:style="{ height: `${layoutOf(section).height}px` }"
:ref="gridBinder(section.key)"
>
<article
v-for="item in section.items"
:key="item.id"
v-for="slot in visibleSlots(section)"
:key="slot.id"
class="drama-card"
:data-card="cardKey(section.key, item.id)"
@click="toggleDrama(item.id, !selected.has(dramaKey(item.id)))"
:data-card="cardKey(section.key, slot.item.id)"
:style="slot.style"
@click="toggleDrama(slot.item.id, !selected.has(dramaKey(slot.item.id)))"
>
<div class="cover" :class="coverState(item.image)">
<span v-if="coverState(item.image) === 'loading'" class="cover-spin" aria-hidden="true"></span>
<div class="cover" :class="coverState(slot.item.image)">
<span v-if="coverState(slot.item.image) === 'loading'" class="cover-spin" aria-hidden="true"></span>
<img
v-if="coverOf(item.image)"
:src="coverOf(item.image)"
:alt="item.title"
@load="markCover(coverOf(item.image), true)"
@error="markCover(coverOf(item.image), false)"
v-if="coverOf(slot.item.image)"
:src="coverOf(slot.item.image)"
:alt="slot.item.title"
decoding="async"
@load="markCover(coverOf(slot.item.image), true)"
@error="onCoverError($event, slot.item.image)"
/>
<span v-if="item.corner || item.locked || item.limitedFree" class="cover-tag">{{ item.corner || (item.limitedFree ? "限免" : item.payType || "付费") }}</span>
<div v-if="coverState(item.image) !== 'loading'" class="cover-play-layer">
<span v-if="slot.item.corner || slot.item.locked || slot.item.limitedFree" class="cover-tag">{{ slot.item.corner || (slot.item.limitedFree ? "限免" : slot.item.payType || "付费") }}</span>
<div v-if="coverState(slot.item.image) !== 'loading'" class="cover-play-layer">
<n-tooltip placement="top">
<template #trigger>
<button type="button" class="cover-play" aria-label="播放" @click.stop="emit('play', item)">
<button type="button" class="cover-play" aria-label="播放" @click.stop="emit('play', slot.item)">
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M9 7.5v9l8-4.5z" /></svg>
</button>
</template>
@@ -479,17 +822,17 @@ async function startDownload() {
<div class="pick" @click.stop>
<n-tooltip placement="left">
<template #trigger>
<n-checkbox :checked="selected.has(dramaKey(item.id))" @update:checked="toggleDrama(item.id, $event)" />
<n-checkbox :checked="selected.has(dramaKey(slot.item.id))" @update:checked="toggleDrama(slot.item.id, $event)" />
</template>
{{ selected.has(dramaKey(item.id)) ? "取消选择" : "选择" }}
{{ selected.has(dramaKey(slot.item.id)) ? "取消选择" : "选择" }}
</n-tooltip>
</div>
<div class="drama-title">{{ item.title }}</div>
<div class="drama-title">{{ slot.item.title }}</div>
<div
v-if="flashKey === cardKey(section.key, item.id)"
v-if="flashKey === cardKey(section.key, slot.item.id)"
:key="flashSerial"
class="drama-mask"
@animationend="finishFlash(cardKey(section.key, item.id), flashSerial, $event)"
@animationend="finishFlash(cardKey(section.key, slot.item.id), flashSerial, $event)"
></div>
</article>
</div>
@@ -514,6 +857,18 @@ async function startDownload() {
<style>
.download-page { height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.load-strip {
flex: none;
display: flex;
align-items: center;
gap: 12px;
min-height: 44px;
padding: 8px 20px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
background: #18181c;
}
.load-strip-bar { width: 180px; flex: none; }
.load-strip-text { flex: 1; min-width: 0; }
.download-body { position: relative; flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.download-scroll { flex: 1; min-height: 0; overflow: auto; padding: 0 0 12px; }
.download-foot {
@@ -561,12 +916,15 @@ async function startDownload() {
.chevron.open { transform: rotate(90deg); }
.category-body { padding: 8px 20px 12px 60px; }
.drama-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(148px, 1fr));
gap: 12px;
position: relative;
width: 100%;
}
.drama-card {
position: relative;
position: absolute;
top: 0;
left: 0;
display: flex;
flex-direction: column;
border-radius: 8px;
overflow: hidden;
background: rgba(255, 255, 255, 0.04);
@@ -574,10 +932,11 @@ async function startDownload() {
}
.cover {
position: relative;
flex: 1;
min-height: 0;
display: flex;
align-items: center;
justify-content: center;
aspect-ratio: 3 / 4;
background: transparent;
}
.cover-spin {
@@ -658,5 +1017,16 @@ async function startDownload() {
0%, 100% { opacity: 0; }
50% { opacity: 1; }
}
.drama-title { padding: 8px; font-size: 13px; line-height: 1.35; }
.drama-title {
flex: none;
height: 52px;
box-sizing: border-box;
padding: 8px;
overflow: hidden;
font-size: 13px;
line-height: 1.35;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>