fix: 补上清单里还没对上的登录拒绝、会话回退和代理清理

This commit is contained in:
2026-11-16 16:46:37 +08:00
parent a1e2b6e65c
commit 3cff9dc37a
19 changed files with 223 additions and 65 deletions
@@ -0,0 +1,19 @@
"""记下代理最近一次被采集到的时间,便于清掉长期失效的节点。"""
from alembic import op
import sqlalchemy as sa
revision = "0008_proxy_last_seen"
down_revision = "0007_study_start_day"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("proxy_nodes") as batch:
batch.add_column(sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True))
def downgrade() -> None:
with op.batch_alter_table("proxy_nodes") as batch:
batch.drop_column("last_seen_at")
+6
View File
@@ -1628,6 +1628,12 @@ class AutoStudyWorker:
course_list = snapshot_courses(db.scalars(select(Course)).all())
if expired:
db.commit()
queried = {row.employee_id for row in users}
with _halt_lock:
stranded = [eid for eid in list(_wanted) if eid not in queried and eid not in _running]
for eid in stranded:
_set_user_status(eid, state="学习失败", message="登录凭证待校验")
drop_work(eid)
wait = max(1.0, min(3600.0, (soonest - as_cn()).total_seconds()))
label = soonest.strftime("%m-%d %H:%M:%S")
return jobs, course_list, wait, f"下一次定时 {label}"
+16 -8
View File
@@ -439,7 +439,7 @@ def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[
}
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int:
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> tuple[int, bool]:
"""倒序分页累加本月分钟,遇到上个月即停。重复页直接返回,不再累加。"""
offset = 0
total = 0
@@ -449,9 +449,9 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int =
if rows is None:
if offset == 0:
raise RuntimeError("学时历史没有获取到")
return total
return total, False
if not rows:
return total
return total, False
mark = (
len(rows),
rows[0].get("studied_at"),
@@ -460,14 +460,14 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int =
rows[-1].get("title"),
)
if mark in seen:
return total
return total, False
seen.add(mark)
add, done = fold_month_minutes(rows, year, month)
total += add
if done or len(rows) != page_size:
return total
return total, False
offset += page_size
return total
return total, True
def parse_training_cards(page: str, status: str) -> list[dict]:
@@ -744,6 +744,10 @@ class JigsawRejected(RuntimeError):
"""这次拼图位置不对,可以换一张再试。"""
class LoginRejected(RuntimeError):
"""平台明确拒绝了账号或密码,不能再自动重试。"""
class ManualJigsaw(Exception):
"""自动拼图已用完,把新拼图交给人来拖。"""
@@ -967,7 +971,9 @@ class EunivClient:
return profile
if any(word in message for word in ("验证码", "拼图", "滑块")):
raise JigsawRejected(message or "拼图未通过")
raise RuntimeError(f"登录失败:{message}")
if any(word in message for word in ("密码", "账号", "用户名", "工号")):
raise LoginRejected("账号或密码错误")
raise RuntimeError("登录没有完成")
def authorize(self, profile: dict) -> None:
account_id = str(profile.get("accountId") or profile.get("userName") or "")
@@ -1209,7 +1215,9 @@ class EunivClient:
return self._study_history_search(pageable=True, offset=offset, limit=limit)
try:
return accumulate_month_minutes(fetch_page, year, month)
total, limited = accumulate_month_minutes(fetch_page, year, month)
self.history_limited = limited
return total
except SessionExpired:
raise
except Exception as exc:
+1
View File
@@ -99,6 +99,7 @@ class ProxyNode(Base):
latency_ms: Mapped[int | None] = mapped_column(nullable=True)
last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
fail_reason: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default=text("''"))
assigns: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
+12
View File
@@ -393,6 +393,7 @@ def _refresh_body() -> dict:
new_ids: list[int] = []
alive_ids: list[int] = []
dead_ids: list[int] = []
seen_at = _now()
for item in candidates:
if not is_china(item.country):
continue
@@ -407,6 +408,7 @@ def _refresh_body() -> dict:
anonymity=item.anonymity,
source=item.source,
status=STATUS_NEW,
last_seen_at=seen_at,
)
db.add(node)
db.flush()
@@ -416,6 +418,7 @@ def _refresh_body() -> dict:
node.country = item.country or node.country
node.anonymity = item.anonymity or node.anonymity
node.source = item.source or node.source
node.last_seen_at = seen_at
if node.status == STATUS_DEAD:
dead_ids.append(node.id)
continue
@@ -423,6 +426,15 @@ def _refresh_body() -> dict:
new_ids.append(node.id)
elif node.status == STATUS_ALIVE:
alive_ids.append(node.id)
stale_before = seen_at - timedelta(days=7)
held = set(_holds.values())
for node in list(existing.values()):
if node.id in held or node.status != STATUS_DEAD:
continue
seen = _aware(node.last_seen_at)
if seen is not None and seen < stale_before:
db.delete(node)
existing.pop((node.scheme, node.host, int(node.port)), None)
for node in existing.values():
if node.id in alive_ids or node.id in new_ids or node.id in dead_ids:
continue
+34 -5
View File
@@ -17,6 +17,7 @@ from euniv.client import (
QR_PASSWORD_MARK,
EunivClient,
JigsawRejected,
LoginRejected,
ManualJigsaw,
QrWaiting,
SessionExpired,
@@ -420,6 +421,14 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic
data["month_hours"] = totals["month"]
data["today_hours"] = totals["today"]
data["total_hours"] = totals["total"]
data["limited"] = False
walker = getattr(client, "month_history_minutes", None)
if callable(walker):
try:
data["month_hours"] = walker()
data["limited"] = bool(getattr(client, "history_limited", False))
except Exception:
data["limited"] = False
return data
@@ -439,13 +448,29 @@ def _api_hour_fields(client) -> dict:
def _hour_fields(data: dict) -> dict:
return {
fields = {
"hours_source": data.get("hours_source") or "api",
"year_hours": data.get("year_hours"),
"month_hours": data.get("month_hours"),
"today_hours": data.get("today_hours"),
"total_hours": data.get("total_hours"),
}
if data.get("limited") is True:
fields["limited"] = True
return fields
def _drop_rejected_password(db: Session, employee_id: str) -> None:
"""密码被平台拒绝后清掉登录凭证,停止自动重试。"""
with _credential_lock(employee_id):
db.rollback()
account = db.get(Account, employee_id)
if account is None:
return
account.credential_cipher = ""
account.credential_valid = False
account.last_refresh_at = datetime.now(timezone.utc)
db.commit()
def _auto_attempts(db: Session) -> int:
@@ -496,6 +521,9 @@ def _live(db: Session, employee_id: str, client_factory, read):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
except LoginRejected:
_drop_rejected_password(db, employee_id)
raise RuntimeError("请先登录") from None
except RuntimeError:
raise
except Exception as exc:
@@ -599,15 +627,16 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
if isinstance(exc, InvalidToken):
logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id)
return
if isinstance(exc, LoginRejected):
logging.getLogger("euniv.service").warning("账号 %s 的密码已被拒绝,停止自动登录", employee_id)
_drop_rejected_password(db, employee_id)
return
logging.getLogger("euniv.service").exception("刷新账号 %s 的登录状态失败", employee_id)
db.rollback()
account = db.get(Account, employee_id)
if account is None:
return
rejected = isinstance(exc, RuntimeError) and any(
word in str(exc) for word in ("登录失败", "登录页校验失败", "密码错误")
)
valid = False if rejected else account.credential_valid
valid = account.credential_valid
finally:
if client is not None:
try:
+4 -2
View File
@@ -382,7 +382,9 @@ class _Dead:
return False
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
raise RuntimeError("登录失败:密码错误")
from euniv.client import LoginRejected
raise LoginRejected("账号或密码错误")
def test_refresh_records_outcome_and_skips_paused_accounts() -> None:
@@ -417,7 +419,7 @@ def test_refresh_records_outcome_and_skips_paused_accounts() -> None:
assert failed.credential_valid is False
assert failed.last_refresh_at is not None
assert decrypt_secret(failed.password_cipher) == "secret-pass"
assert json.loads(decrypt_secret(failed.credential_cipher))["yxt_token"] == "yxt-1"
assert failed.credential_cipher == ""
assert paused.last_refresh_at == stamped.replace(tzinfo=None) or paused.last_refresh_at == stamped
assert paused.credential_valid is True
assert empty.credential_valid is False
+13 -2
View File
@@ -249,14 +249,14 @@ def test_accumulate_month_minutes_stops_at_previous_month() -> None:
calls.append((offset, limit))
return pages[offset // limit]
assert accumulate_month_minutes(fetch, 2026, 11, page_size=2) == 35
assert accumulate_month_minutes(fetch, 2026, 11, page_size=2) == (35, False)
assert calls == [(0, 2), (2, 2)]
dumped = [
{"title": "a", "minutes": 8, "studied_at": "2026-11-14 10:00:00"},
{"title": "b", "minutes": 4, "studied_at": "2026-10-30 10:00:00"},
]
assert fold_month_minutes(dumped, 2026, 11) == (8, True)
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == 8
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == (8, False)
def test_history_hour_totals_splits_year_month_today() -> None:
@@ -519,6 +519,17 @@ def test_interval_plan_manual_one_second_uses_admin_wait() -> None:
assert page == 1
def test_wanted_account_without_credential_is_dropped() -> None:
from euniv.autostudy import AutoStudyWorker, is_wanted, want_work
want_work("missing-user")
AutoStudyWorker()._collect()
assert is_wanted("missing-user") is False
info = autostudy_status()["users"]["missing-user"]
assert info["message"] == "登录凭证待校验"
assert info["state"] == "学习失败"
def test_assemble_prefers_live_month_hours() -> None:
account = _Start(1, 0, 0, 0)
account.month_hours = "10"
+20 -7
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { onMounted, onUnmounted, ref } from "vue";
import { apiFetch, setSessionDenied } from "./shared/http";
import { darkTheme, dateZhCN, NButton, NConfigProvider, NDialogProvider, zhCN } from "naive-ui";
import LoginView from "./features/auth/LoginView.vue";
import Shell from "./shell/Shell.vue";
@@ -18,7 +19,7 @@ function applyPayload(payload: unknown) {
async function loadSession() {
try {
const response = await fetch("/api/session");
const response = await apiFetch("/api/session");
if (response.status === 401) {
session.value = null;
sessionError.value = "";
@@ -43,12 +44,24 @@ async function loadSession() {
}
onMounted(() => {
setSessionDenied(() => {
void loadSession();
});
void loadSession();
window.addEventListener("focus", onWindowFocus);
});
onUnmounted(() => {
window.removeEventListener("focus", onWindowFocus);
});
function onWindowFocus() {
void loadSession();
}
async function exitSystem() {
try {
const response = await fetch("/api/logout", { method: "POST" });
const response = await apiFetch("/api/logout", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有退出。";
return;
@@ -62,7 +75,7 @@ async function exitSystem() {
async function revokeAccount() {
try {
const response = await fetch("/api/revoke", { method: "POST" });
const response = await apiFetch("/api/revoke", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有注销。";
return;
@@ -76,7 +89,7 @@ async function revokeAccount() {
async function exitAdmin() {
try {
const response = await fetch("/api/admin/logout", { method: "POST" });
const response = await apiFetch("/api/admin/logout", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有退出。";
return;
@@ -111,8 +124,8 @@ function onLogin(next: AppSession) {
<n-button size="small" @click="loadSession">重试</n-button>
</div>
<LoginView v-if="!session" @success="onLogin" />
<Shell v-else-if="session.kind === 'user'" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
<AdminShell v-else-if="session.kind === 'admin'" :username="session.username" @logout="exitAdmin" @refresh="loadSession" />
<Shell v-else-if="session.kind === 'user'" :key="session.employeeId" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
<AdminShell v-else-if="session.kind === 'admin'" :key="session.username" :username="session.username" @logout="exitAdmin" @refresh="loadSession" />
</div>
</n-dialog-provider>
</n-config-provider>
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui";
import { DownloadOutline } from "@vicons/ionicons5";
@@ -71,7 +72,7 @@ async function load(clamp = true) {
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/courses?${params}`);
const response = await apiFetch(`/api/admin/courses?${params}`);
if (disposed || seq !== loadSeq) return;
const payload = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
@@ -126,7 +127,7 @@ async function loadCourses() {
setError("");
fetching.value = true;
try {
const response = await fetch("/api/admin/courses/load", { method: "POST" });
const response = await apiFetch("/api/admin/courses/load", { method: "POST" });
await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
+7 -6
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NIcon, NInput, NPagination, NSpin, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -124,7 +125,7 @@ async function load(clamp = true) {
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/proxies?${params}`);
const response = await apiFetch(`/api/admin/proxies?${params}`);
if (disposed || seq !== loadSeq) return;
const payload: unknown = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
@@ -186,7 +187,7 @@ async function probeOne(row: ProxyRow) {
probingId.value = row.id;
setError("");
try {
const response = await fetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
const response = await apiFetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
setError("没有测出延迟。");
@@ -217,7 +218,7 @@ async function filteredIds() {
offset: String(offset),
limit: String(limit),
});
const response = await fetch(`/api/admin/proxies?${params}`);
const response = await apiFetch(`/api/admin/proxies?${params}`);
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload) || !Array.isArray(payload.items)) {
throw new Error("代理列表没有获取到。");
@@ -240,7 +241,7 @@ async function probeAll() {
setError("没有可测试的代理。");
return;
}
const response = await fetch("/api/admin/proxies/probe", {
const response = await apiFetch("/api/admin/proxies/probe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ids ? { ids } : {}),
@@ -252,7 +253,7 @@ async function probeAll() {
}
for (let attempt = 0; attempt < 120; attempt += 1) {
if (disposed) return;
const status = await fetch("/api/admin/proxies/probe");
const status = await apiFetch("/api/admin/proxies/probe");
const body: unknown = await status.json().catch(() => ({}));
if (!status.ok || !isRecord(body)) break;
if (body.running !== true) {
@@ -273,7 +274,7 @@ async function refreshNow() {
setError("");
fetching.value = true;
try {
const response = await fetch("/api/admin/proxies/refresh", { method: "POST" });
const response = await apiFetch("/api/admin/proxies/refresh", { method: "POST" });
await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NForm, NFormItem, NInput, NInputNumber, NRadioButton, NRadioGroup, NSwitch } from "naive-ui";
@@ -54,7 +55,7 @@ onUnmounted(() => window.clearTimeout(savedTimer));
onMounted(async () => {
try {
const response = await fetch("/api/admin/settings");
const response = await apiFetch("/api/admin/settings");
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload || typeof payload !== "object") {
errorText.value = detailOf(payload, "系统配置没有获取到。");
@@ -151,7 +152,7 @@ async function save() {
}
saving.value = true;
try {
const response = await fetch("/api/admin/settings", {
const response = await apiFetch("/api/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
+27 -12
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInputNumber, NModal, NRadioButton, NRadioGroup, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, RefreshOutline, SettingsOutline } from "@vicons/ionicons5";
@@ -249,7 +250,7 @@ function validityClass(text: string) {
async function load() {
loading.value = true;
try {
const response = await fetch("/api/admin/users");
const response = await apiFetch("/api/admin/users");
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "用户列表没有获取到。");
@@ -277,7 +278,7 @@ async function checkOne(row: UserRow) {
checkingId.value = row.employee_id;
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/check`, { method: "POST" });
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/check`, { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload)) {
remember(row.employee_id, "检查失败");
@@ -301,7 +302,7 @@ async function checkAll() {
checkingAll.value = true;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/check-all", { method: "POST" });
const response = await apiFetch("/api/admin/users/check-all", { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "检查失败");
@@ -375,7 +376,7 @@ async function openCredentials(row: UserRow) {
credentialLoading.value = true;
credentialOpen.value = true;
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
const payload: unknown = await response.json().catch(() => ({}));
if (current !== credentialRequest || !credentialOpen.value) return;
if (!response.ok || !isRecord(payload)) {
@@ -393,7 +394,7 @@ async function openCredentials(row: UserRow) {
async function setPaused(row: UserRow, paused: boolean) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ paused }),
@@ -423,7 +424,7 @@ function confirmRefresh(row: UserRow) {
async function removeUser(row: UserRow) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "没有删除。");
@@ -516,11 +517,25 @@ async function openSettings(ids: string[]) {
const row = users.value.find((item) => item.employee_id === employeeId);
if (row) applyRowSettings(row);
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(employeeId)}/proxy`);
const [usersResponse, proxyResponse] = await Promise.all([
apiFetch("/api/admin/users"),
apiFetch(`/api/admin/users/${encodeURIComponent(employeeId)}/proxy`),
]);
if (current !== settingsRequest || !settingsOpen.value) return;
const payload: unknown = await response.json().catch(() => ({}));
const usersPayload: unknown = await usersResponse.json().catch(() => null);
const payload: unknown = await proxyResponse.json().catch(() => ({}));
if (current !== settingsRequest || !settingsOpen.value) return;
if (!response.ok || !isRecord(payload)) {
if (!usersResponse.ok || !Array.isArray(usersPayload)) {
settingsError.value = "学习设置没有获取到,不能保存。";
return;
}
const fresh = usersPayload.map(asUser).find((item) => item?.employee_id === employeeId);
if (!fresh) {
settingsError.value = "学习设置没有获取到,不能保存。";
return;
}
applyRowSettings(fresh);
if (!proxyResponse.ok || !isRecord(payload)) {
settingsError.value = "代理没有获取到,不能保存。";
return;
}
@@ -652,7 +667,7 @@ async function saveSettings() {
}
settingsSaving.value = true;
try {
const response = await fetch("/api/admin/users/study-settings", {
const response = await apiFetch("/api/admin/users/study-settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -703,7 +718,7 @@ async function setStudy(ids: string[], action: "start" | "stop") {
studyBusy.value = true;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/study", {
const response = await apiFetch("/api/admin/users/study", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ employee_ids: ids, action }),
@@ -737,7 +752,7 @@ async function clearProxy(ids: string[]) {
if (!ids.length) return;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/proxy/clear", {
const response = await apiFetch("/api/admin/users/proxy/clear", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ employee_ids: ids }),
+6 -5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NCheckbox, NIcon, NInput, NTooltip } from "naive-ui";
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
@@ -94,7 +95,7 @@ onUnmounted(() => {
async function loadConfig() {
try {
const response = await fetch("/api/login-config");
const response = await apiFetch("/api/login-config");
const payload = await response.json().catch(() => ({}));
if (response.ok && payload && typeof payload === "object") {
showManual.value = Boolean((payload as { show_manual_checkbox?: unknown }).show_manual_checkbox);
@@ -193,7 +194,7 @@ async function startQr() {
qrArmed.value = false;
submitting.value = true;
try {
const response = await fetch("/api/login/qr", { method: "POST" });
const response = await apiFetch("/api/login/qr", { method: "POST" });
const payload = await response.json().catch(() => ({})) as LoginPayload;
if (!response.ok) {
errorText.value = readableDetail(payload.detail, "二维码没有获取到");
@@ -225,7 +226,7 @@ async function pollQr() {
if (!attemptId.value || submitting.value || polling) return;
polling = true;
try {
const response = await fetch("/api/login/qr/poll", {
const response = await apiFetch("/api/login/qr/poll", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ attempt_id: attemptId.value }),
@@ -271,7 +272,7 @@ async function submit() {
errorText.value = "";
submitting.value = true;
try {
const response = await fetch("/api/login", {
const response = await apiFetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -305,7 +306,7 @@ async function sendOffset() {
submitting.value = true;
errorText.value = "";
try {
const response = await fetch("/api/login/jigsaw", {
const response = await apiFetch("/api/login/jigsaw", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ attempt_id: attemptId.value, offset: offset.value }),
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NModal, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -52,7 +53,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/exams");
const response = await apiFetch("/api/home/exams");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = "考试列表没有获取到。";
@@ -98,7 +99,7 @@ async function openDetail(item: ExamItem) {
}
detailLoading.value = true;
try {
const response = await fetch(`/api/exam?${new URLSearchParams({ path: item.detail })}`);
const response = await apiFetch(`/api/exam?${new URLSearchParams({ path: item.detail })}`);
const payload = await response.json().catch(() => ({}));
if (current !== detailRequest) return;
if (!response.ok) {
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, h, onMounted, ref } from "vue";
import { NAlert, NButton, NDataTable, NIcon, NPagination, NTooltip, type DataTableColumns } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -21,6 +22,7 @@ type SectionState = "loading" | "ready" | "error";
const items = ref<HistoryItem[] | null>(null);
const hours = ref<HistoryHours | null>(null);
const historyLimited = ref(false);
const state = ref<SectionState>("loading");
const errorText = ref("");
const refreshing = ref(false);
@@ -69,7 +71,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/history");
const response = await apiFetch("/api/home/history");
const payload = await response.json().catch(() => ({})) as Record<string, unknown>;
if (!response.ok) {
errorText.value = "学时历史没有获取到。";
@@ -94,6 +96,7 @@ async function load() {
today_hours: asHour(payload.today_hours),
total_hours: asHour(payload.total_hours),
};
historyLimited.value = payload.limited === true;
errorText.value = "";
state.value = "ready";
const maxPage = Math.max(1, Math.ceil(parsed.length / pageSize.value));
@@ -178,6 +181,7 @@ onMounted(refresh);
<div>
<h2>学时历史</h2>
<p v-if="items">共 {{ items.length }} 条</p>
<p v-if="historyLimited">只统计了最近 50 页</p>
</div>
<n-tooltip placement="bottom">
<template #trigger>
+13 -9
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInputNumber, NModal, NProgress, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
@@ -17,6 +18,7 @@ interface HomeSummary {
total_hours: string;
total_score: string;
points: string | number | null;
limited?: boolean;
}
interface StudyWorker {
@@ -165,6 +167,7 @@ function asSummary(value: unknown): HomeSummary | null {
total_hours: String(text("total_hours") ?? ""),
total_score: String(text("total_score") ?? ""),
points: typeof row.points === "number" || typeof row.points === "string" ? row.points : null,
limited: row.limited === true,
};
}
@@ -241,7 +244,7 @@ async function loadSummary() {
const hadData = summary.value !== null;
if (!hadData) summaryState.value = "loading";
try {
const response = await fetch("/api/home/summary");
const response = await apiFetch("/api/home/summary");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
summaryError.value = "个人学习信息没有获取到。";
@@ -280,7 +283,7 @@ function refresh() {
async function loadTarget() {
try {
const res = await fetch("/api/settings/monthly-target");
const res = await apiFetch("/api/settings/monthly-target");
if (!res.ok) return false;
const data = await res.json();
monthlyTarget.value = data.monthly_target ?? 600;
@@ -314,7 +317,7 @@ const startTime = computed({
async function loadStart() {
try {
const res = await fetch("/api/settings/study-start");
const res = await apiFetch("/api/settings/study-start");
if (!res.ok) return false;
const data = await res.json();
startDay.value = typeof data.day === "number" ? data.day : STUDY_DAY_DEFAULT;
@@ -335,7 +338,7 @@ const scheduleReady = computed(() => targetLoaded.value && startLoaded.value &&
async function loadWorkers() {
try {
const res = await fetch("/api/settings/course-workers");
const res = await apiFetch("/api/settings/course-workers");
if (!res.ok) return false;
const data = await res.json();
courseWorkers.value = typeof data.workers === "number" ? data.workers : 1;
@@ -347,7 +350,7 @@ async function loadWorkers() {
}
async function putJson(url: string, body: Record<string, unknown>, fallback: string) {
const res = await fetch(url, {
const res = await apiFetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
@@ -451,7 +454,7 @@ const proxyOptions = [
async function loadProxy() {
try {
const res = await fetch("/api/settings/proxy");
const res = await apiFetch("/api/settings/proxy");
const data = await res.json().catch(() => ({}));
if (!res.ok) return false;
proxyScheme.value = typeof data.scheme === "string" && data.scheme ? data.scheme : "off";
@@ -499,7 +502,7 @@ async function saveProxy() {
}
proxySaving.value = true;
try {
const res = await fetch("/api/settings/proxy", {
const res = await apiFetch("/api/settings/proxy", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
@@ -566,7 +569,7 @@ function applyStudyControl(payload: Record<string, unknown>) {
async function loadStudyControl() {
try {
const res = await fetch("/api/settings/study-control");
const res = await apiFetch("/api/settings/study-control");
if (res.status === 401) {
stopStudySocket();
return;
@@ -743,7 +746,7 @@ async function toggleStudy() {
studyError.value = "";
const action = studyControl.value.started ? "stop" : "start";
try {
const res = await fetch("/api/settings/study-control", {
const res = await apiFetch("/api/settings/study-control", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
@@ -830,6 +833,7 @@ onUnmounted(() => {
</dd>
</div>
</dl>
<p v-if="summary?.limited" class="study-live-hint">只统计了最近 50 页</p>
</section>
<section class="panel-card study-card" :class="{ 'is-busy': studyingWorkers.length > 0 }">
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NModal, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -68,7 +69,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/trainings");
const response = await apiFetch("/api/home/trainings");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = "培训列表没有获取到。";
@@ -114,7 +115,7 @@ async function openDetail(item: TrainingItem) {
}
detailLoading.value = true;
try {
const response = await fetch(`/api/training?${new URLSearchParams({ path: item.detail })}`);
const response = await apiFetch(`/api/training?${new URLSearchParams({ path: item.detail })}`);
const payload = await response.json().catch(() => ({}));
if (current !== detailRequest) return;
if (!response.ok) {
+28
View File
@@ -0,0 +1,28 @@
type Denied = () => void;
let onDenied: Denied | null = null;
export function setSessionDenied(handler: Denied) {
onDenied = handler;
}
function requestUrl(input: RequestInfo | URL) {
if (typeof input === "string") return input;
if (input instanceof URL) return input.href;
return input.url;
}
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
const response = await fetch(input, init);
if (requestUrl(input).includes("/api/session")) return response;
if (response.status === 401) {
onDenied?.();
return response;
}
if (response.status === 403) {
const body = await response.clone().json().catch(() => null);
const detail = body && typeof body === "object" ? (body as { detail?: unknown }).detail : "";
if (detail === "管理员不能访问该接口") onDenied?.();
}
return response;
}