geng
This commit is contained in:
+99
-7
@@ -44,6 +44,7 @@ import admin_backend as backend
|
||||
import app_version
|
||||
import archive_api
|
||||
import knowledge_api
|
||||
import remote_api
|
||||
import zyt_auth
|
||||
|
||||
# 账号下拉框里「全部」的取值。用 -1 而不是 0:0 早就有含义了(旧版未归属数据),
|
||||
@@ -220,6 +221,7 @@ class ConfigBody(BaseModel):
|
||||
|
||||
|
||||
class ReleaseBody(BaseModel):
|
||||
package_media_id: str = ""
|
||||
latest_version: str
|
||||
download_url: str = ""
|
||||
release_notes: str = ""
|
||||
@@ -320,10 +322,16 @@ def _frontend_dist() -> Path:
|
||||
return Path(__file__).resolve().parent.parent / "admin-web" / "apps" / "web-antd" / "dist"
|
||||
|
||||
|
||||
def _mobile_dist() -> Path:
|
||||
"""手机远程控制台(admin-web/apps/mobile-h5)的构建产物,托管在 /m/。"""
|
||||
return Path(__file__).resolve().parent.parent / "admin-web" / "apps" / "mobile-h5" / "dist"
|
||||
|
||||
|
||||
def create_app(
|
||||
db_path: Path | str = "backend.db",
|
||||
zyt_token_verifier: Callable[[str], dict[str, Any]] | None = None,
|
||||
zyt_patient_searcher: Callable[[str, str, int, int], dict[str, Any]] | None = None,
|
||||
zyt_mobile_auth: Any = None,
|
||||
) -> FastAPI:
|
||||
database = backend.Database(Path(db_path).resolve())
|
||||
# 每个碰这个库的服务启动时都要把结构升到当前版本。只起 API、不起网页后台的
|
||||
@@ -439,13 +447,13 @@ def create_app(
|
||||
).strip().rstrip("/")
|
||||
return (configured or zyt_auth.api_base_url(), bool(configured))
|
||||
|
||||
def release_payload(row: Any) -> dict[str, Any]:
|
||||
def release_payload(row: Any, *, direct_download: bool = False) -> dict[str, Any]:
|
||||
keys = set(row.keys()) if hasattr(row, "keys") else set()
|
||||
|
||||
def value(name: str, default: Any = "") -> Any:
|
||||
return row[name] if name in keys else default
|
||||
|
||||
return {
|
||||
result = {
|
||||
"latest_version": str(value("latest_version")),
|
||||
"download_url": str(value("download_url")),
|
||||
"release_notes": str(value("release_notes")),
|
||||
@@ -464,6 +472,17 @@ def create_app(
|
||||
),
|
||||
}
|
||||
|
||||
identity = app.state.archive_store.release_package_identity(result['download_url'])
|
||||
result['package_media_id'] = identity[0] if identity else ''
|
||||
if direct_download and identity:
|
||||
try:
|
||||
result['download_url'] = app.state.archive_store.release_package_download_url(*identity)
|
||||
except (KeyError, ValueError, RuntimeError) as exc:
|
||||
raise HTTPException(status_code=409, detail=f"COS 安装包暂不可用:{exc}") from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail="COS 下载地址生成失败,请重试") from exc
|
||||
return result
|
||||
|
||||
# ── 桌面账号认证 ─────────────────────────────────────────────────────
|
||||
@app.get("/api/v2/desktop/auth/config")
|
||||
async def desktop_auth_config() -> dict:
|
||||
@@ -736,8 +755,12 @@ def create_app(
|
||||
if "desktop-account:all" in principal.permissions
|
||||
else database.desktop_account_ids_for_admin(principal.id)
|
||||
)
|
||||
accounts = database.desktop_accounts(allowed, include_counts=include_counts)
|
||||
mobile_counts = app.state.remote_store.mobile_session_counts()
|
||||
for account in accounts:
|
||||
account["mobile_session_count"] = mobile_counts.get(int(account["id"]), 0)
|
||||
return {
|
||||
"accounts": database.desktop_accounts(allowed, include_counts=include_counts),
|
||||
"accounts": accounts,
|
||||
"can_view_all": "desktop-account:all" in principal.permissions,
|
||||
# 尚未分配任何账号的旧角色仍能查看升级前的未归属数据;一旦分配账号,
|
||||
# 就必须明确选择授权账号,不能再借默认值绕过范围限制。
|
||||
@@ -769,6 +792,9 @@ def create_app(
|
||||
archive_store = getattr(app.state, "archive_store", None)
|
||||
if archive_store is not None:
|
||||
archive_store.clear_zyt_session(str(account["tenant_id"]))
|
||||
app.state.remote_store.revoke_mobile_sessions_for_account(
|
||||
account_id, reason="account_disabled"
|
||||
)
|
||||
return {"account": account}
|
||||
|
||||
@app.post("/api/v2/desktop-accounts/{account_id}/revoke-devices")
|
||||
@@ -782,6 +808,10 @@ def create_app(
|
||||
archive_store = getattr(app.state, "archive_store", None)
|
||||
if archive_store is not None:
|
||||
archive_store.clear_zyt_session(tenant)
|
||||
# 「强制下线」同时收回手机控制台的登录,否则被下线的人还能远程启停。
|
||||
app.state.remote_store.revoke_mobile_sessions_for_account(
|
||||
account_id, reason="admin_revoke"
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/api/v2/desktop-accounts/{account_id}/admins")
|
||||
@@ -1031,7 +1061,7 @@ def create_app(
|
||||
# ── 桌面端版本升级 ───────────────────────────────────────────────────
|
||||
@app.get("/api/v2/release")
|
||||
async def get_release(_: Principal = Depends(require("config:read"))) -> dict:
|
||||
return release_payload(database.release())
|
||||
return release_payload(database.release(), direct_download=True)
|
||||
|
||||
@app.post("/api/v2/release")
|
||||
async def save_release(
|
||||
@@ -1040,10 +1070,13 @@ def create_app(
|
||||
principal: Principal = Depends(require("release:write")),
|
||||
) -> dict:
|
||||
try:
|
||||
download_url = app.state.archive_store.normalize_release_download(
|
||||
body.download_url, body.package_sha256, body.package_size, body.package_media_id
|
||||
)
|
||||
release = backend.validate_release_form(
|
||||
{
|
||||
"latest_version": body.latest_version,
|
||||
"download_url": body.download_url,
|
||||
"download_url": download_url,
|
||||
"release_notes": body.release_notes,
|
||||
"force_upgrade": "1" if body.force_upgrade else "",
|
||||
"auto_install": "1" if body.auto_install else "",
|
||||
@@ -1057,6 +1090,8 @@ def create_app(
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
database.save_release(
|
||||
release["latest_version"],
|
||||
release["download_url"],
|
||||
@@ -1072,7 +1107,7 @@ def create_app(
|
||||
rollout_percent=release["rollout_percent"],
|
||||
status=release["status"],
|
||||
)
|
||||
return {"ok": True, **release}
|
||||
return {"ok": True, **release_payload(database.release(), direct_download=True)}
|
||||
|
||||
@app.post("/api/v2/release/package/prepare")
|
||||
async def prepare_release_package(
|
||||
@@ -1217,7 +1252,11 @@ def create_app(
|
||||
eligible and app_version.is_newer_version(latest, current_version)
|
||||
)
|
||||
download_url = release["download_url"]
|
||||
if download_url.startswith("/"):
|
||||
identity = app.state.archive_store.release_package_identity(download_url)
|
||||
if identity:
|
||||
# Each check gets a fresh COS HTTPS URL, including old release rows.
|
||||
download_url = release_payload(release, direct_download=True)["download_url"] if update_available else ""
|
||||
elif download_url.startswith("/"):
|
||||
forwarded_scheme = str(
|
||||
request.headers.get("x-forwarded-proto") or request.url.scheme
|
||||
).split(",", 1)[0].strip()
|
||||
@@ -1237,6 +1276,7 @@ def create_app(
|
||||
return {
|
||||
**release,
|
||||
"download_url": download_url,
|
||||
"download_url_expires_in": 900 if identity and update_available else 0,
|
||||
"update_available": update_available,
|
||||
"eligible": eligible,
|
||||
}
|
||||
@@ -1425,6 +1465,58 @@ def create_app(
|
||||
app, database, require, client_ip, resolve_admin_tenant, current_desktop,
|
||||
)
|
||||
|
||||
remote_api.register_remote_routes(
|
||||
app,
|
||||
database,
|
||||
current_desktop=current_desktop,
|
||||
zyt_api_url=lambda: desktop_login_api_url()[0],
|
||||
zyt_mobile_auth=zyt_mobile_auth,
|
||||
)
|
||||
|
||||
# ── 手机远程控制台 /m/ ───────────────────────────────────────────────
|
||||
# 必须注册在管理端 SPA 的通配路由之前,否则 /m/ 会被当成管理端的前端路由。
|
||||
mobile_dist = _mobile_dist()
|
||||
if (mobile_dist / "index.html").is_file():
|
||||
from starlette.responses import FileResponse as _MobileFile
|
||||
|
||||
mobile_root = mobile_dist.resolve()
|
||||
|
||||
@app.get("/m", include_in_schema=False)
|
||||
async def mobile_entry_redirect():
|
||||
return RedirectResponse("/m/", status_code=308)
|
||||
|
||||
# 远程启停只要"点按钮、点确认"两下,页面不许被别的站点嵌进 iframe 诱导点击。
|
||||
mobile_headers = {
|
||||
"X-Frame-Options": "DENY",
|
||||
"Content-Security-Policy": (
|
||||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
||||
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; "
|
||||
"manifest-src 'self'; worker-src 'self'; frame-ancestors 'none'; "
|
||||
"base-uri 'self'; form-action 'self'"
|
||||
),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
}
|
||||
|
||||
@app.get("/m/{path:path}", include_in_schema=False)
|
||||
async def mobile_spa(path: str):
|
||||
candidate = (mobile_root / path).resolve() if path else mobile_root / "index.html"
|
||||
if not candidate.is_relative_to(mobile_root) or not candidate.is_file():
|
||||
# 发版后还开着的旧页面会去拉旧的哈希文件:回 404 让前端整页刷新到
|
||||
# 新版本;回 index.html 的话浏览器会把 HTML 当脚本执行,页面直接卡死。
|
||||
if path.startswith("assets/"):
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
candidate = mobile_root / "index.html"
|
||||
response = _MobileFile(candidate)
|
||||
# 文件名带哈希的构建产物可以长缓存;入口、清单和 Service Worker 每次都
|
||||
# 要重新验证,否则发版后手机上会一直卡在旧界面。
|
||||
if candidate.parent.name == "assets" and candidate.parent.parent == mobile_root:
|
||||
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
else:
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
response.headers.update(mobile_headers)
|
||||
return response
|
||||
|
||||
# ── 前端静态资源 ─────────────────────────────────────────────────────
|
||||
# 构建产物存在时由本服务一起托管,前后端同源——省掉生产环境的 CORS 配置,
|
||||
# 也省掉一个 Nginx location。开发时前端跑 Vite dev server,走它自己的代理。
|
||||
|
||||
Reference in New Issue
Block a user