feat: 自动代理改为向接口领取,去掉 ProxyHub 和代理列表

This commit is contained in:
2026-11-17 21:15:41 +08:00
parent 19db13b360
commit 2fc5a0421b
14 changed files with 559 additions and 1743 deletions
-434
View File
@@ -1,434 +0,0 @@
<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";
import { formatTime, isRecord, textOf } from "../../shared/text";
interface ProxyRow {
id: number;
scheme: string;
host: string;
port: number;
country: string;
anonymity: string;
source: string;
status: string;
status_text: string;
latency_ms: number | null;
last_checked_at: string | null;
note: string;
}
interface StatusOption {
name: string;
value: string;
count: number;
}
const loading = ref(true);
const errorText = ref("");
const query = ref("");
const appliedQuery = ref("");
const status = ref("");
const items = ref<ProxyRow[]>([]);
const total = ref(0);
const alive = ref(0);
const dead = ref(0);
const pending = ref(0);
const fetchedAt = ref<string | null>(null);
const page = ref(1);
const pageSize = ref(50);
const pageSizes = [20, 50, 100];
const fetching = ref(false);
const probingId = ref<number | null>(null);
const probingAll = ref(false);
let poll = 0;
let disposed = false;
let loadSeq = 0;
const kinds = computed<StatusOption[]>(() => [
{ name: "可用", value: "alive", count: alive.value },
{ name: "失效", value: "dead", count: dead.value },
{ name: "待检测", value: "new", count: pending.value },
]);
const kindTotal = computed(() => alive.value + dead.value + pending.value);
const probeScope = computed(() => (appliedQuery.value || status.value ? "当前筛选" : "全部"));
function asRow(value: unknown): ProxyRow | null {
if (!isRecord(value) || typeof value.id !== "number" || typeof value.host !== "string") return null;
return {
id: value.id,
scheme: textOf(value.scheme),
host: value.host,
port: typeof value.port === "number" ? value.port : 0,
country: textOf(value.country) || "—",
anonymity: textOf(value.anonymity) || "—",
source: textOf(value.source) || "—",
status: textOf(value.status),
status_text: textOf(value.status_text) || "—",
latency_ms: typeof value.latency_ms === "number" ? value.latency_ms : null,
last_checked_at: typeof value.last_checked_at === "string" && value.last_checked_at ? value.last_checked_at : null,
note: textOf(value.note),
};
}
function formatLatency(value: number | null) {
if (value == null) return "—";
return `${value} ms`;
}
const probingHost = computed(() => {
if (probingId.value == null) return "";
const row = items.value.find((item) => item.id === probingId.value);
return row ? `${row.host}:${row.port}` : "";
});
function schemeLabel(value: string) {
return value ? value.toUpperCase() : "—";
}
function setError(next: string) {
if (errorText.value !== next) errorText.value = next;
}
function proxyKey(row: ProxyRow, index: number) {
const first = items.value.findIndex((item) => item.id === row.id);
return first === index ? String(row.id) : `${row.id}#${index}`;
}
function shiftCount(kind: string, delta: number) {
if (kind === "alive") alive.value += delta;
else if (kind === "dead") dead.value += delta;
else if (kind === "new") pending.value += delta;
}
function adjustCounts(previous: ProxyRow, next: ProxyRow) {
if (previous.status === next.status) return;
shiftCount(previous.status, -1);
shiftCount(next.status, 1);
}
function statusClass(row: ProxyRow) {
if (row.status === "alive") return "ok";
if (row.status === "dead") return "late";
return "quiet";
}
async function load(clamp = true) {
const seq = ++loadSeq;
if (items.value.length === 0) loading.value = true;
try {
const params = new URLSearchParams({
q: appliedQuery.value,
status: status.value,
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
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;
if (response.status === 401) {
stopPoll();
if (!items.value.length) setError("代理列表没有获取到。");
return;
}
if (!response.ok) {
setError("代理列表没有获取到。");
return;
}
if (!isRecord(payload) || !Array.isArray(payload.items)) {
setError("数据异常");
return;
}
items.value = payload.items.map(asRow).filter((item): item is ProxyRow => item !== null);
total.value = typeof payload.total === "number" ? payload.total : items.value.length;
alive.value = typeof payload.alive === "number" ? payload.alive : 0;
dead.value = typeof payload.dead === "number" ? payload.dead : 0;
pending.value = typeof payload.pending === "number" ? payload.pending : 0;
fetchedAt.value = typeof payload.fetched_at === "string" && payload.fetched_at ? payload.fetched_at : null;
fetching.value = payload.running === true;
const message = typeof payload.message === "string" ? payload.message : "";
setError(message);
if (fetching.value) startPoll();
else stopPoll();
const maxPage = Math.max(1, Math.ceil(total.value / pageSize.value));
if (clamp && page.value > maxPage) {
page.value = maxPage;
await load(false);
}
} catch {
if (!disposed && seq === loadSeq) setError("代理列表没有获取到。");
} finally {
if (seq === loadSeq) loading.value = false;
}
}
function startPoll() {
if (disposed || poll) return;
poll = window.setTimeout(() => {
poll = 0;
if (!disposed) void load();
}, 2000);
}
function stopPoll() {
window.clearTimeout(poll);
poll = 0;
}
function applyProbed(row: ProxyRow) {
items.value = items.value.map((item) => (item.id === row.id ? row : item));
}
async function probeOne(row: ProxyRow) {
if (probingId.value != null || probingAll.value || fetching.value) return;
probingId.value = row.id;
setError("");
try {
const response = await apiFetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
setError("没有测出延迟。");
return;
}
const next = asRow(payload);
if (next) {
const previous = items.value.find((item) => item.id === next.id);
if (previous) adjustCounts(previous, next);
applyProbed(next);
}
} catch {
setError("没有测出延迟。");
} finally {
probingId.value = null;
}
}
async function filteredIds() {
if (!appliedQuery.value && !status.value) return null;
const ids: number[] = [];
const limit = 100;
let offset = 0;
for (;;) {
const params = new URLSearchParams({
q: appliedQuery.value,
status: status.value,
offset: String(offset),
limit: String(limit),
});
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("代理列表没有获取到。");
}
const page = payload.items.map(asRow).filter((item): item is ProxyRow => item !== null);
for (const row of page) ids.push(row.id);
if (page.length < limit) return ids;
offset += limit;
if (offset > 10000) return ids;
}
}
async function probeAll() {
if (probingId.value != null || probingAll.value || fetching.value) return;
probingAll.value = true;
setError("");
try {
const ids = await filteredIds();
if (ids && !ids.length) {
setError("没有可测试的代理。");
return;
}
const response = await apiFetch("/api/admin/proxies/probe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ids ? { ids } : {}),
});
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload)) {
setError("没有测出延迟。");
return;
}
for (let attempt = 0; attempt < 120; attempt += 1) {
if (disposed) return;
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) {
if (typeof body.error === "string" && body.error) setError(body.error);
break;
}
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
await load();
} catch {
setError("没有测出延迟。");
} finally {
probingAll.value = false;
}
}
async function refreshNow() {
setError("");
fetching.value = true;
try {
const response = await apiFetch("/api/admin/proxies/refresh", { method: "POST" });
await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
setError("没有更新。");
return;
}
await load();
} catch {
fetching.value = false;
setError("没有更新。");
}
}
function pickStatus(value: string) {
status.value = value;
page.value = 1;
void load();
}
function goPage(next: number) {
page.value = next;
void load();
}
function changeSize(size: number) {
pageSize.value = size;
page.value = 1;
void load();
}
function search() {
appliedQuery.value = query.value.trim();
page.value = 1;
void load();
}
function clearSearch() {
query.value = "";
search();
}
onMounted(() => {
void load();
});
onUnmounted(() => {
disposed = true;
stopPoll();
});
</script>
<template>
<section class="page admin-page">
<header class="page-head">
<p v-if="!loading">
可用 {{ alive }} · 失效 {{ dead }}
<template v-if="fetchedAt"> · 更新于 {{ formatTime(fetchedAt, true) }}</template>
</p>
<form class="course-search" @submit.prevent="search">
<n-tooltip>
<template #trigger>
<n-button quaternary circle attr-type="button" :loading="fetching" :disabled="fetching || probingAll" aria-label="立即更新" @click="refreshNow">
<template #icon><n-icon><RefreshOutline /></n-icon></template>
</n-button>
</template>
立即更新
</n-tooltip>
<n-button size="small" attr-type="button" :loading="probingAll" :disabled="probingAll || fetching" @click="probeAll">
测试{{ probeScope }}
</n-button>
<n-input v-model:value="query" placeholder="地址" clearable @clear="clearSearch" />
<n-button attr-type="submit">搜索</n-button>
</form>
</header>
<div v-if="kindTotal > 0" class="course-kinds">
<button type="button" class="kind-chip" :class="{ active: status === '' }" @click="pickStatus('')">全部<span>{{ kindTotal }}</span></button>
<button
v-for="item in kinds"
:key="item.value"
type="button"
class="kind-chip"
:class="{ active: status === item.value }"
@click="pickStatus(item.value)"
>
{{ item.name }}<span>{{ item.count }}</span>
</button>
</div>
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
<n-alert v-if="probingAll" class="admin-alert" type="info">正在测试{{ probeScope }}代理延迟</n-alert>
<n-alert v-else-if="probingId != null" class="admin-alert" type="info">正在测试 {{ probingHost }} 延迟</n-alert>
<div class="admin-scroll">
<p v-if="loading" class="admin-status">正在获取</p>
<p v-else-if="fetching && !items.length" class="admin-status">正在获取</p>
<p v-else-if="!items.length && !errorText" class="admin-status">还没有代理</p>
<table v-else-if="items.length" class="admin-table">
<thead>
<tr>
<th>国家</th>
<th>地址</th>
<th>端口</th>
<th>协议</th>
<th>匿名</th>
<th>来源</th>
<th>延迟</th>
<th>状态</th>
<th>检测时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in items" :key="proxyKey(row, index)">
<td>{{ row.country }}</td>
<td class="employee">{{ row.host }}</td>
<td class="when">{{ row.port }}</td>
<td>{{ schemeLabel(row.scheme) }}</td>
<td>{{ row.anonymity }}</td>
<td>{{ row.source }}</td>
<td class="when">
<span v-if="probingAll || probingId === row.id" class="probe-loading">
<n-spin :size="14" />测试中
</span>
<template v-else>{{ formatLatency(row.latency_ms) }}</template>
</td>
<td :class="statusClass(row)" :title="row.note || undefined">
{{ row.status_text }}<template v-if="row.note"> · {{ row.note }}</template>
</td>
<td class="when">{{ formatTime(row.last_checked_at, true) || "—" }}</td>
<td>
<n-button
size="tiny"
:loading="probingId === row.id"
:disabled="probingAll || fetching || (probingId != null && probingId !== row.id)"
@click="probeOne(row)"
>
测试
</n-button>
</td>
</tr>
</tbody>
</table>
</div>
<n-pagination
v-if="total > 0"
class="course-pager"
:page="page"
:page-size="pageSize"
:item-count="total"
:page-sizes="pageSizes"
show-size-picker
show-quick-jumper
@update:page="goPage"
@update:page-size="changeSize"
>
<template #prefix>共 {{ total }} 条</template>
</n-pagination>
</section>
</template>
+3 -5
View File
@@ -6,7 +6,6 @@ import { isDark, toggleTheme } from "../shared/theme";
import { adminNavOptions, type AdminPageKey } from "./adminNavigation";
import UsersView from "../features/admin/UsersView.vue";
import CoursesView from "../features/admin/CoursesView.vue";
import ProxiesView from "../features/admin/ProxiesView.vue";
import SettingsView from "../features/admin/SettingsView.vue";
defineProps<{ username: string }>();
@@ -14,7 +13,7 @@ const emit = defineEmits<{ logout: []; refresh: [] }>();
const page = ref<AdminPageKey>(pageFromHash());
const collapsed = ref(window.innerWidth < 800);
const holdOpen = ref(false);
const pages = new Set<AdminPageKey>(["users", "courses", "proxies", "settings"]);
const pages = new Set<AdminPageKey>(["users", "courses", "settings"]);
function hashName() {
return window.location.hash.replace(/^#\/?/, "");
@@ -22,7 +21,7 @@ function hashName() {
function pageFromHash(): AdminPageKey {
const name = hashName();
if (name === "courses" || name === "proxies" || name === "settings" || name === "users") return name;
if (name === "courses" || name === "settings" || name === "users") return name;
return "users";
}
@@ -73,7 +72,7 @@ onUnmounted(() => {
});
function onMenu(key: string) {
if (key === "users" || key === "courses" || key === "proxies" || key === "settings") show(key);
if (key === "users" || key === "courses" || key === "settings") show(key);
}
</script>
@@ -132,7 +131,6 @@ function onMenu(key: string) {
<n-layout class="content" :native-scrollbar="false" content-style="height: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column;">
<UsersView v-if="page === 'users'" />
<CoursesView v-else-if="page === 'courses'" />
<ProxiesView v-else-if="page === 'proxies'" />
<SettingsView v-else-if="page === 'settings'" @saved="emit('refresh')" />
</n-layout>
</n-layout>
+2 -3
View File
@@ -1,17 +1,16 @@
import type { Component } from "vue";
import { h } from "vue";
import { NIcon } from "naive-ui";
import { GlobeOutline, LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
import { LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
function renderIcon(icon: Component) {
return () => h(NIcon, null, { default: () => h(icon) });
}
export type AdminPageKey = "users" | "courses" | "proxies" | "settings";
export type AdminPageKey = "users" | "courses" | "settings";
export const adminNavOptions = [
{ label: "用户管理", key: "users" as const, icon: renderIcon(PeopleOutline) },
{ label: "课程清单", key: "courses" as const, icon: renderIcon(LibraryOutline) },
{ label: "代理", key: "proxies" as const, icon: renderIcon(GlobeOutline) },
{ label: "系统配置", key: "settings" as const, icon: renderIcon(SettingsOutline) },
];