mirror of
https://gitee.com/xmz7891/ykxmz.git
synced 2026-10-18 10:10:43 +00:00
用户这次提了一整套升级。这个提交先落地三块(其余几块在做)。
== 一、静默自动更新 ==
用户原话:"手表端点击一个更新按钮,电脑端就可以自动进行静默更新,
其他什么设置都不变 …… 不弹任何窗口出来"。
链路:
手表点按钮 -> 被控端问中转"最新是哪版"
-> 下载到 %TEMP%\ykxmz-update\
-> 校验 sha256
-> 起一个**分离的 .cmd 帮手**
-> 自己退出
-> 帮手等它退出 -> 静默跑安装器 -> 重新拉起
关键设计说明:
* **为什么要有那个 .cmd 帮手**:Windows 上正在运行的 exe 是锁着的,
安装器覆盖不了,所以必须"先退出、再装、再起来",而这三步
不能由被控端自己做(它一退出就没人执行后面的了)。
用 DETACHED_PROCESS 起的助手不受父进程退出影响。
* **配置为什么不会丢**:配置在 %ProgramData%\ykxmz\data\,
**不在程序目录里**。安装器升级只替换 {app} 下的文件,
不碰 ProgramData —— 中转地址、配对码、各种开关原样保留。
这是这个功能能做的前提。
* **更新源是用户自己的中转站**,不是作者的服务器,也不是任何
写死的公网地址。被控端问的是它自己配置的那个地址。
中转没有这个接口(老版本服务端)时会明确提示"先手动升级一次服务端"。
* **sha256 必须校验**:自更新最大的风险是下到一半断了或被换了,
装上去是个坏程序、而且它还会自己再更新 —— 螺旋下去很难救。
对不上就**放弃这一轮**,保持现状(现状至少能用)。
中转新增:GET /v1/update/latest?platform=windows
返回 version / name / url / size / sha256。版本比较按**数字段**
(不能按字符串,否则 "1.9.0" > "2.1.4")。sha256 按
(文件名,大小,mtime) 缓存,避免每次重算 9MB。
手表端:"电脑端版本:点这里查看" 按钮,查完显示
"电脑端 2.1.4 → 2.1.5(点这里更新)",确认后才真的更新。
== 二、远程鼠标控制 ==
新增 windows/lanremote/input.py,用 SendInput 模拟鼠标键盘。
* **为什么用 SendInput 而不是 mouse_event**:后者是 Win95 时代的
API,会被 UIPI 拦,而且没有 dwExtraInfo(多个注入源会互相干扰)。
SendInput 还能一次打包多个事件,按下+抬起之间不会插进别的输入。
* **坐标是 0..65535 归一化**,而且**必须除以 (屏幕宽-1)**。
少了那个 -1,最右边和最下边几像素点不到 —— 表现为
"鼠标到不了屏幕边缘",任务栏在底下的机器上尤其明显。
* **INPUT 结构在 32/64 位下大小不同**(28 / 40),
ctypes 里按进程位数算,不能写死。
* 权限说明:目标窗口如果是管理员权限的(UAC 提升过的),
普通权限的注入会被 UIPI 拦掉。这不是 bug,是 Windows 的设计。
被控端以管理员运行就都能点。
== 三、一键显示桌面 ==
用户要求快捷栏里那个"不能改"的按钮就是这个功能,等于 Win+D。
和鼠标控制共用 input.py。
== 顺手修的一个自己造的坑 ==
往 server.py 插方法时,**两次**把 dispatch 的兜底
`return {"ok": False, "error": f"未知命令: {cmd}"}` 一起卷进了新方法里:
* pyflakes 报 "undefined name 'cmd'"
* 而且 dispatch 丢了兜底分支(未知命令会返回 None)
第一次靠 pyflakes 抓到,第二次也是。为了以后不再犯,
`_tests/test_update_flow.py` 里加了**结构断言**:
兜底必须在带 CMD_UPDATE 的那个方法体里,而各新方法里不能出现它。
(那条断言第一版写得太死 —— 要求"紧跟 CMD_UPDATE 分支",
后来往 dispatch 里插了新分支就误报了。改成验结构真相。)
== 验证 ==
全量回归(含新增的 3a10 / 3a11 两关)全部 PASS
静默自动更新:协议 + updater 15 项 + 服务端结构 8 项
远程鼠标:坐标归一化 / 滚轮夹取 / Win+D 事件顺序 / 非法参数 22 项
610 个 Python 文件语法通过
实际注入鼠标成功(move / click / scroll / show_desktop)
== 还没做的(下一批) ==
手表顶部快捷栏(可自定义最多 4 个,1 个固定"显示桌面")
屏幕镜像去掉提示条、去掉所有弹窗
托盘图标改成设置项
「允许新设备连接」开关(中转后台 + 安卓端)
弹文字窗口位置/大小可自定义
中转后台设备列表显示版本 + 远程点更新
== 顺手清理 ==
_tests/out_app/ 下面那堆 .class 是 Java 编译检查的产物,
以前误提交进仓库了(152 个文件)。这次从索引里移除并加进 .gitignore。
243 lines
8.9 KiB
Python
243 lines
8.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
r'''把「静默自动更新」接进协议和服务端。
|
||
|
||
== 加两条命令 ==
|
||
|
||
{"cmd":"update","action":"check"} -> 查最新版,不改动任何东西
|
||
{"cmd":"update","action":"start"} -> 真的要更新(下载+静默安装+重启)
|
||
|
||
== 为什么"查"和"做"分成两步 ==
|
||
|
||
手表点一下按钮,先看到"有新版本 2.1.5(当前 2.1.4,约 9 MB)",
|
||
再决定要不要升。直接一步到位的话,用户不知道自己触发了什么。
|
||
|
||
== start 为什么要开线程 ==
|
||
|
||
安装包 9 MB,在学校的网上下载可能要几十秒。
|
||
如果同步下载,手表那边的请求会一直挂着;而挂太久用户以为卡死了。
|
||
|
||
所以:立刻回一句"开始更新了",然后在后台线程里下载 + 校验 + 应用。
|
||
进度通过 server 自己的日志广播给正在看的手表。
|
||
|
||
== 应用之后进程必须退出 ==
|
||
|
||
Windows 上正在跑的 exe 是锁着的,安装器覆盖不了。
|
||
所以 updater 会先起一个**分离的 .cmd 帮手**(不受本进程退出影响),
|
||
帮手等本进程退出 -> 静默装 -> 重新拉起。
|
||
这里的顺序不能反。
|
||
'''
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
PROTO = ROOT / "windows" / "lanremote" / "protocol.py"
|
||
SERVER = ROOT / "windows" / "lanremote" / "server.py"
|
||
|
||
|
||
def patch_protocol() -> bool:
|
||
raw = PROTO.read_bytes()
|
||
bom = raw.startswith(b"\xef\xbb\xbf")
|
||
text = raw.decode("utf-8-sig")
|
||
if "CMD_UPDATE" in text:
|
||
print(" protocol.py 已经加过了")
|
||
return True
|
||
anchor = 'CMD_INFO = "info"'
|
||
if anchor not in text:
|
||
print(" ✗ protocol.py 找不到 CMD_INFO")
|
||
return False
|
||
text = text.replace(
|
||
anchor,
|
||
anchor + "\n"
|
||
'# 静默自动更新:从**用户自己的中转站**取新版本包,'
|
||
'静默装好并重启。\n'
|
||
'# action=check 只看不动;action=start 真的更新。\n'
|
||
'CMD_UPDATE = "update"', 1)
|
||
PROTO.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||
print(" ✓ protocol.py 加了 CMD_UPDATE")
|
||
return True
|
||
|
||
|
||
def patch_server() -> bool:
|
||
raw = SERVER.read_bytes()
|
||
bom = raw.startswith(b"\xef\xbb\xbf")
|
||
text = raw.decode("utf-8-sig")
|
||
if "_do_update" in text:
|
||
print(" server.py 已经加过了")
|
||
return True
|
||
|
||
anchors = {
|
||
"info": 'if cmd == P.CMD_INFO:\n return {"ok": True, "info": self.actions.info()}',
|
||
"unknown": ' return {"ok": False, "error": f"未知命令: {cmd}"}',
|
||
"imports": "from . import protocol as P",
|
||
}
|
||
missing = [k for k, v in anchors.items() if v not in text]
|
||
if missing:
|
||
print(" ✗ server.py 这些锚点找不到:%s" % ", ".join(missing))
|
||
return False
|
||
print(" ✓ server.py 锚点全部就位")
|
||
|
||
# ---- import updater ----
|
||
text = text.replace(
|
||
anchors["imports"],
|
||
anchors["imports"] + "\nfrom . import updater as U", 1)
|
||
|
||
# ---- 命令分发 ----
|
||
text = text.replace(
|
||
anchors["info"],
|
||
anchors["info"] + '''
|
||
|
||
if cmd == P.CMD_UPDATE:
|
||
return self._do_update(msg)''', 1)
|
||
|
||
# ---- 实现 ----
|
||
handler = '''
|
||
|
||
# ---------------- 静默自动更新 ----------------
|
||
|
||
def _do_update(self, msg: dict) -> dict:
|
||
"""处理 {"cmd":"update","action":...}。
|
||
|
||
取包的地方是**用户自己配的中转站**(store 里的 relay_url),
|
||
不是任何写死的公网地址 —— 这一点是刻意的,见 updater.py 的说明。
|
||
"""
|
||
from . import __version__ as my_version
|
||
|
||
action = str(msg.get("action") or "check").lower()
|
||
relay = (self.store.relay_url() or "").strip()
|
||
|
||
if action == "check":
|
||
try:
|
||
info = U.check(relay, my_version)
|
||
except U.UpdateError as exc:
|
||
return {"ok": False, "error": str(exc)}
|
||
if not info.get("supported"):
|
||
return {"ok": False,
|
||
"error": info.get("error") or "不支持自动更新"}
|
||
if "error" in info:
|
||
return {"ok": False, "error": info["error"]}
|
||
return {
|
||
"ok": True,
|
||
"current": my_version,
|
||
"latest": info["latest"],
|
||
"needUpdate": bool(info["needUpdate"]),
|
||
"size": info.get("size", 0),
|
||
"name": info.get("name", ""),
|
||
}
|
||
|
||
if action != "start":
|
||
return {"ok": False, "error": "action 只能是 check 或 start"}
|
||
|
||
# ---- 真的更新 ----
|
||
# 先查一遍(在调用方线程里查,失败能立刻报回去)
|
||
try:
|
||
info = U.check(relay, my_version)
|
||
except U.UpdateError as exc:
|
||
return {"ok": False, "error": str(exc)}
|
||
if not info.get("supported") or "error" in info:
|
||
return {"ok": False,
|
||
"error": info.get("error") or "不支持自动更新"}
|
||
if not info["needUpdate"]:
|
||
return {"ok": True, "alreadyLatest": True, "current": my_version,
|
||
"message": "电脑端已经是最新版本 %s" % my_version}
|
||
|
||
# 下载和应用放到后台线程,先回一句让手表知道开始了
|
||
threading.Thread(
|
||
target=self._run_update,
|
||
args=(info, my_version),
|
||
name="ykxmz-update", daemon=True).start()
|
||
|
||
return {
|
||
"ok": True,
|
||
"started": True,
|
||
"from": my_version,
|
||
"to": info["latest"],
|
||
"size": info.get("size", 0),
|
||
"message": "正在下载 %s(%.1f MB),下完会自动装好并重启,"
|
||
"设置和配对码都不变"
|
||
% (info["latest"], (info.get("size") or 0) / 1048576.0),
|
||
}
|
||
|
||
def _run_update(self, info: dict, my_version: str) -> None:
|
||
"""后台线程:下载 -> 校验 -> 起帮手 -> 自己退出。"""
|
||
def log(text: str) -> None:
|
||
try:
|
||
self._log(text)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
try:
|
||
log("[更新] 开始下载 %s(%.1f MB)"
|
||
% (info["latest"], (info.get("size") or 0) / 1048576.0))
|
||
work = Path(tempfile.gettempdir()) / "ykxmz-update"
|
||
last = [0]
|
||
|
||
def progress(got: int, total: int) -> None:
|
||
# 每 25% 报一次,别把日志刷爆
|
||
if total:
|
||
pct = int(got * 100 / total)
|
||
if pct - last[0] >= 25:
|
||
last[0] = pct
|
||
log("[更新] 已下载 %d%%(%.1f/%.1f MB)"
|
||
% (pct, got / 1048576.0, total / 1048576.0))
|
||
|
||
pkg = U.download(info["url"], work,
|
||
info.get("sha256", ""), info.get("size", 0),
|
||
progress=progress)
|
||
log("[更新] 下载完成并校验通过:%s" % pkg.name)
|
||
|
||
# 应用:起分离的 .cmd 帮手,然后**本进程必须退出**
|
||
app_exe = Path(sys.executable if getattr(sys, "frozen", False)
|
||
else sys.argv[0]).resolve()
|
||
logfile = U.apply_update(pkg, app_exe)
|
||
log("[更新] 已交给更新帮手(%s),被控端即将退出并重启" % logfile)
|
||
U.cleanup_old_downloads()
|
||
|
||
# 给日志和网络一点时间落完,再退出
|
||
time.sleep(2)
|
||
os._exit(0)
|
||
except U.UpdateError as exc:
|
||
log("[更新] 失败:%s(保持当前版本 %s)" % (exc, my_version))
|
||
except Exception as exc: # noqa: BLE001
|
||
log("[更新] 意外失败:%s: %s" % (type(exc).__name__, exc))
|
||
|
||
'''
|
||
text = text.replace(anchors["unknown"],
|
||
handler + "\n" + anchors["unknown"], 1)
|
||
|
||
# ---- 补 import ----
|
||
need = []
|
||
head = text.split("class ", 1)[0]
|
||
for mod, line in (("tempfile", "import tempfile"),
|
||
("sys", "import sys"),
|
||
("threading", "import threading"),
|
||
("time", "import time"),
|
||
("os", "import os"),
|
||
("Path", "from pathlib import Path")):
|
||
if line not in head:
|
||
need.append(line)
|
||
if need:
|
||
anchor = "from . import protocol as P"
|
||
text = text.replace(anchor, "\n".join(need) + "\n" + anchor, 1)
|
||
print(" ✓ 补了 import: %s" % ", ".join(need))
|
||
|
||
SERVER.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||
print(" ✓ server.py 加了 _do_update / _run_update")
|
||
return True
|
||
|
||
|
||
def main() -> int:
|
||
print("=" * 58)
|
||
print(" 接「静默自动更新」进协议和服务端")
|
||
print("=" * 58)
|
||
print()
|
||
ok = patch_protocol()
|
||
print()
|
||
ok = patch_server() and ok
|
||
return 0 if ok else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|