mirror of
https://gitee.com/xmz7891/ykxmz.git
synced 2026-10-18 20:40:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48bc392466 | ||
|
|
fd8be87209 | ||
|
|
f0c05079f7 | ||
|
|
3f543b274a | ||
|
|
4d97e40280 | ||
|
|
31a2360031 | ||
|
|
be59a20036 | ||
|
|
7ffd56391e | ||
|
|
0ad3f648c6 |
@@ -81,3 +81,8 @@ admin_password.txt
|
|||||||
/_build/relay_info.json
|
/_build/relay_info.json
|
||||||
# 后台管理密码(绝不进仓库)
|
# 后台管理密码(绝不进仓库)
|
||||||
_build/.admin_password
|
_build/.admin_password
|
||||||
|
|
||||||
|
# 服务器地址(绝不进仓库)
|
||||||
|
_build/.lightsail_host
|
||||||
|
_build/.gitee_token
|
||||||
|
_build/.admin_password
|
||||||
|
|||||||
@@ -45,9 +45,9 @@
|
|||||||
|
|
||||||
| 装在哪 | 是什么 | 文件 |
|
| 装在哪 | 是什么 | 文件 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 教室电脑(Windows) | 被控端 | `ykxmz-setup-2.1.4.exe` |
|
| 教室电脑(Windows) | 被控端 | `ykxmz-setup-2.1.8.exe` |
|
||||||
| 小服务器(随身 WiFi / 云主机 / 树莓派) | 中转站 | `ykxmz-server-2.1.4.zip` |
|
| 小服务器(随身 WiFi / 云主机 / 树莓派) | 中转站 | `ykxmz-server-2.1.8.zip` |
|
||||||
| 手表(安卓) | 控制端 | `ykxmz-watch-2.1.4.apk` |
|
| 手表(安卓) | 控制端 | `ykxmz-watch-2.1.8.apk` |
|
||||||
|
|
||||||
**只在一个教室用?** 那第三件(中转站)可以先不装,手表和电脑连同一个 WiFi 就能直连。
|
**只在一个教室用?** 那第三件(中转站)可以先不装,手表和电脑连同一个 WiFi 就能直连。
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@
|
|||||||
|
|
||||||
### 第一步:电脑上装被控端
|
### 第一步:电脑上装被控端
|
||||||
|
|
||||||
双击 `ykxmz-setup-2.1.4.exe`,按提示装完(默认装到 `C:\Program Files\ykxmz`)。
|
双击 `ykxmz-setup-2.1.8.exe`,按提示装完(默认装到 `C:\Program Files\ykxmz`)。
|
||||||
|
|
||||||
第一次运行会弹出窗口,填两样:
|
第一次运行会弹出窗口,填两样:
|
||||||
|
|
||||||
@@ -94,12 +94,12 @@
|
|||||||
> 想再打开窗口,**再双击一次程序图标**就行,不会起第二个进程。
|
> 想再打开窗口,**再双击一次程序图标**就行,不会起第二个进程。
|
||||||
> 想彻底退出,窗口上点「退出」。
|
> 想彻底退出,窗口上点「退出」。
|
||||||
|
|
||||||
> 不想用安装包的话,`ykxmz-agent-2.1.4.zip` 是绿色版:
|
> 不想用安装包的话,`ykxmz-agent-2.1.8.zip` 是绿色版:
|
||||||
> 解压出来直接跑 `ykxmz.exe`,整个文件夹拷走就能换台机器用,不写注册表。
|
> 解压出来直接跑 `ykxmz.exe`,整个文件夹拷走就能换台机器用,不写注册表。
|
||||||
|
|
||||||
### 第二步:手表上装 App
|
### 第二步:手表上装 App
|
||||||
|
|
||||||
把 `ykxmz-watch-2.1.4.apk` 传到手表装上。手表可能提示"未知来源",去设置里允许一下。
|
把 `ykxmz-watch-2.1.8.apk` 传到手表装上。手表可能提示"未知来源",去设置里允许一下。
|
||||||
|
|
||||||
打开 App,首页有四个入口:
|
打开 App,首页有四个入口:
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@
|
|||||||
中转站就是**一台能上外网的 Linux 小机器**(随身 WiFi、树莓派、云主机都行,
|
中转站就是**一台能上外网的 Linux 小机器**(随身 WiFi、树莓派、云主机都行,
|
||||||
Debian 12 / Ubuntu 实测可用,512 MB 内存就够)。
|
Debian 12 / Ubuntu 实测可用,512 MB 内存就够)。
|
||||||
|
|
||||||
把 `ykxmz-server-2.1.4.zip` 解压到那台机器上,然后一条命令:
|
把 `ykxmz-server-2.1.8.zip` 解压到那台机器上,然后一条命令:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash deploy.sh
|
bash deploy.sh
|
||||||
@@ -456,7 +456,7 @@ windows\build_exe.ps1
|
|||||||
```powershell
|
```powershell
|
||||||
android\build_apk.ps1
|
android\build_apk.ps1
|
||||||
# 流程:aapt2 → javac → d8 → zipalign → apksigner
|
# 流程:aapt2 → javac → d8 → zipalign → apksigner
|
||||||
# 产物:dist\ykxmz-watch-2.1.4.apk
|
# 产物:dist\ykxmz-watch-2.1.8.apk
|
||||||
```
|
```
|
||||||
|
|
||||||
最低支持 Android 7.0(API 24),targetSdk 34。
|
最低支持 Android 7.0(API 24),targetSdk 34。
|
||||||
|
|||||||
@@ -1,3 +1,143 @@
|
|||||||
|
## 2.1.8
|
||||||
|
|
||||||
|
- **快捷栏的按钮做大** —— 上一版 30dp 在手表上按不准,手指按上去
|
||||||
|
一半在栏外。现在 46dp(接近 Android 建议的可点区域),字号 11→14。
|
||||||
|
|
||||||
|
- **快捷栏 4 个格子全部可以自定义** —— 上一版最后一个「显示桌面」
|
||||||
|
是写死不能改的,现在四格平等,想换哪个换哪个。
|
||||||
|
|
||||||
|
「显示桌面」变成一个普通的可选动作,默认仍放在第 4 格 ——
|
||||||
|
所以习惯不用改,但想换成别的也行。可选动作现在共 8 个:
|
||||||
|
传文件 / 屏幕镜像 / 鼠标控制 / 音效 / 关机 / 语音播报 /
|
||||||
|
投图到电脑 / 显示桌面。
|
||||||
|
|
||||||
|
- **修 Win7 上语音播报不能用** —— 以前只走 PowerShell 一条路,
|
||||||
|
而 Win7 上的 PowerShell 是 2.0 版,中文经命令行传进去容易乱码;
|
||||||
|
再加上 `powershell` 可能不在 PATH 里,就彻底播不出来了。
|
||||||
|
|
||||||
|
现在改成**多方案降级**,按"依赖越少越优先"排:
|
||||||
|
|
||||||
|
| 顺序 | 方案 | 依赖 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | cscript + VBScript + SAPI5 | Windows 98 起就有,不用装任何东西 |
|
||||||
|
| 2 | wscript + VBScript + SAPI5 | 上一条被安全软件拦时的备选 |
|
||||||
|
| 3 | powershell + SAPI5 (COM) | 只依赖 PowerShell,**不需要 .NET** |
|
||||||
|
| 4 | powershell + System.Speech | 原来的做法,改用绝对路径 |
|
||||||
|
| 5 | powershell (按 PATH) + System.Speech | 最原始的,兜底 |
|
||||||
|
|
||||||
|
一条通了就记住它,以后直接用(不用每次从头试)。
|
||||||
|
|
||||||
|
**全都失败会明确报错** —— 以前是不等进程结束就返回"已播报",
|
||||||
|
明明没出声也报成功,那是在骗人。
|
||||||
|
|
||||||
|
## 2.1.7
|
||||||
|
|
||||||
|
- **手表端顶部快捷栏** —— 任何页面顶部都有一条栏,最多 4 个按钮:
|
||||||
|
|
||||||
|
- **最后一个是固定的「显示桌面」**(等于电脑上按 Win+D),**改不了**
|
||||||
|
- **前三个自己选**,在设置页里点一下从这 7 个里挑:
|
||||||
|
传文件 / 屏幕镜像 / 鼠标控制 / 音效 / 关机 / 语音播报 / 投图到电脑
|
||||||
|
- 也可以把某一格留空
|
||||||
|
- 还没连上电脑时它们是灰的(不是藏起来 —— "一直在但暂时不能用"
|
||||||
|
比"时有时无"更好理解)
|
||||||
|
|
||||||
|
- **远程鼠标控制(手表上的触摸板)** —— 拖动移动光标、单击左键、
|
||||||
|
双击右键,下面还有专门的左键/右键/滚轮按钮。
|
||||||
|
|
||||||
|
- **弹文字窗口的位置和大小可以自己设** —— 右下(默认)/ 右上 / 左上 /
|
||||||
|
左下 / 屏幕正中间 / 自定义坐标,字号 8~32 可调。
|
||||||
|
在电脑端设置窗口的「显示」里改。
|
||||||
|
|
||||||
|
- **屏幕被观看时的提示条改成默认不显示** ——
|
||||||
|
以前是强制弹的("有人在看你的屏幕,电脑前面的人该知道")。
|
||||||
|
现在默认关掉,跟常见远程工具一样全程无窗口;需要的话在
|
||||||
|
设置里可以打开。**这个开关是刻意保留的**:这软件应该始终有一个
|
||||||
|
"让本机用户看得见正在被控制"的选项可查。
|
||||||
|
|
||||||
|
- **中转后台能看到每台电脑的版本了**,并且可以直接点「更新」
|
||||||
|
让那台电脑自己静默升级(离线设备按钮置灰)。
|
||||||
|
|
||||||
|
- **手表端设置里可以开关「允许新设备连接」** ——
|
||||||
|
关掉之后只有配对过的电脑能连上来,教室里防别人乱连。
|
||||||
|
|
||||||
|
## 2.1.6
|
||||||
|
|
||||||
|
- **电脑端静默自动更新** —— 手表上点一下,电脑自己升到最新版,
|
||||||
|
全程不弹任何窗口,**中转地址、配对码、所有设置一个都不变**。
|
||||||
|
|
||||||
|
流程:手表点按钮 → 电脑端问中转"最新是哪版" → 下载并校验 →
|
||||||
|
起一个后台帮手 → 自己退出 → 帮手等它退出后静默装好 → 重新拉起。
|
||||||
|
|
||||||
|
几个关键点:
|
||||||
|
|
||||||
|
- **配置为什么不会丢**:配置存在 `%ProgramData%\ykxmz\data\`,
|
||||||
|
不在程序目录里。安装器升级只替换程序文件,不碰这个目录。
|
||||||
|
- **更新源是用户自己的中转站**,不是作者的服务器,也不是任何
|
||||||
|
写死的地址。中转没这功能(老版本服务端)时会明确提示
|
||||||
|
"先手动升级一次服务端"。
|
||||||
|
- **校验和不匹配就放弃这一轮**,保持现状(现状至少能用)。
|
||||||
|
自更新最怕的就是装上一个坏程序、然后它还自己继续更新。
|
||||||
|
|
||||||
|
手表首页新增「电脑端版本」按钮,点开就能看到
|
||||||
|
"电脑端 2.1.4 → 2.1.5",确认后才动手。
|
||||||
|
|
||||||
|
- **远程鼠标控制**:移动、左键、右键、中键、滚轮(含横向)。
|
||||||
|
|
||||||
|
这是"能直接操控电脑"的功能,所以参数校验写得很严:
|
||||||
|
非法动作、非法按键、非数字坐标全都会被拒。
|
||||||
|
|
||||||
|
- **一键显示桌面**(等于 Win+D)。
|
||||||
|
|
||||||
|
- **Windows 7 兼容性校验关卡**:打包时和回归里都会检查
|
||||||
|
(内嵌的是不是 3.8 运行库、**有没有**那个 Win7 上不存在的 DLL、
|
||||||
|
exe 是不是 32 位),不过就拒绝出包。
|
||||||
|
|
||||||
|
- 技术说明:
|
||||||
|
- 鼠标坐标用 SendInput 的 **0..65535 归一化**,而且**必须除以
|
||||||
|
(屏幕宽-1)**。少了那个 -1,最右边和最下边几像素点不到。
|
||||||
|
- `INPUT` 结构在 32/64 位下大小不同(28 / 40),代码按进程位数算。
|
||||||
|
- 目标窗口若是管理员权限的(UAC 提升过的),普通权限的注入会被
|
||||||
|
系统拦掉 —— 这是 Windows 的设计,不是 bug。被控端以管理员运行
|
||||||
|
就没问题。
|
||||||
|
|
||||||
|
## 2.1.5
|
||||||
|
|
||||||
|
- **修「Windows 7 装完报 dll 缺失」** —— 学校电脑装不上。
|
||||||
|
|
||||||
|
这一条是用户报的:学校的电脑是 Windows 7,装完提示缺 DLL。
|
||||||
|
|
||||||
|
**根因不是漏打包,是 Python 版本越界**:
|
||||||
|
|
||||||
|
| Python | 支持的系统 |
|
||||||
|
|---|---|
|
||||||
|
| **3.8** | Windows 7 及以上 ← 最后一个支持 Win7 的版本 |
|
||||||
|
| 3.9 ~ 3.13 | 只支持 Windows 8 及以上 |
|
||||||
|
|
||||||
|
Python 3.9 起用到了 `api-ms-win-core-path-l1-1-0.dll` 里的
|
||||||
|
`PathCchCanonicalizeEx`,而这个 DLL **Windows 7 上根本不存在**,
|
||||||
|
也没法用 api-set 转发(那套机制只在 Win8+ 生效)。
|
||||||
|
|
||||||
|
所以之前用 3.11 打出来的包,在 Win7 上必然报缺 DLL ——
|
||||||
|
**那个 DLL 不是"忘了放进包",是"放进去也没用"。**
|
||||||
|
|
||||||
|
**改法:改用 Python 3.8 打包**,而且选 **32 位** ——
|
||||||
|
32 位在 Win7 的 32 位和 64 位系统上**都能跑**,学校不用分两种发。
|
||||||
|
|
||||||
|
顺带加了两道自动关卡,以后不会再退化:
|
||||||
|
- 打包脚本 `windows\build_exe.ps1` **先校验 Python 版本**,
|
||||||
|
不是 3.8 直接报错退出(而不是默默打一个别人装不上的包)
|
||||||
|
- `_build\check_win7_compat.py` 校验产物:
|
||||||
|
内嵌是不是 3.8 的运行库、**有没有**那个要命的 DLL、exe 是不是 32 位。
|
||||||
|
打包时和回归套件里都会跑,不过就拒绝出包
|
||||||
|
|
||||||
|
安装包体积也从 14.4 MB 降到 **9.0 MB**(32 位运行库小一圈)。
|
||||||
|
|
||||||
|
- **顺手修了安装包测试里一个藏了很久的坑**:
|
||||||
|
`_build/test_installer_cycle.py` 里写死了 `ykxmz-setup-1.8.2.exe`,
|
||||||
|
于是它一直在**装一个不存在的旧包** → 静默失败 → 报出一堆
|
||||||
|
莫名其妙的失败("配对码实际是 xxx"、"版本显示 v1.8.2")。
|
||||||
|
改成自动找 `dist` 下版本号最新的包,以后不会再过期。
|
||||||
|
|
||||||
## 2.1.4
|
## 2.1.4
|
||||||
|
|
||||||
- **修一个"填了地址也连不上"的 bug**(手表端)。
|
- **修一个"填了地址也连不上"的 bug**(手表端)。
|
||||||
|
|||||||
@@ -0,0 +1,275 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''弹文字窗口「位置 + 大小」可配置,屏幕共享提示条默认关掉。
|
||||||
|
|
||||||
|
== 用户的要求 ==
|
||||||
|
|
||||||
|
"那个弹文字窗口,不要(现在)在电脑的右下角,(要能放在)屏幕正中间,
|
||||||
|
还可以自定义窗口大小"
|
||||||
|
|
||||||
|
"现在不是要会弹一个屏幕已被共享吗?以后不需要弹,啥窗户都没有,
|
||||||
|
就可以像 uu 远程一样"
|
||||||
|
|
||||||
|
== 现状(查清楚了)==
|
||||||
|
|
||||||
|
headless.py 里有三个窗口定位点,**全在右下角**:
|
||||||
|
|
||||||
|
第 190 行 notify() 里的通知窗口 ┐ 就是用户说的"弹文字窗口"
|
||||||
|
第 231 行 notify()(代码重复了一份)┘ 6 秒自动关
|
||||||
|
第 451 行 _show_notice() 屏幕共享提示条
|
||||||
|
|
||||||
|
三处都写死了 `+{screen_w - width - 24}+{screen_h - height - 72}`。
|
||||||
|
|
||||||
|
== 改法 ==
|
||||||
|
|
||||||
|
1. **加一个统一的定位函数 `_notice_geometry(width, height)`**
|
||||||
|
支持 6 种位置:右下 / 右上 / 左上 / 左下 / 正中间 / 自定义坐标。
|
||||||
|
三处都改调它 —— 这样以后再调位置只用改一个地方。
|
||||||
|
|
||||||
|
2. **加设置项**(config.py):
|
||||||
|
notice_position 默认 bottom-right(保持原样,不改变老用户习惯)
|
||||||
|
notice_x / notice_y position=custom 时用
|
||||||
|
notice_width 0 = 按内容自适应(原来就是这样)
|
||||||
|
notice_font_size 11 = 原来的字号
|
||||||
|
show_screen_notice **默认 False** —— 屏幕被看时不再弹提示条
|
||||||
|
|
||||||
|
3. **`set_screen_sharing` 尊重 `show_screen_notice`**
|
||||||
|
关着就什么都不做(连窗口都不建)。
|
||||||
|
|
||||||
|
== 关于"去掉屏幕提示条"这件事 ==
|
||||||
|
|
||||||
|
原来那条是**故意加**的:有人在看屏幕时,电脑前面的人应该知道。
|
||||||
|
用户现在要求去掉,理由是"像 UU 远程一样不要任何窗口"。
|
||||||
|
|
||||||
|
这是**用户自己的电脑、自己的教室**,属于正当的远程管理需求
|
||||||
|
(极域电子教室、联想网络控制工具这类校园软件也都是无提示的)。
|
||||||
|
但我在 README 和设置界面里都保留了这个选项的描述 ——
|
||||||
|
**能力还在,只是默认关**,这样万一以后有争议,能证明这软件有可见开关。
|
||||||
|
|
||||||
|
== 顺带发现的一个问题 ==
|
||||||
|
|
||||||
|
`notify()` 里那段建窗口的代码**被复制了两份**(第 166-201 和 206-250),
|
||||||
|
两份几乎一模一样。这次不动它(不属于本次需求,动它风险大),
|
||||||
|
但下划线标注一下,以后重构时知道。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
CONFIG = ROOT / "windows" / "lanremote" / "config.py"
|
||||||
|
HEADLESS = ROOT / "windows" / "lanremote" / "headless.py"
|
||||||
|
|
||||||
|
CONFIG_ADD = ''' "screen_fps": 12,
|
||||||
|
# ---- 弹窗外观(用户要求"位置和大小都能自定义")----
|
||||||
|
#
|
||||||
|
# 位置:bottom-right / top-right / top-left / bottom-left / center / custom
|
||||||
|
# 默认保持右下角 —— 不改变老用户的使用习惯。
|
||||||
|
"notice_position": "bottom-right",
|
||||||
|
"notice_x": 0, # position=custom 时的横坐标(像素)
|
||||||
|
"notice_y": 0, # position=custom 时的纵坐标(像素)
|
||||||
|
"notice_width": 0, # 0 = 按内容自适应(240 起)
|
||||||
|
"notice_font_size": 11, # 标题字号;正文自动小 1 号
|
||||||
|
# 屏幕被观看时是否在本机弹提示条。
|
||||||
|
#
|
||||||
|
# ⚠ 原来这个提示条是**强制显示**的("有人在看你的屏幕,
|
||||||
|
# 电脑前面的人必须知道")。用户要求去掉,理由是"像 UU 远程一样
|
||||||
|
# 不要任何窗口"。
|
||||||
|
#
|
||||||
|
# 这是用户自己的电脑,属于正当的远程管理需求
|
||||||
|
# (极域电子教室这类校园软件也都是无提示的)。
|
||||||
|
# 所以能力保留、**默认关闭** —— 需要的话在设置里打开,
|
||||||
|
# 这样这软件始终有一个"可见性开关"可查。
|
||||||
|
"show_screen_notice": False,
|
||||||
|
}'''
|
||||||
|
|
||||||
|
GEOMETRY_HELPER = '''
|
||||||
|
def _notice_geometry(self, width: int, height: int) -> str:
|
||||||
|
"""算出弹窗该放哪。返回 Tk 的 geometry 字符串 `+x+y`。
|
||||||
|
|
||||||
|
用户要求"位置和大小都能自定义",所以这里支持 6 种位置。
|
||||||
|
⚠ 三处弹窗(通知 ×2、屏幕提示 ×1)都调这个函数 ——
|
||||||
|
以前三处各写死一遍右下角,改一次要改三个地方。
|
||||||
|
"""
|
||||||
|
screen_w, screen_h = self.screen_size()
|
||||||
|
pos = str(self.store.get("notice_position") or "bottom-right")
|
||||||
|
pad = 24 # 离屏幕边缘留一点空
|
||||||
|
pad_bottom = 72 # 底下多留些,避开任务栏
|
||||||
|
|
||||||
|
if pos == "custom":
|
||||||
|
try:
|
||||||
|
x = int(self.store.get("notice_x") or 0)
|
||||||
|
y = int(self.store.get("notice_y") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
x = y = 0
|
||||||
|
# 夹到屏幕内,免得设了个离谱的值窗口就找不到了
|
||||||
|
x = max(0, min(screen_w - width, x))
|
||||||
|
y = max(0, min(screen_h - height, y))
|
||||||
|
return f"+{x}+{y}"
|
||||||
|
|
||||||
|
if pos == "center":
|
||||||
|
return (f"+{max(0, (screen_w - width) // 2)}"
|
||||||
|
f"+{max(0, (screen_h - height) // 2)}")
|
||||||
|
|
||||||
|
# 四个角
|
||||||
|
left = pos in ("top-left", "bottom-left")
|
||||||
|
top = pos in ("top-left", "top-right")
|
||||||
|
x = pad if left else screen_w - width - pad
|
||||||
|
y = pad if top else screen_h - height - pad_bottom
|
||||||
|
return f"+{max(0, x)}+{max(0, y)}"
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
SCREEN_SHARING_OLD = ''' def set_screen_sharing(self, on: bool) -> None:
|
||||||
|
"""屏幕共享提示。
|
||||||
|
|
||||||
|
这是**故意保留**的:有人在看你的屏幕时,屏幕右下角会出现一条提示。
|
||||||
|
静默模式只是不显示主控制窗口,不是"让被看的人不知道"。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if on:
|
||||||
|
self._show_notice("屏幕正在被共享")
|
||||||
|
else:
|
||||||
|
self._hide_notice()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.log(f"共享提示失败: {exc}")'''
|
||||||
|
|
||||||
|
SCREEN_SHARING_NEW = ''' def set_screen_sharing(self, on: bool) -> None:
|
||||||
|
"""屏幕共享提示条 —— **默认不显示**。
|
||||||
|
|
||||||
|
用户要求:"以后不需要弹,啥窗户都没有,就可以像 UU 远程一样"。
|
||||||
|
|
||||||
|
所以这里先看设置项 `show_screen_notice`:
|
||||||
|
* 关着(默认)-> 什么都不做,连窗口都不建
|
||||||
|
* 开着 -> 行为跟以前一样,右下角(或用户设的位置)一条红条
|
||||||
|
|
||||||
|
保留这个开关而不是删掉代码,是因为这软件应该始终有一个
|
||||||
|
"让本机用户看得见正在被控制"的选项可查 ——
|
||||||
|
需要的时候在设置里打开就行。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.store.get("show_screen_notice"):
|
||||||
|
# 设置关着:确保之前残留的提示条也收掉(比如用户
|
||||||
|
# 正在被看的时候把开关关了),然后什么都不做
|
||||||
|
if not on:
|
||||||
|
self._hide_notice()
|
||||||
|
return
|
||||||
|
if on:
|
||||||
|
self._show_notice("屏幕正在被共享")
|
||||||
|
else:
|
||||||
|
self._hide_notice()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.log(f"共享提示失败: {exc}")'''
|
||||||
|
|
||||||
|
|
||||||
|
def patch_file(path: Path, pairs: list, what: str) -> bool:
|
||||||
|
"""先校验所有锚点,再一次性替换。"""
|
||||||
|
raw = path.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
missing = [name for name, old, _new in pairs if old not in text]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ %s 这些锚点找不到:%s" % (what, ", ".join(missing)))
|
||||||
|
return False
|
||||||
|
for name, old, new in pairs:
|
||||||
|
text = text.replace(old, new, 1)
|
||||||
|
path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ %s(%d 处)" % (what, len(pairs)))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 弹窗位置/大小可配置 + 屏幕提示条默认关")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
# ---- config.py ----
|
||||||
|
cfg_raw = CONFIG.read_bytes()
|
||||||
|
cfg_bom = cfg_raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
cfg = cfg_raw.decode("utf-8-sig")
|
||||||
|
if "notice_position" in cfg:
|
||||||
|
print(" config.py 已经加过了")
|
||||||
|
else:
|
||||||
|
anchor = ' "screen_fps": 12,\n}'
|
||||||
|
if anchor not in cfg:
|
||||||
|
print(" ✗ config.py 找不到 screen_fps 结尾锚点")
|
||||||
|
return 1
|
||||||
|
cfg = cfg.replace(anchor, CONFIG_ADD, 1)
|
||||||
|
CONFIG.write_bytes((b"\xef\xbb\xbf" if cfg_bom else b"")
|
||||||
|
+ cfg.encode("utf-8"))
|
||||||
|
print(" ✓ config.py 加了 6 个设置项")
|
||||||
|
|
||||||
|
# ---- headless.py ----
|
||||||
|
html_raw = HEADLESS.read_bytes()
|
||||||
|
print()
|
||||||
|
ok = patch_file(HEADLESS, [
|
||||||
|
("_notice_geometry 方法", " def screen_size(self)",
|
||||||
|
GEOMETRY_HELPER.lstrip("\n") + " def screen_size(self)"),
|
||||||
|
("set_screen_sharing 尊重设置项", SCREEN_SHARING_OLD, SCREEN_SHARING_NEW),
|
||||||
|
], "headless.py 主体")
|
||||||
|
|
||||||
|
if not ok:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# ---- 三处写死的 geometry 改成调 helper ----
|
||||||
|
raw = HEADLESS.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
old_line = ('win.geometry(f"+{screen_w - width - 24}'
|
||||||
|
'+{screen_h - height - 72}")')
|
||||||
|
n = text.count(old_line)
|
||||||
|
if n == 0:
|
||||||
|
print(" ⚠ 没找到写死的 geometry 行(可能已改)")
|
||||||
|
else:
|
||||||
|
text = text.replace(old_line, "win.geometry(self._notice_geometry(width, height))")
|
||||||
|
HEADLESS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 替换了 %d 处写死的右下角定位" % n)
|
||||||
|
|
||||||
|
# ---- 字号可配置 ----
|
||||||
|
raw = HEADLESS.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
n2 = 0
|
||||||
|
for old_font, new_font in [
|
||||||
|
('font=("Microsoft YaHei UI", 11, "bold")',
|
||||||
|
'font=("Microsoft YaHei UI", self._notice_font(), "bold")'),
|
||||||
|
('font=("Microsoft YaHei UI", 10)',
|
||||||
|
'font=("Microsoft YaHei UI", self._notice_font() - 1)'),
|
||||||
|
]:
|
||||||
|
c = text.count(old_font)
|
||||||
|
if c:
|
||||||
|
text = text.replace(old_font, new_font)
|
||||||
|
n2 += c
|
||||||
|
if n2:
|
||||||
|
HEADLESS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 替换了 %d 处写死的字号" % n2)
|
||||||
|
|
||||||
|
# ---- 加 _notice_font 方法 ----
|
||||||
|
raw = HEADLESS.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
if "_notice_font" in text and "def _notice_font" not in text:
|
||||||
|
helper = '''
|
||||||
|
def _notice_font(self) -> int:
|
||||||
|
"""弹窗字号。用户要求"大小可以自定义",所以从设置里读。
|
||||||
|
|
||||||
|
夹在 8~32 之间:太小看不清,太大一个通知就把屏幕占满了。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
size = int(self.store.get("notice_font_size") or 11)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
size = 11
|
||||||
|
return max(8, min(32, size))
|
||||||
|
|
||||||
|
'''
|
||||||
|
text = text.replace(" def _notice_geometry(self, width: int, height: int) -> str:",
|
||||||
|
helper.lstrip("\n") + " def _notice_geometry(self, width: int, height: int) -> str:", 1)
|
||||||
|
HEADLESS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 _notice_font 方法")
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把快捷栏那一关加进 verify_all.ps1。
|
||||||
|
|
||||||
|
== 为什么用文件而不是 python -c ==
|
||||||
|
|
||||||
|
要写进 .ps1 的内容里有 `$stageOut`、`$(...)`。
|
||||||
|
用 `python -c "..."` 穿过 PowerShell 时,**PowerShell 会先解析一遍**,
|
||||||
|
把 `$stageOut` 变成 `\` —— 上次 3a12 就是这么坏的
|
||||||
|
(插进去变成 `\ = & python (Join-Path \ "..."`,语法直接错)。
|
||||||
|
|
||||||
|
凡是内容里带 `$` 的,一律写成 .py 文件再跑。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
VERIFY = ROOT / "_tests" / "verify_all.ps1"
|
||||||
|
|
||||||
|
ANCHOR = "# ---------------------------------------------------------------- 3a5"
|
||||||
|
|
||||||
|
STAGE = '''# ---------------------------------------------------------------- 3a13
|
||||||
|
Banner "3a13/9 手表快捷栏 + 允许新设备连接"
|
||||||
|
# 用户要求:"手表端不管干什么,上面都有一栏,栏里的按钮可以在设置页
|
||||||
|
# 自定义,最多可以加 4 个,其中有一个按钮不能改,
|
||||||
|
# 功能就是一键返回桌面"。
|
||||||
|
#
|
||||||
|
# 四个地方最容易漏,漏了都不会报错、只会让人困惑:
|
||||||
|
# 1. buildQuickBar 没挂进 onCreate -> 栏根本不显示
|
||||||
|
# 2. 没加进 showOnly 的数组 -> 面板永远压在上面
|
||||||
|
# 3. 第 4 格做成了可配置 -> 用户找半天"显示桌面"没了
|
||||||
|
# 4. 设置页没有入口 -> 说是能自定义其实改不了
|
||||||
|
$stageOut = & python (Join-Path $root "_tests\\test_quickbar.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "手表快捷栏" ($LASTEXITCODE -eq 0)
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
raw = VERIFY.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "手表快捷栏" in t and "test_quickbar" in t:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
if ANCHOR not in t:
|
||||||
|
print(" ✗ 找不到锚点")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
t = t.replace(ANCHOR, STAGE + ANCHOR, 1)
|
||||||
|
VERIFY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 3a13")
|
||||||
|
|
||||||
|
back = VERIFY.read_text(encoding="utf-8-sig")
|
||||||
|
for token in ('$stageOut = & python (Join-Path $root "_tests\\test_quickbar.py")',
|
||||||
|
'Record "手表快捷栏"'):
|
||||||
|
ok = token in back
|
||||||
|
print(" [%s] %s" % ("PASS" if ok else "FAIL", token[:56]))
|
||||||
|
if not ok:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# 顺手把那些 "3aN/7" 的分母改成 9(关卡总数变了)
|
||||||
|
import re
|
||||||
|
n = len(re.findall(r'Banner "3a\d+/7 ', back))
|
||||||
|
back = re.sub(r'(Banner "3a\d+)/7 ', r'\1/9 ', back)
|
||||||
|
VERIFY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + back.encode("utf-8"))
|
||||||
|
print(" ✓ 把 %d 个 3aN/7 的分母改成 /9" % n)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''在一台服务器上加一个新网站(nginx 虚拟主机 + 证书)。
|
||||||
|
|
||||||
|
== 为什么需要这个 ==
|
||||||
|
|
||||||
|
一台服务器上跑多个网站是常态。做法是:**一个 nginx 占 80/443,
|
||||||
|
每个域名一个 server 块**,nginx 按 Host 头分流到各自的本地端口。
|
||||||
|
|
||||||
|
手写这套配置每次都要复制粘贴改半天,还容易漏:
|
||||||
|
* 忘了签证书 -> 浏览器报不安全
|
||||||
|
* 后端端口写错 -> 502
|
||||||
|
* 忘了把后端绑到 127.0.0.1 -> 服务直接暴露在公网
|
||||||
|
|
||||||
|
所以做成一键的。
|
||||||
|
|
||||||
|
== 用法 ==
|
||||||
|
|
||||||
|
python _build/add_site.py 域名 后端地址 [--php] [--root 目录]
|
||||||
|
|
||||||
|
例:
|
||||||
|
# 反代到一个本地服务
|
||||||
|
python _build/add_site.py blog.xxmxxs.top 127.0.0.1:9000
|
||||||
|
|
||||||
|
# WordPress 那种 PHP 站(走 php-fpm 的 unix socket 或端口)
|
||||||
|
python _build/add_site.py xxmxxs.top 127.0.0.1:9000 --php --root /opt/1panel/www/sites/xxmxxs.top/index
|
||||||
|
|
||||||
|
== 设计上的几个注意 ==
|
||||||
|
|
||||||
|
1. **默认只回源 127.0.0.1**
|
||||||
|
后端服务必须只绑本地。写 0.0.0.0 的话,别人直接打 IP:端口
|
||||||
|
就绕过 nginx 和 Cloudflare 了 —— 那正是用户不想要的。
|
||||||
|
|
||||||
|
2. **证书用 certbot 的 nginx 插件签**
|
||||||
|
它自己改配置、自己加 443。前提是**这个域名的 A 记录已经指过来**
|
||||||
|
(而且最好是橙色云朵,这样 certbot 的 HTTP-01 挑战能经 Cloudflare 回源)。
|
||||||
|
|
||||||
|
3. **不动别的站点**
|
||||||
|
只新建 /etc/nginx/sites-available/<域名>,再链到 sites-enabled。
|
||||||
|
已有的站点(比如遥控中转 ykxmz)一个字都不碰。
|
||||||
|
|
||||||
|
4. **默认 server 的坑**
|
||||||
|
如果有人用 IP 直接访问,nginx 会用**第一个** server 块回应。
|
||||||
|
所以配置文件开头有个显式的 default server 把它们挡掉 ——
|
||||||
|
这样 IP:port 扫不到任何真实站点。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
|
from lssh import run, upload # noqa: E402
|
||||||
|
|
||||||
|
TEMPLATE = """# {domain} —— 由 _build/add_site.py 生成
|
||||||
|
#
|
||||||
|
# 后端: {backend}
|
||||||
|
# 说明: nginx 按 server_name 分流;后端只应该监听 127.0.0.1,
|
||||||
|
# 这样外面只能通过域名(也就是经过 nginx + Cloudflare)访问。
|
||||||
|
|
||||||
|
server {{
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name {domain};
|
||||||
|
|
||||||
|
access_log /var/log/nginx/{safe}_access.log;
|
||||||
|
error_log /var/log/nginx/{safe}_error.log;
|
||||||
|
|
||||||
|
{body}
|
||||||
|
server_tokens off;
|
||||||
|
client_max_body_size {max_body};
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
PROXY_BODY = """ location / {{
|
||||||
|
proxy_pass http://{backend};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 30s;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
PHP_BODY = """ root {root};
|
||||||
|
index index.php index.html;
|
||||||
|
|
||||||
|
location / {{
|
||||||
|
try_files $uri $uri/ /index.php?$args;
|
||||||
|
}}
|
||||||
|
|
||||||
|
location ~ \\.php$ {{
|
||||||
|
include snippets/fastcgi-php.conf;
|
||||||
|
fastcgi_pass {backend};
|
||||||
|
fastcgi_read_timeout 300s;
|
||||||
|
}}
|
||||||
|
|
||||||
|
location ~ /\\.ht {{
|
||||||
|
deny all;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ap = argparse.ArgumentParser(description="加一个网站")
|
||||||
|
ap.add_argument("domain", help="域名,例如 blog.xxmxxs.top")
|
||||||
|
ap.add_argument("backend", help="后端地址,例如 127.0.0.1:9000")
|
||||||
|
ap.add_argument("--php", action="store_true",
|
||||||
|
help="PHP 站(用 fastcgi_pass 而不是 proxy_pass)")
|
||||||
|
ap.add_argument("--root", default="", help="PHP 站的根目录")
|
||||||
|
ap.add_argument("--max-body", default="64m", help="上传大小上限,默认 64m")
|
||||||
|
ap.add_argument("--no-cert", action="store_true",
|
||||||
|
help="只配 80,先不签证书")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
domain = args.domain.strip()
|
||||||
|
backend = args.backend.strip()
|
||||||
|
safe = domain.replace(".", "_").replace("-", "_")
|
||||||
|
|
||||||
|
# ⚠ 后端必须是本地地址。写 0.0.0.0 或公网地址的话,
|
||||||
|
# 等于把后端服务直接暴露出去,nginx 和 Cloudflare 都白搭。
|
||||||
|
if not (backend.startswith("127.0.0.1:") or backend.startswith("localhost:")
|
||||||
|
or backend.startswith("unix:")):
|
||||||
|
print(" ⚠ 后端 %r 不是本地地址。" % backend)
|
||||||
|
print(" 后端必须只监听 127.0.0.1 —— 否则别人直接打 "
|
||||||
|
"IP:端口就绕过了 nginx 和 Cloudflare。")
|
||||||
|
print(" 要继续的话请显式确认(现在中止)。")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if args.php and not args.root:
|
||||||
|
print(" ✗ --php 需要同时给 --root(网站文件目录)")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
body = (PHP_BODY.format(root=args.root, backend=backend)
|
||||||
|
if args.php else PROXY_BODY.format(backend=backend))
|
||||||
|
conf = TEMPLATE.format(domain=domain, backend=backend, safe=safe,
|
||||||
|
body=body, max_body=args.max_body)
|
||||||
|
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 加站点 %s -> %s" % (domain, backend))
|
||||||
|
print("=" * 58)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" ── 1. 写配置 ──")
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.gettempdir()) / ("nginx-%s.conf" % safe)
|
||||||
|
tmp.write_text(conf, encoding="utf-8", newline="\n")
|
||||||
|
upload(str(tmp), "/tmp/%s.conf" % safe)
|
||||||
|
out = run(
|
||||||
|
"sudo mv /tmp/{s}.conf /etc/nginx/sites-available/{d} && "
|
||||||
|
"sudo ln -sf /etc/nginx/sites-available/{d} "
|
||||||
|
"/etc/nginx/sites-enabled/{d} && "
|
||||||
|
"sudo nginx -t 2>&1 | tail -2".format(s=safe, d=domain),
|
||||||
|
timeout=180, quiet=True)
|
||||||
|
for ln in out[1].strip().splitlines():
|
||||||
|
print(" " + ln)
|
||||||
|
if "successful" not in out[1]:
|
||||||
|
print(" ✗ nginx 配置检查没过,撤回")
|
||||||
|
run("sudo rm -f /etc/nginx/sites-enabled/%s" % domain,
|
||||||
|
timeout=60, quiet=True)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" ── 2. 重载 nginx ──")
|
||||||
|
out = run("sudo systemctl reload nginx && sleep 1 && "
|
||||||
|
"systemctl is-active nginx", timeout=120, quiet=True)
|
||||||
|
print(" nginx: " + out[1].strip())
|
||||||
|
|
||||||
|
if not args.no_cert:
|
||||||
|
print()
|
||||||
|
print(" ── 3. 签 Let's Encrypt 证书(顺带加上 443 和跳转)──")
|
||||||
|
out = run(
|
||||||
|
"sudo certbot --nginx -d {d} --non-interactive --agree-tos "
|
||||||
|
"--register-unsafely-without-email --redirect "
|
||||||
|
"--keep-until-expiring 2>&1 | tail -8".format(d=domain),
|
||||||
|
timeout=600, quiet=True)
|
||||||
|
for ln in out[1].strip().splitlines():
|
||||||
|
print(" " + ln)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" ── 4. 复核 ──")
|
||||||
|
# ⚠ 这里**不能用 .format()** —— 远端命令里有 curl 的 `%{http_code}`,
|
||||||
|
# 而 .format() 会把 `{http_code}` 当占位符,抛
|
||||||
|
# "KeyError/IndexError: http_code"。
|
||||||
|
# 和之前用 % 格式化踩的是**同一类坑**(内容里有格式符)。
|
||||||
|
# 凡是把域名等变量拼进含 `{...}` 的远端命令,一律用 replace。
|
||||||
|
probe = (
|
||||||
|
'printf " %-34s %s\\n" "本机带 Host 头" '
|
||||||
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 10 '
|
||||||
|
'-H \'Host: __D__\' http://127.0.0.1:80/)"; '
|
||||||
|
'printf " %-34s %s\\n" "本机 443 带 SNI" '
|
||||||
|
'"$(curl -sk -o /dev/null -w \'%{http_code}\' --max-time 10 '
|
||||||
|
'--resolve __D__:443:127.0.0.1 https://__D__/)"; '
|
||||||
|
'printf " %-34s %s\\n" "公网 443" '
|
||||||
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 20 '
|
||||||
|
'https://__D__/)"'
|
||||||
|
).replace("__D__", domain)
|
||||||
|
out = run(probe, timeout=180, quiet=True)
|
||||||
|
for ln in out[1].strip().splitlines():
|
||||||
|
print(ln)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" 已加好。注意:")
|
||||||
|
print(" * 这个域名的 DNS 要指向这台服务器(Cloudflare 橙色云朵)")
|
||||||
|
print(" * 后端 %s 必须只监听 127.0.0.1" % backend)
|
||||||
|
print(" * 不要动 /etc/nginx/sites-available/ykxmz(那是遥控中转)",
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把「语音播报降级链」加进 verify_all.ps1。
|
||||||
|
|
||||||
|
== 为什么用文件而不是 python -c ==
|
||||||
|
|
||||||
|
要写进 .ps1 的内容里有 `$stageOut`。用 `python -c "..."` 穿过
|
||||||
|
PowerShell 时会被先解析一遍,`$stageOut` 变成 `\` —— 上次 3a12
|
||||||
|
就是这么坏的。
|
||||||
|
|
||||||
|
凡是内容里带 `$` 的,一律写成 .py 文件再跑。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
VERIFY = ROOT / "_tests" / "verify_all.ps1"
|
||||||
|
|
||||||
|
ANCHOR = "# ---------------------------------------------------------------- 3a5"
|
||||||
|
|
||||||
|
STAGE = '''# ---------------------------------------------------------------- 3a14
|
||||||
|
Banner "3a14/9 语音播报降级链(修 Win7 上用不了)"
|
||||||
|
# 用户反馈:"我 win7 上的语音播报好像不能用,你再试一下别的版本能不能用"。
|
||||||
|
#
|
||||||
|
# 原来只有一条路(powershell + System.Speech),而 Win7 上
|
||||||
|
# PowerShell 2.0 + 中文 + PATH 三样都可能出问题。改成降级链之后必须保证:
|
||||||
|
# * cscript/VBScript 排最前(从 Win98 就有,SAPI5 是系统组件,不用装东西)
|
||||||
|
# * 前一条失败要接着试下一条,不是试一条就放弃
|
||||||
|
# * 全失败要**报错**,不能像原来那样 Popen 不等待、明明没出声却说"已播报"
|
||||||
|
# * VBScript 用 ANSI 写(UTF-8 的话 cscript 读出来中文是乱码)
|
||||||
|
$stageOut = & python (Join-Path $root "_tests\\test_tts.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "语音播报降级" ($LASTEXITCODE -eq 0)
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
raw = VERIFY.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "test_tts.py" in t:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
if ANCHOR not in t:
|
||||||
|
print(" ✗ 找不到锚点")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
t = t.replace(ANCHOR, STAGE + ANCHOR, 1)
|
||||||
|
VERIFY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 3a14")
|
||||||
|
|
||||||
|
back = VERIFY.read_text(encoding="utf-8-sig")
|
||||||
|
for token in ('$stageOut = & python (Join-Path $root "_tests\\test_tts.py")',
|
||||||
|
'Record "语音播报降级"'):
|
||||||
|
ok = token in back
|
||||||
|
print(" [%s] %s" % ("PASS" if ok else "FAIL", token[:56]))
|
||||||
|
if not ok:
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''给中转加「最新版本查询」接口 —— 被控端静默自动更新的第一步。
|
||||||
|
|
||||||
|
== 为什么由中转来回答 ==
|
||||||
|
|
||||||
|
被控端已经知道中转地址(那是它的配置),而中转的 downloads/ 目录里
|
||||||
|
就放着各版本的成品。让中转直接回答"最新是哪版、在哪下、校验和多少",
|
||||||
|
就不用把任何地址写死在客户端里 —— 换个域名/换台服务器都不用改代码。
|
||||||
|
|
||||||
|
== 新增 ==
|
||||||
|
|
||||||
|
GET /v1/update/latest?platform=windows
|
||||||
|
|
||||||
|
200 {
|
||||||
|
"ok": true,
|
||||||
|
"platform": "windows",
|
||||||
|
"version": "2.1.5",
|
||||||
|
"name": "ykxmz-setup-2.1.5.exe",
|
||||||
|
"url": "/download/ykxmz-setup-2.1.5.exe",
|
||||||
|
"size": 9395078,
|
||||||
|
"sha256": "....",
|
||||||
|
"notes": "..." <- 可选,取 CHANGELOG 里那一节
|
||||||
|
}
|
||||||
|
|
||||||
|
没找到任何包时:
|
||||||
|
200 {"ok": false, "error": "还没有可用的安装包"}
|
||||||
|
|
||||||
|
== url 给相对路径 ==
|
||||||
|
|
||||||
|
给相对路径(`/download/xxx.exe`),让被控端用**它自己配置的中转地址**
|
||||||
|
拼成完整 URL。这样:
|
||||||
|
* 中转换域名/换 IP 不用改任何东西
|
||||||
|
* 走 Cloudflare 还是直连由被控端那边的配置决定
|
||||||
|
|
||||||
|
== sha256 要缓存 ==
|
||||||
|
|
||||||
|
安装包 9MB,每次请求都算一遍 sha256 大概 30 毫秒 —— 不算慢,
|
||||||
|
但这个接口会被所有被控端周期性调用(每台每小时一次的话,
|
||||||
|
一个学校几十台就是几十次),没必要重复算。
|
||||||
|
按「文件名 + 大小 + 修改时间」做键缓存。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
RELAY = ROOT / "relay" / "relay.py"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
raw = RELAY.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "_latest_package" in text:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# ⚠ **先把所有锚点都验一遍,再动手改。**
|
||||||
|
#
|
||||||
|
# 第一版是把替换都做在内存里、最后才 write_bytes ——
|
||||||
|
# 结果中途某个锚点没匹配上就 `return 1`,
|
||||||
|
# 前面几处改动**全丢了**(脚本还打印了"✓ 已加"),
|
||||||
|
# 而文件其实一个字没变。特别容易误判成"加好了"。
|
||||||
|
#
|
||||||
|
# 教训:**批处理脚本要幺先验后改,幺写一段落一段。**
|
||||||
|
ANCHORS = {
|
||||||
|
"import_json": "\nimport json",
|
||||||
|
"list_downloads": ' items.sort(key=lambda item: item["mtime"], reverse=True)\n return items\n',
|
||||||
|
"downloads_route": ' if path == "/v1/downloads":',
|
||||||
|
}
|
||||||
|
missing = [k for k, v in ANCHORS.items() if v not in text]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 这些锚点找不到,一个字都不改:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点全部就位")
|
||||||
|
|
||||||
|
# ---- 1. import hashlib ----
|
||||||
|
if "\nimport hashlib" not in text:
|
||||||
|
text = text.replace(ANCHORS["import_json"],
|
||||||
|
"\nimport hashlib\nimport json", 1)
|
||||||
|
print(" ✓ 加了 import hashlib")
|
||||||
|
|
||||||
|
# ---- 2. 插到 _list_downloads 之后 ----
|
||||||
|
anchor = ANCHORS["list_downloads"]
|
||||||
|
|
||||||
|
helper = anchor + '''
|
||||||
|
|
||||||
|
# 最新安装包的信息缓存。键 = (文件名, 大小, 修改时间)。
|
||||||
|
_PKG_CACHE: dict = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256_of(path: Path) -> str:
|
||||||
|
"""算文件的 sha256(分块读,别把 9MB 全塞内存)。"""
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with path.open("rb") as f:
|
||||||
|
for chunk in iter(lambda: f.read(256 * 1024), b""):
|
||||||
|
h.update(chunk)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _latest_package(platform: str = "windows") -> dict:
|
||||||
|
"""找 downloads/ 里最新的安装包,给被控端自更新用。
|
||||||
|
|
||||||
|
`platform` 现在只有 windows;留着参数是为了以后加别的平台
|
||||||
|
(手表/服务端不通过这个接口自更新,它们各有各的更新方式)。
|
||||||
|
|
||||||
|
返回 {} 表示"还没有可用的包"。
|
||||||
|
"""
|
||||||
|
# 各平台的成品名前缀
|
||||||
|
prefix = {
|
||||||
|
"windows": "ykxmz-setup-",
|
||||||
|
}.get(platform)
|
||||||
|
if not prefix:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
best = None # (版本元组, 路径)
|
||||||
|
try:
|
||||||
|
if not DOWNLOADS_DIR.is_dir():
|
||||||
|
return {}
|
||||||
|
for entry in DOWNLOADS_DIR.iterdir():
|
||||||
|
if not entry.is_file():
|
||||||
|
continue
|
||||||
|
name = entry.name
|
||||||
|
if not name.startswith(prefix) or not name.endswith(".exe"):
|
||||||
|
continue
|
||||||
|
if not _safe_download_name(name):
|
||||||
|
continue
|
||||||
|
# 从文件名里抠版本号
|
||||||
|
mid = name[len(prefix):-len(".exe")]
|
||||||
|
parts = mid.split(".")
|
||||||
|
if len(parts) != 3 or not all(p.isdigit() for p in parts):
|
||||||
|
continue
|
||||||
|
ver = tuple(int(p) for p in parts)
|
||||||
|
# ⚠ 按**数字段**比大小,不能按字符串 ——
|
||||||
|
# 否则 "1.9.0" > "2.1.4"(字符 '9' > '1')。
|
||||||
|
if best is None or ver > best[0]:
|
||||||
|
best = (ver, entry)
|
||||||
|
except OSError:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if best is None:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
ver, path = best
|
||||||
|
try:
|
||||||
|
st = path.stat()
|
||||||
|
except OSError:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
key = (path.name, st.st_size, int(st.st_mtime))
|
||||||
|
cached = _PKG_CACHE.get(key)
|
||||||
|
if cached:
|
||||||
|
digest = cached
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
digest = _sha256_of(path)
|
||||||
|
except OSError:
|
||||||
|
return {}
|
||||||
|
# 只留最近几个,别让字典涨
|
||||||
|
_PKG_CACHE.clear()
|
||||||
|
_PKG_CACHE[key] = digest
|
||||||
|
|
||||||
|
return {
|
||||||
|
"platform": platform,
|
||||||
|
"version": ".".join(str(p) for p in ver),
|
||||||
|
"name": path.name,
|
||||||
|
"url": "/download/" + quote(path.name),
|
||||||
|
"size": st.st_size,
|
||||||
|
"sha256": digest,
|
||||||
|
"mtime": st.st_mtime,
|
||||||
|
}
|
||||||
|
'''
|
||||||
|
text = text.replace(anchor, helper, 1)
|
||||||
|
print(" ✓ 加了 _latest_package / _sha256_of")
|
||||||
|
|
||||||
|
# ---- 3. 路由 ----
|
||||||
|
route_anchor = ANCHORS["downloads_route"]
|
||||||
|
|
||||||
|
route = ''' if path == "/v1/update/latest":
|
||||||
|
# 被控端自更新用:最新版是哪版、在哪下、校验和多少。
|
||||||
|
# 公开接口 —— 文件名和哈希本来就在下载页上人人可见,
|
||||||
|
# 不含任何敏感信息。
|
||||||
|
platform = (urllib.parse.parse_qs(
|
||||||
|
urllib.parse.urlparse(self.path).query)
|
||||||
|
.get("platform", ["windows"])[0] or "windows")
|
||||||
|
pkg = _latest_package(platform)
|
||||||
|
if not pkg:
|
||||||
|
self._json(200, {"ok": False,
|
||||||
|
"error": "还没有可用的安装包"})
|
||||||
|
else:
|
||||||
|
self._json(200, dict(pkg, ok=True))
|
||||||
|
return
|
||||||
|
|
||||||
|
''' + route_anchor
|
||||||
|
text = text.replace(route_anchor, route, 1)
|
||||||
|
print(" ✓ 加了 /v1/update/latest 路由")
|
||||||
|
|
||||||
|
RELAY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 写回 relay.py")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''往 _tests/verify_all.ps1 里加两个关卡。
|
||||||
|
|
||||||
|
== 加哪两个 ==
|
||||||
|
|
||||||
|
3a10 静默自动更新链路(_tests/test_update_flow.py)
|
||||||
|
3a11 远程鼠标 + 显示桌面(_tests/test_mouse_control.py)
|
||||||
|
|
||||||
|
== 这个脚本自己踩过的坑,写下来免得再犯 ==
|
||||||
|
|
||||||
|
往 server.py 插方法时,我两次把 **dispatch 的兜底 return**
|
||||||
|
一起卷进了新方法里:
|
||||||
|
|
||||||
|
if cmd == P.CMD_XXX:
|
||||||
|
return self._do_xxx(msg)
|
||||||
|
|
||||||
|
return {"ok": False, "error": f"未知命令: {cmd}"} <- dispatch 的兜底
|
||||||
|
|
||||||
|
def _do_xxx(...): <- 我的新方法
|
||||||
|
...
|
||||||
|
return {"ok": False, "error": f"未知命令: {cmd}"} <- 被卷进来了!
|
||||||
|
|
||||||
|
结果 pyflakes 报 "undefined name 'cmd'",而 dispatch 丢了兜底分支。
|
||||||
|
|
||||||
|
这次改 PowerShell 里插关卡用**更笨但更稳**的办法:
|
||||||
|
直接在固定锚点**之前**插,而且插完立刻读回来看一眼结构。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
VERIFY = ROOT / "_tests" / "verify_all.ps1"
|
||||||
|
|
||||||
|
STAGES = '''
|
||||||
|
# ---------------------------------------------------------------- 3a10
|
||||||
|
Banner "3a10/7 静默自动更新链路"
|
||||||
|
# 用户要求:"手表端点击一个更新按钮,电脑端就可以自动进行静默更新,
|
||||||
|
# 其他什么设置都不变 …… 不弹任何窗口出来"
|
||||||
|
# 这条链是:中转 /v1/update/latest -> 被控端 updater.py 下载校验
|
||||||
|
# -> 分离 .cmd 帮手 -> 静默装 -> 重启。
|
||||||
|
#
|
||||||
|
# 这里验协议常量、版本比较(按数字段,不是字符串)、下载校验、
|
||||||
|
# 以及**服务端 dispatch 的结构没被补丁弄坏**。
|
||||||
|
$stageOut = & python (Join-Path $root "_tests\\test_update_flow.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "静默自动更新" ($LASTEXITCODE -eq 0)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 3a11
|
||||||
|
Banner "3a11/7 远程鼠标 + 一键显示桌面"
|
||||||
|
# 鼠标注入是最"有力量"的功能,参数校验写错的话表现是"手表点了没反应",
|
||||||
|
# 教室里没法排查。这里盯坐标归一化(除以 宽-1 那条规则)、
|
||||||
|
# 滚轮夹取、Win+D 的事件顺序、以及非法参数必须被拒。
|
||||||
|
$stageOut = & python (Join-Path $root "_tests\\test_mouse_control.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "远程鼠标控制" ($LASTEXITCODE -eq 0)
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
ANCHOR = '# ---------------------------------------------------------------- 3a5'
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
raw = VERIFY.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "静默自动更新链路" in text:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if ANCHOR not in text:
|
||||||
|
print(" ✗ 找不到锚点 %r" % ANCHOR)
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点就位")
|
||||||
|
|
||||||
|
text = text.replace(ANCHOR, STAGES.lstrip("\n") + "\n" + ANCHOR, 1)
|
||||||
|
VERIFY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 3a10 / 3a11 两个关卡")
|
||||||
|
|
||||||
|
# 读回来确认结构:两个 Record 都在、锚点还在
|
||||||
|
back = VERIFY.read_text(encoding="utf-8-sig")
|
||||||
|
for token in ('Record "静默自动更新"', 'Record "远程鼠标控制"', ANCHOR):
|
||||||
|
ok = token in back
|
||||||
|
print(" [%s] 读回确认:%s" % ("PASS" if ok else "FAIL",
|
||||||
|
token[:40]))
|
||||||
|
if not ok:
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,556 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''手表端:常驻顶部快捷栏。
|
||||||
|
|
||||||
|
== 用户的要求(原话)==
|
||||||
|
|
||||||
|
"手表端不管干什么,上面都有一栏,栏里的按钮可以在设置页自定义,
|
||||||
|
最多可以加 4 个,其中有一个按钮不能改,功能就是一键返回桌面"
|
||||||
|
|
||||||
|
("返回桌面"经确认 = **让被控电脑显示桌面**,即 Win+D。)
|
||||||
|
|
||||||
|
== 做什么 ==
|
||||||
|
|
||||||
|
1. **一条常驻的快捷栏**:贴在屏幕顶部,任何页面都在
|
||||||
|
(控制页 / 镜像页 / 设置页 / 局域网页面板切换时不动)
|
||||||
|
|
||||||
|
2. **最多 4 个按钮**:
|
||||||
|
* **1 个固定**:显示桌面(Win+D)—— 不给改,这是用户明确要求的
|
||||||
|
* **最多 3 个自定义**:从 7 个动作里挑
|
||||||
|
|
||||||
|
3. **7 个可选动作**(都有现成调用,见下面的 QUICK_ACTIONS):
|
||||||
|
file 传文件到电脑
|
||||||
|
mirror 屏幕镜像
|
||||||
|
mouse 鼠标控制(本补丁配套的触摸板)
|
||||||
|
sfx 音效
|
||||||
|
power 关机 / 锁屏
|
||||||
|
tts 语音播报
|
||||||
|
image 投图到电脑
|
||||||
|
|
||||||
|
4. **设置页里能改**:勾选哪 3 个动作。
|
||||||
|
|
||||||
|
== 为什么贴在 FrameLayout 最上层 ==
|
||||||
|
|
||||||
|
现有架构是:一个 FrameLayout `root`,5 个面板都 MATCH_PARENT 叠在里面,
|
||||||
|
靠 `showOnly()` 切可见性。
|
||||||
|
|
||||||
|
快捷栏也加到 `root`,**在 5 个面板之后 addView** —— 这样它在最上层:
|
||||||
|
* 切页面时它不受影响(不用每个页面各建一份)
|
||||||
|
* 面板填满整个屏幕也不会盖住它
|
||||||
|
|
||||||
|
代价:面板内容会被栏盖住一截,所以给每个面板加了 topMargin
|
||||||
|
(见 PATCH_PANEL_MARGIN)。
|
||||||
|
|
||||||
|
== 为什么栏在没连上时也显示 ==
|
||||||
|
|
||||||
|
用户说"不管干什么上面都有一栏",那就**一直在**。
|
||||||
|
没连上的时候按钮置灰(不是隐藏)—— "一直在但暂时不能用"
|
||||||
|
比"时有时无"更好理解,也不会让用户以为功能没了。
|
||||||
|
|
||||||
|
== 存储 ==
|
||||||
|
|
||||||
|
用 SharedPreferences(和 App 其他设置一致),键 `quick_slots`,
|
||||||
|
存逗号分隔的动作 id。默认给 file,mirror,sfx。
|
||||||
|
读取时会**过滤掉不认识的 id**(比如以后删了某个动作),
|
||||||
|
不够 3 个就按默认顺序补齐 —— 这样老配置永远不会让栏变空。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAIN = ROOT / "android" / "src" / "com" / "lanremote" / "watch" / "MainActivity.java"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 字段
|
||||||
|
FIELDS_ANCHOR = " private Button updateButton;"
|
||||||
|
|
||||||
|
FIELDS = ''' private Button updateButton;
|
||||||
|
|
||||||
|
// ---------------- 顶部快捷栏 ----------------
|
||||||
|
//
|
||||||
|
// 用户要求:"不管干什么,上面都有一栏,栏里的按钮可以在设置页
|
||||||
|
// 自定义,最多可以加 4 个,其中有一个按钮不能改,
|
||||||
|
// 功能就是一键返回桌面"。
|
||||||
|
//
|
||||||
|
// 所以这里是 1 个固定(显示桌面)+ 最多 3 个自定义。
|
||||||
|
private LinearLayout quickBar;
|
||||||
|
private final java.util.List<Button> quickButtons =
|
||||||
|
new java.util.ArrayList<Button>();
|
||||||
|
/** 设置页里那 3 个位置各放什么动作。null 表示这个位置空着。 */
|
||||||
|
private String[] quickSlots = new String[]{"file", "mirror", "sfx"};
|
||||||
|
|
||||||
|
/** 快捷栏上能放的动作。id 会存进设置,**改名会让老配置失效**,
|
||||||
|
* 所以这几个英文 id 不要动,界面上显示的中文随便改。 */
|
||||||
|
private static final String[][] QUICK_ACTIONS = {
|
||||||
|
{"file", "传文件"},
|
||||||
|
{"mirror", "屏幕镜像"},
|
||||||
|
{"mouse", "鼠标控制"},
|
||||||
|
{"sfx", "音效"},
|
||||||
|
{"power", "关机"},
|
||||||
|
{"tts", "语音播报"},
|
||||||
|
{"image", "投图到电脑"},
|
||||||
|
};
|
||||||
|
private static final String QUICK_PREF = "quick_slots";
|
||||||
|
private static final int QUICK_CUSTOM_SLOTS = 3; // 固定那个不算在内
|
||||||
|
|
||||||
|
// ---------------- 鼠标控制(触摸板)----------------
|
||||||
|
private FrameLayout mousePanel;
|
||||||
|
private View mousePad;
|
||||||
|
private boolean mouseDragging = false;
|
||||||
|
private float mouseLastX = 0f;
|
||||||
|
private float mouseLastY = 0f;'''
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 建栏方法
|
||||||
|
BUILD_ANCHOR = " private void showOnly(View keep) {"
|
||||||
|
|
||||||
|
BUILD_METHOD = ''' // ==================================================================
|
||||||
|
// 顶部快捷栏
|
||||||
|
// ==================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建快捷栏。挂在 root 最上层,任何页面都在。
|
||||||
|
*
|
||||||
|
* <p>布局:[动作1][动作2][动作3][显示桌面]
|
||||||
|
* 前三个按设置里的选择走,最后一个**永远**是显示桌面(不给改)。
|
||||||
|
*/
|
||||||
|
private void buildQuickBar() {
|
||||||
|
quickBar = new LinearLayout(this);
|
||||||
|
quickBar.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
quickBar.setBackgroundColor(0xE6185CE8); // 半透明蓝,压在任何页面上都看得清
|
||||||
|
quickBar.setPadding(dp(3), dp(3), dp(3), dp(3));
|
||||||
|
quickBar.setGravity(android.view.Gravity.CENTER_VERTICAL);
|
||||||
|
|
||||||
|
quickButtons.clear();
|
||||||
|
// 4 个按钮:3 个自定义 + 1 个固定
|
||||||
|
for (int i = 0; i < QUICK_CUSTOM_SLOTS + 1; i++) {
|
||||||
|
final int slot = i;
|
||||||
|
Button b = new Button(this);
|
||||||
|
b.setTextSize(11f);
|
||||||
|
b.setAllCaps(false);
|
||||||
|
b.setTextColor(0xFFFFFFFF);
|
||||||
|
b.setBackgroundColor(0x33FFFFFF);
|
||||||
|
b.setPadding(dp(2), 0, dp(2), 0);
|
||||||
|
b.setMinWidth(0);
|
||||||
|
b.setMinimumWidth(0);
|
||||||
|
b.setMinHeight(0);
|
||||||
|
b.setMinimumHeight(0);
|
||||||
|
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
|
||||||
|
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
|
||||||
|
lp.setMargins(dp(2), 0, dp(2), 0);
|
||||||
|
b.setLayoutParams(lp);
|
||||||
|
b.setOnClickListener(new View.OnClickListener() {
|
||||||
|
@Override
|
||||||
|
public void onClick(View v) {
|
||||||
|
onQuickClick(slot);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
quickButtons.add(b);
|
||||||
|
quickBar.addView(b);
|
||||||
|
}
|
||||||
|
// 高度固定,免得按钮里的字多一个字整条栏就变高、页面跟着抖
|
||||||
|
FrameLayout.LayoutParams barLp = new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(30));
|
||||||
|
barLp.gravity = android.view.Gravity.TOP;
|
||||||
|
quickBar.setLayoutParams(barLp);
|
||||||
|
|
||||||
|
refreshQuickBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按设置刷新快捷栏上的文字和可用状态。
|
||||||
|
*
|
||||||
|
* <p>连不上的时候置灰而不是隐藏 —— 用户说"不管干什么上面都有一栏",
|
||||||
|
* 时有时无会让人以为功能没了。
|
||||||
|
*/
|
||||||
|
private void refreshQuickBar() {
|
||||||
|
if (quickBar == null || quickButtons.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
boolean connected = isConnected();
|
||||||
|
for (int i = 0; i < quickButtons.size(); i++) {
|
||||||
|
Button b = quickButtons.get(i);
|
||||||
|
String id = (i < QUICK_CUSTOM_SLOTS) ? quickSlots[i] : "desktop";
|
||||||
|
if (id == null || id.isEmpty()) {
|
||||||
|
b.setText("-"); // 这个位置空着
|
||||||
|
b.setEnabled(false);
|
||||||
|
b.setAlpha(0.45f);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
b.setText(quickLabel(id));
|
||||||
|
b.setEnabled(connected);
|
||||||
|
b.setAlpha(connected ? 1f : 0.5f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String quickLabel(String id) {
|
||||||
|
if ("desktop".equals(id)) {
|
||||||
|
return "显示桌面"; // 固定那个
|
||||||
|
}
|
||||||
|
for (String[] pair : QUICK_ACTIONS) {
|
||||||
|
if (pair[0].equals(id)) {
|
||||||
|
return pair[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "-";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点第 slot 个按钮。0..2 是自定义,3 是那个固定的显示桌面。 */
|
||||||
|
private void onQuickClick(int slot) {
|
||||||
|
String id = (slot < QUICK_CUSTOM_SLOTS) ? quickSlots[slot] : "desktop";
|
||||||
|
if (id == null || id.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
runQuickAction(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 执行一个快捷动作。设置页里选的也是这几个 id。 */
|
||||||
|
private void runQuickAction(String id) {
|
||||||
|
try {
|
||||||
|
if ("desktop".equals(id)) {
|
||||||
|
// 用户确认过:"一键返回桌面" = 让**被控电脑**显示桌面(Win+D)
|
||||||
|
sendCommand(Json.obj("cmd", "show_desktop"), "显示桌面");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("file".equals(id)) {
|
||||||
|
pickFile(REQ_FILE, "*/*");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("mirror".equals(id)) {
|
||||||
|
openMirrorPanel();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("mouse".equals(id)) {
|
||||||
|
showMousePanel();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("sfx".equals(id)) {
|
||||||
|
pickSfx();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("power".equals(id)) {
|
||||||
|
showPowerChooser();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("tts".equals(id)) {
|
||||||
|
promptSay();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("image".equals(id)) {
|
||||||
|
pickFile(REQ_IMAGE, "image/*");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast("不认识的动作:" + id);
|
||||||
|
} catch (Throwable error) {
|
||||||
|
toast("执行失败:" + shortReason(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关机这一格点开后让用户选锁屏还是关机(不直接关,太危险)。 */
|
||||||
|
private void showPowerChooser() {
|
||||||
|
final java.util.List<String> items = new java.util.ArrayList<String>();
|
||||||
|
items.add("锁屏");
|
||||||
|
items.add("关机");
|
||||||
|
items.add("重启");
|
||||||
|
showChooser("电源", items, new Chooser() {
|
||||||
|
@Override
|
||||||
|
public void onPick(int index) {
|
||||||
|
if (index == 0) {
|
||||||
|
confirmPower("lock", "锁屏");
|
||||||
|
} else if (index == 1) {
|
||||||
|
confirmPower("shutdown", "关机");
|
||||||
|
} else {
|
||||||
|
confirmPower("restart", "重启");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 快捷栏的存取 ----------------
|
||||||
|
|
||||||
|
private void loadQuickSlots() {
|
||||||
|
String raw = prefs().getString(QUICK_PREF, "");
|
||||||
|
String[] want = (raw == null || raw.isEmpty())
|
||||||
|
? new String[]{"file", "mirror", "sfx"}
|
||||||
|
: raw.split(",", -1);
|
||||||
|
// ⚠ 一定要过滤 + 补齐:
|
||||||
|
// 过滤 —— 万一以后删了某个动作,老配置里的 id 就不认识了,
|
||||||
|
// 不过滤的话那格会显示空白,用户以为坏了
|
||||||
|
// 补齐 —— 保证长度正好 3,少了下标会越界
|
||||||
|
String[] out = new String[QUICK_CUSTOM_SLOTS];
|
||||||
|
int n = 0;
|
||||||
|
for (String id : want) {
|
||||||
|
if (n >= QUICK_CUSTOM_SLOTS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (id != null && !id.isEmpty() && !"desktop".equals(id)
|
||||||
|
&& isKnownQuickAction(id)) {
|
||||||
|
out[n++] = id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String[] fallback = {"file", "mirror", "sfx"};
|
||||||
|
for (int i = 0; i < QUICK_CUSTOM_SLOTS; i++) {
|
||||||
|
if (out[i] == null) {
|
||||||
|
// 补一个没被用过的默认动作
|
||||||
|
for (String f : fallback) {
|
||||||
|
boolean used = false;
|
||||||
|
for (String o : out) {
|
||||||
|
if (f.equals(o)) {
|
||||||
|
used = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!used) {
|
||||||
|
out[i] = f;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
quickSlots = out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isKnownQuickAction(String id) {
|
||||||
|
for (String[] pair : QUICK_ACTIONS) {
|
||||||
|
if (pair[0].equals(id)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveQuickSlots() {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (String id : quickSlots) {
|
||||||
|
if (sb.length() > 0) {
|
||||||
|
sb.append(',');
|
||||||
|
}
|
||||||
|
sb.append(id == null ? "" : id);
|
||||||
|
}
|
||||||
|
prefs().edit().putString(QUICK_PREF, sb.toString()).apply();
|
||||||
|
refreshQuickBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
private android.content.SharedPreferences prefs() {
|
||||||
|
return getSharedPreferences("ykxmz", MODE_PRIVATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 鼠标触摸板
|
||||||
|
MOUSE_METHOD = ''' // ==================================================================
|
||||||
|
// 鼠标控制(触摸板)
|
||||||
|
// ==================================================================
|
||||||
|
|
||||||
|
private void showMousePanel() {
|
||||||
|
if (mousePanel == null) {
|
||||||
|
buildMousePanel();
|
||||||
|
}
|
||||||
|
showOnly(mousePanel);
|
||||||
|
appendLog("鼠标控制:拖动=移动光标,单击=左键,双击=右键");
|
||||||
|
toast("拖动移动光标 · 单击左键 · 双击右键");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触摸板。整块区域接收触摸,按比例映射到电脑屏幕的像素坐标。
|
||||||
|
*
|
||||||
|
* <p>为什么用"按比例映射"而不是"相对位移":
|
||||||
|
* 手表表盘和电脑屏幕尺寸差得远,相对位移要让手表自己猜倍率,
|
||||||
|
* 猜错了光标就飘;绝对映射由电脑端负责落到那个像素,
|
||||||
|
* 责任清晰,也不会累积漂移。
|
||||||
|
*
|
||||||
|
* <p>但表盘太小,绝对映射的精度只有几十像素 —— 所以
|
||||||
|
* **双击左右半屏**这类大幅移动之后,用拖动做细调更实际。
|
||||||
|
* 这里两个都支持:拖动 = 相对微调,点击 = 在当前位置按下/抬起。
|
||||||
|
*/
|
||||||
|
private void buildMousePanel() {
|
||||||
|
mousePanel = new FrameLayout(this);
|
||||||
|
mousePanel.setBackgroundColor(0xFF101418);
|
||||||
|
|
||||||
|
LinearLayout col = new LinearLayout(this);
|
||||||
|
col.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
col.setPadding(dp(6), dp(34), dp(6), dp(4));
|
||||||
|
mousePanel.addView(col, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT));
|
||||||
|
|
||||||
|
TextView tip = new TextView(this);
|
||||||
|
tip.setText("拖动=移动 单击=左键 双击=右键\\n滚轮在下面");
|
||||||
|
tip.setTextSize(10f);
|
||||||
|
tip.setTextColor(0xFF9AA4B2);
|
||||||
|
tip.setGravity(android.view.Gravity.CENTER);
|
||||||
|
col.addView(tip, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||||
|
|
||||||
|
mousePad = new View(this);
|
||||||
|
mousePad.setBackgroundColor(0xFF1B2028);
|
||||||
|
LinearLayout.LayoutParams padLp = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
|
||||||
|
padLp.setMargins(0, dp(4), 0, dp(4));
|
||||||
|
col.addView(mousePad, padLp);
|
||||||
|
|
||||||
|
// 左键 / 右键 / 滚轮
|
||||||
|
LinearLayout keys = new LinearLayout(this);
|
||||||
|
keys.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
col.addView(keys, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(34)));
|
||||||
|
|
||||||
|
keys.addView(mouseKey("左键", new Runnable() {
|
||||||
|
public void run() { sendMouse("click", "left", 0); }
|
||||||
|
}));
|
||||||
|
keys.addView(mouseKey("右键", new Runnable() {
|
||||||
|
public void run() { sendMouse("click", "right", 0); }
|
||||||
|
}));
|
||||||
|
keys.addView(mouseKey("滚↑", new Runnable() {
|
||||||
|
public void run() { sendMouse("scroll", "", 3); }
|
||||||
|
}));
|
||||||
|
keys.addView(mouseKey("滚↓", new Runnable() {
|
||||||
|
public void run() { sendMouse("scroll", "", -3); }
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 返回按钮(快捷栏上也能离开,但这里给个明确的出口)
|
||||||
|
Button back = new Button(this);
|
||||||
|
back.setText("返回");
|
||||||
|
back.setTextSize(11f);
|
||||||
|
back.setAllCaps(false);
|
||||||
|
FrameLayout.LayoutParams backLp = new FrameLayout.LayoutParams(
|
||||||
|
dp(58), dp(26));
|
||||||
|
backLp.gravity = android.view.Gravity.TOP | android.view.Gravity.END;
|
||||||
|
backLp.setMargins(0, dp(4), dp(4), 0);
|
||||||
|
back.setLayoutParams(backLp);
|
||||||
|
back.setOnClickListener(new View.OnClickListener() {
|
||||||
|
@Override
|
||||||
|
public void onClick(View v) {
|
||||||
|
showControlPanel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
mousePanel.addView(back);
|
||||||
|
|
||||||
|
// ---- 触摸处理 ----
|
||||||
|
final android.view.GestureDetector detector =
|
||||||
|
new android.view.GestureDetector(this,
|
||||||
|
new android.view.GestureDetector.SimpleOnGestureListener() {
|
||||||
|
@Override
|
||||||
|
public boolean onSingleTapConfirmed(android.view.MotionEvent e) {
|
||||||
|
sendMouse("click", "left", 0); // 单击 = 左键
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onDoubleTap(android.view.MotionEvent e) {
|
||||||
|
sendMouse("click", "right", 0); // 双击 = 右键
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onScroll(android.view.MotionEvent e1,
|
||||||
|
android.view.MotionEvent e2,
|
||||||
|
float dx, float dy) {
|
||||||
|
// 手指往哪滑,光标往哪走:dx/dy 是"内容移动量",
|
||||||
|
// 也就是手指移动的反方向,所以取负。
|
||||||
|
sendMouseMove(-dx, -dy);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
mousePad.setOnTouchListener(new View.OnTouchListener() {
|
||||||
|
@Override
|
||||||
|
public boolean onTouch(View v, android.view.MotionEvent e) {
|
||||||
|
detector.onTouchEvent(e);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Button mouseKey(String text, final Runnable action) {
|
||||||
|
Button b = new Button(this);
|
||||||
|
b.setText(text);
|
||||||
|
b.setTextSize(10f);
|
||||||
|
b.setAllCaps(false);
|
||||||
|
b.setPadding(0, 0, 0, 0);
|
||||||
|
b.setMinWidth(0);
|
||||||
|
b.setMinimumWidth(0);
|
||||||
|
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
|
||||||
|
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
|
||||||
|
lp.setMargins(dp(1), 0, dp(1), 0);
|
||||||
|
b.setLayoutParams(lp);
|
||||||
|
b.setOnClickListener(new View.OnClickListener() {
|
||||||
|
@Override
|
||||||
|
public void onClick(View v) {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendMouse(String action, String button, int amount) {
|
||||||
|
if (!isConnected()) {
|
||||||
|
toast("还没连上电脑");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> req = Json.obj("cmd", "mouse", "action", action);
|
||||||
|
if (button != null && !button.isEmpty()) {
|
||||||
|
req.put("button", button);
|
||||||
|
}
|
||||||
|
if (amount != 0) {
|
||||||
|
req.put("amount", amount);
|
||||||
|
}
|
||||||
|
sendCommand(req, "鼠标");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendMouseMove(float dx, float dy) {
|
||||||
|
if (!isConnected()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 手表上滑一点,电脑上要走一段 —— 倍率小了手指要划好几次才横穿屏幕。
|
||||||
|
// 取 3.0 是试出来的:1920 宽的屏大约划 4~5 次到底,细调也还行。
|
||||||
|
sendCommand(Json.obj("cmd", "mouse", "action", "moveby",
|
||||||
|
"dx", (int) (dx * 3.0f), "dy", (int) (dy * 3.0f)), "鼠标");
|
||||||
|
}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 设置页那一段
|
||||||
|
SETTINGS_ANCHOR = " private void showSettingsPanel() {"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 手表端:常驻顶部快捷栏 + 鼠标触摸板")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = MAIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "buildQuickBar" in t:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 先校验所有锚点,避免改一半
|
||||||
|
need = {
|
||||||
|
"updateButton 字段": FIELDS_ANCHOR,
|
||||||
|
"showOnly 方法": BUILD_ANCHOR,
|
||||||
|
}
|
||||||
|
missing = [k for k, v in need.items() if v not in t]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 这些锚点找不到:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点全部就位")
|
||||||
|
|
||||||
|
# 1) 字段
|
||||||
|
t = t.replace(FIELDS_ANCHOR, FIELDS, 1)
|
||||||
|
# 2) 方法(插在 showOnly 之前)
|
||||||
|
t = t.replace(BUILD_ANCHOR, BUILD_METHOD + BUILD_ANCHOR, 1)
|
||||||
|
# 3) 鼠标面板方法(也插在 showOnly 之前,跟快捷栏挨着)
|
||||||
|
t = t.replace(BUILD_ANCHOR, MOUSE_METHOD + BUILD_ANCHOR, 1)
|
||||||
|
|
||||||
|
MAIN.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 加了字段 + buildQuickBar/refreshQuickBar/runQuickAction")
|
||||||
|
print(" ✓ 加了鼠标触摸板 buildMousePanel")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''设置页里加「快捷栏」和「允许新设备连接」(第二版)。
|
||||||
|
|
||||||
|
== 第一版为什么不行 ==
|
||||||
|
|
||||||
|
我原来写的 refresh 是重建整个设置面板,但 `buildSettingsPanel()` 是
|
||||||
|
**一次性把整页建完**的(没有"往给定容器里建"的版本),而
|
||||||
|
`root.addView(settingsPanel)` 是在 onCreate 里做的 ——
|
||||||
|
所以重建出来的面板**没挂在视图树上**,刷完页面就白了。
|
||||||
|
|
||||||
|
== 这一版怎么做 ==
|
||||||
|
|
||||||
|
用**一个专用容器**装我这两小节:
|
||||||
|
|
||||||
|
settingsPanel
|
||||||
|
└ ScrollView
|
||||||
|
└ box (LinearLayout)
|
||||||
|
├ ...原有的各小节...
|
||||||
|
├ settingsExtraBox <-- 我加的这个
|
||||||
|
└ 关于
|
||||||
|
|
||||||
|
刷新时只清空 `settingsExtraBox` 再填一遍 —— 不动页面其他部分,
|
||||||
|
也不用碰视图树。开销小,而且不会有"重建后没挂上去"的问题。
|
||||||
|
|
||||||
|
== 加两个小节 ==
|
||||||
|
|
||||||
|
1. **快捷栏**:3 个格子各点一下,从 7 个动作里选(也能选"留空")。
|
||||||
|
第 4 格是固定的「显示桌面」—— 界面上写明它改不了,
|
||||||
|
否则用户会一直找"怎么改第四个"。
|
||||||
|
|
||||||
|
2. **允许新设备连接**:关掉后只有配过对的设备能连。
|
||||||
|
两端的语义必须一致(电脑端设置窗口里也有同名勾选)。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAIN = ROOT / "android" / "src" / "com" / "lanremote" / "watch" / "MainActivity.java"
|
||||||
|
|
||||||
|
ANCHOR = ' // ================= 关于 ================='
|
||||||
|
|
||||||
|
SECTION = ''' // ================= 快捷栏 / 允许新设备连接 =================
|
||||||
|
//
|
||||||
|
// 这两小节装在**专用容器**里(settingsExtraBox),
|
||||||
|
// 这样改完设置只刷这一段,不用重建整页 ——
|
||||||
|
// 重建整页的话 settingsPanel 是新的对象,而 root 上挂的还是旧的,
|
||||||
|
// 表现就是"一改设置页面就白了"。
|
||||||
|
settingsExtraBox = new LinearLayout(this);
|
||||||
|
settingsExtraBox.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
box.addView(settingsExtraBox, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||||
|
fillSettingsExtra();
|
||||||
|
|
||||||
|
''' + ANCHOR
|
||||||
|
|
||||||
|
# ---------------- 各种方法 ----------------
|
||||||
|
METHODS = ''' /** 让用户选第 slot 格放哪个动作。 */
|
||||||
|
private void pickQuickSlot(final int slot) {
|
||||||
|
final java.util.List<String> labels = new java.util.ArrayList<String>();
|
||||||
|
final java.util.List<String> ids = new java.util.ArrayList<String>();
|
||||||
|
labels.add("留空(这一格不显示)");
|
||||||
|
ids.add("");
|
||||||
|
for (String[] pair : QUICK_ACTIONS) {
|
||||||
|
labels.add(pair[1]);
|
||||||
|
ids.add(pair[0]);
|
||||||
|
}
|
||||||
|
showChooser("第 " + (slot + 1) + " 格放什么", labels, new Chooser() {
|
||||||
|
@Override
|
||||||
|
public void onPick(int index) {
|
||||||
|
if (index < 0 || index >= ids.size()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
quickSlots[slot] = ids.get(index);
|
||||||
|
saveQuickSlots();
|
||||||
|
fillSettingsExtra();
|
||||||
|
toast("第 " + (slot + 1) + " 格已设为:"
|
||||||
|
+ quickLabel(quickSlots[slot]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 电脑端当前的「允许新设备连接」状态。本地记一份,连上后以电脑端为准。 */
|
||||||
|
private boolean allowNewPairing() {
|
||||||
|
return prefs().getBoolean("allow_new_pairing", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 填「快捷栏」和「允许新设备连接」这两小节。刷新时也调它。 */
|
||||||
|
private void fillSettingsExtra() {
|
||||||
|
if (settingsExtraBox == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
settingsExtraBox.removeAllViews();
|
||||||
|
|
||||||
|
settingsExtraBox.addView(sectionTitle("快捷栏"));
|
||||||
|
settingsExtraBox.addView(hintText("顶部那条栏,最多 4 个按钮。"
|
||||||
|
+ "最后一个「显示桌面」是固定的、改不了;"
|
||||||
|
+ "前三个点下面自己选。(还没连上电脑时它们是灰的)"));
|
||||||
|
for (int slot = 0; slot < QUICK_CUSTOM_SLOTS; slot++) {
|
||||||
|
final int s = slot;
|
||||||
|
String now = (quickSlots[s] == null || quickSlots[s].isEmpty())
|
||||||
|
? "空着" : quickLabel(quickSlots[s]);
|
||||||
|
settingsExtraBox.addView(smallButton(
|
||||||
|
"第 " + (s + 1) + " 格:" + now, C_CARD,
|
||||||
|
new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
pickQuickSlot(s);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
settingsExtraBox.addView(smallButton(
|
||||||
|
"恢复默认(传文件 / 屏幕镜像 / 音效)", C_CARD,
|
||||||
|
new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
quickSlots = new String[]{"file", "mirror", "sfx"};
|
||||||
|
saveQuickSlots();
|
||||||
|
fillSettingsExtra();
|
||||||
|
toast("快捷栏已恢复默认");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
settingsExtraBox.addView(sectionTitle("允许新设备连接"));
|
||||||
|
settingsExtraBox.addView(hintText("关掉之后,只有已经配对过的电脑"
|
||||||
|
+ "能连上来,新电脑会被拒绝。教室里防别人乱连用这个。"));
|
||||||
|
settingsExtraBox.addView(smallButton(
|
||||||
|
"现在:" + (allowNewPairing() ? "允许"
|
||||||
|
: "不允许(只有老设备能连)"),
|
||||||
|
C_CARD, new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
final boolean want = !allowNewPairing();
|
||||||
|
new android.app.AlertDialog.Builder(MainActivity.this)
|
||||||
|
.setTitle("允许新设备连接")
|
||||||
|
.setMessage(want
|
||||||
|
? "打开后,没配对过的新电脑也能连上。"
|
||||||
|
: "关掉后,只有已经配对过的电脑能连上,"
|
||||||
|
+ "新电脑会被拒绝。")
|
||||||
|
.setPositiveButton(want ? "允许" : "关掉",
|
||||||
|
new android.content.DialogInterface.OnClickListener() {
|
||||||
|
public void onClick(android.content.DialogInterface d,
|
||||||
|
int w) {
|
||||||
|
// 电脑端执行 + 本地记一份(连不上时也能看到选择)
|
||||||
|
runFeature("allow_new_pairing",
|
||||||
|
Json.obj("allow", want),
|
||||||
|
want ? "允许新设备连接"
|
||||||
|
: "只允许老设备连接");
|
||||||
|
prefs().edit()
|
||||||
|
.putBoolean("allow_new_pairing", want)
|
||||||
|
.apply();
|
||||||
|
fillSettingsExtra();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setNegativeButton("取消", null)
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
FIELD_ANCHOR = " private LinearLayout quickBar;"
|
||||||
|
FIELD_ADD = ''' private LinearLayout quickBar;
|
||||||
|
/** 设置页里装「快捷栏 / 允许新设备连接」那两小节的容器。
|
||||||
|
* 用专用容器是为了改完只刷这一段,不用重建整页。 */
|
||||||
|
private LinearLayout settingsExtraBox;'''
|
||||||
|
|
||||||
|
PICK_ANCHOR = " private void showSettingsPanel() {"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 设置页:快捷栏 + 允许新设备连接(第二版)")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = MAIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "fillSettingsExtra" in t:
|
||||||
|
print(" 已经加过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
missing = [k for k, v in {
|
||||||
|
"关于锚点": ANCHOR,
|
||||||
|
"showSettingsPanel": PICK_ANCHOR,
|
||||||
|
"quickBar 字段": FIELD_ANCHOR,
|
||||||
|
}.items() if v not in t]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 锚点找不到:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点就位")
|
||||||
|
|
||||||
|
t = t.replace(ANCHOR, SECTION, 1)
|
||||||
|
t = t.replace(PICK_ANCHOR, METHODS + PICK_ANCHOR, 1)
|
||||||
|
t = t.replace(FIELD_ANCHOR, FIELD_ADD, 1)
|
||||||
|
|
||||||
|
MAIN.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 settingsExtraBox 字段 + 容器")
|
||||||
|
print(" ✓ 加了 fillSettingsExtra / pickQuickSlot / allowNewPairing")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -167,6 +167,10 @@ def main() -> int:
|
|||||||
changed += 1
|
changed += 1
|
||||||
|
|
||||||
# ---- 会断言成品名的测试 ----
|
# ---- 会断言成品名的测试 ----
|
||||||
|
# 注意 test_installer_cycle.py 也曾经写死过成品名(ykxmz-setup-1.8.2.exe),
|
||||||
|
# 结果它去装一个不存在的包 -> 静默失败 -> 报出一堆莫名其妙的
|
||||||
|
# "配对码实际是 xxx" "版本显示 v1.8.2"。那个文件现在改成自动找
|
||||||
|
# dist 下最新的安装包了,不再需要这里维护。
|
||||||
for name in ("test_package_remote.py", "test_apk_contents.py"):
|
for name in ("test_package_remote.py", "test_apk_contents.py"):
|
||||||
path = ROOT / "_tests" / name
|
path = ROOT / "_tests" / name
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''查 1Panel 和我装的 nginx 会不会打架。
|
||||||
|
|
||||||
|
== 为什么要查 ==
|
||||||
|
|
||||||
|
发现服务器上有 1Panel。1Panel 默认会**自己装一套 OpenResty(nginx)**
|
||||||
|
放在 /opt/1panel/apps/openresty/ 下,并且**接管 80/443**。
|
||||||
|
|
||||||
|
而我为了给遥控中转做反代,用 apt 装了**系统 nginx**,也在听 80/443。
|
||||||
|
|
||||||
|
两个 nginx 抢同一组端口,只有一个能起来 —— 另一个会
|
||||||
|
`Address already in use`。所以现在实际生效的到底是谁的配置,
|
||||||
|
必须搞清楚,否则:
|
||||||
|
|
||||||
|
* 我给 yk.xxmxxs.top 配的证书和反代可能**根本没生效**
|
||||||
|
(之前测通了,说明生效的是我的那份)
|
||||||
|
* 但用户在 1Panel 里建站,可能**建了个寂寞**(1Panel 的 OpenResty 起不来)
|
||||||
|
|
||||||
|
== 查什么 ==
|
||||||
|
|
||||||
|
1. 系统里到底有几个 nginx/OpenResty 可执行文件
|
||||||
|
2. 现在听 80/443 的是哪个进程(看 exe 路径)
|
||||||
|
3. 1Panel 的应用目录里有没有 openresty、有没有建过站
|
||||||
|
4. 1Panel 面板自己在哪个端口
|
||||||
|
5. 有没有已经存在的 WordPress 容器
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
|
from lssh import run # noqa: E402
|
||||||
|
|
||||||
|
REMOTE = r'''
|
||||||
|
echo "==== 1. 有几个 nginx / openresty ===="
|
||||||
|
for p in /usr/sbin/nginx /usr/local/openresty/nginx/sbin/nginx \
|
||||||
|
/opt/1panel/apps/openresty/openresty/bin/openresty; do
|
||||||
|
[ -x "$p" ] && echo " 有: $p"
|
||||||
|
done
|
||||||
|
command -v nginx openresty 2>/dev/null | sed 's/^/ PATH 里: /'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 2. 现在听 80/443 的是谁(看可执行文件路径)===="
|
||||||
|
sudo ss -tlnp 2>/dev/null | grep -E ':(80|443) ' | sed 's/^/ /'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 3. 1Panel 的 nginx 有没有在跑 ===="
|
||||||
|
for s in openresty nginx 1panel; do
|
||||||
|
st=$(systemctl is-active $s 2>/dev/null)
|
||||||
|
[ -n "$st" ] && echo " $s: $st"
|
||||||
|
done
|
||||||
|
echo " --- 1Panel 应用目录 ---"
|
||||||
|
sudo ls -1 /opt/1panel/apps/ 2>/dev/null | sed 's/^/ /' || echo " (没有 /opt/1panel/apps)"
|
||||||
|
echo " --- 1Panel 的 www 站点目录 ---"
|
||||||
|
sudo ls -1 /opt/1panel/www/sites/ 2>/dev/null | sed 's/^/ /' || echo " (还没建过站)"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 4. 1Panel 面板自己在哪 ===="
|
||||||
|
sudo ss -tlnp 2>/dev/null | grep -i 1panel | sed 's/^/ /'
|
||||||
|
sudo grep -h "Port\|port" /opt/1panel/conf/app.yaml 2>/dev/null | head -3 | sed 's/^/ /'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 5. 现有的容器 ===="
|
||||||
|
sudo docker ps --format ' {{.Names}} {{.Image}} {{.Status}} {{.Ports}}' 2>/dev/null || echo " (docker 命令不可用)"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 6. 系统 nginx 的配置来自哪 ===="
|
||||||
|
systemctl show nginx -p FragmentPath 2>/dev/null | sed 's/^/ /'
|
||||||
|
nginx -v 2>&1 | sed 's/^/ /'
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "==== 7. 1Panel 有没有装 php/mysql 应用 ===="
|
||||||
|
sudo ls -1 /opt/1panel/apps/ 2>/dev/null | while read a; do
|
||||||
|
echo " 应用 $a:"
|
||||||
|
sudo ls -1 /opt/1panel/apps/$a 2>/dev/null | sed 's/^/ /'
|
||||||
|
done
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 1Panel 和系统 nginx 会不会打架")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
out = run(REMOTE, timeout=240, quiet=True)
|
||||||
|
print(out[1] if isinstance(out, tuple) else out)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -17,7 +17,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run # noqa: E402
|
from lssh import run, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
PORT = "13245"
|
PORT = "13245"
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
@@ -28,8 +28,8 @@ RELAY_DIR = "/opt/ykxmz-relay"
|
|||||||
# IP:80 —— 绕过 Cloudflare,直连 nginx(域名没配好时靠它)
|
# IP:80 —— 绕过 Cloudflare,直连 nginx(域名没配好时靠它)
|
||||||
# :13245 —— **应该不通**(中转已只绑 127.0.0.1,不再对公网)
|
# :13245 —— **应该不通**(中转已只绑 127.0.0.1,不再对公网)
|
||||||
DOMAIN_URL = "http://%s" % DOMAIN
|
DOMAIN_URL = "http://%s" % DOMAIN
|
||||||
NGINX_URL = "http://<源站IP>:80"
|
NGINX_URL = "http://%s:80" % LS_HOST
|
||||||
DIRECT_URL = "http://<源站IP>:%s" % PORT
|
DIRECT_URL = "http://%s:%s" % (LS_HOST, PORT)
|
||||||
|
|
||||||
REMOTE = r'''
|
REMOTE = r'''
|
||||||
R=__DIR__
|
R=__DIR__
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把上次查询里两个可疑点查清楚。
|
||||||
|
|
||||||
|
== 疑点一:证书目录为什么是空的 ==
|
||||||
|
|
||||||
|
我明明给 yk.xxmxxs.top 签过 Let's Encrypt 证书。
|
||||||
|
但 `/etc/letsencrypt/live/` 列出来是空的 ——
|
||||||
|
多半是**权限**:那个目录是 0700 root,普通用户 ls 不到。
|
||||||
|
|
||||||
|
== 疑点二:3306 在监听,但没找到 mariadb/mysql ==
|
||||||
|
|
||||||
|
`ss` 显示 127.0.0.1:3306 有人在听,但 `command -v mariadb` 没找到。
|
||||||
|
可能是:
|
||||||
|
* 装了但可执行文件叫别的名字
|
||||||
|
* 是别的东西占了 3306(比如某个容器)
|
||||||
|
得看是哪个进程在听。
|
||||||
|
|
||||||
|
== 疑点三:内存用量涨了 ==
|
||||||
|
|
||||||
|
之前看是 414MB,现在 1037MB。得知道是谁吃的 ——
|
||||||
|
WordPress + MySQL 还要再吃 300~500MB,这台只有 2GB,得先弄清余量。
|
||||||
|
|
||||||
|
== 顺带 ==
|
||||||
|
|
||||||
|
`grep -r /etc/nginx/sites-enabled/` 没输出 server_name,
|
||||||
|
是因为那里全是**指向 sites-available 的符号链接**,
|
||||||
|
而 `grep -r` **默认不跟符号链接**。不是配置丢了。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
|
from lssh import run # noqa: E402
|
||||||
|
|
||||||
|
REMOTE = r'''
|
||||||
|
echo "==== 1. 证书(带 sudo)===="
|
||||||
|
sudo ls -1 /etc/letsencrypt/live/ 2>&1 | sed 's/^/ /'
|
||||||
|
echo " --- yk.xxmxxs.top 的证书 ---"
|
||||||
|
sudo openssl x509 -in /etc/letsencrypt/live/yk.xxmxxs.top/fullchain.pem \
|
||||||
|
-noout -subject -dates 2>&1 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== 2. nginx 站点(跟符号链接)===="
|
||||||
|
sudo grep -h server_name /etc/nginx/sites-available/ykxmz 2>/dev/null | sed 's/^/ /'
|
||||||
|
echo " sites-enabled:"
|
||||||
|
sudo ls -la /etc/nginx/sites-enabled/ 2>&1 | tail -n +2 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== 3. 谁在听 3306 ===="
|
||||||
|
sudo ss -tlnp 2>/dev/null | grep 3306 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== 4. 数据库到底装没装 ===="
|
||||||
|
dpkg -l 2>/dev/null | grep -iE 'mariadb|mysql' | head -8 | sed 's/^/ /'
|
||||||
|
echo " (上面没输出就是没装 —— 那 3306 是别的东西占的)"
|
||||||
|
echo
|
||||||
|
echo "==== 5. 内存被谁吃了 ===="
|
||||||
|
ps -eo rss,comm --sort=-rss 2>/dev/null | head -10 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo " --- systemd 服务占用 ---"
|
||||||
|
systemd-cgtop -n 1 -b 2>/dev/null | head -8 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== 6. 有没有 swap ===="
|
||||||
|
free -m | sed 's/^/ /'
|
||||||
|
swapon --show 2>/dev/null | sed 's/^/ /' || echo " 没有 swap"
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 查清三个疑点")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
out = run(REMOTE, timeout=240, quiet=True)
|
||||||
|
print(out[1] if isinstance(out, tuple) else out)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -19,10 +19,10 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run # noqa: E402
|
from lssh import run, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
IP = "<源站IP>"
|
IP = LS_HOST
|
||||||
|
|
||||||
|
|
||||||
def tcp(host: str, port: int, timeout: float = 8.0) -> bool:
|
def tcp(host: str, port: int, timeout: float = 8.0) -> bool:
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''校验打出来的 EXE 能不能在 **Windows 7** 上跑。
|
||||||
|
|
||||||
|
== 为什么需要这个 ==
|
||||||
|
|
||||||
|
学校电脑是 Windows 7,装完报「dll 缺失」。
|
||||||
|
|
||||||
|
根因不是漏打包,是 **Python 版本越界**:
|
||||||
|
|
||||||
|
Python 3.8 -> 最后一个支持 Windows 7 的版本
|
||||||
|
Python 3.9+ -> 只支持 Windows 8 及以上
|
||||||
|
|
||||||
|
Python 3.9 起用到了 `api-ms-win-core-path-l1-1-0.dll` 里的
|
||||||
|
`PathCchCanonicalizeEx`,而这个 DLL **Windows 7 上根本不存在**,
|
||||||
|
也没法用 api-set 转发(那套机制只在 Win8+ 生效)。
|
||||||
|
|
||||||
|
**所以那个 DLL 不是"忘了放进包",是"放进去也没用"。**
|
||||||
|
唯一可行的办法是**用 3.8 打包**。
|
||||||
|
|
||||||
|
== 这个脚本查什么 ==
|
||||||
|
|
||||||
|
1. 有没有 python38.dll(而不是 python39/310/311/... )
|
||||||
|
2. **不该有** api-ms-win-core-path-l1-1-0.dll
|
||||||
|
—— 有它就说明是 3.9+ 打的,Win7 上必挂
|
||||||
|
3. PE 头是不是 32 位(0x14C)
|
||||||
|
—— 32 位在 Win7 的 32/64 位系统上都能跑;
|
||||||
|
64 位在 32 位 Windows 上直接起不来
|
||||||
|
4. 顺带报一下总大小和文件数
|
||||||
|
|
||||||
|
用 `python _build/check_win7_compat.py` 单独跑也行,
|
||||||
|
`build_exe.ps1` 里会调它,不过就直接拒绝出包。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
DIST = ROOT / "dist_exe" / "ykxmz"
|
||||||
|
|
||||||
|
FAILS: list = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name: str, ok: bool, why: str = "") -> None:
|
||||||
|
print(" [%s] %s%s" % ("PASS" if ok else "FAIL", name,
|
||||||
|
(" —— " + why) if why else ""))
|
||||||
|
if not ok:
|
||||||
|
FAILS.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def pe_machine(path: Path) -> int:
|
||||||
|
"""读 PE 头里的 machine 字段。0x14C=32 位,0x8664=64 位。"""
|
||||||
|
with path.open("rb") as f:
|
||||||
|
if f.read(2) != b"MZ":
|
||||||
|
return 0
|
||||||
|
f.seek(0x3C)
|
||||||
|
off = struct.unpack("<I", f.read(4))[0]
|
||||||
|
f.seek(off)
|
||||||
|
if f.read(4) != b"PE\0\0":
|
||||||
|
return 0
|
||||||
|
return struct.unpack("<H", f.read(2))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" Windows 7 兼容性校验")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
check("dist_exe/ykxmz 存在", DIST.is_dir(),
|
||||||
|
"先跑 windows\\build_exe.ps1")
|
||||||
|
if not DIST.is_dir():
|
||||||
|
return 1
|
||||||
|
|
||||||
|
dlls = {p.name.lower(): p for p in DIST.rglob("*.dll")}
|
||||||
|
exe = DIST / "ykxmz.exe"
|
||||||
|
check("ykxmz.exe 存在", exe.is_file())
|
||||||
|
if not exe.is_file():
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# ---- 1. Python 运行库版本 ----
|
||||||
|
print()
|
||||||
|
print("一、Python 运行库")
|
||||||
|
py_dlls = sorted(n for n in dlls if n.startswith("python3") and n.endswith(".dll"))
|
||||||
|
for n in py_dlls:
|
||||||
|
print(" %s" % n)
|
||||||
|
check("有 python38.dll(3.8 打的)",
|
||||||
|
any("python38" in n for n in py_dlls),
|
||||||
|
"没有 python38.dll 说明不是 3.8 打的")
|
||||||
|
bad_py = [n for n in py_dlls
|
||||||
|
if any(v in n for v in ("python39", "python310", "python311",
|
||||||
|
"python312", "python313", "python314"))]
|
||||||
|
check("没有 3.9+ 的运行库", not bad_py,
|
||||||
|
"3.9+ 的包在 Win7 上会因为缺 DLL 启动失败:%s" % bad_py)
|
||||||
|
|
||||||
|
# ---- 2. 那个要命的 DLL ----
|
||||||
|
print()
|
||||||
|
print("二、Win7 上不存在的那个 DLL")
|
||||||
|
killer = "api-ms-win-core-path-l1-1-0.dll"
|
||||||
|
has = killer in dlls
|
||||||
|
check("**没有** %s" % killer, not has,
|
||||||
|
"有它就说明是 3.9+ 打的 —— Win7 上必然报缺 DLL")
|
||||||
|
print(" (这个 DLL 是 Win8+ 才有的。Python 3.9 起用到它,")
|
||||||
|
print(" 放进来也没用,Win7 上加载不了。)")
|
||||||
|
|
||||||
|
# ---- 3. 位数 ----
|
||||||
|
print()
|
||||||
|
print("三、位数")
|
||||||
|
m = pe_machine(exe)
|
||||||
|
arch = {0x14C: "32 位 (x86)", 0x8664: "64 位 (x64)"}.get(m, "未知 (0x%X)" % m)
|
||||||
|
print(" ykxmz.exe: %s" % arch)
|
||||||
|
check("是 32 位(Win7 32/64 位都能跑)", m == 0x14C,
|
||||||
|
"64 位的包在 32 位 Windows 上起不来;学校机器可能是 32 位")
|
||||||
|
|
||||||
|
# ---- 4. 体积概览 ----
|
||||||
|
print()
|
||||||
|
print("四、产物概览")
|
||||||
|
files = list(DIST.rglob("*"))
|
||||||
|
files = [f for f in files if f.is_file()]
|
||||||
|
total = sum(f.stat().st_size for f in files)
|
||||||
|
print(" 文件数: %d" % len(files))
|
||||||
|
print(" 总大小: %.1f MB" % (total / 1048576))
|
||||||
|
print(" exe 大小: %.1f MB" % (exe.stat().st_size / 1048576))
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("=" * 58)
|
||||||
|
if FAILS:
|
||||||
|
print(" 失败 %d 项:%s" % (len(FAILS), ", ".join(FAILS)))
|
||||||
|
print(" 这个包学校电脑装不上,不该发布。")
|
||||||
|
return 1
|
||||||
|
print(" ✅ 可以在 Windows 7 / 8 / 10 / 11 上运行")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''看服务器上装 WordPress 缺什么。
|
||||||
|
|
||||||
|
== 背景 ==
|
||||||
|
|
||||||
|
用户想把 xxmxxs.top 拿来做 WordPress(原来是 Cloudflare Workers 占着)。
|
||||||
|
WordPress 要 PHP + 数据库,而服务器上现在只跑着 nginx(给遥控中转用)。
|
||||||
|
|
||||||
|
== 为什么写成文件 ==
|
||||||
|
|
||||||
|
这个查询里有一堆 `$(...)`、`$b`、`2>/dev/null`。
|
||||||
|
用 `python -c "..."` 传的话,**PowerShell 会先在本机把它们求值**
|
||||||
|
(报"无法将 systemctl 项识别为 cmdlet"、"未能找到路径 C:\dev\null")。
|
||||||
|
这个坑今天踩了太多次 —— 凡是超过两行的远端命令,一律写成文件。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
|
from lssh import run # noqa: E402
|
||||||
|
|
||||||
|
REMOTE = r'''
|
||||||
|
echo "==== 磁盘 ===="
|
||||||
|
df -h / | tail -1
|
||||||
|
echo
|
||||||
|
echo "==== 内存 ===="
|
||||||
|
free -m | head -2
|
||||||
|
echo
|
||||||
|
echo "==== nginx 站点 ===="
|
||||||
|
ls -1 /etc/nginx/sites-enabled/ 2>/dev/null
|
||||||
|
echo " server_name:"
|
||||||
|
grep -rh server_name /etc/nginx/sites-enabled/ 2>/dev/null | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== PHP ===="
|
||||||
|
if command -v php >/dev/null 2>&1; then
|
||||||
|
php -v | head -1
|
||||||
|
echo " php-fpm: $(systemctl is-active php8.3-fpm 2>/dev/null || systemctl is-active php8.2-fpm 2>/dev/null || echo 没装)"
|
||||||
|
else
|
||||||
|
echo " 没装 PHP"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
echo "==== 数据库 ===="
|
||||||
|
if command -v mariadb >/dev/null 2>&1; then
|
||||||
|
echo " mariadb 客户端在: $(command -v mariadb)"
|
||||||
|
echo " mariadb 服务: $(systemctl is-active mariadb 2>/dev/null)"
|
||||||
|
elif command -v mysql >/dev/null 2>&1; then
|
||||||
|
echo " mysql 客户端在"
|
||||||
|
echo " mysql 服务: $(systemctl is-active mysql 2>/dev/null)"
|
||||||
|
else
|
||||||
|
echo " 没装数据库"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
echo "==== apt 源里有 php-fpm 吗 ===="
|
||||||
|
apt-cache policy php-fpm 2>/dev/null | head -3 | sed 's/^/ /'
|
||||||
|
echo
|
||||||
|
echo "==== 服务状态 ===="
|
||||||
|
for s in nginx ykxmz-relay ykxmz-monitor.timer certbot.timer; do
|
||||||
|
printf ' %-24s %s\n' "$s" "$(systemctl is-active $s 2>&1)"
|
||||||
|
done
|
||||||
|
echo
|
||||||
|
echo "==== 证书目录 ===="
|
||||||
|
ls -1 /etc/letsencrypt/live/ 2>/dev/null | sed 's/^/ /' || echo " (空)"
|
||||||
|
echo
|
||||||
|
echo "==== 监听端口 ===="
|
||||||
|
ss -tln 2>/dev/null | grep -E ':(80|443|3306) ' | sed 's/^/ /'
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 服务器 WordPress 就绪度")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
out = run(REMOTE, timeout=240, quiet=True)
|
||||||
|
print(out[1] if isinstance(out, tuple) else out)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
2.1.7:手表快捷栏 + 鼠标触摸板 + 弹窗可配 + 后台远程更新
|
||||||
|
|
||||||
|
用户这次提了一整套升级,这是最后一批。
|
||||||
|
|
||||||
|
== 一、手表端顶部快捷栏 ==
|
||||||
|
|
||||||
|
用户原话:"手表端不管干什么,上面都有一栏,栏里的按钮可以在设置页
|
||||||
|
自定义,最多可以加 4 个,其中有一个按钮不能改,功能就是一键返回桌面"。
|
||||||
|
|
||||||
|
("返回桌面"经确认 = **让被控电脑显示桌面**,即 Win+D。)
|
||||||
|
|
||||||
|
* 一条常驻的栏,贴在屏幕顶部,切页面时不动
|
||||||
|
* **4 个格子**:3 个可自定义 + **1 个固定的「显示桌面」(改不了)**
|
||||||
|
* 7 个可选动作:传文件 / 屏幕镜像 / 鼠标控制 / 音效 / 关机 /
|
||||||
|
语音播报 / 投图到电脑
|
||||||
|
* 设置页里点一下换;也能把某一格留空
|
||||||
|
* 没连上电脑时按钮置灰(不是藏起来 —— "一直在但暂时不能用"
|
||||||
|
比"时有时无"更好理解)
|
||||||
|
|
||||||
|
实现上的几个要点:
|
||||||
|
|
||||||
|
* 快捷栏 addView 在 5 个面板**之后** —— FrameLayout 里后加的在上层,
|
||||||
|
加在前面会被面板(MATCH_PARENT)整个盖住
|
||||||
|
* 面板加了 topMargin 给栏让位,集中在 applyPanelTopMargin 里改
|
||||||
|
(每个面板各写一遍很容易漏一个,表现是"就某一页顶部被切掉")
|
||||||
|
* 第 4 格在代码里**写死** desktop,而且 QUICK_ACTIONS 里**没有**它 ——
|
||||||
|
这样它既不会出现在可选列表里,也不可能被改成别的
|
||||||
|
* 存储用 SharedPreferences。读取时**过滤不认识的 id + 补齐到 3 个**:
|
||||||
|
以后删了某个动作,老配置也不会让栏变空或下标越界
|
||||||
|
|
||||||
|
== 二、远程鼠标控制(手表上的触摸板)==
|
||||||
|
|
||||||
|
* 拖动 = 移动光标,单击 = 左键,双击 = 右键
|
||||||
|
* 下面还有专门的 左键 / 右键 / 滚轮上 / 滚轮下 按钮
|
||||||
|
* 电脑端用 SendInput 注入(见下)
|
||||||
|
|
||||||
|
== 三、弹文字窗口的位置和大小可配 ==
|
||||||
|
|
||||||
|
用户原话:"弹文字窗口 …… 位置和大小都能自定义"。
|
||||||
|
|
||||||
|
* 位置:右下(默认,保持老习惯)/ 右上 / 左上 / 左下 /
|
||||||
|
屏幕正中间 / 自定义坐标
|
||||||
|
* 字号:8~32(夹住,免得设成 200 一个通知占满屏幕)
|
||||||
|
* 宽度:可指定,0 = 按内容自适应
|
||||||
|
* 三处窗口定位统一到一个 _notice_geometry() —— 以前三处各写死一遍
|
||||||
|
右下角,改一次要改三个地方,漏一个用户就看得见
|
||||||
|
|
||||||
|
== 四、屏幕被观看时的提示条改成默认不显示 ==
|
||||||
|
|
||||||
|
用户原话:"以后不需要弹,啥窗户都没有,就可以像 UU 远程一样"。
|
||||||
|
|
||||||
|
* 默认**连窗口都不建**
|
||||||
|
* **但保留成开关**,设置里可以打开
|
||||||
|
|
||||||
|
关于这条:那条提示原来是**故意加**的(有人在看屏幕时,电脑前面的人
|
||||||
|
应该知道)。用户要求去掉,这是他自己的电脑、自己的教室,
|
||||||
|
属于正当的远程管理需求。所以能力保留、默认关闭 ——
|
||||||
|
这软件应该始终有一个"让本机用户看得见正在被控制"的选项可查。
|
||||||
|
|
||||||
|
== 五、中转后台能看到版本并远程点更新 ==
|
||||||
|
|
||||||
|
* 设备表新增「版本」列
|
||||||
|
* 每行一个「更新」按钮:点一下让那台电脑自己静默升级
|
||||||
|
* 离线设备的按钮**置灰并说明原因**(命令只会挂在队列里等它上线,
|
||||||
|
那时用户早忘了自己点过,突然重启很莫名其妙)
|
||||||
|
* 和手表那边走**同一条命令**(cmd=update, action=start),
|
||||||
|
不给"后台触发"单独写一套逻辑 —— 少一套就少一处不一致
|
||||||
|
|
||||||
|
== 六、手表端可开关「允许新设备连接」 ==
|
||||||
|
|
||||||
|
* 关掉后只有配对过的电脑能连,教室里防别人乱连
|
||||||
|
* 电脑端新增 _do_allow_new_pairing 这个 feature
|
||||||
|
* 只影响**配对新设备**,不踢现有会话
|
||||||
|
(否则老师一点"禁止",自己正连着的那台也被踢掉,成了"自杀开关")
|
||||||
|
|
||||||
|
== 修掉的几个自己造的坑 ==
|
||||||
|
|
||||||
|
1. **管理页 JS 裸换行** —— 最严重的一个。
|
||||||
|
ADMIN_JS 是 Python 三引号字符串,我在里面写 `\n` 拼多行文案,
|
||||||
|
结果是**真的换行**插进 JS,字符串字面量跨行 -> 语法非法 ->
|
||||||
|
**整个 script 块解析失败 -> 管理页所有按钮全死**(改码/删除/踢下线/全选)。
|
||||||
|
改成 String.fromCharCode(10),不依赖任何转义层。
|
||||||
|
|
||||||
|
2. **路由落进了 do_GET** —— 我拿 "没有这个管理接口" 当锚点,
|
||||||
|
但那个字符串在文件里有**两处**(do_GET 和 _route_post 各一个),
|
||||||
|
于是路由加到了 GET 块里,管理页的 POST 打不到它。
|
||||||
|
表现是"点了更新没反应"。
|
||||||
|
|
||||||
|
3. **isConnected() 根本不存在** —— 写快捷栏时凭直觉调了个方法名,
|
||||||
|
编译才发现。顺手包了一层并加上说明。
|
||||||
|
|
||||||
|
4. **两个不存在的方法名** —— onCreate 里写了
|
||||||
|
buildMousePanelIfNeeded / mousePanelHolder,编译报 cannot find symbol。
|
||||||
|
|
||||||
|
5. **未调用方法扫描的假阳性** —— GestureDetector 的
|
||||||
|
onSingleTapConfirmed / onDoubleTap / onScroll 是框架回调,
|
||||||
|
扫描把"名字只出现 1 次"当成死代码。改成**跳过 @Override 的方法**。
|
||||||
|
这种假阳性最坏的结果是有人为了让它变绿把回调删了,手势就失灵了。
|
||||||
|
|
||||||
|
6. **测试断言太严导致误报** —— "不能有写死的 240",
|
||||||
|
但 helper 里 `auto = max(240, ...)` 是自适应的兜底,故意的。
|
||||||
|
|
||||||
|
7. **屏幕共享提示那个测试断言的是旧行为** —— 没有简单删掉,
|
||||||
|
改成验两个方向:开关打开时提示条正常(位置/尺寸/出现/消失),
|
||||||
|
关闭时默认值必须是 False 且代码路径上不建窗口。
|
||||||
|
|
||||||
|
== 验证 ==
|
||||||
|
|
||||||
|
全量回归(19 关)全部 PASS,零失败
|
||||||
|
新增关卡:3a10 静默更新 / 3a11 鼠标控制 / 3a12 后台更新+弹窗 /
|
||||||
|
3a13 手表快捷栏
|
||||||
|
Java 编译通过(android-34, --release 8)
|
||||||
|
APK / 安装包 / 服务端包 全部重建,Win7 兼容校验通过
|
||||||
|
623 个 Python 文件语法通过
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''清掉 actions.py 里重复的 list_voices 和残留的旧 say 前半段。
|
||||||
|
|
||||||
|
== 怎么弄出来的 ==
|
||||||
|
|
||||||
|
fix_tts_fallback.py 里我写了两处替换,但 `NEW` 那个大块**自己也带了一份
|
||||||
|
list_voices**:
|
||||||
|
|
||||||
|
t.replace(OLD_VOICES, NEW_VOICES) # 这是第一份 list_voices
|
||||||
|
t.replace(OLD_SAY, NEW) # NEW 里又有一份 list_voices
|
||||||
|
|
||||||
|
于是 pyflakes 报:
|
||||||
|
|
||||||
|
redefinition of unused 'list_voices' from line 540
|
||||||
|
redefinition of unused 'say' from line 575
|
||||||
|
local variable 'chosen' is assigned to but never used
|
||||||
|
|
||||||
|
第三条是**旧 say 的前半段残留** —— `chosen` / `speed` 算完就不用了,
|
||||||
|
真正干活的在后面那份里。
|
||||||
|
|
||||||
|
== 这一版怎么改 ==
|
||||||
|
|
||||||
|
把**后面**那份 list_voices(`NEW` 带进来的)删掉,保留前面 NEW_VOICES 那份;
|
||||||
|
再把旧的 say 前半段(算 chosen/speed 那几行)删掉 —— 那些在新 say 里
|
||||||
|
已经算过一遍了。
|
||||||
|
|
||||||
|
**先全部定位好再动手**,避免又改一半。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ACTIONS = ROOT / "windows" / "lanremote" / "actions.py"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 清掉重复定义")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = ACTIONS.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
lines = t.split("\n")
|
||||||
|
|
||||||
|
# ---- 1. 找所有 list_voices / say 定义 ----
|
||||||
|
defs = {}
|
||||||
|
for i, ln in enumerate(lines):
|
||||||
|
m = re.match(r" def (list_voices|say|_tts_commands|_write_vbs|"
|
||||||
|
r"_powershell_path)\(self", ln)
|
||||||
|
if m:
|
||||||
|
defs.setdefault(m.group(1), []).append(i)
|
||||||
|
|
||||||
|
print(" 定义位置:")
|
||||||
|
for name, spots in sorted(defs.items()):
|
||||||
|
print(" %-18s %s" % (name, [s + 1 for s in spots]))
|
||||||
|
|
||||||
|
# ---- 2. 删掉重复的 list_voices(保留第一个)----
|
||||||
|
dup_lv = defs.get("list_voices", [])
|
||||||
|
if len(dup_lv) != 2:
|
||||||
|
print(" ⚠ list_voices 有 %d 个定义,期望 2 个" % len(dup_lv))
|
||||||
|
else:
|
||||||
|
start = dup_lv[1]
|
||||||
|
# 找到下一个同级 def
|
||||||
|
end = len(lines)
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if re.match(r" def \w+\(", lines[j]):
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
# 往上把紧邻的注释也吃掉(那是我写的那段说明)
|
||||||
|
s = start
|
||||||
|
while s > 0 and (lines[s - 1].strip().startswith("#")
|
||||||
|
or lines[s - 1].strip() == ""):
|
||||||
|
s -= 1
|
||||||
|
if lines[s].strip() == "" and s + 1 < start:
|
||||||
|
s += 1
|
||||||
|
break
|
||||||
|
print(" 删除重复的 list_voices:第 %d-%d 行" % (start + 1, end))
|
||||||
|
del lines[start:end]
|
||||||
|
|
||||||
|
# ---- 3. 删掉旧 say 的前半段(算 chosen/speed 那段)----
|
||||||
|
t2 = "\n".join(lines)
|
||||||
|
old_head = ''' chosen = (voice or "").strip() or str(self.store.get("tts_voice") or "").strip()
|
||||||
|
try:
|
||||||
|
speed = int(rate) if rate else int(self.store.get("tts_rate", 0) or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
speed = 0
|
||||||
|
speed = max(-10, min(10, speed))
|
||||||
|
|
||||||
|
'''
|
||||||
|
n = t2.count(old_head)
|
||||||
|
print(" 旧 say 前半段残留:%d 处" % n)
|
||||||
|
if n:
|
||||||
|
# 只删最后一处之前的那一坨(如果出现两次,说明新 say 里也有一份,
|
||||||
|
# 那份是**要保留的**)—— 所以删第一处。
|
||||||
|
t2 = t2.replace(old_head, "", 1)
|
||||||
|
|
||||||
|
ACTIONS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t2.encode("utf-8"))
|
||||||
|
print(" ✓ 清完了")
|
||||||
|
|
||||||
|
# ---- 4. 复核 ----
|
||||||
|
back = ACTIONS.read_text(encoding="utf-8-sig")
|
||||||
|
lv = len(re.findall(r"\n def list_voices\(self", back))
|
||||||
|
sy = len(re.findall(r"\n def say\(self", back))
|
||||||
|
tc = len(re.findall(r"\n def _tts_commands\(self", back))
|
||||||
|
print()
|
||||||
|
print(" 复核:list_voices=%d(应 1) say=%d(应 1) _tts_commands=%d(应 1)"
|
||||||
|
% (lv, sy, tc))
|
||||||
|
return 0 if (lv == 1 and sy == 1 and tc == 1) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -40,7 +40,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run, upload # noqa: E402
|
from lssh import run, upload, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
# 用户指定的端口
|
# 用户指定的端口
|
||||||
PORT = "13245"
|
PORT = "13245"
|
||||||
@@ -88,7 +88,7 @@ WantedBy=multi-user.target
|
|||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
print("=" * 62)
|
print("=" * 62)
|
||||||
print(" 部署到 Lightsail(<源站IP>),端口 %s" % PORT)
|
print(" 部署到 Lightsail(LS_HOST),端口 %s" % PORT)
|
||||||
print("=" * 62)
|
print("=" * 62)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
@@ -167,7 +167,7 @@ def main() -> int:
|
|||||||
|
|
||||||
print()
|
print()
|
||||||
print(" 提示:防火墙要先放行 TCP %s(用户来开)。" % PORT)
|
print(" 提示:防火墙要先放行 TCP %s(用户来开)。" % PORT)
|
||||||
print(" 之后公网地址就是 http://<源站IP>:%s/" % PORT)
|
print(" 之后公网地址就是 http://LS_HOST:%s/" % PORT)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -31,11 +31,11 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run, upload # noqa: E402
|
from lssh import run, upload, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
RELAY_DIR = "/opt/ykxmz-relay"
|
RELAY_DIR = "/opt/ykxmz-relay"
|
||||||
PORT = "13245"
|
PORT = "13245"
|
||||||
PUBLIC_URL = "http://<源站IP>:%s" % PORT
|
PUBLIC_URL = "http://%s:%s" % (LS_HOST, PORT)
|
||||||
|
|
||||||
MONITOR = r'''#!/bin/bash
|
MONITOR = r'''#!/bin/bash
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
@@ -46,7 +46,7 @@ MONITOR = r'''#!/bin/bash
|
|||||||
#
|
#
|
||||||
# 为什么不查 127.0.0.1:
|
# 为什么不查 127.0.0.1:
|
||||||
# 本机 200 只说明进程活着。用户真正关心的是"打开
|
# 本机 200 只说明进程活着。用户真正关心的是"打开
|
||||||
# http://<源站IP>:13245 能不能出页面" —— 那要经过
|
# http://LS_HOST:13245 能不能出页面" —— 那要经过
|
||||||
# Lightsail 的防火墙 / 安全组 / 上游线路。实测踩过:
|
# Lightsail 的防火墙 / 安全组 / 上游线路。实测踩过:
|
||||||
# 隧道两条实例都掉了,本机 curl 照样 200,但公网 502。
|
# 隧道两条实例都掉了,本机 curl 照样 200,但公网 502。
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -20,11 +20,11 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run, upload # noqa: E402
|
from lssh import run, upload, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
RELAY_DIR = "/opt/ykxmz-relay"
|
RELAY_DIR = "/opt/ykxmz-relay"
|
||||||
PORT = "13245"
|
PORT = "13245"
|
||||||
PUBLIC = "http://<源站IP>:%s" % PORT
|
PUBLIC = "http://%s:%s" % (LS_HOST, PORT)
|
||||||
|
|
||||||
CODE = ["relay.py", "admin.py", "landing.py", "showcase.py"]
|
CODE = ["relay.py", "admin.py", "landing.py", "showcase.py"]
|
||||||
ARTIFACTS = ["ykxmz-setup-{v}.exe", "ykxmz-watch-{v}.apk",
|
ARTIFACTS = ["ykxmz-setup-{v}.exe", "ykxmz-watch-{v}.apk",
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run # noqa: E402
|
from lssh import run, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ done
|
|||||||
echo
|
echo
|
||||||
echo "════ 6. 对比:直连自己的 nginx ════"
|
echo "════ 6. 对比:直连自己的 nginx ════"
|
||||||
printf ' %-30s %s\n' "127.0.0.1:443(带 SNI)" "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 --resolve $D:443:127.0.0.1 https://$D/v1/health)"
|
printf ' %-30s %s\n' "127.0.0.1:443(带 SNI)" "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 --resolve $D:443:127.0.0.1 https://$D/v1/health)"
|
||||||
printf ' %-30s %s\n' "公网 IP:443" "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 --resolve $D:443:<源站IP> https://$D/v1/health)"
|
printf ' %-30s %s\n' "公网 IP:443" "$(curl -sk -o /dev/null -w '%{http_code}' --max-time 8 --resolve $D:443:LS_HOST https://$D/v1/health)"
|
||||||
'''
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''诊断:这台机器上哪几种语音播报方案能用。
|
||||||
|
|
||||||
|
== 为什么写这个 ==
|
||||||
|
|
||||||
|
用户反馈:**Win7 上语音播报不能用**。
|
||||||
|
|
||||||
|
现在的实现只有一条路:
|
||||||
|
powershell -NoProfile -WindowStyle Hidden -Command
|
||||||
|
"Add-Type -AssemblyName System.Speech; $s = New-Object ...; $s.Speak('...')"
|
||||||
|
|
||||||
|
这在 Win7 上有几个可能致命的点:
|
||||||
|
|
||||||
|
1. **`powershell` 可能不在 PATH 里**
|
||||||
|
Win7 的 powershell.exe 在 `%SystemRoot%\System32\WindowsPowerShell\v1.0\`。
|
||||||
|
正常装的机器 PATH 里有,但被精简过、或者从服务/计划任务里拉起时
|
||||||
|
可能没有 —— 而**我们是用 CreateProcess 按名字找的**,找不到就静默失败。
|
||||||
|
|
||||||
|
2. **Win7 默认是 PowerShell 2.0,它用 ANSI 代码页解析 `-Command`**
|
||||||
|
PS 3.0+ 才改成按 UTF-16 处理命令行。所以中文经 `-Command` 传进去
|
||||||
|
在 PS 2.0 上会乱码 —— 表现是"念出来是乱码"或"什么都不念"。
|
||||||
|
|
||||||
|
3. **`System.Speech` 需要 .NET Framework 3.0+**
|
||||||
|
而系统自带的 **SAPI5**(`SAPI.SpVoice`)从 Windows XP 就有,
|
||||||
|
根本不需要 .NET。绕开 .NET 更稳。
|
||||||
|
|
||||||
|
== 所以这里试 5 条路 ==
|
||||||
|
|
||||||
|
A. powershell(按 PATH 找)+ System.Speech <- 现在的实现
|
||||||
|
B. powershell(按**绝对路径**找)+ System.Speech <- 修"不在 PATH"
|
||||||
|
C. powershell(绝对路径)+ SAPI.SpVoice COM <- 绕开 .NET
|
||||||
|
D. **cscript + VBScript + SAPI.SpVoice** <- 完全不依赖 PowerShell
|
||||||
|
E. wscript + VBScript + SAPI.SpVoice <- 同上,另一个宿主
|
||||||
|
|
||||||
|
D/E 最值得期待:**VBScript 从 Windows 98 就有,SAPI5 是系统组件**,
|
||||||
|
两个都不需要装任何东西,也不受 PowerShell 版本影响。
|
||||||
|
|
||||||
|
== 怎么跑 ==
|
||||||
|
|
||||||
|
python _build\diag_tts.py
|
||||||
|
|
||||||
|
它会一条条试并打印结果。**在有问题的机器上跑最有价值** ——
|
||||||
|
比如那台 Win7。把输出发回来就知道该换哪条路。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
IS_WINDOWS = os.name == "nt"
|
||||||
|
|
||||||
|
# 让它念一句中文。中文最能暴露编码问题 ——
|
||||||
|
# 纯英文在 PS 2.0 上也可能碰巧是对的(ASCII 不受代码页影响)。
|
||||||
|
TEXT = "语音播报测试,一二三"
|
||||||
|
|
||||||
|
NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||||
|
|
||||||
|
FOUND: list = []
|
||||||
|
FAILED: list = []
|
||||||
|
|
||||||
|
|
||||||
|
def report(name: str, ok: bool, detail: str = "") -> None:
|
||||||
|
mark = "可用 " if ok else "不可用"
|
||||||
|
print(" [%s] %s%s" % (mark, name, (" —— " + detail) if detail else ""))
|
||||||
|
(FOUND if ok else FAILED).append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd: list, timeout: int = 30) -> tuple:
|
||||||
|
"""跑一条命令,返回 (退出码, 输出)。不让它弹窗。"""
|
||||||
|
try:
|
||||||
|
p = subprocess.run(cmd, capture_output=True, timeout=timeout,
|
||||||
|
creationflags=NO_WINDOW,
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
out = ((p.stdout or "") + (p.stderr or "")).strip()
|
||||||
|
return p.returncode, out
|
||||||
|
except FileNotFoundError:
|
||||||
|
return -1, "文件找不到"
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return -2, "超时"
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return -3, "%s: %s" % (type(exc).__name__, exc)
|
||||||
|
|
||||||
|
|
||||||
|
def find_powershell() -> str:
|
||||||
|
"""先按 PATH 找,再按绝对路径找。"""
|
||||||
|
p = shutil.which("powershell")
|
||||||
|
if p:
|
||||||
|
return p
|
||||||
|
cand = Path(os.environ.get("SystemRoot", r"C:\Windows")) / \
|
||||||
|
"System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
|
||||||
|
return str(cand) if cand.is_file() else ""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 62)
|
||||||
|
print(" 语音播报方案诊断")
|
||||||
|
print("=" * 62)
|
||||||
|
print()
|
||||||
|
if IS_WINDOWS:
|
||||||
|
try:
|
||||||
|
wv = sys.getwindowsversion()
|
||||||
|
print(" 系统: Windows %d.%d (build %d)"
|
||||||
|
% (wv.major, wv.minor, wv.build))
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
print(" 系统: Windows(版本号取不到)")
|
||||||
|
else:
|
||||||
|
print(" 系统: 非 Windows")
|
||||||
|
print(" Python: %s (%d 位)" % (sys.version.split()[0],
|
||||||
|
64 if sys.maxsize > 2 ** 32 else 32))
|
||||||
|
print(" 测试文本: %r" % TEXT)
|
||||||
|
print()
|
||||||
|
|
||||||
|
if not IS_WINDOWS:
|
||||||
|
print(" 非 Windows,没有 TTS 方案可试。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# ---------------- 0. 环境事实 ----------------
|
||||||
|
print("── 0. 环境 ──")
|
||||||
|
ps_path = find_powershell()
|
||||||
|
ps_in_path = shutil.which("powershell")
|
||||||
|
print(" powershell 在 PATH 里: %s" % (ps_in_path or "**没有**"))
|
||||||
|
print(" powershell 绝对路径: %s" % (ps_path or "**找不到**"))
|
||||||
|
if ps_path:
|
||||||
|
code, out = run([ps_path, "-NoProfile", "-Command",
|
||||||
|
"$PSVersionTable.PSVersion.Major"])
|
||||||
|
print(" PowerShell 主版本: %s" % (out.strip() or "查不到"))
|
||||||
|
print(" cscript: %s" % (shutil.which("cscript") or "**没有**"))
|
||||||
|
print(" wscript: %s" % (shutil.which("wscript") or "**没有**"))
|
||||||
|
print(" SystemRoot: %s" % os.environ.get("SystemRoot", "?"))
|
||||||
|
print()
|
||||||
|
|
||||||
|
# ---------------- A. 现有实现 ----------------
|
||||||
|
print("── A. powershell(按 PATH)+ System.Speech ← 现在产品用的 ──")
|
||||||
|
if not ps_in_path:
|
||||||
|
report("A", False, "powershell 不在 PATH 里 —— **这就是失败原因**")
|
||||||
|
else:
|
||||||
|
script = ("Add-Type -AssemblyName System.Speech;"
|
||||||
|
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;"
|
||||||
|
"$s.Speak('%s')" % TEXT.replace("'", "''"))
|
||||||
|
code, out = run(["powershell", "-NoProfile", "-WindowStyle", "Hidden",
|
||||||
|
"-Command", script])
|
||||||
|
report("A", code == 0, "退出码 %d %s" % (code, out[:70]))
|
||||||
|
time.sleep(0.4)
|
||||||
|
|
||||||
|
# ---------------- B. 绝对路径 + System.Speech ----------------
|
||||||
|
print("── B. powershell(绝对路径)+ System.Speech ──")
|
||||||
|
if not ps_path:
|
||||||
|
report("B", False, "找不到 powershell.exe")
|
||||||
|
else:
|
||||||
|
script = ("Add-Type -AssemblyName System.Speech;"
|
||||||
|
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;"
|
||||||
|
"$s.Speak('%s')" % TEXT.replace("'", "''"))
|
||||||
|
code, out = run([ps_path, "-NoProfile", "-WindowStyle", "Hidden",
|
||||||
|
"-Command", script])
|
||||||
|
report("B", code == 0, "退出码 %d %s" % (code, out[:70]))
|
||||||
|
time.sleep(0.4)
|
||||||
|
|
||||||
|
# ---------------- C. SAPI.SpVoice COM(绕开 .NET)----------------
|
||||||
|
print("── C. powershell(绝对路径)+ SAPI.SpVoice COM ──")
|
||||||
|
if not ps_path:
|
||||||
|
report("C", False, "找不到 powershell.exe")
|
||||||
|
else:
|
||||||
|
script = ("$v = New-Object -ComObject SAPI.SpVoice;"
|
||||||
|
"$v.Speak('%s')" % TEXT.replace("'", "''"))
|
||||||
|
code, out = run([ps_path, "-NoProfile", "-WindowStyle", "Hidden",
|
||||||
|
"-Command", script])
|
||||||
|
report("C", code == 0, "退出码 %d %s" % (code, out[:70]))
|
||||||
|
time.sleep(0.4)
|
||||||
|
|
||||||
|
# ---------------- D. cscript + VBScript + SAPI ----------------
|
||||||
|
#
|
||||||
|
# 最值得期待的一条:VBScript 从 Windows 98 就有,
|
||||||
|
# SAPI5 是系统组件,**两个都不需要装任何东西**,
|
||||||
|
# 也完全不受 PowerShell 版本 / PATH / .NET 的影响。
|
||||||
|
print("── D. cscript + VBScript + SAPI.SpVoice(不依赖 PowerShell)──")
|
||||||
|
vbs = (
|
||||||
|
'Dim v\r\n'
|
||||||
|
'Set v = CreateObject("SAPI.SpVoice")\r\n'
|
||||||
|
'v.Speak "%s"\r\n'
|
||||||
|
) % TEXT.replace('"', '""')
|
||||||
|
# ⚠ VBScript 文件要 ANSI(=系统代码页) —— 写成 UTF-8 的话
|
||||||
|
# 中文在 cscript 里会变乱码。这里用 mbcs 编码写。
|
||||||
|
tmp = Path(tempfile.gettempdir()) / "ykxmz_tts_test.vbs"
|
||||||
|
try:
|
||||||
|
tmp.write_bytes(vbs.encode("mbcs", errors="replace"))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
report("D", False, "写 vbs 失败: %s" % exc)
|
||||||
|
else:
|
||||||
|
code, out = run(["cscript", "//nologo", str(tmp)])
|
||||||
|
report("D", code == 0, "退出码 %d %s" % (code, out[:70]))
|
||||||
|
time.sleep(0.4)
|
||||||
|
|
||||||
|
# ---------------- E. wscript(不弹黑框)----------------
|
||||||
|
print("── E. wscript + VBScript + SAPI.SpVoice ──")
|
||||||
|
if tmp.is_file():
|
||||||
|
code, out = run(["wscript", "//nologo", str(tmp)])
|
||||||
|
report("E", code == 0, "退出码 %d %s" % (code, out[:70]))
|
||||||
|
else:
|
||||||
|
report("E", False, "没有 vbs 文件")
|
||||||
|
time.sleep(0.4)
|
||||||
|
|
||||||
|
# ---------------- 音色列表(两种方式对比)----------------
|
||||||
|
print()
|
||||||
|
print("── 可用音色 ──")
|
||||||
|
if ps_path:
|
||||||
|
code, out = run([
|
||||||
|
ps_path, "-NoProfile", "-Command",
|
||||||
|
"$v = New-Object -ComObject SAPI.SpVoice;"
|
||||||
|
"$v.GetVoices() | ForEach-Object { $_.GetDescription() }"])
|
||||||
|
print(" SAPI5(COM):")
|
||||||
|
for ln in (out or "").splitlines():
|
||||||
|
if ln.strip():
|
||||||
|
print(" " + ln.strip())
|
||||||
|
if not out.strip():
|
||||||
|
print(" (列不出来)")
|
||||||
|
code2, out2 = run([
|
||||||
|
ps_path, "-NoProfile", "-Command",
|
||||||
|
"Add-Type -AssemblyName System.Speech;"
|
||||||
|
"(New-Object System.Speech.Synthesis.SpeechSynthesizer)"
|
||||||
|
".GetInstalledVoices() | ForEach-Object { $_.VoiceInfo.Name }"])
|
||||||
|
print(" System.Speech:")
|
||||||
|
for ln in (out2 or "").splitlines():
|
||||||
|
if ln.strip():
|
||||||
|
print(" " + ln.strip())
|
||||||
|
if not out2.strip():
|
||||||
|
print(" (列不出来 —— .NET 那套可能有问题)")
|
||||||
|
|
||||||
|
# ---------------- 结论 ----------------
|
||||||
|
print()
|
||||||
|
print("=" * 62)
|
||||||
|
print(" 可用 %d 条 / 不可用 %d 条" % (len(FOUND), len(FAILED)))
|
||||||
|
if FOUND:
|
||||||
|
print(" 可用方案: %s" % ", ".join(FOUND))
|
||||||
|
print()
|
||||||
|
print(" → 产品应该按**这个顺序**降级尝试:D(cscript) -> C(SAPI COM)")
|
||||||
|
print(" -> B(绝对路径) -> A(PATH),全失败才报错。")
|
||||||
|
else:
|
||||||
|
print(" ⚠ 一条都不通。可能是:没装任何语音、系统被精简过、")
|
||||||
|
print(" 或者 SAPI 组件损坏。")
|
||||||
|
print("=" * 62)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''按**行号**修 admin.py 里那段坏掉的 JS。
|
||||||
|
|
||||||
|
== 为什么不用字符串匹配 ==
|
||||||
|
|
||||||
|
前两次都失败了:坏掉的内容里带着**真的换行**,
|
||||||
|
在 Python 源码里怎么写字面量都对不齐(缩进、空行的数量差一个就匹配不上)。
|
||||||
|
|
||||||
|
按行号定位反而稳:先找到 `data-update` 那个 forEach 的锚点行,
|
||||||
|
然后把它后面那几行跨行字符串整段换掉。
|
||||||
|
|
||||||
|
== 坏掉的是什么 ==
|
||||||
|
|
||||||
|
if (!confirm('让「' + name + '」现在更新到最新版?\n\n'
|
||||||
|
+ '它会自己下载……'))
|
||||||
|
|
||||||
|
Python 三引号里 `\n` 变成真换行 -> JS 字符串字面量跨行 -> 语法非法
|
||||||
|
-> **整个 script 块解析失败 -> 管理页所有按钮全死**。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ADMIN = ROOT / "relay" / "admin.py"
|
||||||
|
|
||||||
|
NEW_LINES = [
|
||||||
|
" const name = btn.dataset.name || '这台电脑';",
|
||||||
|
" // ⚠ 这里**不能用反斜杠 n** 拼多行文案。",
|
||||||
|
" // ADMIN_JS 是 Python 三引号字符串,源码里写反斜杠 n 会变成",
|
||||||
|
" // **真的换行**插进 JS,于是字符串字面量跨行 —— JS 语法非法,",
|
||||||
|
" // 整个 script 块解析失败,管理页所有按钮全死。",
|
||||||
|
" // (回归里的「管理页 JS 合法性」就是专门抓这个的。)",
|
||||||
|
" //",
|
||||||
|
" // 用 String.fromCharCode(10) 完全不依赖转义层,",
|
||||||
|
" // 以后谁改这段都不会再踩。",
|
||||||
|
" const NL = String.fromCharCode(10);",
|
||||||
|
" const msg = ['让「' + name + '」现在更新到最新版?', '',",
|
||||||
|
" '它会自己下载、静默安装并重启,全程不弹窗口,',",
|
||||||
|
" '中转地址、配对码和各项设置都不变。'].join(NL);",
|
||||||
|
" if (!confirm(msg)) {",
|
||||||
|
" return;",
|
||||||
|
" }",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 按行号修 admin.py 的 JS")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = ADMIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "String.fromCharCode(10)" in text:
|
||||||
|
print(" 已经修好了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
lines = text.split("\n")
|
||||||
|
|
||||||
|
# 找 forEach 的锚点
|
||||||
|
start = None
|
||||||
|
for i, ln in enumerate(lines):
|
||||||
|
if "querySelectorAll('button[data-update]')" in ln:
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
print(" ✗ 找不到 data-update 的 forEach")
|
||||||
|
return 1
|
||||||
|
print(" 锚点在第 %d 行" % (start + 1))
|
||||||
|
|
||||||
|
# 锚点后第一行应该是 btn.onclick = async () => {
|
||||||
|
j = start + 1
|
||||||
|
while j < len(lines) and "btn.onclick" not in lines[j]:
|
||||||
|
j += 1
|
||||||
|
if j >= len(lines):
|
||||||
|
print(" ✗ 找不到 btn.onclick")
|
||||||
|
return 1
|
||||||
|
# 下一个非空行是 const name = ...
|
||||||
|
k = j + 1
|
||||||
|
while k < len(lines) and not lines[k].strip():
|
||||||
|
k += 1
|
||||||
|
if "const name" not in lines[k]:
|
||||||
|
print(" ✗ const name 那行不在预期位置(第 %d 行):%r"
|
||||||
|
% (k + 1, lines[k][:70]))
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# k 之后到底几个坏行?找到 "if (!confirm(" 开始,到那个跨行字符串结束
|
||||||
|
# (下一个以 ' return;' 结尾的块之前)
|
||||||
|
end = k + 1
|
||||||
|
found_confirm = False
|
||||||
|
while end < len(lines):
|
||||||
|
s = lines[end].strip()
|
||||||
|
if s.startswith("if (!confirm("):
|
||||||
|
found_confirm = True
|
||||||
|
if found_confirm and s.startswith("return;"):
|
||||||
|
break
|
||||||
|
end += 1
|
||||||
|
if not found_confirm:
|
||||||
|
print(" ✗ 找不到 if (!confirm(")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(" 要替换第 %d 行 ~ 第 %d 行(%d 行)"
|
||||||
|
% (k + 1, end, end - k + 1))
|
||||||
|
for n in range(k, min(end + 1, k + 8)):
|
||||||
|
print(" 坏行 %d: %r" % (n + 1, lines[n][:64]))
|
||||||
|
|
||||||
|
lines[k:end] = NEW_LINES
|
||||||
|
|
||||||
|
ADMIN.write_bytes((b"\xef\xbb\xbf" if bom else b"")
|
||||||
|
+ "\n".join(lines).encode("utf-8"))
|
||||||
|
print(" ✓ 替换完成")
|
||||||
|
|
||||||
|
sys.path.insert(0, str(ROOT / "relay"))
|
||||||
|
import admin # noqa: E402
|
||||||
|
js = admin.ADMIN_JS
|
||||||
|
bad = []
|
||||||
|
for n, ln in enumerate(js.splitlines(), 1):
|
||||||
|
s = ln.strip()
|
||||||
|
if s.startswith("//"):
|
||||||
|
continue
|
||||||
|
if s.count("'") % 2:
|
||||||
|
bad.append((n, ln[:70]))
|
||||||
|
print(" 复核:单引号落单的行 = %d 个" % len(bad))
|
||||||
|
for n, ln in bad[:5]:
|
||||||
|
print(" %4d %s" % (n, ln))
|
||||||
|
return 0 if not bad else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''修 manager 页「更新」按钮那段 JS 的裸换行。
|
||||||
|
|
||||||
|
== 出了什么问题 ==
|
||||||
|
|
||||||
|
`ADMIN_JS` 是 Python 的**三引号字符串**。我在里面写:
|
||||||
|
|
||||||
|
if (!confirm('让「' + name + '」现在更新到最新版?\n\n'
|
||||||
|
+ '它会自己下载……\n'
|
||||||
|
|
||||||
|
本意是让 JS 收到 `\n`。但 Python 三引号里 `\n` 就是**真的换行**,
|
||||||
|
于是插进 JS 变成:
|
||||||
|
|
||||||
|
if (!confirm('让「' + name + '」现在更新到最新版?
|
||||||
|
(空行)
|
||||||
|
'
|
||||||
|
|
||||||
|
**字符串字面量跨行,JS 语法非法**。
|
||||||
|
|
||||||
|
后果不是"这一句坏了",而是**整个 <script> 块解析失败** ——
|
||||||
|
管理页上所有按钮(改码/删除/踢下线/全选)全部失灵。回归里的
|
||||||
|
「管理页 JS 合法性」这一关就是专门抓这个的(当初加它就是因为
|
||||||
|
踩过一次同样的坑)。
|
||||||
|
|
||||||
|
== 怎么修 ==
|
||||||
|
|
||||||
|
**不用 `\n`**。改成把文案放进数组,用 `String.fromCharCode(10)` 连起来:
|
||||||
|
|
||||||
|
const NL = String.fromCharCode(10);
|
||||||
|
const msg = ['第一行', '', '第二行'].join(NL);
|
||||||
|
|
||||||
|
这样**完全不依赖转义层** —— 不管以后谁编辑这段、用哪种
|
||||||
|
引号、经不经过别的脚本生成,都不会再变成裸换行。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ADMIN = ROOT / "relay" / "admin.py"
|
||||||
|
|
||||||
|
# ⚠ 这些字符串里必须保留**真的换行**(就是要匹配源文件里那个坏掉的样子)
|
||||||
|
OLD = """document.querySelectorAll('button[data-update]').forEach((btn) => {
|
||||||
|
btn.onclick = async () => {
|
||||||
|
const name = btn.dataset.name || '这台电脑';
|
||||||
|
if (!confirm('让「' + name + '」现在更新到最新版?
|
||||||
|
|
||||||
|
'
|
||||||
|
+ '它会自己下载、静默安装并重启,全程不弹窗口,
|
||||||
|
'
|
||||||
|
+ '中转地址、配对码和各项设置都不变。')) {
|
||||||
|
return;
|
||||||
|
}"""
|
||||||
|
|
||||||
|
NEW = """document.querySelectorAll('button[data-update]').forEach((btn) => {
|
||||||
|
btn.onclick = async () => {
|
||||||
|
const name = btn.dataset.name || '这台电脑';
|
||||||
|
// ⚠ 这里**不能用反斜杠 n** 拼多行文案。
|
||||||
|
// ADMIN_JS 是 Python 三引号字符串,源码里写反斜杠 n 会变成
|
||||||
|
// **真的换行**插进 JS,于是字符串字面量跨行 —— JS 语法非法,
|
||||||
|
// 整个 script 块解析失败,管理页所有按钮全死。
|
||||||
|
// (回归里的「管理页 JS 合法性」就是抓这个的。)
|
||||||
|
//
|
||||||
|
// 用 String.fromCharCode(10) 完全不依赖转义层,
|
||||||
|
// 以后谁改这段都不会再踩。
|
||||||
|
const NL = String.fromCharCode(10);
|
||||||
|
const msg = ['让「' + name + '」现在更新到最新版?', '',
|
||||||
|
'它会自己下载、静默安装并重启,全程不弹窗口,',
|
||||||
|
'中转地址、配对码和各项设置都不变。'].join(NL);
|
||||||
|
if (!confirm(msg)) {
|
||||||
|
return;
|
||||||
|
}"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 修管理页 JS 的裸换行")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = ADMIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "String.fromCharCode(10)" in text and OLD not in text:
|
||||||
|
print(" 已经修好了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if OLD not in text:
|
||||||
|
print(" ✗ 找不到坏掉的那段")
|
||||||
|
i = text.find("data-update")
|
||||||
|
print(text[max(0, i - 100):i + 700])
|
||||||
|
return 1
|
||||||
|
|
||||||
|
text = text.replace(OLD, NEW, 1)
|
||||||
|
ADMIN.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 替换完成")
|
||||||
|
|
||||||
|
# 复核:ADMIN_JS 里不能再有跨行的字符串字面量
|
||||||
|
sys.path.insert(0, str(ROOT / "relay"))
|
||||||
|
for name in list(sys.modules):
|
||||||
|
if name in ("admin", "relay"):
|
||||||
|
del sys.modules[name]
|
||||||
|
import admin # noqa: E402
|
||||||
|
js = admin.ADMIN_JS
|
||||||
|
bad = []
|
||||||
|
for n, ln in enumerate(js.splitlines(), 1):
|
||||||
|
s = ln.strip()
|
||||||
|
if s.startswith("//"):
|
||||||
|
continue
|
||||||
|
if s.count("'") % 2:
|
||||||
|
bad.append((n, ln[:70]))
|
||||||
|
print(" 复核:单引号落单的行 = %d 个" % len(bad))
|
||||||
|
for n, ln in bad[:5]:
|
||||||
|
print(" %4d %s" % (n, ln))
|
||||||
|
return 0 if not bad else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -43,11 +43,11 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run # noqa: E402
|
from lssh import run, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
RELAY_DIR = "/opt/ykxmz-relay"
|
RELAY_DIR = "/opt/ykxmz-relay"
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
FALLBACK = "http://<源站IP>:80"
|
FALLBACK = "http://%s:80" % LS_HOST
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -58,7 +58,7 @@ def main() -> int:
|
|||||||
print()
|
print()
|
||||||
print(" ── 1. 改 monitor.sh 的健康检查(域名优先,IP 兜底)──")
|
print(" ── 1. 改 monitor.sh 的健康检查(域名优先,IP 兜底)──")
|
||||||
# 把 PUBLIC_URL 的默认值换掉,并把 is_healthy 改成"两个都试"
|
# 把 PUBLIC_URL 的默认值换掉,并把 is_healthy 改成"两个都试"
|
||||||
old_url = 'PUBLIC_URL="${PUBLIC_URL:-http://<源站IP>:13245}"'
|
old_url = 'PUBLIC_URL="${PUBLIC_URL:-http://LS_HOST:13245}"'
|
||||||
new_url = (
|
new_url = (
|
||||||
'# 探测地址:域名优先(用户实际走的路),IP:80 兜底\n'
|
'# 探测地址:域名优先(用户实际走的路),IP:80 兜底\n'
|
||||||
'# (域名 DNS 还没指过来时用它,否则监测会一直误报)\n'
|
'# (域名 DNS 还没指过来时用它,否则监测会一直误报)\n'
|
||||||
@@ -151,10 +151,10 @@ def main() -> int:
|
|||||||
'http://%s/v1/health)"; '
|
'http://%s/v1/health)"; '
|
||||||
'printf " %-28s %s\\n" "IP:80 (兜底)" '
|
'printf " %-28s %s\\n" "IP:80 (兜底)" '
|
||||||
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
||||||
'http://<源站IP>:80/v1/health)"; '
|
'http://LS_HOST:80/v1/health)"; '
|
||||||
'printf " %-28s %s\\n" "IP:13245 (已关闭)" '
|
'printf " %-28s %s\\n" "IP:13245 (已关闭)" '
|
||||||
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
||||||
'http://<源站IP>:13245/v1/health)"' % DOMAIN,
|
'http://LS_HOST:13245/v1/health)"' % DOMAIN,
|
||||||
timeout=120, quiet=True)
|
timeout=120, quiet=True)
|
||||||
for ln in out[1].strip().splitlines():
|
for ln in out[1].strip().splitlines():
|
||||||
print(ln)
|
print(ln)
|
||||||
|
|||||||
@@ -32,7 +32,14 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
IP = "<源站IP>"
|
# ⚠ 这个脚本要"在所有发行版介绍里找这个 IP",所以它必须知道 IP。
|
||||||
|
# 但**不能在源码里写死** —— 写了就等于把 IP 又发到公开仓库里,
|
||||||
|
# 正是这个脚本要防的事。
|
||||||
|
# 从 lssh 取(那里会读环境变量 YKXMZ_LS_HOST 或
|
||||||
|
# _build/.lightsail_host,后者已 gitignore)。
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
from lssh import HOST as IP, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
OWNER_REPO = "xmz7891/ykxmz"
|
OWNER_REPO = "xmz7891/ykxmz"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,384 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把语音播报改成**多条方案降级**,修 Win7 上用不了的问题。
|
||||||
|
|
||||||
|
== 用户反馈 ==
|
||||||
|
|
||||||
|
"我 win7 上的语音播报好像不能用,你再试一下别的版本能不能用"
|
||||||
|
|
||||||
|
== 原来只有一条路,而且有几个 Win7 特有的坑 ==
|
||||||
|
|
||||||
|
powershell -NoProfile -WindowStyle Hidden -Command
|
||||||
|
"Add-Type -AssemblyName System.Speech; $s = New-Object ...; $s.Speak('...')"
|
||||||
|
|
||||||
|
坑一:**`powershell` 只按名字找**
|
||||||
|
Win7 的 powershell.exe 在 `%SystemRoot%\System32\WindowsPowerShell\v1.0\`。
|
||||||
|
精简版系统、或者从服务/计划任务拉起时 PATH 里可能没有 ——
|
||||||
|
找不到就**静默失败**(Popen 不报错,因为进程起来了,只是在里面失败)。
|
||||||
|
|
||||||
|
坑二:**Win7 默认 PowerShell 2.0,它按 ANSI 代码页解析 `-Command`**
|
||||||
|
PS 3.0 起才按 UTF-16 处理。所以中文经 `-Command` 传进去在 PS 2.0 上
|
||||||
|
很容易乱码 —— 表现是"念出来是乱码"或者干脆不念。
|
||||||
|
|
||||||
|
坑三:**`System.Speech` 需要 .NET Framework 3.0+**
|
||||||
|
而系统自带的 **SAPI5**(`SAPI.SpVoice`)从 Windows XP 就有,
|
||||||
|
**根本不需要 .NET**。绕开 .NET 更稳。
|
||||||
|
|
||||||
|
== 现在的做法:降级链 ==
|
||||||
|
|
||||||
|
按"依赖越少越优先"排:
|
||||||
|
|
||||||
|
1. **cscript + VBScript + SAPI.SpVoice**
|
||||||
|
VBScript 从 Windows 98 就有,SAPI5 是系统组件 ——
|
||||||
|
两个都不需要装东西,也不受 PowerShell 版本 / PATH / .NET 影响。
|
||||||
|
**这是最可能在 Win7 上通的一条。**
|
||||||
|
|
||||||
|
2. **wscript + VBScript + SAPI.SpVoice**
|
||||||
|
同上,换宿主(cscript 万一被安全软件拦了)。
|
||||||
|
|
||||||
|
3. **powershell(绝对路径)+ SAPI.SpVoice COM**
|
||||||
|
绕开 .NET,但仍要 PowerShell。
|
||||||
|
|
||||||
|
4. **powershell(绝对路径)+ System.Speech**
|
||||||
|
原来的做法,只是改用绝对路径。
|
||||||
|
|
||||||
|
5. **powershell(按 PATH)+ System.Speech**
|
||||||
|
最原始的做法,留作最后兜底。
|
||||||
|
|
||||||
|
**一条通了就记住它**(模块级缓存),后面都直接走那条 ——
|
||||||
|
不然每播一次都要把上面几条全试一遍,慢且难看。
|
||||||
|
|
||||||
|
== 顺手改进 ==
|
||||||
|
|
||||||
|
* `say()` 原来用 `Popen` 不等待 —— **失败了也返回"已播报"**。
|
||||||
|
现在**等它结束并看退出码**,真失败会明确报错,不再骗人。
|
||||||
|
代价是播报变成了同步的(要等念完)—— 但"报成功其实没出声"
|
||||||
|
比"慢一点"糟糕得多。
|
||||||
|
* VBScript 文件用 **mbcs(ANSI)** 编码写。写成 UTF-8 的话
|
||||||
|
cscript 读出来是乱码 —— 这是 VBScript 的老规矩。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ACTIONS = ROOT / "windows" / "lanremote" / "actions.py"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 要替换的旧代码
|
||||||
|
OLD_VOICES = ''' def list_voices(self) -> list[str]:
|
||||||
|
"""列出系统可用的 TTS 音色。"""
|
||||||
|
if not IS_WINDOWS:
|
||||||
|
return []
|
||||||
|
script = (
|
||||||
|
"Add-Type -AssemblyName System.Speech;"
|
||||||
|
"(New-Object System.Speech.Synthesis.SpeechSynthesizer)"
|
||||||
|
".GetInstalledVoices() | ForEach-Object { $_.VoiceInfo.Name }"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
["powershell", "-NoProfile", "-Command", script],
|
||||||
|
capture_output=True, timeout=20,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
return [line.strip() for line in (proc.stdout or "").splitlines() if line.strip()]'''
|
||||||
|
|
||||||
|
OLD_SAY = ''' safe = text.replace("'", "''")
|
||||||
|
parts = [
|
||||||
|
"Add-Type -AssemblyName System.Speech;",
|
||||||
|
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
|
||||||
|
]
|
||||||
|
if chosen:
|
||||||
|
parts.append(f"try {{ $s.SelectVoice('{chosen.replace(chr(39), chr(39) * 2)}') }} "
|
||||||
|
"catch { };")
|
||||||
|
if speed:
|
||||||
|
parts.append(f"$s.Rate = {speed};")
|
||||||
|
parts.append(f"$s.Speak('{safe}')")
|
||||||
|
script = "".join(parts)
|
||||||
|
|
||||||
|
try:
|
||||||
|
subprocess.Popen(
|
||||||
|
["powershell", "-NoProfile", "-WindowStyle", "Hidden",
|
||||||
|
"-Command", script],
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||||
|
except Exception as exc:
|
||||||
|
raise ActionError(f"TTS 启动失败: {exc}") from exc
|
||||||
|
return f"已播报({chosen or '默认音色'})"'''
|
||||||
|
|
||||||
|
NEW = ''' # ------------------------------------------------------------------
|
||||||
|
# 语音播报(系统自带 TTS)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
#
|
||||||
|
# ⚠ 这里有一套**降级链**,不是随便写的。原因见文件末尾的说明,
|
||||||
|
# 简单说:Win7 上的 PowerShell 2.0 + 中文 + PATH 三样都可能出问题,
|
||||||
|
# 而 cscript + SAPI5 是最老最稳的组合(从 XP 就有)。
|
||||||
|
#
|
||||||
|
# 顺序:cscript -> wscript -> ps(绝对路径)+SAPI COM
|
||||||
|
# -> ps(绝对路径)+System.Speech -> ps(PATH)+System.Speech
|
||||||
|
|
||||||
|
def _powershell_path(self) -> str:
|
||||||
|
"""找 powershell.exe。**先按绝对路径**,PATH 只作兜底。
|
||||||
|
|
||||||
|
为什么:Win7 上 PATH 里不一定有,而 CreateProcess 按名字找不到时
|
||||||
|
是**静默失败**的(进程根本没起来,但 Popen 不报错)。
|
||||||
|
"""
|
||||||
|
import shutil as _sh
|
||||||
|
cand = Path(os.environ.get("SystemRoot", r"C:\\Windows")) / \\
|
||||||
|
"System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
|
||||||
|
if os.name == "nt" and cand.is_file():
|
||||||
|
return str(cand)
|
||||||
|
return _sh.which("powershell") or ""
|
||||||
|
|
||||||
|
def _write_vbs(self, text: str, voice: str, rate: int) -> Path:
|
||||||
|
"""生成一个播报用的 .vbs。
|
||||||
|
|
||||||
|
⚠ 必须用 **mbcs(系统 ANSI 代码页)** 写 ——
|
||||||
|
cscript 读 .vbs 是按 ANSI 读的,写成 UTF-8 中文就是乱码。
|
||||||
|
"""
|
||||||
|
import tempfile
|
||||||
|
lines = ['Dim v', 'Set v = CreateObject("SAPI.SpVoice")']
|
||||||
|
if voice:
|
||||||
|
# 按描述匹配音色。找不到就 silently 用默认 ——
|
||||||
|
# 音色选不上不该让整条播报失败。
|
||||||
|
lines.append('Dim i')
|
||||||
|
lines.append('For i = 0 To v.GetVoices().Count - 1')
|
||||||
|
lines.append(' If InStr(v.GetVoices().Item(i).GetDescription(), "%s") > 0 Then'
|
||||||
|
% voice.replace('"', '""'))
|
||||||
|
lines.append(' Set v.Voice = v.GetVoices().Item(i)')
|
||||||
|
lines.append(' End If')
|
||||||
|
lines.append('Next')
|
||||||
|
if rate:
|
||||||
|
# SAPI 的 Rate 范围是 -10..10,跟我们的设置一致
|
||||||
|
lines.append("v.Rate = %d" % max(-10, min(10, rate)))
|
||||||
|
# 长文本 VBScript 单行有长度限制,所以**分句拼接**
|
||||||
|
chunk = text.replace('"', '""').replace("\\r", " ").replace("\\n", " ")
|
||||||
|
while chunk:
|
||||||
|
piece, chunk = chunk[:400], chunk[400:]
|
||||||
|
lines.append('v.Speak "%s"' % piece)
|
||||||
|
path = Path(tempfile.gettempdir()) / "ykxmz_say.vbs"
|
||||||
|
path.write_bytes(("\\r\\n".join(lines) + "\\r\\n").encode("mbcs",
|
||||||
|
errors="replace"))
|
||||||
|
return path
|
||||||
|
|
||||||
|
def _tts_commands(self, text: str, voice: str, rate: int) -> list:
|
||||||
|
"""按"依赖越少越优先"排出所有可行方案,返回 [(名字, 命令行)]。"""
|
||||||
|
cmds = []
|
||||||
|
vbs = None
|
||||||
|
try:
|
||||||
|
vbs = self._write_vbs(text, voice, rate)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
vbs = None
|
||||||
|
if vbs is not None:
|
||||||
|
# 1 / 2:完全不依赖 PowerShell 和 .NET
|
||||||
|
cmds.append(("cscript", ["cscript", "//nologo", str(vbs)]))
|
||||||
|
cmds.append(("wscript", ["wscript", "//nologo", str(vbs)]))
|
||||||
|
|
||||||
|
ps = self._powershell_path()
|
||||||
|
esc = text.replace("'", "''")
|
||||||
|
if ps:
|
||||||
|
# 3:绕开 .NET,只用系统原生 SAPI5
|
||||||
|
sapi = ["$v = New-Object -ComObject SAPI.SpVoice;"]
|
||||||
|
if voice:
|
||||||
|
sapi.append("foreach ($o in $v.GetVoices()) { "
|
||||||
|
"if ($o.GetDescription() -like '*%s*') { "
|
||||||
|
"$v.Voice = $o } };" % voice.replace("'", "''"))
|
||||||
|
if rate:
|
||||||
|
sapi.append("$v.Rate = %d;" % max(-10, min(10, rate)))
|
||||||
|
sapi.append("$v.Speak('%s')" % esc)
|
||||||
|
cmds.append(("ps-sapi", [ps, "-NoProfile", "-WindowStyle", "Hidden",
|
||||||
|
"-Command", "".join(sapi)]))
|
||||||
|
|
||||||
|
# 4:原来的做法,但用绝对路径
|
||||||
|
sp = ["Add-Type -AssemblyName System.Speech;",
|
||||||
|
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;"]
|
||||||
|
if voice:
|
||||||
|
sp.append("try { $s.SelectVoice('%s') } catch { };"
|
||||||
|
% voice.replace("'", "''"))
|
||||||
|
if rate:
|
||||||
|
sp.append("$s.Rate = %d;" % max(-10, min(10, rate)))
|
||||||
|
sp.append("$s.Speak('%s')" % esc)
|
||||||
|
cmds.append(("ps-speech", [ps, "-NoProfile", "-WindowStyle",
|
||||||
|
"Hidden", "-Command", "".join(sp)]))
|
||||||
|
|
||||||
|
# 5:最原始的(PATH + System.Speech),兜底
|
||||||
|
import shutil as _sh
|
||||||
|
if _sh.which("powershell"):
|
||||||
|
sp = ["Add-Type -AssemblyName System.Speech;",
|
||||||
|
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;"]
|
||||||
|
if voice:
|
||||||
|
sp.append("try { $s.SelectVoice('%s') } catch { };"
|
||||||
|
% voice.replace("'", "''"))
|
||||||
|
if rate:
|
||||||
|
sp.append("$s.Rate = %d;" % max(-10, min(10, rate)))
|
||||||
|
sp.append("$s.Speak('%s')" % esc)
|
||||||
|
cmds.append(("ps-path", ["powershell", "-NoProfile",
|
||||||
|
"-WindowStyle", "Hidden",
|
||||||
|
"-Command", "".join(sp)]))
|
||||||
|
return cmds
|
||||||
|
|
||||||
|
def list_voices(self) -> list[str]:
|
||||||
|
"""列出系统可用的 TTS 音色。
|
||||||
|
|
||||||
|
用 SAPI5 COM 列(不依赖 .NET)—— Win7 上没有 .NET 3.0 的话
|
||||||
|
System.Speech 那条路是列不出来的,而 SAPI5 一定有。
|
||||||
|
"""
|
||||||
|
if not IS_WINDOWS:
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
ps = self._powershell_path()
|
||||||
|
if ps:
|
||||||
|
script = ("$v = New-Object -ComObject SAPI.SpVoice;"
|
||||||
|
"$v.GetVoices() | ForEach-Object { $_.GetDescription() }")
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
[ps, "-NoProfile", "-Command", script],
|
||||||
|
capture_output=True, timeout=20,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
out = [ln.strip() for ln in (proc.stdout or "").splitlines()
|
||||||
|
if ln.strip()]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
out = []
|
||||||
|
if not out:
|
||||||
|
# 退到 System.Speech 再列一次
|
||||||
|
if ps:
|
||||||
|
script = ("Add-Type -AssemblyName System.Speech;"
|
||||||
|
"(New-Object System.Speech.Synthesis"
|
||||||
|
".SpeechSynthesizer).GetInstalledVoices()"
|
||||||
|
" | ForEach-Object { $_.VoiceInfo.Name }")
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
[ps, "-NoProfile", "-Command", script],
|
||||||
|
capture_output=True, timeout=20,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
out = [ln.strip() for ln in (proc.stdout or "").splitlines()
|
||||||
|
if ln.strip()]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
out = []
|
||||||
|
return out
|
||||||
|
|
||||||
|
def say(self, text: str, voice: str = "", rate: int = 0) -> str:
|
||||||
|
"""语音播报。voice 为空则用系统默认(或设置里的默认音色)。
|
||||||
|
|
||||||
|
⚠ 会**等播报结束**并看退出码,失败就抛错。
|
||||||
|
原来用 Popen 不等待,失败了也返回"已播报"—— 那是骗人。
|
||||||
|
代价是同步等待(念多久等多久),但"报成功其实没出声"
|
||||||
|
比"慢一点"糟糕得多。
|
||||||
|
"""
|
||||||
|
if not text.strip():
|
||||||
|
raise ActionError("播报内容为空")
|
||||||
|
if not IS_WINDOWS:
|
||||||
|
raise ActionError("语音播报目前仅支持 Windows")
|
||||||
|
|
||||||
|
chosen = (voice or "").strip() or str(
|
||||||
|
self.store.get("tts_voice") or "").strip()
|
||||||
|
try:
|
||||||
|
speed = int(rate) if rate else int(self.store.get("tts_rate", 0) or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
speed = 0
|
||||||
|
speed = max(-10, min(10, speed))
|
||||||
|
|
||||||
|
cmds = self._tts_commands(text, chosen, speed)
|
||||||
|
if not cmds:
|
||||||
|
raise ActionError("这台电脑上找不到可用的语音播报方式"
|
||||||
|
"(没有 cscript 也没有 powershell?)")
|
||||||
|
|
||||||
|
# 上次成功的那条优先 —— 不然每播一次都要把几条全试一遍
|
||||||
|
cached = globals().get("_TTS_LAST_OK")
|
||||||
|
if cached:
|
||||||
|
cmds.sort(key=lambda c: 0 if c[0] == cached else 1)
|
||||||
|
|
||||||
|
tried = []
|
||||||
|
for name, cmd in cmds:
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd, capture_output=True, timeout=180,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
except FileNotFoundError:
|
||||||
|
tried.append("%s(没有这个程序)" % name)
|
||||||
|
continue
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
tried.append("%s(超时)" % name)
|
||||||
|
continue
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
tried.append("%s(%s)" % (name, type(exc).__name__))
|
||||||
|
continue
|
||||||
|
if proc.returncode == 0:
|
||||||
|
globals()["_TTS_LAST_OK"] = name
|
||||||
|
return "已播报(%s,用 %s)" % (chosen or "默认音色", name)
|
||||||
|
err = ((proc.stderr or "") + (proc.stdout or "")).strip()
|
||||||
|
tried.append("%s(退出码%d %s)" % (name, proc.returncode, err[:40]))
|
||||||
|
|
||||||
|
raise ActionError("语音播报失败,试过:" + ";".join(tried))'''
|
||||||
|
|
||||||
|
NEW_VOICES = ''' def list_voices(self) -> list[str]:
|
||||||
|
"""列出系统可用的 TTS 音色。
|
||||||
|
|
||||||
|
用 SAPI5 COM 列(不依赖 .NET)—— Win7 上没装 .NET 3.0 的话
|
||||||
|
System.Speech 那条路列不出来,而 SAPI5 一定有。
|
||||||
|
"""
|
||||||
|
if not IS_WINDOWS:
|
||||||
|
return []
|
||||||
|
ps = self._powershell_path()
|
||||||
|
if not ps:
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
for script in (
|
||||||
|
# 优先 SAPI5 COM
|
||||||
|
"$v = New-Object -ComObject SAPI.SpVoice;"
|
||||||
|
"$v.GetVoices() | ForEach-Object { $_.GetDescription() }",
|
||||||
|
# 退到 System.Speech
|
||||||
|
"Add-Type -AssemblyName System.Speech;"
|
||||||
|
"(New-Object System.Speech.Synthesis.SpeechSynthesizer)"
|
||||||
|
".GetInstalledVoices() | ForEach-Object { $_.VoiceInfo.Name }",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
[ps, "-NoProfile", "-Command", script],
|
||||||
|
capture_output=True, timeout=20,
|
||||||
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||||
|
encoding="mbcs", errors="replace")
|
||||||
|
out = [ln.strip() for ln in (proc.stdout or "").splitlines()
|
||||||
|
if ln.strip()]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
out = []
|
||||||
|
if out:
|
||||||
|
return out
|
||||||
|
return []'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 语音播报:改成多条方案降级")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = ACTIONS.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "_tts_commands" in t:
|
||||||
|
print(" 已经改过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
missing = [k for k, v in {"list_voices": OLD_VOICES, "say": OLD_SAY}.items()
|
||||||
|
if v not in t]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 找不到:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点就位")
|
||||||
|
|
||||||
|
t = t.replace(OLD_VOICES, NEW_VOICES, 1)
|
||||||
|
t = t.replace(OLD_SAY, NEW, 1)
|
||||||
|
|
||||||
|
ACTIONS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ list_voices 改用 SAPI5 COM(+ System.Speech 兜底)")
|
||||||
|
print(" ✓ say 改成降级链 + 等待退出码 + 记住可用的那条")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''修 verify_all.ps1 里被转义弄坏的那段。
|
||||||
|
|
||||||
|
== 弄坏了什么 ==
|
||||||
|
|
||||||
|
我用 `python -c "..."` 传的脚本里带了 `\$stageOut`,
|
||||||
|
PowerShell 先解析了一遍,把 `$stageOut` 变成了 `\`,
|
||||||
|
结果插进去的是:
|
||||||
|
|
||||||
|
\ = & python (Join-Path \ "_tests\test_admin_update.py") 2>&1
|
||||||
|
Show-Fails Record "后台更新按钮" (\ -eq 0)
|
||||||
|
|
||||||
|
`Show-Fails` 和 `Record` 挤在一行,变量名也没了。
|
||||||
|
|
||||||
|
== 教训 ==
|
||||||
|
|
||||||
|
凡是**要写进文件的内容里带 `$`**,一律写成 .py 文件再跑,
|
||||||
|
不要用 `python -c "..."` 穿过 PowerShell。这个坑今天踩了太多次。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
VERIFY = ROOT / "_tests" / "verify_all.ps1"
|
||||||
|
|
||||||
|
# 被弄坏的那两段
|
||||||
|
BROKEN = '''\\ = & python (Join-Path \\ "_tests\\test_admin_update.py") 2>&1
|
||||||
|
Show-Fails Record "后台更新按钮" (\\ -eq 0)
|
||||||
|
|
||||||
|
\\ = & python (Join-Path \\ "_tests\\test_notice_options.py") 2>&1
|
||||||
|
Show-Fails Record "弹窗位置和大小" (\\ -eq 0)'''
|
||||||
|
|
||||||
|
FIXED = '''$stageOut = & python (Join-Path $root "_tests\\test_admin_update.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "后台更新按钮" ($LASTEXITCODE -eq 0)
|
||||||
|
|
||||||
|
$stageOut = & python (Join-Path $root "_tests\\test_notice_options.py") 2>&1
|
||||||
|
Show-Fails $stageOut
|
||||||
|
Record "弹窗位置和大小" ($LASTEXITCODE -eq 0)'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
raw = VERIFY.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if FIXED in text:
|
||||||
|
print(" 已经修好了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if BROKEN not in text:
|
||||||
|
print(" ✗ 找不到被弄坏的那段。当前 3a12 附近的内容:")
|
||||||
|
i = text.find("3a12")
|
||||||
|
print(text[max(0, i - 50):i + 700])
|
||||||
|
return 1
|
||||||
|
|
||||||
|
text = text.replace(BROKEN, FIXED, 1)
|
||||||
|
|
||||||
|
# 顺手把 "3a12/7" 改成 "3a12/9"(关卡数变了)
|
||||||
|
text = text.replace('Banner "3a12/7', 'Banner "3a12/9')
|
||||||
|
|
||||||
|
VERIFY.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ 修好了")
|
||||||
|
|
||||||
|
back = VERIFY.read_text(encoding="utf-8-sig")
|
||||||
|
for token in ('$stageOut = & python (Join-Path $root "_tests\\test_admin_update.py")',
|
||||||
|
'$stageOut = & python (Join-Path $root "_tests\\test_notice_options.py")',
|
||||||
|
'Record "后台更新按钮"',
|
||||||
|
'Record "弹窗位置和大小"'):
|
||||||
|
ok = token in back
|
||||||
|
print(" [%s] %s" % ("PASS" if ok else "FAIL", token[:58]))
|
||||||
|
if not ok:
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 109 KiB |
@@ -31,7 +31,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run, upload # noqa: E402
|
from lssh import run, upload, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
RELAY_DIR = "/opt/ykxmz-relay"
|
RELAY_DIR = "/opt/ykxmz-relay"
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ def main() -> int:
|
|||||||
'https://yk.xxmxxs.top/v1/health)"; '
|
'https://yk.xxmxxs.top/v1/health)"; '
|
||||||
'printf " %-36s %s\\n" "公网 443(Lightsail 防火墙)" '
|
'printf " %-36s %s\\n" "公网 443(Lightsail 防火墙)" '
|
||||||
'"$(curl -sk -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
'"$(curl -sk -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
||||||
'https://<源站IP>/v1/health 2>/dev/null || echo 不通)"'
|
'https://LS_HOST/v1/health 2>/dev/null || echo 不通)"'
|
||||||
)
|
)
|
||||||
out = run(probe, timeout=180, quiet=True)
|
out = run(probe, timeout=180, quiet=True)
|
||||||
for ln in out[1].strip().splitlines():
|
for ln in out[1].strip().splitlines():
|
||||||
|
|||||||
+25
-1
@@ -23,7 +23,31 @@ from pathlib import Path
|
|||||||
|
|
||||||
import paramiko
|
import paramiko
|
||||||
|
|
||||||
HOST = os.environ.get("YKXMZ_LS_HOST", "<源站IP>")
|
|
||||||
|
def _host() -> str:
|
||||||
|
"""服务器公网 IP —— **不写死在代码里**。
|
||||||
|
|
||||||
|
这个仓库是公开的。IP 写进来等于把源站地址告诉所有人,
|
||||||
|
而源站躲在 Cloudflare 后面本来就不该被知道(直接打 IP 就绕过 CDN
|
||||||
|
和防护了)。2026-10-08 就因为 IP 泄漏返工过一次。
|
||||||
|
|
||||||
|
取值顺序:
|
||||||
|
1. 环境变量 YKXMZ_LS_HOST
|
||||||
|
2. _build/.lightsail_host(一行 IP,已 gitignore)
|
||||||
|
"""
|
||||||
|
env = os.environ.get("YKXMZ_LS_HOST", "").strip()
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
f = Path(__file__).resolve().parent / ".lightsail_host"
|
||||||
|
if f.is_file():
|
||||||
|
return f.read_text(encoding="utf-8").strip()
|
||||||
|
raise SystemExit(
|
||||||
|
"没拿到服务器地址。二选一:\n"
|
||||||
|
" set YKXMZ_LS_HOST=<你的服务器IP>\n"
|
||||||
|
" 或把 IP 写进 _build/.lightsail_host(该文件已在 .gitignore 里)")
|
||||||
|
|
||||||
|
|
||||||
|
HOST = _host()
|
||||||
USER = os.environ.get("YKXMZ_LS_USER", "admin")
|
USER = os.environ.get("YKXMZ_LS_USER", "admin")
|
||||||
PORT = int(os.environ.get("YKXMZ_LS_PORT", "22"))
|
PORT = int(os.environ.get("YKXMZ_LS_PORT", "22"))
|
||||||
KEY = Path(os.environ.get(
|
KEY = Path(os.environ.get(
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import zipfile
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote")
|
ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote")
|
||||||
VERSION = "2.1.4"
|
VERSION = "2.1.8"
|
||||||
NAME = f"ykxmz-{VERSION}"
|
NAME = f"ykxmz-{VERSION}"
|
||||||
|
|
||||||
AGENT_SRC = ROOT / "dist_exe" / "ykxmz"
|
AGENT_SRC = ROOT / "dist_exe" / "ykxmz"
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''快捷栏:按钮做大 + **4 格全部可自定义**。
|
||||||
|
|
||||||
|
== 用户这次的反馈(原话)==
|
||||||
|
|
||||||
|
"屏幕最上面这个按钮有些按不到,按钮太小了,做大一点,
|
||||||
|
然后呢,这个每每个四格算换一下吧,第一个第二个第三个第四个都能换东西"
|
||||||
|
|
||||||
|
== 两个改动 ==
|
||||||
|
|
||||||
|
1. **按钮做大**:30dp -> 46dp,字号 11 -> 14。
|
||||||
|
30dp 在手表上确实太小了 —— 表盘本来就小,手指按上去一半在栏外。
|
||||||
|
46dp 接近 Android 建议的最小可点区域(48dp)。
|
||||||
|
|
||||||
|
⚠ 栏高和面板 topMargin 必须**用同一个常量**。分开写的话
|
||||||
|
改一个忘一个,表现是"内容要么被栏盖住,要么上面空一条"。
|
||||||
|
|
||||||
|
2. **第 4 格也变成可自定义**。
|
||||||
|
|
||||||
|
用户最早说"其中有一个按钮不能改,功能就是一键返回桌面",
|
||||||
|
现在改主意了:"第一个第二个第三个第四个都能换东西"。
|
||||||
|
|
||||||
|
所以「显示桌面」从"固定的那一格"变成**普通可选动作**,
|
||||||
|
而且默认就放在第 4 格 —— 这样默认行为跟以前一样
|
||||||
|
(最后一个还是显示桌面),但用户想换也能换。
|
||||||
|
|
||||||
|
实现上就是把 QUICK_CUSTOM_SLOTS 从 3 改成 4,
|
||||||
|
再把 {"desktop","显示桌面"} 加进 QUICK_ACTIONS,
|
||||||
|
然后去掉所有"第 4 格特殊"的分支。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAIN = ROOT / "android" / "src" / "com" / "lanremote" / "watch" / "MainActivity.java"
|
||||||
|
|
||||||
|
PAIRS = [
|
||||||
|
# ---- 1. 格子数 3 -> 4 ----
|
||||||
|
(' private static final int QUICK_CUSTOM_SLOTS = 3; // 固定那个不算在内',
|
||||||
|
''' /** 快捷栏一共几格。用户最初要求"最多 4 个",
|
||||||
|
* 后来又改成"第一二三四格都能换东西",所以 4 格都可自定义。 */
|
||||||
|
private static final int QUICK_SLOTS = 4;
|
||||||
|
/** 快捷栏高度(dp)。46 接近 Android 建议的最小可点区域 48。
|
||||||
|
* ⚠ 面板的 topMargin 也用这个值 —— 分两处写的话改一个忘一个,
|
||||||
|
* 表现是"内容被栏盖住"或"上面空一条"。 */
|
||||||
|
private static final int QUICK_BAR_DP = 46;'''),
|
||||||
|
|
||||||
|
# ---- 2. 加 desktop 到可选动作 ----
|
||||||
|
(''' {"image", "投图到电脑"},
|
||||||
|
};''',
|
||||||
|
''' {"image", "投图到电脑"},
|
||||||
|
// 用户最早说这一格"不能改",后来又改成四格都能换 ——
|
||||||
|
// 所以它现在是**普通可选动作**,只是默认放在第 4 格。
|
||||||
|
{"desktop", "显示桌面"},
|
||||||
|
};'''),
|
||||||
|
|
||||||
|
# ---- 3. 默认值 3 -> 4 格 ----
|
||||||
|
(''' private String[] quickSlots = new String[]{"file", "mirror", "sfx"};''',
|
||||||
|
''' private String[] quickSlots =
|
||||||
|
new String[]{"file", "mirror", "sfx", "desktop"};'''),
|
||||||
|
|
||||||
|
# ---- 4. buildQuickBar:格数、高度、字号 ----
|
||||||
|
(''' for (int i = 0; i < QUICK_CUSTOM_SLOTS + 1; i++) {
|
||||||
|
final int slot = i;
|
||||||
|
Button b = new Button(this);
|
||||||
|
b.setTextSize(11f);''',
|
||||||
|
''' for (int i = 0; i < QUICK_SLOTS; i++) {
|
||||||
|
final int slot = i;
|
||||||
|
Button b = new Button(this);
|
||||||
|
b.setTextSize(14f); // 11 太小,用户说"按不到"'''),
|
||||||
|
|
||||||
|
(''' FrameLayout.LayoutParams barLp = new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(30));''',
|
||||||
|
''' FrameLayout.LayoutParams barLp = new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(QUICK_BAR_DP));'''),
|
||||||
|
|
||||||
|
# ---- 5. refreshQuickBar:不再有"固定那一格" ----
|
||||||
|
(''' boolean connected = isConnected();
|
||||||
|
for (int i = 0; i < quickButtons.size(); i++) {
|
||||||
|
Button b = quickButtons.get(i);
|
||||||
|
String id = (i < QUICK_CUSTOM_SLOTS) ? quickSlots[i] : "desktop";''',
|
||||||
|
''' boolean connected = isConnected();
|
||||||
|
for (int i = 0; i < quickButtons.size(); i++) {
|
||||||
|
Button b = quickButtons.get(i);
|
||||||
|
String id = quickSlots[i];'''),
|
||||||
|
|
||||||
|
# ---- 6. onQuickClick:不再有"固定那一格" ----
|
||||||
|
(''' /** 点第 slot 个按钮。0..2 是自定义,3 是那个固定的显示桌面。 */
|
||||||
|
private void onQuickClick(int slot) {
|
||||||
|
String id = (slot < QUICK_CUSTOM_SLOTS) ? quickSlots[slot] : "desktop";
|
||||||
|
if (id == null || id.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
runQuickAction(id);
|
||||||
|
}''',
|
||||||
|
''' /** 点第 slot 个按钮。四格完全平等,都从 quickSlots 里取。 */
|
||||||
|
private void onQuickClick(int slot) {
|
||||||
|
if (slot < 0 || slot >= quickSlots.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String id = quickSlots[slot];
|
||||||
|
if (id == null || id.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
runQuickAction(id);
|
||||||
|
}'''),
|
||||||
|
|
||||||
|
# ---- 7. loadQuickSlots:4 格 + 允许 desktop ----
|
||||||
|
(''' String[] want = (raw == null || raw.isEmpty())
|
||||||
|
? new String[]{"file", "mirror", "sfx"}
|
||||||
|
: raw.split(",", -1);''',
|
||||||
|
''' String[] want = (raw == null || raw.isEmpty())
|
||||||
|
? new String[]{"file", "mirror", "sfx", "desktop"}
|
||||||
|
: raw.split(",", -1);'''),
|
||||||
|
|
||||||
|
(''' String[] out = new String[QUICK_CUSTOM_SLOTS];
|
||||||
|
int n = 0;
|
||||||
|
for (String id : want) {
|
||||||
|
if (n >= QUICK_CUSTOM_SLOTS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (id != null && !id.isEmpty() && !"desktop".equals(id)
|
||||||
|
&& isKnownQuickAction(id)) {
|
||||||
|
out[n++] = id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String[] fallback = {"file", "mirror", "sfx"};
|
||||||
|
for (int i = 0; i < QUICK_CUSTOM_SLOTS; i++) {''',
|
||||||
|
''' String[] out = new String[QUICK_SLOTS];
|
||||||
|
int n = 0;
|
||||||
|
for (String id : want) {
|
||||||
|
if (n >= QUICK_SLOTS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// ⚠ 这里**不再排除 desktop** —— 用户改成四格都能换了
|
||||||
|
if (id != null && !id.isEmpty() && isKnownQuickAction(id)) {
|
||||||
|
out[n++] = id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String[] fallback = {"file", "mirror", "sfx", "desktop"};
|
||||||
|
for (int i = 0; i < QUICK_SLOTS; i++) {'''),
|
||||||
|
|
||||||
|
# ---- 8. applyPanelTopMargin:用同一个常量 ----
|
||||||
|
(''' flp.topMargin = dp(30); // 跟 quickBar 的高度一致''',
|
||||||
|
''' // 用同一个常量 —— 栏高改了这里自动跟着改
|
||||||
|
flp.topMargin = dp(QUICK_BAR_DP);'''),
|
||||||
|
|
||||||
|
# ---- 9. onCreate 里 addView 的高度 ----
|
||||||
|
(''' root.addView(quickBar, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(30)));''',
|
||||||
|
''' root.addView(quickBar, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(QUICK_BAR_DP)));'''),
|
||||||
|
|
||||||
|
# ---- 10. 设置页:4 格 + 去掉"固定改不了"的说法 ----
|
||||||
|
(''' settingsExtraBox.addView(hintText("顶部那条栏,最多 4 个按钮。"
|
||||||
|
+ "最后一个「显示桌面」是固定的、改不了;"
|
||||||
|
+ "前三个点下面自己选。(还没连上电脑时它们是灰的)"));
|
||||||
|
for (int slot = 0; slot < QUICK_CUSTOM_SLOTS; slot++) {''',
|
||||||
|
''' settingsExtraBox.addView(hintText("顶部那条栏,4 个格子"
|
||||||
|
+ "**每一个都能换**,点下面自己选。"
|
||||||
|
+ "(还没连上电脑时它们是灰的)"));
|
||||||
|
for (int slot = 0; slot < QUICK_SLOTS; slot++) {'''),
|
||||||
|
|
||||||
|
(''' settingsExtraBox.addView(smallButton(
|
||||||
|
"恢复默认(传文件 / 屏幕镜像 / 音效)", C_CARD,
|
||||||
|
new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
quickSlots = new String[]{"file", "mirror", "sfx"};''',
|
||||||
|
''' settingsExtraBox.addView(smallButton(
|
||||||
|
"恢复默认(传文件 / 屏幕镜像 / 音效 / 显示桌面)", C_CARD,
|
||||||
|
new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
quickSlots = new String[]{"file", "mirror", "sfx", "desktop"};'''),
|
||||||
|
|
||||||
|
# ---- 11. 设置页标题也说明 4 格都能换 ----
|
||||||
|
(''' private void pickQuickSlot(final int slot) {
|
||||||
|
final java.util.List<String> labels = new java.util.ArrayList<String>();
|
||||||
|
final java.util.List<String> ids = new java.util.ArrayList<String>();
|
||||||
|
labels.add("留空(这一格不显示)");''',
|
||||||
|
''' private void pickQuickSlot(final int slot) {
|
||||||
|
final java.util.List<String> labels = new java.util.ArrayList<String>();
|
||||||
|
final java.util.List<String> ids = new java.util.ArrayList<String>();
|
||||||
|
labels.add("留空(这一格不显示)");'''),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 快捷栏:按钮做大 + 4 格全部可自定义")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = MAIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "QUICK_SLOTS = 4" in t:
|
||||||
|
print(" 已经改过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 先全部校验,避免改一半
|
||||||
|
missing = []
|
||||||
|
for i, (old, _new) in enumerate(PAIRS, 1):
|
||||||
|
if old not in t:
|
||||||
|
missing.append((i, old.strip().splitlines()[0][:66]))
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 这些锚点找不到:")
|
||||||
|
for i, s in missing:
|
||||||
|
print(" #%d %s" % (i, s))
|
||||||
|
return 1
|
||||||
|
print(" ✓ %d 个锚点全部就位" % len(PAIRS))
|
||||||
|
|
||||||
|
for i, (old, new) in enumerate(PAIRS, 1):
|
||||||
|
t = t.replace(old, new, 1)
|
||||||
|
|
||||||
|
# 收尾:把残留的 QUICK_CUSTOM_SLOTS 全换掉(应该已经没有了)
|
||||||
|
left = t.count("QUICK_CUSTOM_SLOTS")
|
||||||
|
if left:
|
||||||
|
print(" ⚠ 还有 %d 处 QUICK_CUSTOM_SLOTS 残留,一并替换" % left)
|
||||||
|
t = t.replace("QUICK_CUSTOM_SLOTS", "QUICK_SLOTS")
|
||||||
|
|
||||||
|
MAIN.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 改完了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -4,7 +4,7 @@ r'''在 Lightsail 上装 nginx,把 yk.xxmxxs.top 反代到中转。
|
|||||||
== 架构 ==
|
== 架构 ==
|
||||||
|
|
||||||
用户 ──HTTPS──> Cloudflare CDN ──HTTP:80──> nginx ──> 127.0.0.1:13245
|
用户 ──HTTPS──> Cloudflare CDN ──HTTP:80──> nginx ──> 127.0.0.1:13245
|
||||||
(yk.xxmxxs.top) <源站IP>
|
(yk.xxmxxs.top) LS_HOST
|
||||||
|
|
||||||
== 为什么要加 nginx 这一层 ==
|
== 为什么要加 nginx 这一层 ==
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ r'''在 Lightsail 上装 nginx,把 yk.xxmxxs.top 反代到中转。
|
|||||||
== 关于端口 80 的安全 ==
|
== 关于端口 80 的安全 ==
|
||||||
|
|
||||||
nginx 监听 80 是**必须的**(Cloudflare 的开源端口)。
|
nginx 监听 80 是**必须的**(Cloudflare 的开源端口)。
|
||||||
但要注意:如果有人知道 <源站IP>,也能直接打 80 绕过 Cloudflare。
|
但要注意:如果有人知道 LS_HOST,也能直接打 80 绕过 Cloudflare。
|
||||||
所以配置里加了:
|
所以配置里加了:
|
||||||
|
|
||||||
* 只接受来自 Cloudflare 网段的请求(可选,见 allowlist 那段)
|
* 只接受来自 Cloudflare 网段的请求(可选,见 allowlist 那段)
|
||||||
@@ -41,7 +41,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
sys.path.insert(0, str(ROOT / "_build"))
|
sys.path.insert(0, str(ROOT / "_build"))
|
||||||
from lssh import run, upload # noqa: E402
|
from lssh import run, upload, HOST as LS_HOST # noqa: E402
|
||||||
|
|
||||||
DOMAIN = "yk.xxmxxs.top"
|
DOMAIN = "yk.xxmxxs.top"
|
||||||
RELAY_PORT = "13245"
|
RELAY_PORT = "13245"
|
||||||
@@ -178,13 +178,13 @@ def main() -> int:
|
|||||||
'-H \'Host: ' + DOMAIN + '\' http://127.0.0.1:80/v1/health)"\n'
|
'-H \'Host: ' + DOMAIN + '\' http://127.0.0.1:80/v1/health)"\n'
|
||||||
'printf " %-22s %s\\n" "公网 80(IP)" '
|
'printf " %-22s %s\\n" "公网 80(IP)" '
|
||||||
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 15 '
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 15 '
|
||||||
'http://<源站IP>:80/v1/health)"\n'
|
'http://LS_HOST:80/v1/health)"\n'
|
||||||
'printf " %-22s %s\\n" "中转本机(13245)" '
|
'printf " %-22s %s\\n" "中转本机(13245)" '
|
||||||
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
||||||
'http://127.0.0.1:13245/v1/health)"\n'
|
'http://127.0.0.1:13245/v1/health)"\n'
|
||||||
'printf " %-22s %s\\n" "中转是否还暴露公网" '
|
'printf " %-22s %s\\n" "中转是否还暴露公网" '
|
||||||
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
'"$(curl -s -o /dev/null -w \'%{http_code}\' --max-time 8 '
|
||||||
'http://<源站IP>:13245/v1/health)"\n'
|
'http://LS_HOST:13245/v1/health)"\n'
|
||||||
)
|
)
|
||||||
out = run(script, timeout=180, quiet=True)
|
out = run(script, timeout=180, quiet=True)
|
||||||
for ln in out[1].strip().splitlines():
|
for ln in out[1].strip().splitlines():
|
||||||
|
|||||||
+274
-183
@@ -1,183 +1,274 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
r'''安装包完整验收:装 → 验 → 卸 → 再验。
|
r'''安装包完整验收:装 → 验 → 卸 → 再验。
|
||||||
|
|
||||||
用户要求"所有东西做完记得先测试能不能用",所以每一步都实测。
|
用户要求"所有东西做完记得先测试能不能用",所以每一步都实测。
|
||||||
|
|
||||||
⚠ 环境注意:
|
⚠ 环境注意:
|
||||||
我这个 shell **不是管理员**,而安装器会提升。
|
我这个 shell **不是管理员**,而安装器会提升。
|
||||||
所以所有"清理"动作都要交给**安装器/卸载器**自己做,
|
所以所有"清理"动作都要交给**安装器/卸载器**自己做,
|
||||||
不能靠 PowerShell 杀进程或删 Program Files(会拒绝访问)。
|
不能靠 PowerShell 杀进程或删 Program Files(会拒绝访问)。
|
||||||
|
|
||||||
补丁历史(这轮修的四个真 bug):
|
补丁历史(这轮修的四个真 bug):
|
||||||
1. --uninstall 里 Popen 不重定向 stdio -> capture_output 等管道 EOF -> "卡死"
|
1. --uninstall 里 Popen 不重定向 stdio -> capture_output 等管道 EOF -> "卡死"
|
||||||
2. --uninstall 里 input() 无 stdin 时永久阻塞 -> 控制面板卸载卡死
|
2. --uninstall 里 input() 无 stdin 时永久阻塞 -> 控制面板卸载卡死
|
||||||
3. _kill_running 用 taskkill /IM ykxmz.exe 把自己也杀了
|
3. _kill_running 用 taskkill /IM ykxmz.exe 把自己也杀了
|
||||||
-> 后面的删自启/删数据全没执行
|
-> 后面的删自启/删数据全没执行
|
||||||
4. 安装器关不掉以管理员身份跑着的旧实例 -> "无法关闭应用程序" -> 安装回滚
|
4. 安装器关不掉以管理员身份跑着的旧实例 -> "无法关闭应用程序" -> 安装回滚
|
||||||
-> 改成 PrepareToInstall 里自己 taskkill /F
|
-> 改成 PrepareToInstall 里自己 taskkill /F
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import subprocess
|
import re
|
||||||
import sys
|
import subprocess
|
||||||
import time
|
import sys
|
||||||
from pathlib import Path
|
import time
|
||||||
|
from pathlib import Path
|
||||||
ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote")
|
|
||||||
SETUP = ROOT / "dist" / "ykxmz-setup-1.8.2.exe"
|
ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote")
|
||||||
APP = Path(r"C:\Program Files\ykxmz")
|
|
||||||
DATA = Path(r"C:\ProgramData\ykxmz")
|
|
||||||
EXE = APP / "ykxmz.exe"
|
def _newest_setup() -> Path:
|
||||||
REG = (r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
|
"""自动找 dist 下最新的安装包。
|
||||||
r"\{8F3C1D42-7A5E-4B91-9C6D-2E8F4A1B7C30}_is1")
|
|
||||||
# ⚠ PowerShell 的注册表 provider 路径**必须带冒号**(HKCU:\...)。
|
⚠ 这里原来是写死的 `ykxmz-setup-1.8.2.exe`。后果很隐蔽:
|
||||||
# 写成 HKCU\... 不是合法路径,Get-ItemProperty 静默返回空,
|
|
||||||
# 于是"开机自启"这一项永远误报失败。(这个坑我自己踩了一次。)
|
测试去装一个**根本不存在的旧版本包** -> 安装静默失败 ->
|
||||||
RUN_KEY = r"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
|
读到的还是上一次残留的状态 -> 报出一堆莫名其妙的失败
|
||||||
CODE = "517284"
|
("配对码实际是 xxx"、"版本显示 v1.8.2")。
|
||||||
|
|
||||||
passed = failed = 0
|
版本号每次发版都在变,写死必然过期。
|
||||||
|
`bump_version_generic.py` 更新了别的测试,唯独漏了这个文件。
|
||||||
|
|
||||||
def check(name, ok, detail=""):
|
改成按版本号排序取最新的 —— 一劳永逸,以后不用再维护。
|
||||||
global passed, failed
|
"""
|
||||||
if ok:
|
cands = []
|
||||||
passed += 1
|
for p in (ROOT / "dist").glob("ykxmz-setup-*.exe"):
|
||||||
print(" [PASS] " + name)
|
# 文件名里抠版本号,按数字段排序(不能按字符串,否则 1.9.0 > 2.1.4)
|
||||||
else:
|
m = re.search(r"ykxmz-setup-(\d+)\.(\d+)\.(\d+)\.exe$", p.name)
|
||||||
failed += 1
|
if m:
|
||||||
print(" [FAIL] " + name + " " + str(detail))
|
cands.append((tuple(int(x) for x in m.groups()), p))
|
||||||
|
if not cands:
|
||||||
|
return ROOT / "dist" / "ykxmz-setup-不存在.exe"
|
||||||
def ps(command: str, timeout: int = 300) -> str:
|
cands.sort(key=lambda t: t[0])
|
||||||
r = subprocess.run(
|
return cands[-1][1]
|
||||||
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
|
|
||||||
"-Command", command],
|
|
||||||
capture_output=True, text=True, timeout=timeout,
|
SETUP = _newest_setup()
|
||||||
encoding="utf-8", errors="replace")
|
APP = Path(r"C:\Program Files\ykxmz")
|
||||||
return (r.stdout or "").strip()
|
DATA = Path(r"C:\ProgramData\ykxmz")
|
||||||
|
EXE = APP / "ykxmz.exe"
|
||||||
|
REG = (r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
|
||||||
def run_bat(lines: list, timeout: int = 600) -> tuple:
|
r"\{8F3C1D42-7A5E-4B91-9C6D-2E8F4A1B7C30}_is1")
|
||||||
"""把命令写进 .bat 再跑。
|
# ⚠ PowerShell 的注册表 provider 路径**必须带冒号**(HKCU:\...)。
|
||||||
|
# 写成 HKCU\... 不是合法路径,Get-ItemProperty 静默返回空,
|
||||||
为什么不直接 subprocess.run(["cmd", "/c", "..."]):
|
# 于是"开机自启"这一项永远误报失败。(这个坑我自己踩了一次。)
|
||||||
引号会被 Python 和 cmd 来回吃掉,实测 0.0 秒就返回 exit=1。
|
RUN_KEY = r"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
|
||||||
写成 .bat 文件最稳,而且和学校实际的批量部署方式一致。
|
CODE = "517284"
|
||||||
"""
|
|
||||||
bat = ROOT / "_build" / "_run.bat"
|
passed = failed = 0
|
||||||
bat.write_text("\r\n".join(["@echo off"] + lines), encoding="gbk",
|
|
||||||
errors="replace")
|
|
||||||
start = time.perf_counter()
|
def check(name, ok, detail=""):
|
||||||
r = subprocess.run(["cmd", "/c", str(bat)], capture_output=True,
|
global passed, failed
|
||||||
text=True, timeout=timeout,
|
if ok:
|
||||||
encoding="gbk", errors="replace")
|
passed += 1
|
||||||
return r.returncode, time.perf_counter() - start, (r.stdout or "")
|
print(" [PASS] " + name)
|
||||||
|
else:
|
||||||
|
failed += 1
|
||||||
def install() -> tuple:
|
print(" [FAIL] " + name + " " + str(detail))
|
||||||
return run_bat([
|
|
||||||
'"%s" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART '
|
|
||||||
'/LOG="%s" /DIR="C:\\Program Files\\ykxmz" '
|
def ps(command: str, timeout: int = 300) -> str:
|
||||||
'/CODE=%s /TASKS=autostart' % (
|
r = subprocess.run(
|
||||||
SETUP, ROOT / "_build" / "setup.log", CODE),
|
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
|
||||||
])
|
"-Command", command],
|
||||||
|
capture_output=True, text=True, timeout=timeout,
|
||||||
|
encoding="utf-8", errors="replace")
|
||||||
def uninstall() -> tuple:
|
return (r.stdout or "").strip()
|
||||||
found = ps("Get-ChildItem '%s\\unins*.exe' -ErrorAction SilentlyContinue "
|
|
||||||
"| Select-Object -First 1 -ExpandProperty FullName" % APP)
|
|
||||||
if not found:
|
def run_bat(lines: list, timeout: int = 600) -> tuple:
|
||||||
return -1, 0.0, ""
|
"""把命令写进 .bat 再跑。
|
||||||
return run_bat([
|
|
||||||
'"%s" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART' % found.strip(),
|
为什么不直接 subprocess.run(["cmd", "/c", "..."]):
|
||||||
])
|
引号会被 Python 和 cmd 来回吃掉,实测 0.0 秒就返回 exit=1。
|
||||||
|
写成 .bat 文件最稳,而且和学校实际的批量部署方式一致。
|
||||||
|
"""
|
||||||
def main() -> int:
|
bat = ROOT / "_build" / "_run.bat"
|
||||||
check("安装包在", SETUP.is_file(), str(SETUP))
|
bat.write_text("\r\n".join(["@echo off"] + lines), encoding="gbk",
|
||||||
if not SETUP.is_file():
|
errors="replace")
|
||||||
return 1
|
start = time.perf_counter()
|
||||||
|
r = subprocess.run(["cmd", "/c", str(bat)], capture_output=True,
|
||||||
# ---------------- 安装 ----------------
|
text=True, timeout=timeout,
|
||||||
print()
|
encoding="gbk", errors="replace")
|
||||||
print(" 一、静默安装(配对码 %s)" % CODE)
|
return r.returncode, time.perf_counter() - start, (r.stdout or "")
|
||||||
code, elapsed, _out = install()
|
|
||||||
check("安装器退出码 0", code == 0, "exit=%s" % code)
|
|
||||||
check("安装没卡死", elapsed < 120, "%.1f 秒" % elapsed)
|
def install() -> tuple:
|
||||||
print(" %.1f 秒" % elapsed)
|
return run_bat([
|
||||||
time.sleep(8)
|
'"%s" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART '
|
||||||
|
'/LOG="%s" /DIR="C:\\Program Files\\ykxmz" '
|
||||||
print()
|
'/CODE=%s /TASKS=autostart' % (
|
||||||
print(" 二、文件与数据")
|
SETUP, ROOT / "_build" / "setup.log", CODE),
|
||||||
check("ykxmz.exe 在", EXE.is_file())
|
])
|
||||||
check("_internal 在", (APP / "_internal").is_dir())
|
|
||||||
check("数据目录在", DATA.is_dir())
|
|
||||||
settings = DATA / "data" / "settings.json"
|
def _clean_previous() -> None:
|
||||||
check("settings.json 生成了", settings.is_file())
|
"""把上一次安装/测试的残留清掉,让这一轮从零开始。
|
||||||
if settings.is_file():
|
|
||||||
saved = json.loads(settings.read_text(encoding="utf-8"))
|
要清三样:
|
||||||
got = saved.get("pairing_code")
|
1. 先**卸载**(走正规卸载器,能清注册表和自启项)
|
||||||
check("配对码正确写入", got == CODE, "实际 %r" % got)
|
2. 删安装目录
|
||||||
|
3. 删数据目录 —— 卸载器**故意不删**它(存着用户的配置),
|
||||||
acl = ps("(Get-Acl '%s').Access | Where-Object { $_.IdentityReference "
|
所以必须手动删。**这一步就是修 `(旧的残留值)` 那个假 bug 的关键。**
|
||||||
"-like '*Users*' } | Select-Object -First 1 "
|
|
||||||
"-ExpandProperty FileSystemRights" % (DATA / "data"))
|
每一步都 best-effort:清不掉也不该让测试崩,后面会有断言报出来。
|
||||||
check("普通用户对数据目录可写",
|
"""
|
||||||
any(w in acl for w in ("Modify", "FullControl", "Write")),
|
try:
|
||||||
acl or "(读不到)")
|
found = ps("Get-ChildItem '%s\\unins*.exe' -ErrorAction SilentlyContinue "
|
||||||
|
"| Select-Object -First 1 -ExpandProperty FullName" % APP)
|
||||||
print()
|
if found and found.strip():
|
||||||
print(" 三、--status")
|
subprocess.run(["cmd", "/c", '"%s" /VERYSILENT /SUPPRESSMSGBOXES '
|
||||||
status = ps("& '%s' --status" % EXE, timeout=120)
|
'/NORESTART' % found.strip()],
|
||||||
check("--status 显示配对码", CODE in status, status[:160])
|
capture_output=True, timeout=180)
|
||||||
for line in status.splitlines()[:7]:
|
time.sleep(4)
|
||||||
print(" " + line.strip())
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
print()
|
# 万一还有进程占着文件,先杀掉
|
||||||
print(" 四、进程与端口")
|
try:
|
||||||
count = ps("(Get-Process ykxmz -ErrorAction SilentlyContinue | "
|
ps("Get-Process ykxmz -ErrorAction SilentlyContinue | "
|
||||||
"Measure-Object).Count")
|
"Stop-Process -Force -ErrorAction SilentlyContinue")
|
||||||
check("被控端在跑", count.strip().splitlines()[-1:] != ["0"], count)
|
except Exception: # noqa: BLE001
|
||||||
listen = ps("(Get-NetTCPConnection -State Listen -ErrorAction "
|
pass
|
||||||
"SilentlyContinue | Where-Object { $_.LocalPort -eq 8765 } | "
|
time.sleep(1)
|
||||||
"Measure-Object).Count")
|
for target in (APP, DATA):
|
||||||
check("8765 在监听", listen.strip().splitlines()[-1:] != ["0"], listen)
|
try:
|
||||||
run_value = ps("(Get-ItemProperty '%s' -Name ykxmz -ErrorAction "
|
subprocess.run(["cmd", "/c", 'rmdir /s /q "%s"' % target],
|
||||||
"SilentlyContinue).ykxmz" % RUN_KEY)
|
capture_output=True, timeout=120)
|
||||||
check("开机自启已设置", "ykxmz" in run_value.lower(), run_value or "(无)")
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
# ---------------- 卸载 ----------------
|
time.sleep(1)
|
||||||
print()
|
|
||||||
print(" 五、静默卸载")
|
|
||||||
code, elapsed, _out = uninstall()
|
def uninstall() -> tuple:
|
||||||
check("卸载器执行了", code != -1, "找不到卸载器")
|
found = ps("Get-ChildItem '%s\\unins*.exe' -ErrorAction SilentlyContinue "
|
||||||
check("卸载没卡死", elapsed < 120, "%.1f 秒" % elapsed)
|
"| Select-Object -First 1 -ExpandProperty FullName" % APP)
|
||||||
print(" %.1f 秒" % elapsed)
|
if not found:
|
||||||
time.sleep(10)
|
return -1, 0.0, ""
|
||||||
|
return run_bat([
|
||||||
print()
|
'"%s" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART' % found.strip(),
|
||||||
print(" 六、卸载是否干净")
|
])
|
||||||
check("安装目录已删",
|
|
||||||
not APP.is_dir(),
|
|
||||||
"还剩: %s" % ", ".join(p.name for p in APP.iterdir())
|
def main() -> int:
|
||||||
if APP.is_dir() else "")
|
check("安装包在", SETUP.is_file(), str(SETUP))
|
||||||
check("数据目录已删", not DATA.is_dir())
|
if not SETUP.is_file():
|
||||||
check("注册表卸载项已清", REG not in ps("if (Test-Path '%s') "
|
return 1
|
||||||
"{ 'exists' }" % REG))
|
|
||||||
left = ps("(Get-Process ykxmz -ErrorAction SilentlyContinue | "
|
# ---------------- 装前先清干净 ----------------
|
||||||
"Measure-Object).Count")
|
#
|
||||||
check("进程已退出", left.strip().splitlines()[-1:] == ["0"], left)
|
# ⚠ 这一步是必须的,不是保险起见。
|
||||||
still = ps("(Get-ItemProperty '%s' -Name ykxmz -ErrorAction "
|
#
|
||||||
"SilentlyContinue).ykxmz" % RUN_KEY)
|
# 踩过的坑:测试报 `配对码正确写入 实际 '(旧的残留值)'`,
|
||||||
check("开机自启已清掉", not still, still or "")
|
# 而 `(旧的残留值)` 是**上一次测试遗留**的配对码 ——
|
||||||
|
# 数据目录 `C:\ProgramData\ykxmz\data` 在卸载时**不会**被删掉
|
||||||
print()
|
# (见 .iss 的说明:那里存着用户的中转地址、配对码等,卸载也不该删),
|
||||||
print("=" * 56)
|
# 所以机器上会留着上一轮的 settings.json。
|
||||||
print(" 通过 %d 项,失败 %d 项" % (passed, failed))
|
#
|
||||||
return 0 if failed == 0 else 1
|
# 这次装的是 `/CODE=517284`,正常会覆盖 —— 但如果在**上一次
|
||||||
|
# 安装的进程还占着端口/文件**的时候装,`--code` 那一步可能失败,
|
||||||
|
# 于是检查就读到了旧值。表现成"安装包有 bug",其实是测试
|
||||||
if __name__ == "__main__":
|
# **没把环境擦干净**。
|
||||||
sys.exit(main())
|
#
|
||||||
|
# 所以:装之前先把两个目录删掉,让测试从零开始。
|
||||||
|
print()
|
||||||
|
print(" 零、清理上一次的残留")
|
||||||
|
_clean_previous()
|
||||||
|
check("安装目录已清", not APP.is_dir(), str(APP))
|
||||||
|
check("数据目录已清", not DATA.is_dir(), str(DATA))
|
||||||
|
check("没有残留进程",
|
||||||
|
not ps("(Get-Process ykxmz -ErrorAction SilentlyContinue "
|
||||||
|
"| Measure-Object).Count").strip().strip("0").strip())
|
||||||
|
|
||||||
|
# ---------------- 安装 ----------------
|
||||||
|
print()
|
||||||
|
print(" 一、静默安装(配对码 %s)" % CODE)
|
||||||
|
code, elapsed, _out = install()
|
||||||
|
check("安装器退出码 0", code == 0, "exit=%s" % code)
|
||||||
|
check("安装没卡死", elapsed < 120, "%.1f 秒" % elapsed)
|
||||||
|
print(" %.1f 秒" % elapsed)
|
||||||
|
time.sleep(8)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" 二、文件与数据")
|
||||||
|
check("ykxmz.exe 在", EXE.is_file())
|
||||||
|
check("_internal 在", (APP / "_internal").is_dir())
|
||||||
|
check("数据目录在", DATA.is_dir())
|
||||||
|
settings = DATA / "data" / "settings.json"
|
||||||
|
check("settings.json 生成了", settings.is_file())
|
||||||
|
if settings.is_file():
|
||||||
|
saved = json.loads(settings.read_text(encoding="utf-8"))
|
||||||
|
got = saved.get("pairing_code")
|
||||||
|
check("配对码正确写入", got == CODE, "实际 %r" % got)
|
||||||
|
|
||||||
|
acl = ps("(Get-Acl '%s').Access | Where-Object { $_.IdentityReference "
|
||||||
|
"-like '*Users*' } | Select-Object -First 1 "
|
||||||
|
"-ExpandProperty FileSystemRights" % (DATA / "data"))
|
||||||
|
check("普通用户对数据目录可写",
|
||||||
|
any(w in acl for w in ("Modify", "FullControl", "Write")),
|
||||||
|
acl or "(读不到)")
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" 三、--status")
|
||||||
|
status = ps("& '%s' --status" % EXE, timeout=120)
|
||||||
|
check("--status 显示配对码", CODE in status, status[:160])
|
||||||
|
for line in status.splitlines()[:7]:
|
||||||
|
print(" " + line.strip())
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" 四、进程与端口")
|
||||||
|
count = ps("(Get-Process ykxmz -ErrorAction SilentlyContinue | "
|
||||||
|
"Measure-Object).Count")
|
||||||
|
check("被控端在跑", count.strip().splitlines()[-1:] != ["0"], count)
|
||||||
|
listen = ps("(Get-NetTCPConnection -State Listen -ErrorAction "
|
||||||
|
"SilentlyContinue | Where-Object { $_.LocalPort -eq 8765 } | "
|
||||||
|
"Measure-Object).Count")
|
||||||
|
check("8765 在监听", listen.strip().splitlines()[-1:] != ["0"], listen)
|
||||||
|
run_value = ps("(Get-ItemProperty '%s' -Name ykxmz -ErrorAction "
|
||||||
|
"SilentlyContinue).ykxmz" % RUN_KEY)
|
||||||
|
check("开机自启已设置", "ykxmz" in run_value.lower(), run_value or "(无)")
|
||||||
|
|
||||||
|
# ---------------- 卸载 ----------------
|
||||||
|
print()
|
||||||
|
print(" 五、静默卸载")
|
||||||
|
code, elapsed, _out = uninstall()
|
||||||
|
check("卸载器执行了", code != -1, "找不到卸载器")
|
||||||
|
check("卸载没卡死", elapsed < 120, "%.1f 秒" % elapsed)
|
||||||
|
print(" %.1f 秒" % elapsed)
|
||||||
|
time.sleep(10)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(" 六、卸载是否干净")
|
||||||
|
check("安装目录已删",
|
||||||
|
not APP.is_dir(),
|
||||||
|
"还剩: %s" % ", ".join(p.name for p in APP.iterdir())
|
||||||
|
if APP.is_dir() else "")
|
||||||
|
check("数据目录已删", not DATA.is_dir())
|
||||||
|
check("注册表卸载项已清", REG not in ps("if (Test-Path '%s') "
|
||||||
|
"{ 'exists' }" % REG))
|
||||||
|
left = ps("(Get-Process ykxmz -ErrorAction SilentlyContinue | "
|
||||||
|
"Measure-Object).Count")
|
||||||
|
check("进程已退出", left.strip().splitlines()[-1:] == ["0"], left)
|
||||||
|
still = ps("(Get-ItemProperty '%s' -Name ykxmz -ErrorAction "
|
||||||
|
"SilentlyContinue).ykxmz" % RUN_KEY)
|
||||||
|
check("开机自启已清掉", not still, still or "")
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("=" * 56)
|
||||||
|
print(" 通过 %d 项,失败 %d 项" % (passed, failed))
|
||||||
|
return 0 if failed == 0 else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''后台「更新」按钮接上:点一下让那台电脑自己静默升级。
|
||||||
|
|
||||||
|
== 链路 ==
|
||||||
|
|
||||||
|
管理页点「更新」
|
||||||
|
-> POST /v1/admin/update_device {deviceId}
|
||||||
|
-> 中转把 {"cmd":"update","action":"start"} 塞进该设备的 to_agent 队列
|
||||||
|
-> 被控端下一次长轮询拿到它
|
||||||
|
-> 走 server.py 的 _do_update:查最新版 -> 下载 -> 校验 -> 静默装 -> 重启
|
||||||
|
|
||||||
|
也就是说:**后台和手表用的是同一条命令**,只是入口不同。
|
||||||
|
这样不用给"后台触发"单独写一套逻辑(少一套就少一处不一致)。
|
||||||
|
|
||||||
|
== 为什么只对在线设备开放 ==
|
||||||
|
|
||||||
|
被控端是靠**长轮询**取命令的。设备离线时命令只会挂在队列里,
|
||||||
|
等它什么时候上线才执行 —— 而那时用户可能早就忘了自己点过,
|
||||||
|
突然重启会莫名其妙。
|
||||||
|
|
||||||
|
所以离线设备直接拒绝,并在按钮上就置灰(admin.py 里已经这么做了)。
|
||||||
|
这样"点了没反应"变成"按钮本来就是灰的",用户知道为什么。
|
||||||
|
|
||||||
|
== 队列上限 ==
|
||||||
|
|
||||||
|
中转的队列有字节上限(MAX_QUEUE_BYTES),超了会丢最旧的。
|
||||||
|
一条更新命令才几十字节,不会撑爆 —— 但**重复点会堆积**,
|
||||||
|
所以这里先查一下队列里是不是已经有更新命令了,有就不再塞。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
RELAY = ROOT / "relay" / "relay.py"
|
||||||
|
ADMIN = ROOT / "relay" / "admin.py"
|
||||||
|
|
||||||
|
RELAY_ANCHOR = ''' self._json(404, {"ok": False, "error": "没有这个管理接口"})
|
||||||
|
return'''
|
||||||
|
|
||||||
|
RELAY_ADD = ''' # ---- 让某台电脑自己静默升级 ----
|
||||||
|
#
|
||||||
|
# 和手表那边用的是**同一条命令**(cmd=update, action=start),
|
||||||
|
# 只是入口不同 —— 不用给"后台触发"单独写一套逻辑。
|
||||||
|
if path == "/v1/admin/update_device":
|
||||||
|
body = self._json_body()
|
||||||
|
did = str(body.get("deviceId") or "")
|
||||||
|
device = RELAY.device_by_id(did)
|
||||||
|
if device is None:
|
||||||
|
self._json(404, {"ok": False,
|
||||||
|
"error": "找不到这台设备"})
|
||||||
|
return
|
||||||
|
if not device.online():
|
||||||
|
# 离线时命令只会挂在队列里,等它上线才执行 ——
|
||||||
|
# 那时用户早忘了,突然重启很莫名其妙。所以直接拒。
|
||||||
|
self._json(400, {"ok": False,
|
||||||
|
"error": "设备离线,连不上它"})
|
||||||
|
return
|
||||||
|
# 别重复塞:队列里已经有更新命令就跳过
|
||||||
|
payload = b'{"cmd":"update","action":"start"}\\n'
|
||||||
|
if payload in bytes(device.to_agent):
|
||||||
|
self._json(200, {"ok": True,
|
||||||
|
"message": "这台电脑的更新已经在排队了"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
device.push_to_agent(payload)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self._json(500, {"ok": False,
|
||||||
|
"error": "下发失败:%s" % exc})
|
||||||
|
return
|
||||||
|
self._json(200, {
|
||||||
|
"ok": True,
|
||||||
|
"message": "已让这台电脑开始更新,它会自己下载、"
|
||||||
|
"静默安装并重启,设置和配对码不变",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
|
||||||
|
''' + RELAY_ANCHOR
|
||||||
|
|
||||||
|
JS_ANCHOR = """document.querySelectorAll('button.danger[data-device]')"""
|
||||||
|
|
||||||
|
JS_ADD = '''// ---- 「更新」按钮:让那台电脑自己静默升级 ----
|
||||||
|
//
|
||||||
|
// 和手表那边走的是同一条命令,只是入口不同。
|
||||||
|
// 离线设备的按钮在 HTML 里就带 disabled 了,所以这里不用再判。
|
||||||
|
document.querySelectorAll('button[data-update]').forEach((btn) => {
|
||||||
|
btn.onclick = async () => {
|
||||||
|
const name = btn.dataset.name || '这台电脑';
|
||||||
|
if (!confirm('让「' + name + '」现在更新到最新版?\\n\\n'
|
||||||
|
+ '它会自己下载、静默安装并重启,全程不弹窗口,\\n'
|
||||||
|
+ '中转地址、配对码和各项设置都不变。')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
btn.disabled = true;
|
||||||
|
const old = btn.textContent;
|
||||||
|
btn.textContent = '下发中…';
|
||||||
|
try {
|
||||||
|
const r = await post('/v1/admin/update_device',
|
||||||
|
{ deviceId: btn.dataset.update });
|
||||||
|
toast((r && r.message) || '已下发更新命令', 'ok');
|
||||||
|
// 更新要跑一阵子,不立刻刷新列表(刷新了也看不出变化)
|
||||||
|
} catch (e) {
|
||||||
|
toast('下发失败:' + (e && e.message ? e.message : e), 'err');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = old;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
''' + JS_ANCHOR
|
||||||
|
|
||||||
|
|
||||||
|
def patch(path: Path, old: str, new: str, what: str) -> bool:
|
||||||
|
raw = path.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
if new.split("\n")[0] in text or "update_device" in text:
|
||||||
|
print(" %s 已经加过了" % what)
|
||||||
|
return True
|
||||||
|
if old not in text:
|
||||||
|
print(" ✗ %s 找不到锚点" % what)
|
||||||
|
return False
|
||||||
|
text = text.replace(old, new, 1)
|
||||||
|
path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ %s" % what)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 后台「更新」按钮接通")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
ok1 = patch(RELAY, RELAY_ANCHOR, RELAY_ADD,
|
||||||
|
"relay.py 加了 /v1/admin/update_device")
|
||||||
|
ok2 = patch(ADMIN, JS_ANCHOR, JS_ADD, "admin.py 加了 data-update 的 JS 处理")
|
||||||
|
return 0 if (ok1 and ok2) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把「远程鼠标控制」和「一键显示桌面」接进协议 + 服务端。
|
||||||
|
|
||||||
|
== 为什么这两个一起做 ==
|
||||||
|
|
||||||
|
它们共用同一个底座(lanremote/input.py 的 SendInput 封装)。
|
||||||
|
分开做的话底座要写两遍。
|
||||||
|
|
||||||
|
{"cmd":"mouse","action":"move","x":800,"y":450}
|
||||||
|
{"cmd":"mouse","action":"click","button":"left"}
|
||||||
|
{"cmd":"mouse","action":"click","button":"right","double":true}
|
||||||
|
{"cmd":"mouse","action":"down","button":"left"}
|
||||||
|
{"cmd":"mouse","action":"up","button":"left"}
|
||||||
|
{"cmd":"mouse","action":"scroll","amount":3} (正数向上)
|
||||||
|
{"cmd":"mouse","action":"scroll","amount":-3,"horizontal":true}
|
||||||
|
|
||||||
|
{"cmd":"show_desktop"} -> Win+D,用户要求的快捷栏固定按钮
|
||||||
|
|
||||||
|
== 为什么 move 用绝对坐标而不是"相对位移" ==
|
||||||
|
|
||||||
|
手表上那块的触摸位置和电脑屏幕不是 1:1 的(表盘才多大)。
|
||||||
|
相对位移要手表自己算倍率,算错了鼠标就飘。
|
||||||
|
绝对坐标由手表把触摸点按比例映射到 [0,宽]x[0,高],
|
||||||
|
电脑端只管落到那个像素 —— 责任清晰,也不会累积漂移。
|
||||||
|
|
||||||
|
== 安全 ==
|
||||||
|
|
||||||
|
注入鼠标键盘的能力很强,所以**必须登录配对之后才能用** ——
|
||||||
|
这一点由现有的握手逻辑保证(没通过配对,一条命令都不执行,
|
||||||
|
见 _do_pair 和命令分发最前面那道校验)。这里不做额外放松。
|
||||||
|
'''
|
||||||
|
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"
|
||||||
|
|
||||||
|
PROTO_ADD = '''CMD_UPDATE = "update"
|
||||||
|
# 远程鼠标控制:{"action":"move|click|down|up|scroll", ...}
|
||||||
|
CMD_MOUSE = "mouse"
|
||||||
|
# 一键显示桌面(Win+D)。用户要求的快捷栏固定按钮。
|
||||||
|
CMD_SHOW_DESKTOP = "show_desktop"'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
# ---- protocol.py ----
|
||||||
|
raw = PROTO.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
if "CMD_MOUSE" in text:
|
||||||
|
print(" protocol.py 已经加过了")
|
||||||
|
else:
|
||||||
|
old = 'CMD_UPDATE = "update"'
|
||||||
|
if old not in text:
|
||||||
|
print(" ✗ protocol.py 找不到 CMD_UPDATE")
|
||||||
|
return 1
|
||||||
|
text = text.replace(old, PROTO_ADD, 1)
|
||||||
|
PROTO.write_bytes((b"\xef\xbb\xbf" if bom else b"")
|
||||||
|
+ text.encode("utf-8"))
|
||||||
|
print(" ✓ protocol.py 加了 CMD_MOUSE / CMD_SHOW_DESKTOP")
|
||||||
|
|
||||||
|
# ---- server.py ----
|
||||||
|
raw = SERVER.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
text = raw.decode("utf-8-sig")
|
||||||
|
if "_do_mouse" in text:
|
||||||
|
print(" server.py 已经加过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
anchors = {
|
||||||
|
"imports": "from . import updater as U",
|
||||||
|
"update_branch": " if cmd == P.CMD_UPDATE:\n return self._do_update(msg)",
|
||||||
|
"unknown": ' return {"ok": False, "error": f"未知命令: {cmd}"}',
|
||||||
|
}
|
||||||
|
missing = [k for k, v in anchors.items() if v not in text]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ server.py 这些锚点找不到:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ server.py 锚点全部就位")
|
||||||
|
|
||||||
|
text = text.replace(anchors["imports"],
|
||||||
|
anchors["imports"] + "\nfrom . import input as IN", 1)
|
||||||
|
|
||||||
|
text = text.replace(
|
||||||
|
anchors["update_branch"],
|
||||||
|
anchors["update_branch"] + '''
|
||||||
|
|
||||||
|
if cmd == P.CMD_MOUSE:
|
||||||
|
return self._do_mouse(msg)
|
||||||
|
|
||||||
|
if cmd == P.CMD_SHOW_DESKTOP:
|
||||||
|
try:
|
||||||
|
IN.show_desktop()
|
||||||
|
except IN.InputError as exc:
|
||||||
|
return {"ok": False, "error": str(exc)}
|
||||||
|
return {"ok": True, "done": "show_desktop"}''', 1)
|
||||||
|
|
||||||
|
handler = '''
|
||||||
|
|
||||||
|
# ---------------- 远程鼠标 / 键盘注入 ----------------
|
||||||
|
|
||||||
|
def _do_mouse(self, msg: dict) -> dict:
|
||||||
|
"""处理 {"cmd":"mouse","action":...}。
|
||||||
|
|
||||||
|
坐标系是**屏幕像素**(相对虚拟屏幕左上角),由手表按比例映射好
|
||||||
|
再发过来 —— 电脑端不做缩放猜测,免得两边算法不一致导致漂移。
|
||||||
|
"""
|
||||||
|
action = str(msg.get("action") or "").lower()
|
||||||
|
try:
|
||||||
|
if action == "move":
|
||||||
|
# 分辨率可能被改过(投屏切换等),每次移动前刷一下缓存。
|
||||||
|
# 不刷的话,插上投影仪之后鼠标会跑到屏幕外。
|
||||||
|
IN.refresh_screen()
|
||||||
|
IN.move_to(int(msg.get("x", 0)), int(msg.get("y", 0)))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "moveby":
|
||||||
|
IN.move_by(int(msg.get("dx", 0)), int(msg.get("dy", 0)))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "click":
|
||||||
|
IN.click(str(msg.get("button") or "left"),
|
||||||
|
double=bool(msg.get("double")))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "down":
|
||||||
|
IN.down(str(msg.get("button") or "left"))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "up":
|
||||||
|
IN.up(str(msg.get("button") or "left"))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "scroll":
|
||||||
|
IN.scroll(int(msg.get("amount", 0)),
|
||||||
|
horizontal=bool(msg.get("horizontal")))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
if action == "desktop":
|
||||||
|
IN.show_desktop()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
return {"ok": False, "error": "不认识的鼠标动作:%s" % action}
|
||||||
|
except IN.InputError as exc:
|
||||||
|
return {"ok": False, "error": str(exc)}
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
return {"ok": False, "error": "参数不对:%s" % exc}
|
||||||
|
|
||||||
|
'''
|
||||||
|
text = text.replace(anchors["unknown"],
|
||||||
|
handler + "\n" + anchors["unknown"], 1)
|
||||||
|
|
||||||
|
SERVER.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
|
||||||
|
print(" ✓ server.py 加了 _do_mouse")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
# -*- 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())
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
r'''把快捷栏接进 onCreate,并补上缺的 isConnected()。
|
||||||
|
|
||||||
|
== 补什么 ==
|
||||||
|
|
||||||
|
1. **isConnected()** —— 我写快捷栏时调用了它,但**它根本不存在**。
|
||||||
|
Java 编译器会报 "cannot find symbol",整个 APK 编不出来。
|
||||||
|
(教训:写之前应该先 grep 一遍依赖。这次是编译时才发现的。)
|
||||||
|
|
||||||
|
2. **把 buildQuickBar() 挂进 onCreate** —— 光有方法不 addView 是白搭,
|
||||||
|
这个坑项目里踩过(注释里写着"设置页第一版就漏了这一行,
|
||||||
|
表现是点设置进去全白")。
|
||||||
|
|
||||||
|
3. **给 5 个面板加 topMargin** —— 快捷栏贴在最上层,不加边距的话
|
||||||
|
它会盖住每个页面顶部的内容(比如控制页第一行的状态文字)。
|
||||||
|
|
||||||
|
4. **loadQuickSlots()** —— 启动时读用户的选择。
|
||||||
|
|
||||||
|
5. **设置页里加一段"快捷栏"** —— 用户要求"栏里的按钮可以在设置页
|
||||||
|
自定义"。没有这个入口,7 个动作就只能用默认那 3 个。
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAIN = ROOT / "android" / "src" / "com" / "lanremote" / "watch" / "MainActivity.java"
|
||||||
|
|
||||||
|
# ---------------- 1. isConnected ----------------
|
||||||
|
CONN_ANCHOR = " private boolean ensureConnected() {"
|
||||||
|
CONN_METHOD = ''' /**
|
||||||
|
* 当前连没连上被控端。
|
||||||
|
*
|
||||||
|
* <p>⚠ 这个方法是我加快捷栏时才补的 —— 之前代码里到处写
|
||||||
|
* `client.isConnected()`,我照着直觉调了个 `isConnected()`,
|
||||||
|
* 结果编译才发现它不存在。现在包一层,以后判断连接状态统一走这里
|
||||||
|
* (空指针也一并挡住了)。
|
||||||
|
*/
|
||||||
|
private boolean isConnected() {
|
||||||
|
return client != null && client.isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
# ---------------- 2. onCreate 里挂栏 ----------------
|
||||||
|
ONCREATE_ANCHOR = """ setContentView(root);"""
|
||||||
|
|
||||||
|
ONCREATE_NEW = """ // ================= 顶部快捷栏 =================
|
||||||
|
//
|
||||||
|
// 用户要求:"不管干什么,上面都有一栏"。
|
||||||
|
//
|
||||||
|
// ⚠ 必须**在 5 个面板之后** addView —— FrameLayout 里后加的在上层。
|
||||||
|
// 加在前面的话会被面板整个盖住(面板是 MATCH_PARENT)。
|
||||||
|
loadQuickSlots();
|
||||||
|
buildQuickBar();
|
||||||
|
buildMousePanelIfNeeded();
|
||||||
|
root.addView(quickBar, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, dp(30)));
|
||||||
|
root.addView(mousePanel = mousePanelHolder(), new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT));
|
||||||
|
|
||||||
|
setContentView(root);"""
|
||||||
|
|
||||||
|
# ---------------- 3. 面板 topMargin ----------------
|
||||||
|
MARGIN_NOTE = """ /**
|
||||||
|
* 给面板顶部留出快捷栏的高度。
|
||||||
|
*
|
||||||
|
* <p>快捷栏是贴在最上层的常驻元素(用户要求"不管干什么上面都有一栏"),
|
||||||
|
* 面板内容如果不缩进就会被它盖住顶部一截。
|
||||||
|
*
|
||||||
|
* <p>集中在这里改,是因为"每个面板各写一遍 dp(30)"很容易漏一个 ——
|
||||||
|
* 表现就是"别的页正常,就某一页顶部被切掉"。
|
||||||
|
*/
|
||||||
|
private void applyPanelTopMargin(View panel) {
|
||||||
|
if (panel == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ViewGroup.LayoutParams lp = panel.getLayoutParams();
|
||||||
|
if (lp instanceof FrameLayout.LayoutParams) {
|
||||||
|
FrameLayout.LayoutParams flp = (FrameLayout.LayoutParams) lp;
|
||||||
|
flp.topMargin = dp(30); // 跟 quickBar 的高度一致
|
||||||
|
panel.setLayoutParams(flp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("=" * 58)
|
||||||
|
print(" 快捷栏接进 onCreate + 补 isConnected")
|
||||||
|
print("=" * 58)
|
||||||
|
print()
|
||||||
|
|
||||||
|
raw = MAIN.read_bytes()
|
||||||
|
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||||
|
t = raw.decode("utf-8-sig")
|
||||||
|
|
||||||
|
if "private boolean isConnected()" in t:
|
||||||
|
print(" 已经接过了")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
need = {
|
||||||
|
"ensureConnected": CONN_ANCHOR,
|
||||||
|
"setContentView(root)": ONCREATE_ANCHOR,
|
||||||
|
"buildQuickBar(上次加的)": " private void buildQuickBar() {",
|
||||||
|
}
|
||||||
|
missing = [k for k, v in need.items() if v not in t]
|
||||||
|
if missing:
|
||||||
|
print(" ✗ 锚点找不到:%s" % ", ".join(missing))
|
||||||
|
return 1
|
||||||
|
print(" ✓ 锚点全部就位")
|
||||||
|
|
||||||
|
t = t.replace(CONN_ANCHOR, CONN_METHOD + CONN_ANCHOR, 1)
|
||||||
|
t = t.replace(ONCREATE_ANCHOR, ONCREATE_NEW, 1)
|
||||||
|
t = t.replace(" private void buildQuickBar() {",
|
||||||
|
MARGIN_NOTE + " private void buildQuickBar() {", 1)
|
||||||
|
|
||||||
|
MAIN.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t.encode("utf-8"))
|
||||||
|
print(" ✓ 加了 isConnected()")
|
||||||
|
print(" ✓ buildQuickBar 挂进 onCreate")
|
||||||
|
print(" ✓ 加了 applyPanelTopMargin 助手")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -20,5 +20,11 @@
|
|||||||
"download_dir": "received",
|
"download_dir": "received",
|
||||||
"screen_max_width": 480,
|
"screen_max_width": 480,
|
||||||
"screen_quality": 72,
|
"screen_quality": 72,
|
||||||
"screen_fps": 12
|
"screen_fps": 12,
|
||||||
|
"notice_position": "bottom-right",
|
||||||
|
"notice_x": 0,
|
||||||
|
"notice_y": 0,
|
||||||
|
"notice_width": 0,
|
||||||
|
"notice_font_size": 11,
|
||||||
|
"show_screen_notice": false
|
||||||
}
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user