feat: 按账号调度自动学习并让首页实时跟上状态

This commit is contained in:
2026-11-16 01:14:36 +08:00
parent 158578d17c
commit 7f0466b0f6
31 changed files with 2699 additions and 631 deletions
+3 -6
View File
@@ -167,12 +167,9 @@ onUnmounted(() => stopPoll());
<template>
<section class="page admin-page">
<header class="page-head">
<div>
<h2>课程清单</h2>
<p v-if="!loading && !errorText">
{{ total }} 门<template v-if="syncedAt"> · 更新于 {{ formatTime(syncedAt) }}</template>
</p>
</div>
<p v-if="!loading && !errorText">
{{ total }} 门<template v-if="syncedAt"> · 更新于 {{ formatTime(syncedAt) }}</template>
</p>
<form class="course-search" @submit.prevent="search">
<n-tooltip>
<template #trigger>
+4 -7
View File
@@ -251,13 +251,10 @@ onUnmounted(() => stopPoll());
<template>
<section class="page admin-page">
<header class="page-head">
<div>
<h2>代理</h2>
<p v-if="!loading">
可用 {{ alive }} · 失效 {{ dead }}
<template v-if="fetchedAt"> · 更新于 {{ formatTime(fetchedAt) }}</template>
</p>
</div>
<p v-if="!loading">
可用 {{ alive }} · 失效 {{ dead }}
<template v-if="fetchedAt"> · 更新于 {{ formatTime(fetchedAt) }}</template>
</p>
<form class="course-search" @submit.prevent="search">
<n-tooltip>
<template #trigger>
+11 -12
View File
@@ -93,16 +93,16 @@ async function save() {
return;
}
if (hbMode.value === "manual") {
if (invalidInteger(hbVideo.value, 10, 300)) {
errorText.value = "视频心跳间隔须为 10 到 300 的整数";
if (invalidInteger(hbVideo.value, 0, 300)) {
errorText.value = "视频心跳间隔须为 0 到 300 的整数";
return;
}
if (invalidInteger(hbDocument.value, 30, 600)) {
errorText.value = "文档心跳间隔须为 30 到 600 的整数";
if (invalidInteger(hbDocument.value, 0, 600)) {
errorText.value = "文档心跳间隔须为 0 到 600 的整数";
return;
}
if (invalidInteger(hbScorm.value, 30, 600)) {
errorText.value = "Scorm 心跳间隔须为 30 到 600 的整数";
if (invalidInteger(hbScorm.value, 0, 600)) {
errorText.value = "Scorm 心跳间隔须为 0 到 600 的整数";
return;
}
}
@@ -158,12 +158,11 @@ async function save() {
<section class="page admin-page">
<form class="settings-form" @submit.prevent="save">
<header class="page-head">
<h2>系统配置</h2>
<n-button type="primary" attr-type="submit" :loading="saving" :disabled="!loaded">保存</n-button>
</header>
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
<n-alert v-else-if="successText" class="admin-alert" type="success">{{ successText }}</n-alert>
<div class="admin-scroll settings-stack">
<div class="settings-stack">
<p v-if="loading && !loaded" class="admin-status">正在获取</p>
<template v-else-if="loaded">
<section class="panel-card">
@@ -202,19 +201,19 @@ async function save() {
<template v-else>
<n-form-item label="视频">
<div class="target-control">
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="10" :max="300" :precision="0" />
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="0" :max="300" :precision="0" />
<span class="target-unit">秒</span>
</div>
</n-form-item>
<n-form-item label="文档">
<div class="target-control">
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="30" :max="600" :precision="0" />
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="0" :max="600" :precision="0" />
<span class="target-unit">秒</span>
</div>
</n-form-item>
<n-form-item label="Scorm">
<div class="target-control">
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="30" :max="600" :precision="0" />
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="0" :max="600" :precision="0" />
<span class="target-unit">秒</span>
</div>
</n-form-item>
@@ -231,7 +230,7 @@ async function save() {
</n-radio-group>
</n-form-item>
</n-form>
<p class="form-hint">学时历史按倒序分页统计到上个月为止</p>
<p class="form-hint">首页、学时历史和达标判断使用同一来源</p>
</section>
<section class="panel-card">
<h3>管理员</h3>
+13 -5
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NSelect, NSwitch, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, HelpCircleOutline, PauseOutline, PlayOutline, SettingsOutline, WarningOutline } from "@vicons/ionicons5";
import { dayOptions, workerHint, workerOptions } from "../../shared/studyFields";
@@ -19,6 +19,7 @@ interface UserRow {
study_start_hour: number;
study_start_minute: number;
study_start_second: number;
study_schedule_enabled: boolean;
course_workers: number;
study_paused: boolean;
study_ignore_window: boolean;
@@ -54,6 +55,7 @@ const startDay = ref<number | null>(1);
const startHour = ref<number | null>(0);
const startMinute = ref<number | null>(0);
const startSecond = ref<number | null>(0);
const scheduleEnabled = ref(true);
const workersValue = ref<number | null>(1);
const proxyScheme = ref("off");
const proxyHost = ref("");
@@ -142,6 +144,7 @@ function asUser(value: unknown): UserRow | null {
study_start_hour: typeof value.study_start_hour === "number" ? value.study_start_hour : 0,
study_start_minute: typeof value.study_start_minute === "number" ? value.study_start_minute : 0,
study_start_second: typeof value.study_start_second === "number" ? value.study_start_second : 0,
study_schedule_enabled: value.study_schedule_enabled !== false,
course_workers: typeof value.course_workers === "number" ? value.course_workers : 1,
study_paused: value.study_paused === true,
study_ignore_window: value.study_ignore_window === true,
@@ -388,6 +391,7 @@ function resetSettingsForm() {
startHour.value = 0;
startMinute.value = 0;
startSecond.value = 0;
scheduleEnabled.value = true;
workersValue.value = 1;
proxyScheme.value = "off";
proxyHost.value = "";
@@ -404,6 +408,7 @@ function applyRowSettings(row: UserRow) {
startHour.value = row.study_start_hour;
startMinute.value = row.study_start_minute;
startSecond.value = row.study_start_second;
scheduleEnabled.value = row.study_schedule_enabled !== false;
workersValue.value = row.course_workers;
}
@@ -475,6 +480,7 @@ async function saveSettings() {
hour: startHour.value,
minute: startMinute.value,
second: startSecond.value,
schedule_enabled: scheduleEnabled.value,
workers: workersValue.value,
scheme: proxyScheme.value,
host: proxyHost.value.trim(),
@@ -585,7 +591,6 @@ onMounted(() => {
<template>
<section class="page admin-page">
<header class="page-head">
<h2>用户管理</h2>
<div class="page-head-actions">
<n-tooltip>
<template #trigger>
@@ -712,16 +717,19 @@ onMounted(() => {
<span class="target-unit">分钟</span>
</div>
</n-form-item>
<n-form-item label="定时开启">
<n-switch v-model:value="scheduleEnabled" size="small" />
</n-form-item>
<n-form-item label="定时启动">
<div class="target-control start-control">
<n-select id="admin-start-day" v-model:value="startDay" :options="dayOptions" class="day-select" />
<n-tooltip v-if="startDay === 1" placement="top">
<n-select id="admin-start-day" v-model:value="startDay" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
<n-tooltip v-if="scheduleEnabled && startDay === 1" placement="top">
<template #trigger>
<n-icon class="day-warn"><WarningOutline /></n-icon>
</template>
不推荐使用
</n-tooltip>
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" />
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" :disabled="!scheduleEnabled" />
</div>
</n-form-item>
<n-form-item>
+34 -35
View File
@@ -10,9 +10,17 @@ interface HistoryItem {
path: string;
}
interface HistoryHours {
year_hours: string | number | null;
month_hours: string | number | null;
today_hours: string | number | null;
total_hours: string | number | null;
}
type SectionState = "loading" | "ready" | "error";
const items = ref<HistoryItem[] | null>(null);
const hours = ref<HistoryHours | null>(null);
const state = ref<SectionState>("loading");
const errorText = ref("");
const refreshing = ref(false);
@@ -40,6 +48,20 @@ function asItem(value: unknown): HistoryItem | null {
};
}
function asHour(value: unknown): string | number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string") return value;
return null;
}
function amount(value: string | number | null | undefined) {
if (value === null || value === undefined || value === "") return "—";
const numeric = Number(value);
if (!Number.isFinite(numeric)) return String(value);
if (Number.isInteger(numeric)) return String(numeric);
return String(value);
}
async function load() {
if (busy) return;
busy = true;
@@ -47,7 +69,7 @@ async function load() {
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/history");
const payload = await response.json().catch(() => ({}));
const payload = await response.json().catch(() => ({})) as Record<string, unknown>;
if (!response.ok) {
if (!hadData) {
errorText.value = failureText(payload, "学时历史没有获取到。");
@@ -62,6 +84,12 @@ async function load() {
if (item) parsed.push(item);
}
items.value = parsed;
hours.value = {
year_hours: asHour(payload.year_hours),
month_hours: asHour(payload.month_hours),
today_hours: asHour(payload.today_hours),
total_hours: asHour(payload.total_hours),
};
errorText.value = "";
state.value = "ready";
const maxPage = Math.max(1, Math.ceil(parsed.length / pageSize.value));
@@ -86,42 +114,13 @@ function refresh() {
});
}
function beijingParts(now = new Date()) {
const fmt = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Shanghai",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const mapped = Object.fromEntries(fmt.formatToParts(now).map((part) => [part.type, part.value]));
return { y: Number(mapped.year), m: Number(mapped.month), d: Number(mapped.day) };
}
function stampParts(text: string) {
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(text.trim());
if (!match) return null;
return { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) };
}
function sumMinutes(filter: (stamp: { y: number; m: number; d: number }) => boolean) {
const rows = items.value ?? [];
let total = 0;
for (const item of rows) {
if (typeof item.minutes !== "number") continue;
const stamp = stampParts(item.studied_at);
if (!stamp) continue;
if (filter(stamp)) total += item.minutes;
}
return total;
}
const historyFacts = computed(() => {
const now = beijingParts();
const current = hours.value;
return [
{ label: "总学时", value: sumMinutes(() => true) },
{ label: "本年学时", value: sumMinutes((stamp) => stamp.y === now.y) },
{ label: "本月学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m) },
{ label: "本日学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m && stamp.d === now.d) },
{ label: "总学时", value: current ? amount(current.total_hours) : "" },
{ label: "本年学时", value: current ? amount(current.year_hours) : "" },
{ label: "本月学时", value: current ? amount(current.month_hours) : "" },
{ label: "本日学时", value: current ? amount(current.today_hours) : "" },
];
});
+379 -162
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NTimePicker, NTooltip } from "naive-ui";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, HelpCircleOutline, PlayOutline, RefreshOutline, StopOutline, WarningOutline } from "@vicons/ionicons5";
import { dayOptions, workerHint, workerOptions } from "../../shared/studyFields";
@@ -23,6 +23,8 @@ interface StudyWorker {
progress: number;
interval: number;
heartbeat_at: number;
sent: number;
total: number;
ok: boolean;
}
@@ -35,18 +37,27 @@ const summaryError = ref("");
const refreshing = ref(false);
let refreshRunning = false;
let busy = false;
let studyPoll = 0;
let studyTick = 0;
let studySocket: WebSocket | null = null;
let studyReconnect = 0;
let studyPing = 0;
let studyFallback = 0;
let studyBackoff = 1000;
let studyClosed = false;
const nowTick = ref(Date.now());
const monthlyTarget = ref<number | null>(null);
const targetLoaded = ref(false);
let targetSaveTimer: ReturnType<typeof setTimeout> | undefined;
const scheduleSaving = ref(false);
const scheduleError = ref("");
const studyControl = ref({
started: false,
paused: false,
ignore_window: false,
window_open: false,
hours_met: false,
schedule_enabled: true,
active: false,
state: "",
course: "",
@@ -56,19 +67,52 @@ const studyControl = ref({
const studyBusy = ref(false);
const studyError = ref("");
const studyingWorkers = computed(() => (
studyControl.value.workers.filter((row) => row.course.trim() && workerPercent(row) < 100)
));
const countdownOn = computed(() => (
studyingWorkers.value.some((row) => row.interval > 0 && row.heartbeat_at > 0)
));
const studyFailed = computed(() => {
const state = studyControl.value.state;
return state === "会话失效" || state === "学习失败";
});
const monthProgress = computed(() => {
const match = String(summary.value?.month_hours ?? "").match(/(\d+)/);
const current = match ? Number(match[1]) : 0;
const target = monthlyTarget.value ?? 0;
const pct = target > 0 ? Math.min(100, Math.round((current * 100) / target)) : 0;
return { current, target, pct };
});
const studyLabel = computed(() => {
const state = studyControl.value.state;
const course = studyControl.value.course;
if (state === "已达标") return "本月目标已达到";
const message = studyControl.value.message.trim();
if (studyControl.value.hours_met || state === "已达标") return "本月目标已达到";
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
if (studyControl.value.active) {
return `正在学习:${course || state || "准备中"}`;
}
if (studyControl.value.started) return "任务已开始,等待执行";
if (studyControl.value.message) return studyControl.value.message;
if (state === "已学完") return "课程已学完";
if (studyFailed.value) return message || state;
if (state === "准备") return "正在连接学习平台";
if (studyingWorkers.value.length) return studyControl.value.course || "学习中";
if (state === "学习中") return "正在领取课程";
if (studyControl.value.active || studyControl.value.started) return "正在启动学习任务";
if (!studyControl.value.schedule_enabled) return "未开启定时自动学习";
if (message && !message.startsWith("下一次") && !message.startsWith("运行中")) return message;
return "未到开始时间";
});
const studyHint = computed(() => {
if (studyingWorkers.value.length) return "";
if (studyControl.value.hours_met) return "达到本月目标后不能再开始。改大目标并保存后才会再启动。";
if (studyFailed.value) return "点立即开始或保存定时配置会再启动。";
if (studyControl.value.started || studyControl.value.active) return "开始后会列出正在学的课。";
if (!studyControl.value.schedule_enabled) return "关闭定时后,只能点立即开始。";
return "到点后会自动开始。保存定时配置时,若已过点且未达标也会立刻启动。";
});
function amount(value: string | number | null | undefined) {
if (value === null || value === undefined || value === "") return "—";
const numeric = Number(value);
@@ -109,6 +153,8 @@ function asWorkers(value: unknown): StudyWorker[] {
progress: typeof row.progress === "number" ? row.progress : 0,
interval: typeof row.interval === "number" ? row.interval : 0,
heartbeat_at: typeof row.heartbeat_at === "number" ? row.heartbeat_at : 0,
sent: typeof row.sent === "number" ? row.sent : 0,
total: typeof row.total === "number" ? row.total : 0,
ok: row.ok !== false,
});
}
@@ -125,11 +171,25 @@ function workerTitle(row: StudyWorker) {
return "准备";
}
function showHeartbeat(row: StudyWorker) {
return row.interval > 0 && row.heartbeat_at > 0;
}
function workerCount(row: StudyWorker) {
if (row.total > 0) return `${row.sent}/${row.total}`;
if (row.sent > 0) return `${row.sent}/—`;
return "—";
}
function heartbeatLeft(row: StudyWorker) {
void nowTick.value;
if (!row.heartbeat_at) return "—";
const left = Math.max(0, Math.ceil(row.heartbeat_at - Date.now() / 1000));
return `${left}s`;
const now = Date.now() / 1000;
const cycle = Math.max(0, row.interval);
let left = row.heartbeat_at - now;
if (left < 0 && cycle > 0) {
left = cycle - ((now - row.heartbeat_at) % cycle);
}
return `${Math.max(0, Math.ceil(left))}s`;
}
async function loadSummary() {
@@ -181,28 +241,12 @@ async function loadTarget() {
} catch { /* 静默 */ }
}
function saveTarget(value: number | null) {
if (value == null || !Number.isInteger(value) || value < 0 || value > 9999) return;
clearTimeout(targetSaveTimer);
targetSaveTimer = setTimeout(async () => {
try {
await fetch("/api/settings/monthly-target", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ monthly_target: value }),
});
} catch { /* 静默 */ }
}, 600);
}
watch(monthlyTarget, (v) => { if (targetLoaded.value) saveTarget(v); });
const startLoaded = ref(false);
const scheduleEnabled = ref(true);
const startDay = ref<number | null>(1);
const startHour = ref<number | null>(0);
const startMinute = ref<number | null>(0);
const startSecond = ref<number | null>(0);
let startSaveTimer: ReturnType<typeof setTimeout> | undefined;
const startTime = computed({
get() {
@@ -227,37 +271,15 @@ async function loadStart() {
startHour.value = typeof data.hour === "number" ? data.hour : 0;
startMinute.value = typeof data.minute === "number" ? data.minute : 0;
startSecond.value = typeof data.second === "number" ? data.second : 0;
scheduleEnabled.value = data.enabled !== false;
startLoaded.value = true;
}
} catch { /* 静默 */ }
}
function saveStart() {
const day = startDay.value;
const hour = startHour.value;
const minute = startMinute.value;
const second = startSecond.value;
if (
day == null || hour == null || minute == null || second == null
|| !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)
) return;
clearTimeout(startSaveTimer);
startSaveTimer = setTimeout(async () => {
try {
await fetch("/api/settings/study-start", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ day, hour, minute, second }),
});
} catch { /* 静默 */ }
}, 600);
}
watch([startDay, startHour, startMinute, startSecond], () => { if (startLoaded.value) saveStart(); });
const workersLoaded = ref(false);
const courseWorkers = ref<number | null>(1);
let workersSaveTimer: ReturnType<typeof setTimeout> | undefined;
const scheduleReady = computed(() => targetLoaded.value && startLoaded.value && workersLoaded.value);
async function loadWorkers() {
try {
@@ -270,21 +292,52 @@ async function loadWorkers() {
} catch { /* 静默 */ }
}
function saveWorkers(value: number | null) {
if (value == null || !Number.isInteger(value) || value < 1 || value > 8) return;
clearTimeout(workersSaveTimer);
workersSaveTimer = setTimeout(async () => {
try {
await fetch("/api/settings/course-workers", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ workers: value }),
});
} catch { /* 静默 */ }
}, 600);
async function putJson(url: string, body: Record<string, unknown>, fallback: string) {
const res = await fetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(failureText(data, fallback));
}
watch(courseWorkers, (v) => { if (workersLoaded.value) saveWorkers(v); });
async function saveSchedule() {
if (scheduleSaving.value || !scheduleReady.value) return;
const target = monthlyTarget.value;
const day = startDay.value;
const hour = startHour.value;
const minute = startMinute.value;
const second = startSecond.value;
const workers = courseWorkers.value;
if (target == null || !Number.isInteger(target) || target < 0 || target > 9999) {
scheduleError.value = "每月学时目标须为 0 到 9999 的整数";
return;
}
if (
day == null || hour == null || minute == null || second == null
|| !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)
) {
scheduleError.value = "请填写完整的定时启动时间";
return;
}
if (workers == null || !Number.isInteger(workers) || workers < 1 || workers > 8) {
scheduleError.value = "线程数量须为 1 到 8";
return;
}
scheduleSaving.value = true;
scheduleError.value = "";
try {
await putJson("/api/settings/monthly-target", { monthly_target: target }, "没有保存每月目标。");
await putJson("/api/settings/study-start", { day, hour, minute, second, enabled: scheduleEnabled.value }, "没有保存定时启动。");
await putJson("/api/settings/course-workers", { workers }, "没有保存线程数量。");
await loadStudyControl();
} catch (exc) {
scheduleError.value = exc instanceof Error ? exc.message : "没有保存。";
} finally {
scheduleSaving.value = false;
}
}
const proxyOpen = ref(false);
const proxyLoaded = ref(false);
@@ -411,12 +464,17 @@ function applyStudyControl(payload: Record<string, unknown>) {
paused: payload.paused === true,
ignore_window: payload.ignore_window === true,
window_open: payload.window_open === true,
hours_met: payload.hours_met === true,
schedule_enabled: payload.schedule_enabled !== false,
active: payload.active === true,
state: typeof payload.state === "string" ? payload.state : "",
course: typeof payload.course === "string" ? payload.course : "",
message: typeof payload.message === "string" ? payload.message : "",
workers: asWorkers(payload.workers),
};
if (typeof payload.month_hours === "string" && summary.value) {
summary.value = { ...summary.value, month_hours: payload.month_hours };
}
}
async function loadStudyControl() {
@@ -427,32 +485,148 @@ async function loadStudyControl() {
} catch { /* 静默 */ }
}
function startStudyPoll() {
if (studyPoll) return;
studyPoll = window.setInterval(() => {
nowTick.value = Date.now();
void loadStudyControl();
}, 1000);
function studySocketUrl() {
const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${proto}//${window.location.host}/api/settings/study-control/ws`;
}
function stopStudyPoll() {
if (studyPoll) {
window.clearInterval(studyPoll);
studyPoll = 0;
function stopStudyFallback() {
if (studyFallback) {
window.clearTimeout(studyFallback);
studyFallback = 0;
}
}
function startStudyFallback() {
if (studyClosed) return;
if (studyFallback) return;
const tick = async () => {
studyFallback = 0;
await loadStudyControl();
if (!studyClosed && (!studySocket || studySocket.readyState !== WebSocket.OPEN)) {
studyFallback = window.setTimeout(tick, 3000);
}
};
void tick();
}
function stopStudySocket() {
studyClosed = true;
if (studyReconnect) {
window.clearTimeout(studyReconnect);
studyReconnect = 0;
}
if (studyPing) {
window.clearInterval(studyPing);
studyPing = 0;
}
stopStudyFallback();
const ws = studySocket;
studySocket = null;
if (ws) {
ws.onclose = null;
ws.onerror = null;
ws.onmessage = null;
ws.close();
}
}
function scheduleStudyReconnect() {
if (studyClosed || studyReconnect) return;
const delay = studyBackoff;
studyBackoff = Math.min(10000, delay * 2);
studyReconnect = window.setTimeout(() => {
studyReconnect = 0;
connectStudySocket();
}, delay);
}
function connectStudySocket() {
if (studyClosed) return;
if (studySocket && (studySocket.readyState === WebSocket.OPEN || studySocket.readyState === WebSocket.CONNECTING)) {
return;
}
let ws: WebSocket;
try {
ws = new WebSocket(studySocketUrl());
} catch {
startStudyFallback();
scheduleStudyReconnect();
return;
}
studySocket = ws;
ws.onmessage = (event) => {
try {
const data = JSON.parse(String(event.data));
if (data && typeof data === "object") applyStudyControl(data as Record<string, unknown>);
} catch { /* ignore */ }
};
ws.onopen = () => {
studyBackoff = 1000;
stopStudyFallback();
void loadStudyControl();
if (studyPing) window.clearInterval(studyPing);
studyPing = window.setInterval(() => {
if (ws.readyState === WebSocket.OPEN) ws.send("ping");
}, 8000);
};
ws.onclose = () => {
if (studyPing) {
window.clearInterval(studyPing);
studyPing = 0;
}
if (studySocket === ws) studySocket = null;
if (!studyClosed) {
startStudyFallback();
scheduleStudyReconnect();
}
};
ws.onerror = () => {
ws.close();
};
}
function stopStudyTick() {
if (studyTick) {
window.clearInterval(studyTick);
studyTick = 0;
}
}
function startStudyTick() {
if (studyTick) return;
nowTick.value = Date.now();
studyTick = window.setInterval(() => {
nowTick.value = Date.now();
}, 1000);
}
watch(proxyOpen, (open, wasOpen) => {
if (wasOpen && !open) restoreProxy();
});
watch(
() => studyControl.value.started,
(started) => {
if (started) startStudyPoll();
else stopStudyPoll();
},
);
function studyWake() {
if (studyClosed) return;
void loadStudyControl();
if (!studySocket || studySocket.readyState === WebSocket.CLOSING || studySocket.readyState === WebSocket.CLOSED) {
connectStudySocket();
return;
}
if (studySocket.readyState === WebSocket.OPEN) {
try {
studySocket.send("ping");
} catch { /* ignore */ }
}
}
function onStudyVisible() {
if (document.visibilityState === "visible") studyWake();
}
watch(countdownOn, (on) => {
if (on) startStudyTick();
else stopStudyTick();
});
async function toggleStudy() {
if (studyBusy.value) return;
@@ -484,13 +658,20 @@ onMounted(() => {
loadStart();
loadWorkers();
loadProxy();
connectStudySocket();
document.addEventListener("visibilitychange", onStudyVisible);
window.addEventListener("focus", studyWake);
window.addEventListener("online", studyWake);
window.addEventListener("pageshow", studyWake);
});
onUnmounted(() => {
stopStudyPoll();
clearTimeout(targetSaveTimer);
clearTimeout(startSaveTimer);
clearTimeout(workersSaveTimer);
document.removeEventListener("visibilitychange", onStudyVisible);
window.removeEventListener("focus", studyWake);
window.removeEventListener("online", studyWake);
window.removeEventListener("pageshow", studyWake);
stopStudySocket();
stopStudyTick();
});
</script>
@@ -548,89 +729,125 @@ onUnmounted(() => {
</dl>
</section>
<section class="panel-card study-card">
<section class="panel-card study-card" :class="{ 'is-busy': studyingWorkers.length > 0 }">
<header class="panel-card-head">
<h3>自动学习</h3>
<div class="study-head-actions">
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
<template #icon><n-icon><GlobeOutline /></n-icon></template>
代理
</n-button>
<n-button
:type="studyControl.started ? 'error' : 'primary'"
size="small"
:loading="studyBusy"
@click="toggleStudy"
>
<template #icon>
<n-icon><StopOutline v-if="studyControl.started" /><PlayOutline v-else /></n-icon>
</template>
{{ studyControl.started ? "停止" : "立即开始" }}
</n-button>
</div>
</header>
<n-alert v-if="studyError" class="summary-error" type="error">{{ studyError }}</n-alert>
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
<n-form-item v-if="targetLoaded" label="每月目标">
<div class="target-control">
<n-input-number
id="monthly-target"
v-model:value="monthlyTarget"
button-placement="both"
:min="0"
:max="9999"
:precision="0"
size="small"
/>
<span class="target-unit">分钟</span>
</div>
</n-form-item>
<n-form-item v-if="startLoaded" label="定时启动">
<div class="target-control start-control">
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" />
<n-tooltip v-if="startDay === 1" placement="top">
<n-alert v-if="scheduleError" class="summary-error" type="error">{{ scheduleError }}</n-alert>
<div class="study-card-body">
<div class="study-config">
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
<n-form-item v-if="targetLoaded" label="每月目标">
<div class="target-control">
<n-input-number
id="monthly-target"
v-model:value="monthlyTarget"
button-placement="both"
:min="0"
:max="9999"
:precision="0"
size="small"
/>
<span class="target-unit">分钟</span>
</div>
</n-form-item>
<n-form-item v-if="startLoaded" label="定时开启">
<n-switch v-model:value="scheduleEnabled" size="small" />
</n-form-item>
<n-form-item v-if="startLoaded" label="定时启动">
<div class="start-control">
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
<n-tooltip v-if="scheduleEnabled && startDay === 1" placement="top">
<template #trigger>
<n-icon class="day-warn"><WarningOutline /></n-icon>
</template>
不推荐使用
</n-tooltip>
<n-time-picker
class="start-time"
v-model:formatted-value="startTime"
value-format="HH:mm:ss"
size="small"
:actions="null"
:disabled="!scheduleEnabled"
/>
</div>
</n-form-item>
<n-form-item v-if="workersLoaded" label="线程数量">
<div class="target-control">
<n-select id="course-workers" class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
<n-tooltip v-if="courseWorkers === 1" placement="top">
<template #trigger>
<button type="button" class="hint-icon" aria-label="说明">
<n-icon><HelpCircleOutline /></n-icon>
</button>
</template>
{{ workerHint }}
</n-tooltip>
</div>
</n-form-item>
</n-form>
<div class="study-actions">
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
<template #icon><n-icon><GlobeOutline /></n-icon></template>
代理
</n-button>
<n-button v-if="scheduleReady" type="primary" size="small" :loading="scheduleSaving" @click="saveSchedule">保存定时配置</n-button>
<n-tooltip v-if="!studyControl.started" placement="top">
<template #trigger>
<n-icon class="day-warn"><WarningOutline /></n-icon>
<span class="study-start-wrap">
<n-button type="success" size="small" :disabled="studyControl.hours_met" :loading="studyBusy" @click="toggleStudy">
<template #icon>
<n-icon><PlayOutline /></n-icon>
</template>
立即开始
</n-button>
</span>
</template>
不推荐使用
{{ studyControl.hours_met ? "本月目标已达到" : "会跳过设定的定时启动时间,立刻开始学习任务。" }}
</n-tooltip>
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" size="small" :actions="null" />
<n-button v-else type="error" size="small" :loading="studyBusy" @click="toggleStudy">
<template #icon>
<n-icon><StopOutline /></n-icon>
</template>
停止
</n-button>
</div>
</n-form-item>
<n-form-item v-if="workersLoaded">
<template #label>
<span class="field-title">
<span>线程数量</span>
<n-tooltip placement="top">
<template #trigger>
<button type="button" class="hint-icon" aria-label="说明">
<n-icon><HelpCircleOutline /></n-icon>
</button>
</template>
{{ workerHint }}
</n-tooltip>
</span>
</template>
<n-select id="course-workers" class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
</n-form-item>
</n-form>
<div class="home-study-status">
<span class="study-indicator" :class="{ active: studyControl.started || studyControl.active }"></span>
<span class="study-text" :class="{ muted: !studyControl.active }">{{ studyLabel }}</span>
</div>
<div class="study-live">
<div class="study-live-status">
<span
class="study-indicator"
:class="{
active: !studyFailed && (studyControl.started || studyControl.active),
down: studyFailed,
}"
></span>
<span class="study-text" :class="{ muted: !studyControl.started && !studyControl.active }">{{ studyLabel }}</span>
</div>
<div v-if="targetLoaded" class="study-progress">
<div class="study-progress-meta">
<span>本月进度</span>
<span>{{ monthProgress.current }} / {{ monthProgress.target }} 分钟</span>
</div>
<n-progress type="line" :percentage="monthProgress.pct" :show-indicator="false" :height="6" />
</div>
<ul v-if="studyingWorkers.length" class="study-workers" aria-label="当前课程">
<li v-for="row in studyingWorkers" :key="row.id" class="study-worker">
<span class="study-worker-title">{{ workerTitle(row) }}</span>
<div class="study-worker-bar">
<n-progress type="line" :percentage="workerPercent(row)" :show-indicator="false" :height="6" />
</div>
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
<span class="study-worker-count">{{ workerCount(row) }}</span>
<span v-if="showHeartbeat(row)" class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
<span class="study-dot" :class="row.ok ? 'up' : 'down'" :aria-label="row.ok ? '正常' : '异常'"></span>
</li>
</ul>
<p v-else-if="studyHint" class="study-live-hint">{{ studyHint }}</p>
</div>
</div>
<ul v-if="studyControl.started && studyControl.workers.length" class="study-workers">
<li v-for="row in studyControl.workers" :key="row.id" class="study-worker">
<div class="study-worker-main">
<span class="study-worker-title">{{ workerTitle(row) }}</span>
<n-progress type="line" :percentage="workerPercent(row)" :show-indicator="false" :height="8" />
</div>
<div class="study-worker-meta">
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
<span class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
<span class="study-dot" :class="row.ok ? 'up' : 'down'"></span>
</div>
</li>
</ul>
</section>
</div>
<n-modal
+11 -2
View File
@@ -8,10 +8,19 @@ export const workerOptions = [
{ label: "5", value: 5 },
{ label: "6", value: 6 },
{ label: "7", value: 7 },
{ label: "8 · 最大", value: 8 },
{ label: "8", value: 8 },
];
export const dayOptions = Array.from({ length: 31 }, (_, index) => ({
label: `${index + 1}日`,
label: `每月 ${index + 1}号`,
value: index + 1,
}));
export const STUDY_POLL_FLOOR = 10;
export function studyPollSeconds(intervals: number[]): number {
if (intervals.some((value) => value <= 0)) return STUDY_POLL_FLOOR;
const positive = intervals.filter((value) => value > 0);
if (!positive.length) return STUDY_POLL_FLOOR;
return Math.max(STUDY_POLL_FLOOR, Math.min(...positive));
}
+15
View File
@@ -60,12 +60,19 @@ export const scheme = computed(() => schemes.find((item) => item.id === schemeId
export const isDark = computed(() => scheme.value.dark);
export const themeOverrides = computed<GlobalThemeOverrides>(() => {
const current = scheme.value;
const success = current.dark ? "#238636" : "#1A7F37";
const successHover = current.dark ? "#2EA043" : "#2DA44E";
const successPressed = current.dark ? "#196C2E" : "#116329";
return {
common: {
primaryColor: current.primary,
primaryColorHover: current.primaryHover,
primaryColorPressed: current.primaryPressed,
primaryColorSuppl: current.primary,
successColor: success,
successColorHover: successHover,
successColorPressed: successPressed,
successColorSuppl: success,
errorColor: current.danger,
errorColorHover: current.danger,
errorColorPressed: current.danger,
@@ -92,6 +99,14 @@ export const themeOverrides = computed<GlobalThemeOverrides>(() => {
textColorHoverPrimary: "#ffffff",
textColorPressedPrimary: "#ffffff",
textColorFocusPrimary: "#ffffff",
textColorSuccess: "#ffffff",
textColorHoverSuccess: "#ffffff",
textColorPressedSuccess: "#ffffff",
textColorFocusSuccess: "#ffffff",
textColorError: "#ffffff",
textColorHoverError: "#ffffff",
textColorPressedError: "#ffffff",
textColorFocusError: "#ffffff",
},
Menu: {
itemTextColor: current.vars["--ink"],
+236 -40
View File
@@ -432,7 +432,7 @@ select {
.home {
flex: 1;
min-height: 0;
overflow: auto;
overflow: hidden;
display: flex;
flex-direction: column;
gap: 16px;
@@ -491,7 +491,9 @@ select {
}
.compact-nform .n-form-item-blank {
min-width: 0;
min-height: 32px;
max-width: 100%;
}
.compact-nform .n-form-item-feedback-wrapper {
@@ -521,10 +523,27 @@ select {
}
.settings-stack {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
gap: 16px;
overflow: hidden;
}
.settings-stack > .panel-card {
box-sizing: border-box;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: 16px;
max-width: 640px;
overflow: auto;
}
.settings-stack .compact-nform {
max-width: none;
width: 100%;
}
.settings-stack .form-hint {
@@ -542,6 +561,7 @@ select {
}
.home-summary {
flex: none;
display: flex;
flex-direction: column;
gap: 16px;
@@ -616,18 +636,35 @@ select {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
max-width: 100%;
}
.target-control .n-input-number {
width: 120px;
max-width: 100%;
}
.start-control .n-input-number {
width: 88px;
.start-control {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
min-width: 0;
width: 100%;
max-width: 100%;
}
.start-control .day-select {
width: 108px;
.start-control .day-select,
.start-control .start-time {
flex: 1 1 8.5rem;
width: auto;
min-width: 0;
max-width: 100%;
}
.start-control .start-time .n-input {
width: 100%;
}
.worker-select {
@@ -635,14 +672,17 @@ select {
max-width: 100%;
}
.study-head-actions {
display: flex;
align-items: center;
gap: 8px;
.study-start-wrap {
display: inline-flex;
}
.start-control .n-time-picker {
width: 148px;
.study-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding-left: 96px;
margin-top: 12px;
}
.day-warn {
@@ -656,13 +696,12 @@ select {
font-size: 13px;
}
.home-study-status {
.home-study-status,
.study-live-status {
display: flex;
align-items: center;
gap: 8px;
padding-top: 8px;
margin-top: 4px;
border-top: 1px solid var(--line);
min-height: 32px;
}
.study-indicator {
@@ -678,6 +717,11 @@ select {
box-shadow: 0 0 6px rgba(63, 185, 80, 0.5);
}
.study-indicator.down {
background: var(--danger);
box-shadow: 0 0 6px rgba(248, 81, 73, 0.5);
}
.study-text {
font-size: 13px;
}
@@ -687,59 +731,143 @@ select {
}
.study-card {
flex: 0 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.study-card.is-busy {
flex: 1 1 auto;
overflow: hidden;
}
.study-card-body {
display: grid;
grid-template-columns: minmax(0, 30rem) minmax(0, 1fr);
gap: 16px 32px;
align-items: start;
padding-top: 12px;
}
.study-card.is-busy .study-card-body {
flex: 1 1 auto;
min-height: 0;
grid-template-columns: minmax(0, 30rem) minmax(0, 1fr);
align-items: stretch;
}
.study-config {
min-width: 0;
max-width: 30rem;
}
.study-config .compact-nform {
max-width: none;
}
.study-live {
min-width: 0;
display: flex;
flex-direction: column;
gap: 12px;
padding-left: 24px;
border-left: 1px solid var(--line);
}
.study-card.is-busy .study-live {
min-height: 0;
}
.study-progress {
display: flex;
flex-direction: column;
gap: 8px;
max-width: 28rem;
}
.study-progress-meta {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.study-progress-meta span:first-child {
color: var(--muted);
}
.study-live-hint {
margin: 0;
max-width: 36rem;
font-size: 13px;
line-height: 1.5;
color: var(--muted);
}
.study-workers {
list-style: none;
margin: 12px 0 0;
margin: 0;
padding: 0;
flex: 1;
min-height: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.study-worker {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 12px;
align-items: center;
}
.study-worker-main {
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
align-items: center;
gap: 10px;
min-width: 0;
}
.study-worker-title {
flex: 1 1 9rem;
min-width: 0;
font-size: 13px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.study-worker-meta {
display: flex;
align-items: center;
gap: 8px;
.study-worker-bar {
flex: 1 1 10rem;
min-width: 72px;
}
.study-worker-bar .n-progress {
width: 100%;
}
.study-worker-pct,
.study-worker-count {
flex: none;
text-align: right;
font-variant-numeric: tabular-nums;
font-size: 12px;
color: var(--muted);
}
.study-worker-pct {
width: 36px;
text-align: right;
color: var(--text);
width: 3.25em;
}
.study-worker-count {
min-width: 3.75em;
color: var(--muted);
}
.study-heartbeat {
width: 36px;
flex: none;
width: 2.75em;
text-align: right;
font-variant-numeric: tabular-nums;
font-size: 12px;
color: var(--muted);
}
.study-dot {
@@ -1182,6 +1310,25 @@ select {
}
}
@media (max-width: 1099px) {
.study-card-body,
.study-card.is-busy .study-card-body {
grid-template-columns: minmax(0, 1fr);
gap: 16px;
}
.study-card.is-busy .study-card-body {
grid-template-rows: auto minmax(0, 1fr);
}
.study-live {
padding-left: 0;
border-left: 0;
padding-top: 12px;
border-top: 1px solid var(--line);
}
}
@media (max-width: 800px) {
.page {
padding: 16px 12px;
@@ -1212,14 +1359,15 @@ select {
.admin-page .page-head {
flex: none;
align-items: center;
justify-content: flex-end;
}
.admin-page .page-head h2 {
margin: 0;
.admin-page .page-head:has(> :nth-child(2)) {
justify-content: space-between;
}
.admin-page .page-head p {
margin: 4px 0 0;
margin: 0;
color: var(--muted);
font-size: 12px;
}
@@ -1441,6 +1589,54 @@ select {
justify-content: flex-end;
}
body .n-input .n-input__input-el,
body .n-input .n-input__textarea-el,
body .n-input-number .n-input__input-el {
text-align: center;
}
body .n-input .n-input__placeholder {
justify-content: center;
text-align: center;
}
body .n-base-selection-input,
body .n-base-selection-input__content,
body .n-base-selection-overlay,
body .n-base-selection-placeholder,
body .n-base-selection-input-tag__input {
text-align: center;
}
body .n-base-selection-label,
body .n-base-selection-placeholder,
body .n-base-selection-overlay {
justify-content: center;
}
body .n-base-selection-input__content,
body .n-base-selection-overlay {
display: block;
width: 100%;
}
body .n-base-select-menu .n-base-select-option {
justify-content: center;
}
body .n-base-select-menu .n-base-select-option__content {
flex: 1;
text-align: center;
}
@media (max-width: 1100px) {
.settings-stack {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: none;
grid-auto-rows: auto;
}
}
@media (max-width: 800px) {
.settings-form .form-row {
grid-template-columns: minmax(0, 1fr);