diff --git a/backend/admin/users.py b/backend/admin/users.py index f50fbec..23b1402 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -38,10 +38,7 @@ def build_client(login_name: str, password: str, proxy: str | None = None): def _open_client(login_name: str, password: str, proxy: str | None = None): - try: - return build_client(login_name, password, proxy) - except TypeError: - return build_client(login_name, password) + return build_client(login_name, password, proxy) def record_outcome(account: Account, valid: bool | None) -> None: diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 6464080..47e9864 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -13,6 +13,8 @@ from sqlalchemy.orm import Session from euniv.client import EUNIV from euniv.models import Account, Course, CourseSync +UNCATEGORIZED = "__none__" + _lock = threading.Lock() _running = False _message = "" @@ -65,19 +67,26 @@ def course_message() -> str: return _message +def _like_pattern(value: str) -> str: + escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + return f"%{escaped}%" + + def course_page(db: Session, query: str, offset: int, limit: int, kind: str = "") -> dict: text = query.strip() base = [] if text: - like = f"%{text}%" - base.append(or_(Course.title.like(like), Course.contributor.like(like))) + like = _like_pattern(text) + base.append(or_(Course.title.like(like, escape="\\"), Course.contributor.like(like, escape="\\"))) counts = db.execute(select(Course.kind, func.count()).where(*base).group_by(Course.kind)).all() kinds = [ - {"name": name or "未分类", "value": name, "count": int(count)} + {"name": name or "未分类", "value": name if name else UNCATEGORIZED, "count": int(count)} for name, count in sorted(counts, key=lambda row: (_kind_rank(row[0]), row[0])) ] filters = list(base) - if kind: + if kind == UNCATEGORIZED: + filters.append(Course.kind == "") + elif kind: filters.append(Course.kind == kind) total = db.scalar(select(func.count()).select_from(Course).where(*filters)) or 0 rows = db.scalars( diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 7e1283a..ceb0c01 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -176,10 +176,7 @@ def _client(factory, employee_id: str, password: str, account: Account | None = from euniv.proxy import bind_url proxy = bind_url(account) if account is not None else None - try: - return factory(employee_id, password, proxy) - except TypeError: - return factory(employee_id, password) + return factory(employee_id, password, proxy) def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool: diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index fb4241e..9e23dca 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -365,7 +365,7 @@ class _Alive: class _Dead: - def __init__(self, login_name: str, password: str) -> None: + def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: self.login_name = login_name def close(self) -> None: @@ -391,7 +391,7 @@ def test_refresh_records_outcome_and_skips_paused_accounts() -> None: _add_account("empty-user", credential=None, refreshed_at=stamped, valid=False) created = [] - def factory(login_name: str, password: str): + def factory(login_name: str, password: str, proxy: str | None = None): created.append(login_name) if login_name == "failed-user": return _Dead(login_name, password) @@ -426,8 +426,8 @@ def test_paused_account_still_updates_when_opening_home() -> None: _add_account("paused-user", paused=True) class HomeClient(_Alive): - def __init__(self, login_name: str, password: str) -> None: - super().__init__(login_name, password) + def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: + super().__init__(login_name, password, proxy) self._token = "yxt-1" def home_summary(self) -> dict: @@ -455,7 +455,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None: _add_account("saved-user") calls = [] - def factory(login_name: str, password: str): + def factory(login_name: str, password: str, proxy: str | None = None): calls.append(login_name) return _Alive(login_name, password) @@ -525,7 +525,7 @@ def test_check_all_reports_each_saved_account() -> None: _add_account("c-user", credential=None) calls = [] - def factory(login_name: str, password: str): + def factory(login_name: str, password: str, proxy: str | None = None): calls.append(login_name) if login_name == "b-user": raise RuntimeError("网络失败") diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 3b6141b..80682f8 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -213,7 +213,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None: service_module._pending.clear() class ManualClient: - def __init__(self, login_name: str, password: str) -> None: + def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: self.login_name = login_name self.password = password self._profile = { diff --git a/backend/tests/test_courses.py b/backend/tests/test_courses.py index e7b602b..40abe56 100644 --- a/backend/tests/test_courses.py +++ b/backend/tests/test_courses.py @@ -100,5 +100,56 @@ def test_course_page_filters_by_title() -> None: assert {item["name"] for item in filtered["kinds"]} == {"课程包", "文档"} +def test_uncategorized_filter_and_like_escape() -> None: + from euniv.courses import UNCATEGORIZED, course_page + from euniv.db import SessionLocal + from euniv.models import Course + + with SessionLocal() as db: + db.add(Course( + path="/kng/view/document/plain.html", + title="100%完成", + kind="", + contributor="甲", + recommend="0", + learners="1", + released_on="2026-01-01", + updated_on="2026-01-01", + comments="0", + )) + db.add(Course( + path="/kng/view/document/other.html", + title="axb", + kind="文档", + contributor="乙", + recommend="0", + learners="1", + released_on="2026-01-02", + updated_on="2026-01-02", + comments="0", + )) + db.add(Course( + path="/kng/view/document/underscore.html", + title="a_b", + kind="文档", + contributor="丙", + recommend="0", + learners="1", + released_on="2026-01-03", + updated_on="2026-01-03", + comments="0", + )) + db.commit() + blank = course_page(db, "", 0, 50, kind=UNCATEGORIZED) + assert blank["total"] == 1 + assert blank["items"][0]["title"] == "100%完成" + kinds = {item["name"]: item["value"] for item in blank["kinds"]} + assert kinds["未分类"] == UNCATEGORIZED + found = course_page(db, "100%", 0, 50) + assert [item["title"] for item in found["items"]] == ["100%完成"] + underscore = course_page(db, "a_b", 0, 50) + assert [item["title"] for item in underscore["items"]] == ["a_b"] + + def test_course_gap_stays_between_eight_and_sixteen_hours() -> None: assert next_gap(_FixedRandom()) == timedelta(hours=12) diff --git a/web/src/features/admin/CoursesView.vue b/web/src/features/admin/CoursesView.vue index 3687522..d3c3fcc 100644 --- a/web/src/features/admin/CoursesView.vue +++ b/web/src/features/admin/CoursesView.vue @@ -2,6 +2,7 @@ import { computed, onMounted, onUnmounted, ref } from "vue"; import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui"; import { DownloadOutline } from "@vicons/ionicons5"; +import { formatTime, isRecord, textOf } from "../../shared/text"; interface CourseRow { title: string; @@ -35,14 +36,6 @@ const kindTotal = computed(() => kinds.value.reduce((sum, item) => sum + item.co const fetching = ref(false); let poll = 0; -function isRecord(value: unknown): value is Record { - return !!value && typeof value === "object" && !Array.isArray(value); -} - -function textOf(value: unknown) { - return typeof value === "string" ? value : ""; -} - function asCourse(value: unknown): CourseRow | null { if (!isRecord(value) || typeof value.title !== "string") return null; return { @@ -66,14 +59,6 @@ function courseKey(row: CourseRow, index: number) { return first === index ? base : `${base}#${index}`; } -function formatTime(value: string | null) { - if (!value) return ""; - const date = new Date(value); - if (Number.isNaN(date.getTime())) return value; - const pad = (part: number) => String(part).padStart(2, "0"); - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; -} - async function load(clamp = true) { if (items.value.length === 0) loading.value = true; try { diff --git a/web/src/features/admin/ProxiesView.vue b/web/src/features/admin/ProxiesView.vue index 7e537b3..bb75ecb 100644 --- a/web/src/features/admin/ProxiesView.vue +++ b/web/src/features/admin/ProxiesView.vue @@ -2,6 +2,7 @@ import { computed, onMounted, onUnmounted, ref } from "vue"; import { NAlert, NButton, NIcon, NInput, NPagination, NSpin, NTooltip } from "naive-ui"; import { RefreshOutline } from "@vicons/ionicons5"; +import { formatTime, isRecord, textOf } from "../../shared/text"; interface ProxyRow { id: number; @@ -51,14 +52,6 @@ const kinds = computed(() => [ const kindTotal = computed(() => alive.value + dead.value + pending.value); const probeScope = computed(() => (appliedQuery.value || status.value ? "当前筛选" : "全部")); -function isRecord(value: unknown): value is Record { - return !!value && typeof value === "object" && !Array.isArray(value); -} - -function textOf(value: unknown) { - return typeof value === "string" ? value : ""; -} - function asRow(value: unknown): ProxyRow | null { if (!isRecord(value) || typeof value.id !== "number" || typeof value.host !== "string") return null; return { @@ -77,14 +70,6 @@ function asRow(value: unknown): ProxyRow | null { }; } -function formatTime(value: string | null) { - if (!value) return ""; - const date = new Date(value); - if (Number.isNaN(date.getTime())) return value; - const pad = (part: number) => String(part).padStart(2, "0"); - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; -} - function formatLatency(value: number | null) { if (value == null) return "—"; return `${value} ms`; @@ -323,7 +308,7 @@ onUnmounted(() => stopPoll());

可用 {{ alive }} · 失效 {{ dead }} - +