Skip to content

Commit 261f647

Browse files
authored
feat: 自更新支持 GitHub 加速代理与 CNB 镜像,WebUI 可配置 (#9)
- 新增配置项 MIMO_CONSOLE_GITHUB_PROXY:空为直连,支持 gh-proxy 风格前缀、 CNB 镜像仓库地址及自定义地址;写入 .env 并热更新内存配置,保存立即生效 - 版本检测与自更新按该配置解析实际拉取地址(resolve_git_url/resolve_version_url) - 概览页新增「GitHub 加速」卡片:内置 4 个加速前缀 + CNB 镜像 + 自定义, 支持一键测试连通性(返回延迟);长 URL 选项自适应换行 - 版本号 0.1.2 → 0.1.3
1 parent 2fd61ca commit 261f647

9 files changed

Lines changed: 328 additions & 12 deletions

File tree

‎pyproject.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "nonebot-plugin-mimo-console"
3-
version = "0.1.2"
3+
version = "0.1.3"
44
description = "A glass-style WebUI management console for NoneBot2"
55
readme = "README.md"
66
requires-python = ">=3.10"
@@ -54,7 +54,7 @@ requires = ["uv_build>=0.10.0,<0.12.0"]
5454
build-backend = "uv_build"
5555

5656
[tool.bumpversion]
57-
current_version = "0.1.2"
57+
current_version = "0.1.3"
5858
commit = true
5959
message = "chore: 发布 v{new_version}"
6060
tag = true

‎src/nonebot_plugin_mimo_console/api.py‎

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from collections import defaultdict, deque
88
from typing import Annotated, Any, Literal
99

10+
import httpx
1011
from fastapi import APIRouter, Depends, HTTPException, Query, Request, UploadFile, status
1112
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
1213
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
@@ -19,7 +20,14 @@
1920
from .security import AuthError, Session
2021
from .state import ConsoleState
2122
from .store import StoreError, _clean_output, build_self_update_command
22-
from .version import PACKAGE_GIT_URL, PACKAGE_NAME, get_installed_version
23+
from .version import (
24+
GITHUB_PROXY_PRESETS,
25+
PACKAGE_NAME,
26+
get_installed_version,
27+
normalize_github_proxy,
28+
resolve_git_url,
29+
resolve_version_url,
30+
)
2331

2432

2533
class SetupBody(BaseModel):
@@ -45,6 +53,10 @@ class PluginActionBody(BaseModel):
4553
action: Literal["install", "update", "uninstall"]
4654

4755

56+
class GithubProxyBody(BaseModel):
57+
proxy: str = Field(default="", max_length=512)
58+
59+
4860
class AttemptLimiter:
4961
def __init__(self, limit: int = 10, window: int = 300) -> None:
5062
self.limit = limit
@@ -312,9 +324,65 @@ async def system_version(
312324
session: Annotated[Session, Depends(require_session)],
313325
force: bool = Query(default=False),
314326
) -> dict[str, Any]:
315-
await state.release_cache.fetch(force=force)
327+
await state.release_cache.fetch(force=force, proxy=state.config.mimo_console_github_proxy)
316328
return state.release_cache.snapshot(get_installed_version())
317329

330+
@router.get("/api/system/github-proxy")
331+
async def get_github_proxy(
332+
session: Annotated[Session, Depends(require_session)],
333+
) -> dict[str, Any]:
334+
return {
335+
"proxy": state.config.mimo_console_github_proxy,
336+
"presets": list(GITHUB_PROXY_PRESETS),
337+
}
338+
339+
@router.put("/api/system/github-proxy")
340+
async def set_github_proxy(
341+
body: GithubProxyBody,
342+
session: Annotated[Session, Depends(require_session)],
343+
) -> dict[str, Any]:
344+
try:
345+
proxy = normalize_github_proxy(body.proxy)
346+
except ValueError as exc:
347+
raise HTTPException(status_code=400, detail=str(exc)) from exc
348+
environment = str(getattr(get_driver().config, "environment", "prod"))
349+
path = locate_env_file(state.config.project_root(), environment)
350+
try:
351+
await asyncio.to_thread(
352+
update_env, path, {"MIMO_CONSOLE_GITHUB_PROXY": proxy}, state.backup_dir
353+
)
354+
except (OSError, ValueError) as exc:
355+
raise HTTPException(status_code=400, detail=str(exc)) from exc
356+
# 热更新内存配置,无需重启即可生效
357+
state.config.mimo_console_github_proxy = proxy
358+
logger.info(f"[Mimo Console] GitHub 加速已设置为:{proxy or '直连'}")
359+
return {"ok": True, "proxy": proxy}
360+
361+
@router.post("/api/system/github-proxy/test")
362+
async def test_github_proxy(
363+
body: GithubProxyBody,
364+
session: Annotated[Session, Depends(require_session)],
365+
) -> dict[str, Any]:
366+
try:
367+
proxy = normalize_github_proxy(body.proxy)
368+
except ValueError as exc:
369+
raise HTTPException(status_code=400, detail=str(exc)) from exc
370+
url = resolve_version_url(proxy)
371+
started = time.perf_counter()
372+
try:
373+
async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:
374+
response = await client.get(url, headers={"User-Agent": PACKAGE_NAME})
375+
latency = int((time.perf_counter() - started) * 1000)
376+
except (httpx.HTTPError, OSError) as exc:
377+
return {"ok": False, "latency_ms": None, "detail": f"连接失败:{exc}"}
378+
if response.status_code != 200:
379+
return {
380+
"ok": False,
381+
"latency_ms": latency,
382+
"detail": f"加速地址返回 HTTP {response.status_code}",
383+
}
384+
return {"ok": True, "latency_ms": latency, "detail": ""}
385+
318386
@router.post("/api/system/update")
319387
async def system_update(
320388
session: Annotated[Session, Depends(require_session)],
@@ -324,7 +392,7 @@ async def system_update(
324392
command = build_self_update_command(
325393
state.config.project_root(),
326394
PACKAGE_NAME,
327-
PACKAGE_GIT_URL,
395+
resolve_git_url(state.config.mimo_console_github_proxy),
328396
)
329397
env = os.environ.copy()
330398
env.update({"NO_COLOR": "1", "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"})

‎src/nonebot_plugin_mimo_console/config.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
from pydantic import BaseModel, Field, field_validator
66

7+
from .version import normalize_github_proxy
8+
79

810
class ConsoleConfig(BaseModel):
911
"""NoneBot 环境变量中的控制台配置。"""
@@ -16,12 +18,18 @@ class ConsoleConfig(BaseModel):
1618
mimo_console_store_cache_seconds: int = Field(default=600, ge=60, le=86400)
1719
mimo_console_package_timeout: int = Field(default=300, ge=60, le=1800)
1820
mimo_console_background_url: str | None = None
21+
mimo_console_github_proxy: str = ""
1922

2023
@field_validator("mimo_console_path")
2124
@classmethod
2225
def normalize_path(cls, value: str) -> str:
2326
path = "/" + value.strip().strip("/")
2427
return path if path != "/" else "/mimo-console"
2528

29+
@field_validator("mimo_console_github_proxy")
30+
@classmethod
31+
def normalize_proxy(cls, value: str) -> str:
32+
return normalize_github_proxy(value)
33+
2634
def project_root(self) -> Path:
2735
return (self.mimo_console_project_root or Path.cwd()).expanduser().resolve()

‎src/nonebot_plugin_mimo_console/static/assets/app.js‎

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ const state = {
2828
background: { source: "default", url: "" },
2929
theme: null,
3030
version: null,
31+
proxy: { proxy: "", presets: [] },
3132
};
3233

3334
const $ = (selector, context = document) => context.querySelector(selector);
@@ -186,6 +187,8 @@ function bindEvents() {
186187
$("#theme-reset").addEventListener("click", resetTheme);
187188
$("#restart-button").addEventListener("click", restartNonebot);
188189
$("#check-update-btn").addEventListener("click", checkUpdate);
190+
$("#proxy-save").addEventListener("click", saveProxySettings);
191+
$("#proxy-test-btn").addEventListener("click", testProxySettings);
189192
$$(".view-toggle button").forEach((button) => button.addEventListener("click", () => {
190193
$$(".view-toggle button").forEach((item) => item.classList.remove("active"));
191194
button.classList.add("active");
@@ -242,7 +245,7 @@ function enterApp(username) {
242245
clearTimers();
243246
state.timers.push(setInterval(() => loadDashboard(false), 5000));
244247
state.timers.push(setInterval(loadLogs, 2000));
245-
Promise.allSettled([loadDashboard(), loadPlugins(), loadLogs(), loadBackground(), loadVersion()]);
248+
Promise.allSettled([loadDashboard(), loadPlugins(), loadLogs(), loadBackground(), loadVersion(), loadProxySettings()]);
246249
}
247250

248251
async function signOut(requestLogout) {
@@ -1146,6 +1149,106 @@ function renderVersion(data) {
11461149
$("#version-current").textContent = data.current ? `v${data.current}` : "--";
11471150
}
11481151

1152+
const PROXY_CUSTOM_VALUE = "__custom__";
1153+
1154+
function presetLabel(url) {
1155+
return url.includes("cnb.cool") ? "CNB 镜像仓库" : "GitHub 加速代理";
1156+
}
1157+
1158+
async function loadProxySettings() {
1159+
try {
1160+
state.proxy = await api("/system/github-proxy");
1161+
renderProxySettings();
1162+
} catch (_) { /* 读取失败不影响使用 */ }
1163+
}
1164+
1165+
function renderProxySettings() {
1166+
const container = $("#proxy-modes");
1167+
if (!container) return;
1168+
const presets = state.proxy.presets || [];
1169+
const current = state.proxy.proxy || "";
1170+
const options = [
1171+
{ value: "", title: "不使用 GitHub 加速", desc: "直连 GitHub" },
1172+
...presets.map((url) => ({ value: url, title: url, desc: presetLabel(url) })),
1173+
{ value: PROXY_CUSTOM_VALUE, title: "自定义", desc: "填入自定义加速前缀或镜像仓库地址" },
1174+
];
1175+
container.innerHTML = options
1176+
.map(
1177+
(opt) => `<label class="bg-mode">
1178+
<input type="radio" name="gh-proxy" value="${escapeHtml(opt.value)}"${opt.value === "" ? " data-proxy-off" : ""}>
1179+
<span class="bg-mode-text"><strong>${escapeHtml(opt.title)}</strong><small>${escapeHtml(opt.desc)}</small></span>
1180+
</label>`,
1181+
)
1182+
.join("");
1183+
const mode = current === "" ? "" : presets.includes(current) ? current : PROXY_CUSTOM_VALUE;
1184+
$$('input[name="gh-proxy"]', container).forEach((input) => {
1185+
input.checked = input.value === mode;
1186+
});
1187+
$("#proxy-custom-field").classList.toggle("hidden", mode !== PROXY_CUSTOM_VALUE);
1188+
if (mode === PROXY_CUSTOM_VALUE) $("#proxy-custom-input").value = current;
1189+
container.onchange = () => {
1190+
const checked = $('input[name="gh-proxy"]:checked', container);
1191+
$("#proxy-custom-field").classList.toggle(
1192+
"hidden",
1193+
!checked || checked.value !== PROXY_CUSTOM_VALUE,
1194+
);
1195+
};
1196+
updateProxyStatus();
1197+
}
1198+
1199+
function selectedProxyValue() {
1200+
const checked = $('input[name="gh-proxy"]:checked');
1201+
if (!checked) return "";
1202+
if (checked.value === PROXY_CUSTOM_VALUE) return ($("#proxy-custom-input").value || "").trim();
1203+
return checked.value;
1204+
}
1205+
1206+
function updateProxyStatus() {
1207+
const current = state.proxy.proxy || "";
1208+
$("#proxy-status").textContent = current ? `当前:${current}` : "当前:直连";
1209+
}
1210+
1211+
async function saveProxySettings() {
1212+
const button = $("#proxy-save");
1213+
button.disabled = true;
1214+
try {
1215+
const data = await api("/system/github-proxy", {
1216+
method: "PUT",
1217+
body: JSON.stringify({ proxy: selectedProxyValue() }),
1218+
});
1219+
state.proxy.proxy = data.proxy || "";
1220+
renderProxySettings();
1221+
toast("GitHub 加速设置已保存,立即生效");
1222+
} catch (error) {
1223+
toast(error.message, "error");
1224+
} finally {
1225+
button.disabled = false;
1226+
}
1227+
}
1228+
1229+
async function testProxySettings() {
1230+
const button = $("#proxy-test-btn");
1231+
const original = button.textContent;
1232+
button.disabled = true;
1233+
button.textContent = "测试中…";
1234+
try {
1235+
const data = await api("/system/github-proxy/test", {
1236+
method: "POST",
1237+
body: JSON.stringify({ proxy: selectedProxyValue() }),
1238+
});
1239+
if (data.ok) {
1240+
toast(`连通正常(${data.latency_ms}ms)`);
1241+
} else {
1242+
toast(data.detail || "连接失败", "error");
1243+
}
1244+
} catch (error) {
1245+
toast(error.message, "error");
1246+
} finally {
1247+
button.disabled = false;
1248+
button.textContent = original;
1249+
}
1250+
}
1251+
11491252
async function checkUpdate() {
11501253
const button = $("#check-update-btn");
11511254
const original = button.textContent;

‎src/nonebot_plugin_mimo_console/static/assets/styles.css‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,13 @@ a { color: inherit; text-decoration: none; }
770770
.bot-chip strong { display: block; font-size: 12px; }
771771
.bot-chip span, .empty-mini { color: var(--muted); font-size: 11px; }
772772
.recent-panel { margin-top: 12px; }
773+
.proxy-panel { margin-top: 12px; padding: 22px; }
774+
.proxy-panel .proxy-hint { margin: -8px 0 16px; font-size: 13px; line-height: 1.6; }
775+
.proxy-panel .bg-modes { grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); }
776+
.proxy-panel .bg-mode-text { min-width: 0; }
777+
.proxy-panel .bg-mode-text strong { overflow-wrap: anywhere; word-break: break-all; line-height: 1.45; }
778+
.proxy-panel .bg-actions { align-items: center; }
779+
.proxy-panel #proxy-status { font-size: 12px; overflow-wrap: anywhere; }
773780
.recent-logs {
774781
overflow: hidden;
775782
border: 1px solid var(--line);
@@ -1719,6 +1726,7 @@ a { color: inherit; text-decoration: none; }
17191726
.metric,
17201727
.dash-grid > .panel,
17211728
.recent-panel,
1729+
.proxy-panel,
17221730
.toolbar,
17231731
.tabs,
17241732
.plugin-card,

‎src/nonebot_plugin_mimo_console/static/index.html‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
<link rel="preconnect" href="https://fonts.googleapis.com">
2424
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
2525
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&display=swap" rel="stylesheet">
26-
<link rel="stylesheet" href="./assets/styles.css?v=0.6.1">
26+
<link rel="stylesheet" href="./assets/styles.css?v=0.6.3">
2727
</head>
2828
<body>
2929
<div class="bg-glow glow-a"></div>
@@ -115,7 +115,7 @@ <h2 id="auth-title">欢迎回来</h2>
115115
</div>
116116
<button id="logout-button" class="icon-btn logout-btn" title="退出登录"></button>
117117
</div>
118-
<div class="version">Mimo Console · v0.1.2</div>
118+
<div class="version">Mimo Console · v0.1.3</div>
119119
</div>
120120
</aside>
121121

@@ -231,6 +231,25 @@ <h2>最近日志</h2>
231231
<div class="empty-state compact">正在等待日志…</div>
232232
</div>
233233
</article>
234+
235+
<article class="panel proxy-panel">
236+
<div class="panel-head">
237+
<h2>GitHub 加速</h2>
238+
<button class="btn btn-secondary btn-sm" id="proxy-test-btn" type="button">测试代理连通性</button>
239+
</div>
240+
<p class="muted proxy-hint">用于控制台自身的版本检测与在线更新,保存后立即生效。</p>
241+
<div class="bg-modes" id="proxy-modes"></div>
242+
<div id="proxy-custom-field" class="bg-field hidden">
243+
<label class="field">
244+
<span>自定义加速地址</span>
245+
<input id="proxy-custom-input" type="text" autocomplete="off" placeholder="https://gh-proxy.com 或镜像仓库地址">
246+
</label>
247+
</div>
248+
<div class="bg-actions">
249+
<button id="proxy-save" class="btn btn-primary" type="button">保存设置</button>
250+
<span id="proxy-status" class="muted"></span>
251+
</div>
252+
</article>
234253
</section>
235254

236255
<!-- Plugins -->
@@ -498,6 +517,6 @@ <h2 id="detail-title">插件详情</h2>
498517
</div>
499518

500519
<div id="toast-stack" class="toast-stack" aria-live="polite"></div>
501-
<script src="./assets/app.js?v=0.6.1" defer></script>
520+
<script src="./assets/app.js?v=0.6.2" defer></script>
502521
</body>
503522
</html>

0 commit comments

Comments
 (0)