fix: 打开时等后台就绪再显示已保存登录
This commit is contained in:
@@ -143,7 +143,7 @@ async def _merge(changes: list[tuple[str, str, dict | None]]) -> None:
|
|||||||
|
|
||||||
|
|
||||||
async def available_accounts() -> list[dict]:
|
async def available_accounts() -> list[dict]:
|
||||||
"""并发向平台确认每条凭证。失效的删掉,暂时连不上的留着但不显示。"""
|
"""并发向平台确认每条凭证。确认失效的删掉,暂时连不上的仍显示本机保存的信息。"""
|
||||||
items = _read()
|
items = _read()
|
||||||
probed = await asyncio.gather(*(_probe(item) for item in items))
|
probed = await asyncio.gather(*(_probe(item) for item in items))
|
||||||
changes: list[tuple[str, str, dict | None]] = []
|
changes: list[tuple[str, str, dict | None]] = []
|
||||||
@@ -151,8 +151,9 @@ async def available_accounts() -> list[dict]:
|
|||||||
for item, (status, record) in zip(items, probed):
|
for item, (status, record) in zip(items, probed):
|
||||||
login_id = str(item.get("loginId") or "")
|
login_id = str(item.get("loginId") or "")
|
||||||
changes.append((login_id, status, record))
|
changes.append((login_id, status, record))
|
||||||
if status == "ok" and record is not None:
|
if status == "drop":
|
||||||
visible.append(public_view(record))
|
continue
|
||||||
|
visible.append(public_view(record if status == "ok" and record is not None else item))
|
||||||
await _merge(changes)
|
await _merge(changes)
|
||||||
return visible
|
return visible
|
||||||
|
|
||||||
|
|||||||
@@ -415,7 +415,7 @@ async def _saved_accounts_keep_temporary_failures(tmp_path: Path, monkeypatch):
|
|||||||
monkeypatch.setattr(NqiClient, "export_cookies", exported)
|
monkeypatch.setattr(NqiClient, "export_cookies", exported)
|
||||||
visible = await sessions.available_accounts()
|
visible = await sessions.available_accounts()
|
||||||
stored = {item["loginId"]: item for item in sessions._read()}
|
stored = {item["loginId"]: item for item in sessions._read()}
|
||||||
assert [item["loginId"] for item in visible] == ["a"]
|
assert [item["loginId"] for item in visible] == ["a", "down"]
|
||||||
assert "dead" not in stored
|
assert "dead" not in stored
|
||||||
assert stored["down"]["cookies"][0]["value"] == "down"
|
assert stored["down"]["cookies"][0]["value"] == "down"
|
||||||
assert stored["a"]["cookies"][0]["value"] == "a-new"
|
assert stored["a"]["cookies"][0]["value"] == "a-new"
|
||||||
@@ -445,7 +445,7 @@ async def _saved_accounts_probe_together_and_timeout_keeps_cookie(tmp_path: Path
|
|||||||
visible = await sessions.available_accounts()
|
visible = await sessions.available_accounts()
|
||||||
assert time.monotonic() - started < 0.5
|
assert time.monotonic() - started < 0.5
|
||||||
assert max(starts) - min(starts) < 0.2
|
assert max(starts) - min(starts) < 0.2
|
||||||
assert [item["loginId"] for item in visible] == ["b"]
|
assert [item["loginId"] for item in visible] == ["b", "slow"]
|
||||||
stored = {item["loginId"]: item for item in sessions._read()}
|
stored = {item["loginId"]: item for item in sessions._read()}
|
||||||
assert stored["slow"]["cookies"][0]["value"] == "slow"
|
assert stored["slow"]["cookies"][0]["value"] == "slow"
|
||||||
assert stored["b"]["cookies"][0]["value"] == "b-new"
|
assert stored["b"]["cookies"][0]["value"] == "b-new"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { onMounted, onUnmounted, ref } from "vue";
|
import { onMounted, onUnmounted, ref } from "vue";
|
||||||
import { NAlert, NButton, NIcon, NInput, NModal, NSelect, NSpin, NTooltip } from "naive-ui";
|
import { NAlert, NButton, NIcon, NInput, NModal, NSelect, NSpin, NTooltip } from "naive-ui";
|
||||||
import { HelpCircleOutline, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
import { HelpCircleOutline, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||||
import { ApiError, canRestartBackend, resetApi, restartBackend } from "../../shared/http";
|
import { ApiError, canRestartBackend, initApi, resetApi, restartBackend } from "../../shared/http";
|
||||||
import { loadCaptcha, loadSaved, login, refreshCaptcha, resumeSaved, sendSms, type UserInfo } from "./api";
|
import { loadCaptcha, loadSaved, login, refreshCaptcha, resumeSaved, sendSms, type UserInfo } from "./api";
|
||||||
import { isDark, toggleTheme } from "../../shared/theme";
|
import { isDark, toggleTheme } from "../../shared/theme";
|
||||||
|
|
||||||
@@ -35,19 +35,31 @@ let timer = 0;
|
|||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
void connect();
|
void connect();
|
||||||
void refreshSaved();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function wait(ms: number) {
|
||||||
|
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function retryable(error: unknown) {
|
||||||
|
if (!(error instanceof ApiError)) return true;
|
||||||
|
if (error.status === 0 || error.status >= 500) return true;
|
||||||
|
return /连接失败|请求失败|后台服务没有启动|平台响应超时|服务出错/.test(error.message);
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSaved() {
|
async function refreshSaved() {
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
try {
|
try {
|
||||||
const result = await loadSaved();
|
const result = await loadSaved();
|
||||||
saved.value = result.accounts;
|
saved.value = result.accounts;
|
||||||
if (!result.accounts.some((item) => item.loginId === savedId.value)) {
|
if (!result.accounts.some((item) => item.loginId === savedId.value)) {
|
||||||
savedId.value = result.accounts[0]?.loginId ?? null;
|
savedId.value = result.accounts[0]?.loginId ?? null;
|
||||||
}
|
}
|
||||||
} catch {
|
return;
|
||||||
saved.value = [];
|
} catch (error) {
|
||||||
savedId.value = null;
|
if (attempt === 4 || !retryable(error)) return;
|
||||||
|
await wait(400);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,32 +71,44 @@ async function connect() {
|
|||||||
allowRestart.value = false;
|
allowRestart.value = false;
|
||||||
offline.value = "";
|
offline.value = "";
|
||||||
ready.value = false;
|
ready.value = false;
|
||||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
try {
|
try {
|
||||||
const result = await loadCaptcha();
|
await initApi();
|
||||||
sessionId.value = result.sessionId;
|
break;
|
||||||
captchaUrl.value = result.captcha;
|
|
||||||
ready.value = true;
|
|
||||||
connecting.value = false;
|
|
||||||
offline.value = "";
|
|
||||||
return;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const failedLocally = !(error instanceof ApiError) || error.status === 0;
|
|
||||||
offline.value = error instanceof ApiError ? error.message : "连接失败";
|
|
||||||
backendUnavailable.value = error instanceof ApiError && error.message === "后台服务没有启动";
|
backendUnavailable.value = error instanceof ApiError && error.message === "后台服务没有启动";
|
||||||
if (!failedLocally) {
|
if (attempt === 2) {
|
||||||
ready.value = true;
|
|
||||||
connecting.value = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await new Promise((resolve) => window.setTimeout(resolve, 500));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
connecting.value = false;
|
connecting.value = false;
|
||||||
connectFailed.value = true;
|
connectFailed.value = true;
|
||||||
ready.value = false;
|
ready.value = false;
|
||||||
offline.value = backendUnavailable.value ? "后台服务没有启动" : "连接失败";
|
offline.value = backendUnavailable.value ? "后台服务没有启动" : "连接失败";
|
||||||
allowRestart.value = backendUnavailable.value && canRestartBackend();
|
allowRestart.value = backendUnavailable.value && canRestartBackend();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resetApi();
|
||||||
|
await wait(500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connecting.value = false;
|
||||||
|
void refreshSaved();
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const result = await loadCaptcha();
|
||||||
|
sessionId.value = result.sessionId;
|
||||||
|
captchaUrl.value = result.captcha;
|
||||||
|
ready.value = true;
|
||||||
|
offline.value = "";
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
if (attempt === 4 || !retryable(error)) {
|
||||||
|
offline.value = error instanceof ApiError ? error.message : "连接失败";
|
||||||
|
connectFailed.value = retryable(error);
|
||||||
|
ready.value = !connectFailed.value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await wait(500);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onRestart() {
|
async function onRestart() {
|
||||||
|
|||||||
@@ -86,12 +86,27 @@ function commandMissing(error: unknown, name: string) {
|
|||||||
return text.includes("not found") && text.includes(name.toLowerCase());
|
return text.includes("not found") && text.includes(name.toLowerCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function pingHealth(): Promise<boolean> {
|
||||||
|
if (!apiBase) return false;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = window.setTimeout(() => controller.abort(), 800);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${apiBase}/api/health`, { signal: controller.signal });
|
||||||
|
return response.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
window.clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function probeBackend(): Promise<boolean> {
|
async function probeBackend(): Promise<boolean> {
|
||||||
const { invoke } = await import("@tauri-apps/api/core");
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
try {
|
try {
|
||||||
const info = await invoke<BackendInfo>("backend_info");
|
const info = await invoke<BackendInfo>("backend_info");
|
||||||
restartAvailable = true;
|
restartAvailable = true;
|
||||||
return applyBackend(info);
|
if (!applyBackend(info)) return false;
|
||||||
|
return pingHealth();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!commandMissing(error, "backend_info")) {
|
if (!commandMissing(error, "backend_info")) {
|
||||||
restartAvailable = true;
|
restartAvailable = true;
|
||||||
@@ -104,7 +119,7 @@ async function probeBackend(): Promise<boolean> {
|
|||||||
const port = await invoke<number>("backend_port");
|
const port = await invoke<number>("backend_port");
|
||||||
if (port > 0) {
|
if (port > 0) {
|
||||||
apiBase = `http://127.0.0.1:${port}`;
|
apiBase = `http://127.0.0.1:${port}`;
|
||||||
return true;
|
return pingHealth();
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 窗口可能比端口命令更早就绪。
|
// 窗口可能比端口命令更早就绪。
|
||||||
@@ -115,10 +130,12 @@ async function probeBackend(): Promise<boolean> {
|
|||||||
|
|
||||||
async function resolveApiBase(): Promise<void> {
|
async function resolveApiBase(): Promise<void> {
|
||||||
if (!isTauri()) return;
|
if (!isTauri()) return;
|
||||||
const attempts = deepScanDone ? 1 : 50;
|
const attempts = deepScanDone ? 1 : 80;
|
||||||
deepScanDone = true;
|
|
||||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||||
if (await probeBackend()) return;
|
if (await probeBackend()) {
|
||||||
|
deepScanDone = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (attempt + 1 < attempts) {
|
if (attempt + 1 < attempts) {
|
||||||
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user