# -*- coding: utf-8 -*- """强制更新门禁 version_gate(2026-10-27,《企业和个人版.md》5.9,主人拍板)。 - 版本信息文件:软件商统一服务器静态 JSON {latest_version, min_required_version, release_notes, package_url, sha256} (URL 出包烧入 BUILD.VERSION_INFO_URL;开发态无 BUILD → 一律旁路,不拉取不拦截)。 - 拉取:启动 + 后台低频线程(默认 30 分钟),成功后原子落盘 data/version_cache.json (首装包可预置一份快照,由 build_portable 负责;拉取失败静默沿用旧缓存)。 - 判定(纯本地,只读缓存):当前 APP_VERSION < min_required_version → 全员阻断 (页面回自包含强制更新页;API 回 403 UPDATE_REQUIRED,绝不回 HTML 给 API—— 同授权门禁纪律);否则放行,仅版本卡提示有新版。 - fail 原则:版本检查不得比授权更硬——从未拉到且无快照 = 不拦; min_required_version 解析失败 = 不拦(视为 0);断网用最近缓存判定 (与租约 7 天口径天然对齐:长期断网本来就会被授权先拦住)。 - 升级 = 换包(B/S 只更服务器):新版 APP_VERSION ≥ min_required 自动解除拦截。 """ import json import os import threading import time try: from . import license_build_config as BUILD # 出包生成;开发态不存在 except Exception: try: import license_build_config as BUILD # 裸跑(server/ 直挂 sys.path)时 except Exception: BUILD = None CACHE_NAME = "version_cache.json" ALWAYS_PREFIX = ("/api/license/", "/api/version") # 授权三口 + 版本状态口:永不拦 DEFAULT_INTERVAL = 30 * 60 # 后台拉取间隔(秒) FETCH_TIMEOUT = 10.0 _lock = threading.Lock() _cache = None # 最近一次成功拉取的信息(含 fetched_at) _cfg = {"app_version": None, "info_url": None, "interval": DEFAULT_INTERVAL, "data_dir": None} # ---------------------------------------------------------------- 版本比较 def vkey(s): """'1.2.10' → (1, 2, 10);解析失败 → ()(配合调用方 fail-open,不当硬门禁)。""" try: return tuple(int(x) for x in str(s).strip().lstrip("vV").split(".")) except Exception: return () # ---------------------------------------------------------------- 初始化/缓存 def init(data_dir, build=None, start_thread=True): """run() 启动时调用。build 不传 = 读出包烧入的 license_build_config。""" b = build if build is not None else BUILD _cfg["data_dir"] = data_dir _cfg["app_version"] = str(getattr(b, "APP_VERSION", "") or "").strip() if b else None _cfg["info_url"] = str(getattr(b, "VERSION_INFO_URL", "") or "").strip() if b else None try: _cfg["interval"] = int(getattr(b, "VERSION_CHECK_INTERVAL", DEFAULT_INTERVAL) or DEFAULT_INTERVAL) if b else DEFAULT_INTERVAL except Exception: _cfg["interval"] = DEFAULT_INTERVAL load_cache() if start_thread and effective() and _cfg["info_url"]: threading.Thread(target=_loop, name="version-gate", daemon=True).start() def effective(): """开发态(无 BUILD / APP_VERSION 空 / 'dev')旁路:不拦截。""" v = _cfg.get("app_version") return bool(v) and v not in ("dev", "0.0.0") def _cache_path(): dd = _cfg.get("data_dir") return os.path.join(dd, CACHE_NAME) if dd else None def load_cache(): global _cache fp = _cache_path() if not fp: return None try: with open(fp, "r", encoding="utf-8") as f: d = json.load(f) if isinstance(d, dict): _cache = d return d except Exception: pass # 快照损坏 = 当没有(fail-open) return None def _save_cache(info): global _cache _cache = info fp = _cache_path() if not fp: return tmp = fp + ".tmp" try: with open(tmp, "w", encoding="utf-8") as f: json.dump(info, f, ensure_ascii=False, indent=1) f.flush() os.fsync(f.fileno()) os.replace(tmp, fp) # 原子写:中断不留半个文件 except Exception: pass # 写盘失败不致命:内存缓存仍在 # ---------------------------------------------------------------- 拉取 def fetch_once(http_get=None): """拉一次版本信息文件。成功 → 落缓存返回 True;失败静默返回 False(用旧缓存)。""" url = _cfg.get("info_url") if not url: return False try: get = http_get or _http_get d = get(url) if not isinstance(d, dict): return False if not isinstance(d.get("latest_version"), str) or \ not isinstance(d.get("min_required_version"), str): return False keep = {k: d.get(k) for k in ("latest_version", "min_required_version", "release_notes", "package_url", "sha256")} keep["fetched_at"] = time.strftime("%Y-%m-%d %H:%M:%S") with _lock: _save_cache(keep) return True except Exception: return False def _http_get(url): import httpx # 决策 30 已入包依赖 r = httpx.get(url, timeout=FETCH_TIMEOUT, headers={"User-Agent": "costreview-versiongate/1"}) r.raise_for_status() return r.json() def _loop(): fetch_once() while True: time.sleep(max(300, _cfg.get("interval") or DEFAULT_INTERVAL)) fetch_once() # ---------------------------------------------------------------- 判定/拦截 def check(): """(ok, info)。ok=False = 低于最低要求版本。""" if not effective(): return True, {"bypass": "dev"} c = _cache or load_cache() or {} cur = vkey(_cfg.get("app_version")) req = vkey(c.get("min_required_version")) info = {"current": _cfg.get("app_version"), "latest": c.get("latest_version") or "", "min_required": c.get("min_required_version") or "", "notes": c.get("release_notes") or "", "package_url": c.get("package_url") or "", "last_check": c.get("fetched_at") or ""} if not cur or not req: # 无缓存/解析失败:不拦(fail-open) return True, info return (cur >= req), info def intercept(method, path): """仿 license_client.gate.intercept:None=放行;dict=拦截(html 强制页 / json 403)。""" if not effective(): return None ok, info = check() if ok: return None p = (path or "").split("?")[0] if p.startswith(ALWAYS_PREFIX): return None if method == "GET": return {"kind": "html", "code": 200, "text": forced_page(info)} return {"kind": "json", "code": 403, "obj": {"error": {"code": "UPDATE_REQUIRED", "message": "当前版本已停止服务,请升级到 %s 或更高版本" % (info.get("min_required") or "最新版")}}} def status(): """/api/version_info:当前/最新/最低要求/是否被强制/是否有新版。""" ok, info = check() out = dict(info) out["forced"] = not ok cur, lat = vkey(info.get("current")), vkey(info.get("latest")) out["update_available"] = bool(ok and cur and lat and cur < lat) return out def forced_page(info): cur = info.get("current") or "?" req = info.get("min_required") or "?" notes = str(info.get("notes") or "") pkg = str(info.get("package_url") or "") return """
当前版本:__CUR__ | 本软件要求的最低版本:__REQ__
升级方法:请联系软件提供方获取升级包(或在服务器上运行升级流程),完成后重新打开本页即可自动恢复。
__PKG____NOTES__升级包地址:%s
' % (pkg, pkg) if pkg else "") \ .replace("__NOTES__", "更新说明:%s
" % notes if notes else "")