feat(extension): 插件配置集中管理 + 桌面端策略安装 + 跨网下载修复
- 后端:sys_config 存插件配置(识别前缀/生效站点/模板),平台管理员 GET/PUT /api/web/admin/extension; 插件读取 GET /api/web/extension/config(Redis 缓存 1 小时,保存即失效) - 前端:平台管理 → 插件配置页(只维护前缀,单号正则由服务端生成) - 插件:改为只拉取执行(每 5 分钟 + 手动同步),移除规则编辑/试跑/导入导出;安装包地址自动取最新发布 - 桌面端:工具 → 安装/卸载谷歌插件(生成 .reg + reg import 写 HKLM 策略,读注册表验证); 跨网下载改走云端中转;局域网探测补排障日志;自动更新按包类型取 md5Exe/sizeExe - 发布:npm run extension:publish(crx + updates.xml)、extension:zip(商店上传包), nginx 对 /download/extension/updates.xml 关缓存 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
4586fe5217
commit
11ebb33966
7
.gitignore
vendored
7
.gitignore
vendored
@ -1,4 +1,4 @@
|
||||
# ============================================================
|
||||
# ============================================================
|
||||
# 仓库根忽略规则(backend / frontend / extension 通用)
|
||||
# 只在这一处维护;各子项目不必再各写一份(不带斜杠的规则对任意层级都生效)
|
||||
# ============================================================
|
||||
@ -93,3 +93,8 @@ desktop/native/ffmpeg/*.exe
|
||||
|
||||
# ---------- 调试用的视频拆帧产物(video_split/frame_*.jpg,别提交) ----------
|
||||
video_split/
|
||||
|
||||
# Chrome 插件打包产物(.crx / updates.xml,由 npm run extension:build 生成)
|
||||
extension/out/
|
||||
# 注意:extension/keys/key.pem **是入库的**(决定扩展 ID,丢了就换 ID)。
|
||||
# 它绝不能随安装包发给客户 —— desktop/YuncangTrace.LocalService.csproj 已显式排除 keys\ 与 out\。
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# 云仓视频溯源系统(pack-service)
|
||||
# 云仓视频溯源系统(pack-service)
|
||||
|
||||
> 中文名(前端页面/邮件里显示的那个)在 **`config.siteName`** 里,默认「云仓视频溯源系统」,可用环境变量 `SITE_NAME` 覆盖 ——
|
||||
> 要改名只改这一处(邮件用 `app.config.siteName`)。
|
||||
@ -37,6 +37,8 @@ packService/backend
|
||||
│ │ │ ├── admin_member.js # /api/web/admin/members[/:id]、/me 平台管理员名单(❗需平台管理员)
|
||||
│ │ │ ├── admin_subject.js # /api/web/admin/subjects[/:id] 所有主体 + 改授权到期时间
|
||||
│ │ │ ├── admin_order.js # /api/web/admin/orders[/:orderNo/confirm] 所有订单 + 确认订单
|
||||
│ │ │ ├── admin_extension.js # /api/web/admin/extension Chrome 插件集中配置(❗需平台管理员)
|
||||
│ │ │ ├── extension.js # /api/web/extension/config 插件读取的配置(公开只读,无令牌)
|
||||
│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口(仅非生产环境注册)
|
||||
│ │ ├── internal/ # 运维/内部(❗需内部令牌,挂在 middleware.internalAuth() 后面)
|
||||
│ │ │ ├── user.js # /api/users* 用户 CRUD(含缓存)
|
||||
@ -218,7 +220,7 @@ npm run db:deploy:prod # 基线表 + 全部未执行迁移(幂等,可反
|
||||
├── frontend.prev/ # 上一版前端(回退用)
|
||||
├── download/ # 安装包分发(nginx 直接托管)
|
||||
│ ├── version.json # 桌面端版本信息(不缓存,客户端写死这个地址)
|
||||
│ ├── desktop/ # 桌面端 MSI(长缓存)
|
||||
│ ├── desktop/ # 桌面端 MSI + EXE(长缓存)
|
||||
│ └── android_client/ # Android APK + version.json
|
||||
├── shared-config/ # 服务端私有配置(不随发布包走)
|
||||
│ └── env.prod.sh # 启动前 source 的环境变量
|
||||
@ -291,6 +293,10 @@ npm run db:deploy:prod # 基线表 + 全部未执行迁移(幂等,可反
|
||||
|
||||
发布说明:
|
||||
|
||||
> ⚠️ `npm run deploy` **只发后端 + 前端 + nginx**:桌面端安装包(`npm run desktop:publish`)和
|
||||
> Chrome 插件(`npm run extension:publish`)是**两条独立命令**,不会跟着 deploy 走。
|
||||
> 三者的远端目录互不重叠(`/download/desktop/`、`/download/extension/`),可以各自单独发布。
|
||||
|
||||
- 前端构建产物单独上传到 `deployRoot/frontend`,由 **nginx 直接托管**(SPA 回退到 `index.html`);上一版保留在 `frontend.prev`,`npm run rollback` 会连前端一起切回。
|
||||
nginx 前端/反代配置由发布脚本写入 `deployRoot/front.conf`;Egg 只提供 `/api`、`/health`(`FRONTEND_ENABLE=false`)。
|
||||
`buildFrontend: false` 时跳过前端构建与发布(适合前端完全独立部署)。
|
||||
@ -311,19 +317,46 @@ npm run desktop:build # 只构建(dry-run),产物在 deskt
|
||||
npm run desktop:publish # 构建 + 上传 + 刷新 nginx
|
||||
npm run desktop:publish -- --version=1.0.90 --notes="修复 xxx"
|
||||
npm run desktop:publish -- --skip-nginx
|
||||
npm run desktop:publish -- --target=Msi # 只出 MSI(不发 EXE)
|
||||
```
|
||||
|
||||
- `--target=Both|Msi|Exe` 直接透传给 `desktop/installer/build.ps1 -Target`;
|
||||
⚠️ 客户端版本 `≤ 1.0.151` 有个 bug:优先下载 EXE,却拿 version.json 里的 `md5`(**MSI 的**)去校验,
|
||||
必然报「安装包 MD5 不一致」。**给这些客户端发的第一个修复版必须只出 MSI**
|
||||
(`--target=Msi`,此时 version.json 里没有 `downloadUrlExe`,老客户端会回落到 MSI + `md5`,能正常升级),
|
||||
等它们升上来之后再恢复 `Both`。
|
||||
|
||||
- 版本默认取本地已有最高版本 + 1(补丁号),也可用 `--version=` 指定;
|
||||
- 构建复用 `desktop/installer/build.ps1 -Environment Production`;
|
||||
- 上传到 `deployRoot/download/desktop/`(MSI),`version.json` 传到 `deployRoot/download/`
|
||||
(路径不能改:老客户端写死 `/download/version.json`;先传 MSI,再原子替换 `version.json`);
|
||||
- nginx 的 `/download/` 静态托管该目录:`version.json` 不缓存,MSI 长缓存;
|
||||
- 上传到 `deployRoot/download/desktop/`(MSI + EXE),`version.json` 传到 `deployRoot/download/`
|
||||
(路径不能改:老客户端写死 `/download/version.json`;先传安装包,再原子替换 `version.json`);
|
||||
- nginx 的 `/download/` 静态托管该目录:`version.json` 不缓存,安装包长缓存;
|
||||
- `desktop/installer/package.config.json` 的 Production `serverBaseUrl` 必须是 `https://`,安装包内嵌的接口 / 下载地址会跟着变;
|
||||
- **谷歌插件一起打进包**:`extension/` 发布到 `<安装目录>\extension`,菜单「工具 → 复制谷歌插件地址」给出该 Windows 路径;
|
||||
- **谷歌插件一起打进包**:`extension/` 发布到 `<安装目录>\extension`;正式分发走企业策略
|
||||
(`npm run extension:publish` + 菜单「工具 → 安装谷歌插件」,见下节);
|
||||
- 不会重启 Egg、不会重新发布后端、不会跑数据库迁移;
|
||||
- 前置:.NET 8 SDK、WiX 5.0.2(`dotnet tool install --global wix --version 5.0.2`)、`desktop/native/ffmpeg/ffmpeg.exe`。
|
||||
|
||||
下载地址:`<desktopBaseUrl>/download/desktop/YuncangTraceSetup-<版本>.msi`
|
||||
### Chrome 插件正式包(.crx + updates.xml)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run extension:build # 只打包(dry-run),产物在 extension/out
|
||||
npm run extension:publish # 打包 + 上传 + 刷新 nginx
|
||||
npm run extension:publish -- --version=1.2.0 --skip-nginx
|
||||
```
|
||||
|
||||
- 用本机 Chrome/Edge 的 `--pack-extension` 打包(找不到浏览器时用 `--browser=<路径>` 指定);
|
||||
- 产物:`YuncangTraceExtension-<version>.crx`、`updates.xml`、`extension-id.txt`;
|
||||
- 上传到 `deployRoot/download/extension/`;nginx 对 **`updates.xml` 关缓存**(浏览器靠它自动升级),
|
||||
`.crx` 文件名带版本号、走长缓存;
|
||||
- 扩展 ID 由 `extension/keys/key.pem` 决定(首次运行自动生成,**必须备份**,换了 ID 就变,
|
||||
已下发到客户机的策略全部失效);
|
||||
- 客户机侧:桌面端「工具 → 安装谷歌插件」写 `ExtensionInstallForcelist` + `ExtensionInstallSources`
|
||||
(Chrome 与 Edge 各一份,HKLM),重启浏览器即自动安装;
|
||||
- 前置:.NET 8 SDK、WiX 5.0.2(`dotnet tool install --global wix --version 5.0.2`)、Inno Setup 6(`winget install --id JRSoftware.InnoSetup`,出 EXE 用)、`desktop/native/ffmpeg/ffmpeg.exe`。
|
||||
|
||||
下载地址:`<desktopBaseUrl>/download/desktop/YuncangTraceSetup-<版本>.exe`(新客户端优先)
|
||||
`<desktopBaseUrl>/download/desktop/YuncangTraceSetup-<版本>.msi`(老客户端只认这个)
|
||||
更新信息:`<desktopBaseUrl>/download/version.json`
|
||||
|
||||
### Android 设备端正式包(单独发布,不动后端)
|
||||
@ -350,7 +383,7 @@ npm run android:publish -- --skip-nginx
|
||||
|
||||
网页端**所有页面**的右上角都有两个下载按钮(`frontend/src/components/AppLayout.vue`,**与权限无关**,登录后就能看到):
|
||||
|
||||
- 「桌面端 vX.Y.Z」→ `version.json` 里的 `downloadUrl`(MSI)
|
||||
- 「桌面端 vX.Y.Z」→ `version.json` 里的 `downloadUrlExe`(EXE)/ `downloadUrl`(MSI,老客户端)
|
||||
- 「Android 扫码台 vX.Y.Z」→ `version.json` 里的 `downloadUrl`(APK)
|
||||
|
||||
版本信息由 `frontend/src/api/download.ts` 直接 `fetch` 两个 `version.json`(**注意:这两个路径返回的是
|
||||
@ -979,6 +1012,24 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
|
||||
|
||||
改授权到期时间后必须失效主体状态缓存(`subjectState.invalidate`),否则设备心跳 / 上报最多要等一个 TTL 才看到新期限 —— `service/subject.js#setExpireAt()` 已经做了。
|
||||
|
||||
### Chrome 插件配置(集中下发)
|
||||
|
||||
插件**只拉取执行**,配置存在 `sys_config`(`group='extension'`, `config_key='config'`, `value_type=json`),不新建表。
|
||||
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/web/admin/extension` | 平台管理员 | 当前配置(含 `version` / `updatedAt` / 已生成的正则 `pattern`) |
|
||||
| PUT | `/api/web/admin/extension` | 平台管理员 | 保存 `{ enabled, hosts, prefixes, minDigits, maxDigits, urlTemplate, appUrlTemplate, downloadUrl }`;**不收 `pattern`**,正则由服务端拼;成功后 `version + 1` |
|
||||
| GET | `/api/web/extension/config` | 公开(可选 `?key=`) | 插件读的副本;`config.extension.appKey`(env `EXTENSION_APP_KEY`)非空时要求 key 一致 |
|
||||
|
||||
- 单号正则 = `\b(?:<前缀用 \| 连接>)\d{min,max}\b`(`service/extension_config.js#buildPattern`),前缀只允许大写字母/数字、1~8 位、最多 50 个;
|
||||
- `hosts` 是插件生效站点(glob,支持 `*.abc.com`);留空按 `['*']` 处理;
|
||||
- 插件每 **5 分钟**拉一次,靠 `version` 判断要不要更新(版本没变不写存储);`GET /api/web/extension/config` 的返回在 Redis 缓存 **1 小时**(`extension:config:public`),后台 `PUT` 保存时立刻删缓存 —— 提交即生效,平时又不会每 5 分钟回源一次;
|
||||
- **发布新安装包不用清缓存**:安装包地址由插件每次直接读 nginx 的 `/download/version.json`(nginx 对这个路径是 no-cache),不进这份 1 小时缓存;`service/extensionConfig.invalidate()` 留给运维/发布脚本需要时手工调用;
|
||||
- `downloadUrl` **不用配**:插件同步时优先读 `GET /download/version.json`,永远用最新发布版本
|
||||
(后台页面已不提供这个输入框;配置里的值只在 version.json 拉不到时兜底);
|
||||
- 生产若配了 `CORS_ORIGINS` 白名单,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。
|
||||
|
||||
### 前端(`frontend/`)
|
||||
|
||||
左侧菜单在**平台管理员**登录后会多出一组「平台管理」(`components/AppLayout.vue`):
|
||||
|
||||
34
backend/app/controller/web/admin_extension.js
Normal file
34
backend/app/controller/web/admin_extension.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 平台管理:Chrome 插件配置(`/api/web/admin/extension`)
|
||||
*
|
||||
* 鉴权:`middleware.apiAuth()` + `middleware.platformAdmin()`。
|
||||
*
|
||||
* - `GET /api/web/admin/extension` 当前配置(含 version / updatedAt)
|
||||
* - `PUT /api/web/admin/extension` 保存(只收 enabled / hosts / prefixes / 位数 / 模板 / 下载地址,
|
||||
* **正则由服务端生成**,不接受前端传 pattern)
|
||||
*
|
||||
* 保存成功后 `version + 1`,插件端每小时拉一次,靠 version 判断要不要更新。
|
||||
*/
|
||||
class WebAdminExtensionController extends Controller {
|
||||
/** GET /api/web/admin/extension */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const data = await ctx.service.extensionConfig.read();
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** PUT /api/web/admin/extension */
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const data = await ctx.service.extensionConfig.save(ctx.request.body || {});
|
||||
ctx.logger.info('[extension] 插件配置已更新:v%s,站点 %s,前缀 %s',
|
||||
data.version, data.hosts.join(','), data.prefixes.join(','));
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebAdminExtensionController;
|
||||
34
backend/app/controller/web/extension.js
Normal file
34
backend/app/controller/web/extension.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* Chrome 插件读取配置(`GET /api/web/extension/config`)
|
||||
*
|
||||
* **公开只读**:插件装在员工浏览器里,没有用户令牌;下发的只有
|
||||
* 识别前缀 / 生效站点 / 跳转模板 / 安装包地址,不含任何账号或业务数据。
|
||||
*
|
||||
* 两道保护:
|
||||
* - `config.extension.appKey` 非空时要求 `?key=` 一致(env `EXTENSION_APP_KEY`),
|
||||
* 避免站点清单被随便抓走;不设就完全公开(内网部署的常见做法);
|
||||
* - 响应 `Cache-Control: no-cache`:配置改了要能马上生效,别被 nginx/浏览器缓存一小时。
|
||||
*/
|
||||
class WebExtensionController extends Controller {
|
||||
/** GET /api/web/extension/config */
|
||||
async config() {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const expected = (app.config.extension && app.config.extension.appKey) || '';
|
||||
if (expected && String(ctx.query.key || '') !== expected) {
|
||||
ctx.throw(403, '插件配置需要正确的 key');
|
||||
}
|
||||
|
||||
const data = await ctx.service.extensionConfig.publicView();
|
||||
|
||||
ctx.set('Cache-Control', 'no-cache, max-age=0');
|
||||
ctx.set('X-Config-Version', String(data.version));
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebExtensionController;
|
||||
@ -77,6 +77,14 @@ module.exports = (app) => {
|
||||
router.get('/api/web/admin/orders', apiAuth, platformAdmin, controller.web.adminOrder.index);
|
||||
// 确认订单 = 支付回调的后续动作(同一套 payNotify:标记已支付 + 主体顺延 + 失效缓存)
|
||||
router.post('/api/web/admin/orders/:orderNo/confirm', apiAuth, platformAdmin, controller.web.adminOrder.confirm);
|
||||
// Chrome 插件的集中配置:只维护「前缀 / 生效站点 / 模板」,单号正则由服务端生成
|
||||
router.get('/api/web/admin/extension', apiAuth, platformAdmin, controller.web.adminExtension.show);
|
||||
router.put('/api/web/admin/extension', apiAuth, platformAdmin, controller.web.adminExtension.update);
|
||||
|
||||
// ---------- Chrome 插件读取(公开只读,无令牌) ----------
|
||||
// 只下发:前缀 + 生成好的正则 + 生效站点 + 跳转模板 + 安装包地址;不含任何账号/业务数据。
|
||||
// 生产若配了 CORS_ORIGINS,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。
|
||||
router.get('/api/web/extension/config', controller.web.extension.config);
|
||||
|
||||
// ---------- 主体(租户):不输主体 id,靠「当前用户是否是成员」判定 ----------
|
||||
// 除这几个以外的业务接口都要额外带 `X-Subject-Id`(middleware/subjectAuth)
|
||||
|
||||
236
backend/app/service/extension_config.js
Normal file
236
backend/app/service/extension_config.js
Normal file
@ -0,0 +1,236 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/**
|
||||
* Chrome 插件的**集中配置**(平台管理员维护,插件只拉取执行)
|
||||
*
|
||||
* 存 `sys_config`(group=extension, key=config, valueType=json),不新建表:
|
||||
* 配置是「一套全局值」,读写频率极低,且有 Redis 缓存(见 service/config.js)。
|
||||
*
|
||||
* 设计要点:
|
||||
* - 后台**只维护前缀**(`YT` / `SF` / `32`…),单号正则由这里拼出来(`pattern`),
|
||||
* 插件端不再自己拼正则、也不展示正则;
|
||||
* - `hosts` 是插件允许工作的站点(glob:`*.abc.com`、`192.168.11.206`、`*`);
|
||||
* - 每次保存 `version + 1`:插件靠它判断"配置变没变",没变就不重写 storage(避免整页重扫);
|
||||
* - `pattern` 一并下发:服务端生成一次,所有客户端行为一致,不会各拼各的。
|
||||
*/
|
||||
|
||||
/** sys_config 位置 */
|
||||
const GROUP = 'extension';
|
||||
const KEY = 'config';
|
||||
|
||||
/** 默认前缀(和老版插件内置的快递规则一致) */
|
||||
const DEFAULT_PREFIXES = [ 'YT', 'SF', 'JD', 'ZTO', 'YTO', 'STO', 'EMS', 'DBL', '32', '77' ];
|
||||
|
||||
const DEFAULT_URL_TEMPLATE = 'http://localhost:7301/local?code={code}';
|
||||
const DEFAULT_APP_URL_TEMPLATE = 'yuncang://open?code={code}';
|
||||
|
||||
/** 前缀:字母/数字,1~8 位(`32` / `77` 这种数字前缀也要支持) */
|
||||
const PREFIX_RE = /^[A-Z0-9]{1,8}$/;
|
||||
|
||||
/**
|
||||
* 插件读取结果的服务端缓存
|
||||
*
|
||||
* 插件每 5 分钟拉一次,几百台机器就是每小时上万次请求 —— 但配置几乎不变,
|
||||
* 所以服务端算一次缓存 **1 小时**;后台保存配置时立刻删掉(`save()` → `invalidate()`),
|
||||
* 保证「提交新版本」马上生效。
|
||||
*
|
||||
* 安装包地址不参与这份缓存:插件自己读 nginx 的 `/download/version.json`(那边是 no-cache),
|
||||
* 所以打包上传新安装包**天然即时**,不需要清这里的缓存。
|
||||
*/
|
||||
const PUBLIC_CACHE_KEY = 'extension:config:public';
|
||||
const PUBLIC_CACHE_TTL_SECONDS = 3600;
|
||||
|
||||
/** 没配置过时的默认值 */
|
||||
function defaults() {
|
||||
return {
|
||||
version: 0,
|
||||
enabled: true,
|
||||
hosts: [ '*' ],
|
||||
prefixes: DEFAULT_PREFIXES.slice(),
|
||||
minDigits: 10,
|
||||
maxDigits: 16,
|
||||
urlTemplate: DEFAULT_URL_TEMPLATE,
|
||||
appUrlTemplate: DEFAULT_APP_URL_TEMPLATE,
|
||||
downloadUrl: '',
|
||||
updatedAt: null,
|
||||
pattern: buildPattern(DEFAULT_PREFIXES, 10, 16),
|
||||
flags: 'g',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 由前缀生成单号正则:`\b(?:YT|SF|…)\d{10,16}\b`
|
||||
*
|
||||
* 用 `g`(不带 `i`):前缀统一存成大写,避免把 `yt` 这类普通词误判成单号。
|
||||
*/
|
||||
function buildPattern(prefixes, minDigits, maxDigits) {
|
||||
const list = prefixes.map(item => String(item).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
if (list.length === 0) return '';
|
||||
return '\\b(?:' + list.join('|') + ')\\d{' + minDigits + ',' + maxDigits + '}\\b';
|
||||
}
|
||||
|
||||
/** 数组去空去重(保持顺序) */
|
||||
function uniq(list) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of list) {
|
||||
if (seen.has(item)) continue;
|
||||
seen.add(item);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 生效站点:glob 字符串;留空 = 不限制(`*`) */
|
||||
function normalizeHosts(value) {
|
||||
const list = (Array.isArray(value) ? value : [])
|
||||
.map(item => String(item == null ? '' : item).trim())
|
||||
.filter(Boolean);
|
||||
return list.length > 0 ? uniq(list) : [ '*' ];
|
||||
}
|
||||
|
||||
/** 前缀:转大写、校验字符集、去重、限制数量 */
|
||||
function normalizePrefixes(value) {
|
||||
const list = (Array.isArray(value) ? value : [])
|
||||
.map(item => String(item == null ? '' : item).trim().toUpperCase())
|
||||
.filter(Boolean);
|
||||
|
||||
const bad = list.find(item => !PREFIX_RE.test(item));
|
||||
if (bad) {
|
||||
const error = new Error(`单号前缀「${bad}」不合法:只能是大写字母或数字,1~8 位`);
|
||||
error.status = 422;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const out = uniq(list);
|
||||
if (out.length > 50) {
|
||||
const error = new Error('单号前缀最多 50 个');
|
||||
error.status = 422;
|
||||
throw error;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 数字位数:4~24,且 min ≤ max */
|
||||
function normalizeDigits(min, max) {
|
||||
const toInt = (value, fallback) => {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) ? parsed : fallback;
|
||||
};
|
||||
|
||||
let minDigits = Math.min(Math.max(toInt(min, 10), 4), 24);
|
||||
let maxDigits = Math.min(Math.max(toInt(max, 16), 4), 24);
|
||||
if (minDigits > maxDigits) [ minDigits, maxDigits ] = [ maxDigits, minDigits ];
|
||||
return { minDigits, maxDigits };
|
||||
}
|
||||
|
||||
/** 模板:必须含 `{code}`,否则回落到默认值(空串也算没填) */
|
||||
function normalizeTemplate(value, fallback) {
|
||||
const text = String(value == null ? '' : value).trim() || fallback;
|
||||
return text.includes('{code}') ? text : fallback;
|
||||
}
|
||||
|
||||
/** 把任意输入整理成合法配置(不含 version / updatedAt) */
|
||||
function normalize(input) {
|
||||
const source = input && typeof input === 'object' ? input : {};
|
||||
|
||||
const prefixes = normalizePrefixes(source.prefixes);
|
||||
const { minDigits, maxDigits } = normalizeDigits(source.minDigits, source.maxDigits);
|
||||
|
||||
return {
|
||||
enabled: source.enabled !== false,
|
||||
hosts: normalizeHosts(source.hosts),
|
||||
prefixes,
|
||||
minDigits,
|
||||
maxDigits,
|
||||
urlTemplate: normalizeTemplate(source.urlTemplate, DEFAULT_URL_TEMPLATE),
|
||||
appUrlTemplate: normalizeTemplate(source.appUrlTemplate, DEFAULT_APP_URL_TEMPLATE),
|
||||
// 留空 = 插件同步时自己读 /download/version.json(永远用最新发布版本);
|
||||
// 只有要指到内网镜像之类才需要填,后台页面已经不提供这个输入框。
|
||||
downloadUrl: String(source.downloadUrl == null ? '' : source.downloadUrl).trim(),
|
||||
pattern: buildPattern(prefixes, minDigits, maxDigits),
|
||||
flags: 'g',
|
||||
};
|
||||
}
|
||||
|
||||
class ExtensionConfigService extends Service {
|
||||
/**
|
||||
* 读当前配置(给管理员看,含默认值)
|
||||
*
|
||||
* 存量数据可能是旧结构(例如手改过 sys_config),这里统一过一遍 normalize,
|
||||
* 保证返回给前端 / 插件的字段永远齐全。
|
||||
*/
|
||||
async read() {
|
||||
const stored = await this.ctx.service.config.get(GROUP, KEY, null);
|
||||
if (!stored || typeof stored !== 'object') return defaults();
|
||||
|
||||
const config = normalize(stored);
|
||||
return {
|
||||
...config,
|
||||
version: Number(stored.version) || 0,
|
||||
updatedAt: stored.updatedAt || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 保存(管理端):校验 → version 自增 → 写 sys_config(带缓存失效) */
|
||||
async save(input) {
|
||||
const previous = await this.read();
|
||||
const next = normalize(input);
|
||||
|
||||
next.version = (Number(previous.version) || 0) + 1;
|
||||
next.updatedAt = new Date().toISOString();
|
||||
|
||||
await this.ctx.service.config.set({
|
||||
groupName: GROUP,
|
||||
configKey: KEY,
|
||||
configValue: next,
|
||||
valueType: 'json',
|
||||
remark: 'Chrome 插件集中配置(识别前缀 / 生效站点 / 跳转模板)',
|
||||
});
|
||||
|
||||
// 提交即生效:插件下次(最多 5 分钟)来拉的时候就能拿到新配置
|
||||
await this.invalidate();
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件读取用的公开视图(Redis 缓存 1 小时)
|
||||
*
|
||||
* 只给插件执行所需字段,**不含任何内部信息**(主体、账号、密钥一概没有)。
|
||||
*/
|
||||
async publicView() {
|
||||
const cached = await this.ctx.service.cache.get(PUBLIC_CACHE_KEY);
|
||||
if (cached) return cached;
|
||||
|
||||
const view = this.buildPublicView(await this.read());
|
||||
await this.ctx.service.cache.set(PUBLIC_CACHE_KEY, view, PUBLIC_CACHE_TTL_SECONDS);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** 主动失效(保存配置时调用;发布脚本/内部运维需要时也能用) */
|
||||
async invalidate() {
|
||||
await this.ctx.service.cache.del(PUBLIC_CACHE_KEY);
|
||||
}
|
||||
|
||||
buildPublicView(config) {
|
||||
return {
|
||||
version: config.version,
|
||||
enabled: config.enabled,
|
||||
hosts: config.hosts,
|
||||
prefixes: config.prefixes,
|
||||
minDigits: config.minDigits,
|
||||
maxDigits: config.maxDigits,
|
||||
pattern: config.pattern,
|
||||
flags: config.flags,
|
||||
urlTemplate: config.urlTemplate,
|
||||
appUrlTemplate: config.appUrlTemplate,
|
||||
downloadUrl: config.downloadUrl,
|
||||
updatedAt: config.updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExtensionConfigService;
|
||||
@ -56,6 +56,15 @@ module.exports = (appInfo) => {
|
||||
buffer: false, // MSI / APK 几十 MB,流式发送
|
||||
};
|
||||
|
||||
// ==================== Chrome 插件(集中配置) ====================
|
||||
// 插件只拉取执行:`GET /api/web/extension/config`(公开只读,内容由平台管理员在
|
||||
// `/api/web/admin/extension` 维护,存 sys_config 的 group=extension)。
|
||||
// `appKey` 非空时要求 `?key=` 一致(env `EXTENSION_APP_KEY`),防止站点清单被随便抓走;
|
||||
// 不设就完全公开(内网部署的常见做法)。
|
||||
config.extension = {
|
||||
appKey: env.EXTENSION_APP_KEY || '',
|
||||
};
|
||||
|
||||
// ==================== 前端入口(页面不在后端渲染) ====================
|
||||
// 开发(env=local):页面请求(非 /api、/health)反代到前端 dev server(frontend/ 里 npm run dev)
|
||||
// 生产:直接托管前端构建产物 dist(SPA 深链回退到 index.html)
|
||||
|
||||
@ -76,6 +76,9 @@ module.exports = {
|
||||
desktopBaseUrl: 'https://pack.example.com',
|
||||
desktopKeepVersions: 5,
|
||||
desktopOwner: 'www:www',
|
||||
// Chrome 插件(npm run extension:publish):.crx + updates.xml 放这里
|
||||
// nginx 对 /download/extension/updates.xml 关缓存,浏览器靠它自动升级
|
||||
extensionDownloadDir: '/www/wwwroot/packService/download/extension',
|
||||
|
||||
// Android 设备端发布(npm run android:publish):同样只构建/上传 APK
|
||||
androidBuildScript: 'android_client/build.ps1',
|
||||
|
||||
@ -62,6 +62,9 @@
|
||||
"version:history": "node ./scripts/deploy/version-history.cjs --limit=50",
|
||||
"desktop:build": "node ./scripts/deploy/publish-desktop.cjs production --dry-run",
|
||||
"desktop:publish": "node ./scripts/deploy/publish-desktop.cjs production",
|
||||
"extension:build": "node ./scripts/deploy/publish-extension.cjs production --dry-run",
|
||||
"extension:zip": "node ./scripts/deploy/publish-extension.cjs production --zip",
|
||||
"extension:publish": "node ./scripts/deploy/publish-extension.cjs production",
|
||||
"android:build": "node ./scripts/deploy/publish-android.cjs production --dry-run",
|
||||
"android:publish": "node ./scripts/deploy/publish-android.cjs production",
|
||||
"guard:git": "node ./scripts/deploy/git-safety-check.cjs",
|
||||
|
||||
@ -213,6 +213,9 @@ function normalizeDeployConfig(config, envName) {
|
||||
desktopDownloadDir: config.desktopDownloadDir || `${deployRoot}/download/desktop`,
|
||||
// version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
|
||||
desktopVersionDir: config.desktopVersionDir || `${deployRoot}/download`,
|
||||
// Chrome 插件(.crx + updates.xml):npm run extension:publish
|
||||
// updates.xml 必须不缓存(浏览器靠它判断有没有新版本),.crx 文件名带版本号可以长缓存
|
||||
extensionDownloadDir: config.extensionDownloadDir || `${deployRoot}/download/extension`,
|
||||
desktopBaseUrl: config.desktopBaseUrl || (config.serverName ? `http://${config.serverName}` : ''),
|
||||
desktopKeepVersions: Number(config.desktopKeepVersions || 5),
|
||||
desktopOwner: config.desktopOwner || 'www:www',
|
||||
@ -460,7 +463,7 @@ function buildFrontConf(config) {
|
||||
: [ '# nginxUpstreamFile 未配置,跳过 /api、/health 反代' ]),
|
||||
'',
|
||||
'# 桌面端 / Android 安装包:由 nginx 直接托管 deployRoot/download',
|
||||
'# download/desktop/*.msi、download/android_client/*.apk 长缓存;',
|
||||
'# download/desktop/*.exe、*.msi、download/android_client/*.apk 长缓存;',
|
||||
'# version.json 一律不缓存(客户端靠它判断有没有新版本)。',
|
||||
'location = /download/version.json {',
|
||||
` root ${config.deployRoot};`,
|
||||
@ -471,6 +474,16 @@ function buildFrontConf(config) {
|
||||
' expires 0;',
|
||||
'}',
|
||||
'',
|
||||
'# Chrome 插件更新清单:浏览器每次启动都会来问,必须不缓存(策略安装 + 自动升级都靠它)',
|
||||
'location = /download/extension/updates.xml {',
|
||||
` root ${config.deployRoot};`,
|
||||
' default_type text/xml;',
|
||||
' add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";',
|
||||
' add_header Pragma "no-cache";',
|
||||
hsts,
|
||||
' expires 0;',
|
||||
'}',
|
||||
'',
|
||||
'location = /download/android_client/version.json {',
|
||||
` root ${config.deployRoot};`,
|
||||
' default_type application/json;',
|
||||
|
||||
@ -1,15 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 桌面端正式包:构建 MSI + version.json,并单独发布到 nginx 静态目录
|
||||
* 桌面端正式包:构建 MSI + EXE + version.json,并单独发布到 nginx 静态目录
|
||||
*
|
||||
* 特点:
|
||||
* - 只动桌面端产物,不重新发布后端、不重启 Egg、不跑数据库迁移;
|
||||
* - 构建复用 desktop/installer/build.ps1(Production 环境);
|
||||
* - 构建复用 desktop/installer/build.ps1(Production 环境,默认同时出 MSI 和 EXE);
|
||||
* - 安装包上传到 deploy.config.local.cjs 里的 desktopDownloadDir(deployRoot/download/desktop);
|
||||
* - version.json 上传到 desktopVersionDir(默认 deployRoot/download,nginx 对 /download/version.json 关缓存);
|
||||
* - 同时刷新 front.conf 里的 /download/ 静态托管配置并 reload nginx。
|
||||
*
|
||||
* 为什么两个包都要传:老客户端只认 downloadUrl(MSI);新客户端优先 downloadUrlExe(EXE,
|
||||
* 不依赖 Windows Installer,现场装不了 MSI 的机器靠它)。少传任何一个都会让对应客户端 404。
|
||||
*
|
||||
* 用法:
|
||||
* npm run desktop:publish # 自动递增补丁版本并发布
|
||||
* npm run desktop:publish -- --version=1.0.90
|
||||
@ -38,6 +41,7 @@ function parseArgs(argv) {
|
||||
version: '',
|
||||
notes: '',
|
||||
keep: 0,
|
||||
target: '',
|
||||
dryRun: false,
|
||||
skipNginx: false,
|
||||
};
|
||||
@ -59,6 +63,12 @@ function parseArgs(argv) {
|
||||
options.notes = item.slice('--notes='.length);
|
||||
} else if (item.startsWith('--keep=')) {
|
||||
options.keep = Number(item.slice('--keep='.length)) || 0;
|
||||
} else if (item.startsWith('--target=')) {
|
||||
options.target = item.slice('--target='.length).trim();
|
||||
const allowed = [ 'Both', 'Msi', 'Exe' ];
|
||||
if (!allowed.includes(options.target)) {
|
||||
throw new Error(`--target 只能是 ${allowed.join(' / ')}:${options.target}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -77,13 +87,13 @@ function compareVersion(a, b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** 取本地已有 MSI / version.json 中最高的版本,并默认 +1 补丁号 */
|
||||
/** 取本地已有安装包 / version.json 中最高的版本,并默认 +1 补丁号 */
|
||||
function nextVersion(outDir) {
|
||||
const versions = [];
|
||||
|
||||
if (fs.existsSync(outDir)) {
|
||||
for (const name of fs.readdirSync(outDir)) {
|
||||
const match = name.match(/^YuncangTraceSetup-(\d+\.\d+\.\d+)\.msi$/);
|
||||
const match = name.match(/^YuncangTraceSetup-(\d+\.\d+\.\d+)\.(?:msi|exe)$/);
|
||||
if (match) versions.push(match[1]);
|
||||
}
|
||||
}
|
||||
@ -107,7 +117,7 @@ function nextVersion(outDir) {
|
||||
}
|
||||
|
||||
/** 用 build.ps1 构建 Production 包 */
|
||||
function buildDesktop(config, { version, notes, baseUrl }) {
|
||||
function buildDesktop(config, { version, notes, baseUrl, target }) {
|
||||
const buildScript = path.resolve(ROOT, config.desktopBuildScript);
|
||||
if (!fs.existsSync(buildScript)) {
|
||||
throw new Error(`找不到桌面端构建脚本: ${buildScript}`);
|
||||
@ -125,6 +135,10 @@ function buildDesktop(config, { version, notes, baseUrl }) {
|
||||
if (notes) {
|
||||
args.push('-ReleaseNotes', notes);
|
||||
}
|
||||
// 只出某一种包(例如老客户端 MD5 校验有 bug 时,先发一个「只有 MSI」的版本把它们拉上来)
|
||||
if (target) {
|
||||
args.push('-Target', target);
|
||||
}
|
||||
|
||||
console.log(`构建桌面端正式包: ${version}(${baseUrl})`);
|
||||
runCommand(shell, args, { cwd: path.dirname(buildScript), stdio: 'inherit' });
|
||||
@ -150,23 +164,41 @@ function main() {
|
||||
throw new Error('未配置 desktopVersionDir(version.json 发布目录)。');
|
||||
}
|
||||
|
||||
buildDesktop(config, { version, notes: options.notes, baseUrl });
|
||||
buildDesktop(config, { version, notes: options.notes, baseUrl, target: options.target });
|
||||
|
||||
const msiName = `YuncangTraceSetup-${version}.msi`;
|
||||
const exeName = `YuncangTraceSetup-${version}.exe`;
|
||||
const msiPath = path.join(outDir, msiName);
|
||||
const exePath = path.join(outDir, exeName);
|
||||
const versionPath = path.join(outDir, 'version.json');
|
||||
|
||||
if (!fs.existsSync(msiPath)) {
|
||||
throw new Error(`构建完成但 MSI 不存在: ${msiPath}`);
|
||||
}
|
||||
if (!fs.existsSync(versionPath)) {
|
||||
throw new Error(`构建完成但 version.json 不存在: ${versionPath}`);
|
||||
}
|
||||
|
||||
const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
|
||||
console.log(`安装包: ${msiPath}(${(fs.statSync(msiPath).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
|
||||
// version.json 里有 downloadUrlExe 就必须把 EXE 一起传上去,否则新客户端拿到的是 404
|
||||
const packages = [];
|
||||
if (fs.existsSync(msiPath)) packages.push(msiPath);
|
||||
if (versionJson.downloadUrlExe) {
|
||||
if (!fs.existsSync(exePath)) {
|
||||
throw new Error(`version.json 指向 EXE,但文件不存在: ${exePath}`);
|
||||
}
|
||||
packages.push(exePath);
|
||||
}
|
||||
if (!packages.length) {
|
||||
throw new Error(`构建完成但没找到安装包(${msiName} / ${exeName})`);
|
||||
}
|
||||
|
||||
for (const pkg of packages) {
|
||||
console.log(`安装包: ${pkg}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
}
|
||||
console.log(`版本文件: ${versionPath}`);
|
||||
console.log(`下载地址: ${versionJson.downloadUrl}`);
|
||||
if (versionJson.downloadUrlExe) {
|
||||
console.log(`下载地址(EXE): ${versionJson.downloadUrlExe}`);
|
||||
}
|
||||
console.log(`发布目录: ${config.username}@${config.host}:${remoteDir}`);
|
||||
console.log(`版本目录: ${config.username}@${config.host}:${remoteVersionDir}`);
|
||||
|
||||
@ -179,7 +211,6 @@ function main() {
|
||||
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
|
||||
|
||||
const stamp = getNowStamp();
|
||||
const remoteMsiTmp = `${remoteDir}/.${msiName}.upload-${stamp}`;
|
||||
const remoteVersionTmp = `${remoteVersionDir}/.version.json.upload-${stamp}`;
|
||||
|
||||
runSsh(config, [
|
||||
@ -191,22 +222,26 @@ function main() {
|
||||
'find "$DIR" "$VDIR" -maxdepth 1 -type f -name ".*.upload-*" -delete',
|
||||
].join('\n'), { stdio: 'pipe' });
|
||||
|
||||
console.log(`上传安装包(${(fs.statSync(msiPath).size / 1024 / 1024).toFixed(1)} MB)…`);
|
||||
runScp(config, msiPath, remoteMsiTmp);
|
||||
for (const pkg of packages) {
|
||||
const name = path.basename(pkg);
|
||||
const remoteTmp = `${remoteDir}/.${name}.upload-${stamp}`;
|
||||
|
||||
runSsh(config, [
|
||||
'set -euo pipefail',
|
||||
`DIR=${quoteForBash(remoteDir)}`,
|
||||
`TMP=${quoteForBash(remoteMsiTmp)}`,
|
||||
`FINAL=${quoteForBash(`${remoteDir}/${msiName}`)}`,
|
||||
'mv "$TMP" "$FINAL"',
|
||||
'chmod 644 "$FINAL"',
|
||||
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$FINAL" || true`,
|
||||
'echo "MSI_UPLOADED"',
|
||||
].join('\n'), { stdio: 'pipe' });
|
||||
console.log(`安装包已发布: ${remoteDir}/${msiName}`);
|
||||
console.log(`上传安装包 ${name}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)…`);
|
||||
runScp(config, pkg, remoteTmp);
|
||||
|
||||
// MSI 就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
|
||||
runSsh(config, [
|
||||
'set -euo pipefail',
|
||||
`TMP=${quoteForBash(remoteTmp)}`,
|
||||
`FINAL=${quoteForBash(`${remoteDir}/${name}`)}`,
|
||||
'mv "$TMP" "$FINAL"',
|
||||
'chmod 644 "$FINAL"',
|
||||
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$FINAL" || true`,
|
||||
`echo "PACKAGE_UPLOADED ${name}"`,
|
||||
].join('\n'), { stdio: 'pipe' });
|
||||
console.log(`安装包已发布: ${remoteDir}/${name}`);
|
||||
}
|
||||
|
||||
// 所有安装包就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
|
||||
runScp(config, versionPath, remoteVersionTmp);
|
||||
runSsh(config, [
|
||||
'set -euo pipefail',
|
||||
@ -217,12 +252,17 @@ function main() {
|
||||
'chmod 644 "$VDIR/version.json"',
|
||||
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$VDIR/version.json" || true`,
|
||||
'echo "VERSION_JSON_UPLOADED"',
|
||||
// 只保留最近 N 个安装包
|
||||
// 只保留最近 N 个安装包(MSI / EXE 分别计算)
|
||||
'COUNT=0',
|
||||
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.msi 2>/dev/null || true); do`,
|
||||
' COUNT=$((COUNT + 1))',
|
||||
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
|
||||
'done',
|
||||
'COUNT=0',
|
||||
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.exe 2>/dev/null || true); do`,
|
||||
' COUNT=$((COUNT + 1))',
|
||||
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
|
||||
'done',
|
||||
'ls -1t "$DIR" | head -20',
|
||||
].join('\n'), { stdio: 'pipe' });
|
||||
|
||||
@ -233,7 +273,9 @@ function main() {
|
||||
console.log('');
|
||||
console.log('桌面端发布完成:');
|
||||
console.log(` 版本: ${version}`);
|
||||
console.log(` 安装包: ${baseUrl}/download/desktop/${msiName}`);
|
||||
for (const pkg of packages) {
|
||||
console.log(` 安装包: ${baseUrl}/download/desktop/${path.basename(pkg)}`);
|
||||
}
|
||||
console.log(` 更新信息: ${baseUrl}/download/version.json`);
|
||||
}
|
||||
|
||||
|
||||
292
backend/scripts/deploy/publish-extension.cjs
Normal file
292
backend/scripts/deploy/publish-extension.cjs
Normal file
@ -0,0 +1,292 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Chrome 插件正式包:打包 .crx + 生成 updates.xml,并发布到 nginx 静态目录
|
||||
*
|
||||
* 为什么需要它:
|
||||
* - 浏览器只认**已签名**的扩展包,`chrome://extensions` 里「加载已解压」没法被策略/安装包注入;
|
||||
* - 企业策略 `ExtensionInstallForcelist` 只接受 `<扩展ID>;<update_url>`,update_url 必须是一个
|
||||
* 可访问的 XML(不是本地目录);
|
||||
* - 所以这里把仓库里的 `extension/` 打成 `.crx`,连同 `updates.xml` 一起放到
|
||||
* `deployRoot/download/extension/`(nginx 对 updates.xml 关缓存,.crx 长缓存)。
|
||||
*
|
||||
* 产物(extension/out/):
|
||||
* - `YuncangTraceExtension-<version>.crx` 扩展包(文件名带版本号,可以长缓存)
|
||||
* - `updates.xml` 更新清单(`<app appid>` 就是扩展 ID)
|
||||
* - `extension-id.txt` 扩展 ID(给安装/排障用)
|
||||
*
|
||||
* 扩展 ID 由**私钥**决定:`extension/keys/key.pem`(首次运行自动生成,**务必备份**;
|
||||
* 换私钥 = 换 ID = 已下发到客户机的策略全部失效)。
|
||||
*
|
||||
* 用法:
|
||||
* npm run extension:publish # 打包 + 上传 + 刷新 nginx
|
||||
* npm run extension:publish -- --dry-run # 只打包,不上传
|
||||
* npm run extension:publish -- --version=1.2.0
|
||||
* npm run extension:publish -- --skip-nginx # 不改 nginx
|
||||
* npm run extension:publish -- --browser="C:\Program Files\Microsoft\Edge\Application\msedge.exe"
|
||||
*/
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const {
|
||||
ROOT,
|
||||
ensureCommandAvailable,
|
||||
getNowStamp,
|
||||
loadDeployConfig,
|
||||
quoteForBash,
|
||||
refreshNginx,
|
||||
runCommand,
|
||||
runScp,
|
||||
runSsh,
|
||||
} = require('./deploy-lib.cjs');
|
||||
|
||||
/** 仓库根(backend 的上一级) */
|
||||
const REPO_ROOT = path.resolve(ROOT, '..');
|
||||
const EXT_DIR = path.join(REPO_ROOT, 'extension');
|
||||
const KEY_FILE = path.join(EXT_DIR, 'keys', 'key.pem');
|
||||
const OUT_DIR = path.join(EXT_DIR, 'out');
|
||||
const PACKAGE_NAME = 'YuncangTraceExtension';
|
||||
|
||||
/** 打进 crx 的内容(其余 README/test/tools/out/keys 不进包) */
|
||||
const INCLUDE = [ 'manifest.json', 'icons', 'src' ];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
envName: 'production',
|
||||
version: '',
|
||||
baseUrl: '',
|
||||
browser: '',
|
||||
dryRun: false,
|
||||
zipOnly: false,
|
||||
skipNginx: false,
|
||||
};
|
||||
|
||||
for (const item of argv) {
|
||||
if (!item) continue;
|
||||
if (!item.startsWith('--') && !options.envNameExplicit) {
|
||||
options.envName = item;
|
||||
options.envNameExplicit = true;
|
||||
continue;
|
||||
}
|
||||
if (item === '--dry-run') {
|
||||
options.dryRun = true;
|
||||
} else if (item === '--zip') {
|
||||
// 只打「商店上传用的 zip」,不打包 crx、不上传
|
||||
options.zipOnly = true;
|
||||
} else if (item === '--skip-nginx') {
|
||||
options.skipNginx = true;
|
||||
} else if (item.startsWith('--version=')) {
|
||||
options.version = item.slice('--version='.length).trim().replace(/^v/i, '');
|
||||
} else if (item.startsWith('--base-url=')) {
|
||||
options.baseUrl = item.slice('--base-url='.length).trim();
|
||||
} else if (item.startsWith('--browser=')) {
|
||||
options.browser = item.slice('--browser='.length).trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (options.version && !/^\d+(\.\d+){1,3}$/.test(options.version)) {
|
||||
throw new Error(`版本号格式应为 x.y.z:${options.version}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/** 读 manifest 里的版本号(没传 --version 时用) */
|
||||
function manifestVersion() {
|
||||
const data = JSON.parse(fs.readFileSync(path.join(EXT_DIR, 'manifest.json'), 'utf8'));
|
||||
const version = String(data.version || '').trim();
|
||||
if (!/^\d+(\.\d+){1,3}$/.test(version)) {
|
||||
throw new Error(`manifest.json 里的 version 不合法:${version}`);
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
/** 找本机可用的 Chromium 内核浏览器(打包用;Chrome/Edge 都支持 --pack-extension) */
|
||||
function resolveBrowser(explicit) {
|
||||
const candidates = [
|
||||
explicit,
|
||||
process.env.CHROME_PATH,
|
||||
process.env.EDGE_PATH,
|
||||
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
||||
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
||||
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
||||
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
|
||||
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
|
||||
].filter(Boolean);
|
||||
|
||||
for (const item of candidates) {
|
||||
if (fs.existsSync(item)) return item;
|
||||
}
|
||||
throw new Error('找不到 chrome.exe / msedge.exe(打包 crx 要用)。可用 --browser=<路径> 指定。');
|
||||
}
|
||||
|
||||
/** 把扩展源码复制到临时目录(只带 INCLUDE 里的东西) */
|
||||
function stageSources(workDir) {
|
||||
const target = path.join(workDir, PACKAGE_NAME);
|
||||
fs.mkdirSync(target, { recursive: true });
|
||||
for (const name of INCLUDE) {
|
||||
const from = path.join(EXT_DIR, name);
|
||||
if (!fs.existsSync(from)) throw new Error(`扩展源码缺少:${from}`);
|
||||
fs.cpSync(from, path.join(target, name), { recursive: true });
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用浏览器命令行打包 crx
|
||||
*
|
||||
* - 不给 `--pack-extension-key` 时浏览器会在同级生成 `.pem`(第一次运行用这个拿私钥);
|
||||
* - 必须给独立的 `--user-data-dir`:否则命令会被**已经在运行的 Chrome** 接走,不会真的打包。
|
||||
*/
|
||||
function packCrx(browser, srcDir, keyPath, workDir) {
|
||||
const baseArgs = [
|
||||
`--pack-extension=${srcDir}`,
|
||||
`--user-data-dir=${path.join(workDir, 'profile')}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-gpu',
|
||||
];
|
||||
|
||||
const crxPath = `${srcDir}.crx`;
|
||||
const pemPath = `${srcDir}.pem`;
|
||||
|
||||
if (!fs.existsSync(keyPath)) {
|
||||
console.log('没有私钥,先生成一个(决定扩展 ID,生成后请备份):', keyPath);
|
||||
runCommand(browser, baseArgs, { stdio: 'inherit' });
|
||||
if (!fs.existsSync(pemPath)) throw new Error('浏览器没有生成 .pem,打包失败');
|
||||
fs.mkdirSync(path.dirname(keyPath), { recursive: true });
|
||||
fs.copyFileSync(pemPath, keyPath);
|
||||
if (fs.existsSync(crxPath)) fs.rmSync(crxPath);
|
||||
}
|
||||
|
||||
runCommand(browser, [ ...baseArgs, `--pack-extension-key=${keyPath}` ], { stdio: 'inherit' });
|
||||
if (!fs.existsSync(crxPath)) throw new Error(`打包失败:没有生成 ${crxPath}`);
|
||||
return crxPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由私钥算扩展 ID
|
||||
*
|
||||
* Chrome 的规则:公钥 DER(SPKI)→ SHA256 → 取前 16 字节 → 每个十六进制位映射成 a~p。
|
||||
*/
|
||||
function extensionIdFromKey(pem) {
|
||||
const publicKey = crypto.createPublicKey(crypto.createPrivateKey(pem));
|
||||
const spki = publicKey.export({ type: 'spki', format: 'der' });
|
||||
const hex = crypto.createHash('sha256').update(spki).digest('hex').slice(0, 32);
|
||||
return hex.split('').map(ch => String.fromCharCode(97 + parseInt(ch, 16))).join('');
|
||||
}
|
||||
|
||||
/** updates.xml:浏览器靠它判断有没有新版本 */
|
||||
function writeUpdatesXml({ id, version, codebase }) {
|
||||
return [
|
||||
'<?xml version=\'1.0\' encoding=\'UTF-8\'?>',
|
||||
'<gupdate xmlns=\'http://www.google.com/update2/response\' protocol=\'2.0\'>',
|
||||
` <app appid='${id}'>`,
|
||||
` <updatecheck codebase='${codebase}' version='${version}' />`,
|
||||
' </app>',
|
||||
'</gupdate>',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** 上传一个文件到远端目录(先传临时名再 mv,避免中途被下到半个文件) */
|
||||
function uploadFile(config, localPath, remoteDir, name, stamp) {
|
||||
const remoteTmp = `${remoteDir}/.${name}.upload-${stamp}`;
|
||||
runScp(config, localPath, remoteTmp);
|
||||
runSsh(config, [
|
||||
'set -euo pipefail',
|
||||
`mv ${quoteForBash(remoteTmp)} ${quoteForBash(`${remoteDir}/${name}`)}`,
|
||||
`chmod 644 ${quoteForBash(`${remoteDir}/${name}`)}`,
|
||||
...(config.desktopOwner ? [ `chown ${quoteForBash(config.desktopOwner)} ${quoteForBash(`${remoteDir}/${name}`)}` ] : []),
|
||||
`echo "UPLOADED ${name}"`,
|
||||
].join('\n'));
|
||||
}
|
||||
|
||||
function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const config = loadDeployConfig(options.envName);
|
||||
|
||||
const version = options.version || manifestVersion();
|
||||
const baseUrl = String(options.baseUrl || config.desktopBaseUrl || (config.serverName ? `https://${config.serverName}` : ''))
|
||||
.replace(/\/+$/, '');
|
||||
// --zip 只出商店上传包,不需要后端地址
|
||||
if (!options.zipOnly && !baseUrl) {
|
||||
throw new Error('拿不到后端地址:请在 deploy.config.local.cjs 里配 desktopBaseUrl 或 serverName');
|
||||
}
|
||||
|
||||
// --dry-run 也要真的打包(只是不上传):本机得有 Chrome/Edge;--zip 不需要浏览器
|
||||
const browser = options.zipOnly ? '' : resolveBrowser(options.browser);
|
||||
|
||||
// 打包在临时目录里做,仓库里只留 out/ 产物
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yuncang-ext-'));
|
||||
try {
|
||||
console.log(`打包 Chrome 插件 ${version}(${path.relative(REPO_ROOT, EXT_DIR)})`);
|
||||
const srcDir = stageSources(workDir);
|
||||
|
||||
// 商店上传用的是 zip(manifest.json 必须在压缩包根目录)
|
||||
if (options.zipOnly) {
|
||||
const zipName = `${PACKAGE_NAME}-${version}.zip`;
|
||||
const zipPath = path.join(OUT_DIR, zipName);
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
fs.rmSync(zipPath, { force: true });
|
||||
runCommand('powershell.exe', [
|
||||
'-NoProfile', '-Command',
|
||||
`Compress-Archive -Path '${path.join(srcDir, '*')}' -DestinationPath '${zipPath}' -Force`,
|
||||
], { stdio: 'inherit' });
|
||||
|
||||
console.log(`商店上传包: ${zipPath}(${(fs.statSync(zipPath).size / 1024).toFixed(0)} KB)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const crxPath = packCrx(browser, srcDir, KEY_FILE, workDir);
|
||||
|
||||
const id = extensionIdFromKey(fs.readFileSync(KEY_FILE, 'utf8'));
|
||||
const crxName = `${PACKAGE_NAME}-${version}.crx`;
|
||||
const codebase = `${baseUrl}/download/extension/${crxName}`;
|
||||
const updateUrl = `${baseUrl}/download/extension/updates.xml`;
|
||||
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
fs.copyFileSync(crxPath, path.join(OUT_DIR, crxName));
|
||||
fs.writeFileSync(path.join(OUT_DIR, 'updates.xml'), writeUpdatesXml({ id, version, codebase }));
|
||||
fs.writeFileSync(path.join(OUT_DIR, 'extension-id.txt'), `${id}\n`);
|
||||
|
||||
console.log(`扩展 ID : ${id}`);
|
||||
console.log(`CRX : ${path.join(OUT_DIR, crxName)}`);
|
||||
console.log(`更新清单: ${updateUrl}`);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('--dry-run:只打包,不上传。');
|
||||
return;
|
||||
}
|
||||
|
||||
const remoteDir = config.extensionDownloadDir;
|
||||
if (!remoteDir) throw new Error('未配置 extensionDownloadDir(插件发布目录)');
|
||||
|
||||
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
||||
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
|
||||
|
||||
const stamp = getNowStamp();
|
||||
runSsh(config, [
|
||||
'set -euo pipefail',
|
||||
`mkdir -p ${quoteForBash(remoteDir)}`,
|
||||
`find ${quoteForBash(remoteDir)} -maxdepth 1 -type f -name ".upload-*" -delete`,
|
||||
].join('\n'));
|
||||
|
||||
uploadFile(config, path.join(OUT_DIR, crxName), remoteDir, crxName, stamp);
|
||||
// 最后传 updates.xml:新包先就位,浏览器再看到新版本号
|
||||
uploadFile(config, path.join(OUT_DIR, 'updates.xml'), remoteDir, 'updates.xml', stamp);
|
||||
|
||||
if (!options.skipNginx) refreshNginx(config);
|
||||
|
||||
console.log('');
|
||||
console.log('发布完成。客户机「工具 → 安装谷歌插件」会写入策略:');
|
||||
console.log(` ExtensionInstallForcelist = ${id};${updateUrl}`);
|
||||
console.log(` ExtensionInstallSources = ${baseUrl}/download/extension/*`);
|
||||
} finally {
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@ -25,7 +25,9 @@
|
||||
<MenuItem Header="打开日志目录" Click="OpenLogFolder_Click" />
|
||||
<MenuItem Header="清理日志" Click="ClearLogs_Click" />
|
||||
<Separator />
|
||||
<MenuItem Header="复制谷歌插件地址" Click="CopyExtensionPath_Click" />
|
||||
<MenuItem Header="安装谷歌插件(Chrome / Edge)" Click="InstallExtension_Click" />
|
||||
<MenuItem Header="卸载谷歌插件" Click="UninstallExtension_Click" />
|
||||
<MenuItem Header="复制插件路径(开发者模式)" Click="CopyExtensionPath_Click" />
|
||||
<Separator />
|
||||
<MenuItem Header="清理更新缓存" Click="ClearUpdateCache_Click" />
|
||||
<Separator />
|
||||
@ -110,7 +112,7 @@
|
||||
<Button DockPanel.Dock="Right" x:Name="DownloadButton" Content="下载录像…"
|
||||
Padding="12,5" Margin="8,0,0,0" IsEnabled="False" Click="Download_Click"
|
||||
Visibility="Collapsed"
|
||||
ToolTip="按工作台布局逐路下载这段时间的录像到本地目录(校验有录像后才显示)" />
|
||||
ToolTip="按工作台布局下载这段时间的录像到本地目录;跨网时由仓库设备代取(校验有录像后才显示)" />
|
||||
<Button DockPanel.Dock="Right" x:Name="PreviewButton" Content="预览回放"
|
||||
Padding="12,5" Margin="8,0,0,0" IsEnabled="False" Click="Preview_Click"
|
||||
Visibility="Collapsed"
|
||||
|
||||
@ -66,6 +66,12 @@ public partial class MainWindow : Window
|
||||
/// </summary>
|
||||
private IReadOnlyList<PackStream> _validatedStreams = Array.Empty<PackStream>();
|
||||
|
||||
/// <summary>
|
||||
/// 这次查询是「跨网」:查询机连不到仓库的 NVR,下载只能由云端转给能访问 NVR 的扫码服务代取。
|
||||
/// 由 <see cref="ValidatePlaybackAsync"/> 的选路结果设置。
|
||||
/// </summary>
|
||||
private bool _cloudDownload;
|
||||
|
||||
/// <summary>录像机凭据缓存(同一台 NVR 只取一次密码;多路并行下载会同时访问)</summary>
|
||||
private readonly ConcurrentDictionary<int, NvrCredential> _credentials = new();
|
||||
|
||||
@ -787,7 +793,80 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 「工具 → 复制谷歌插件地址」:插件随安装包释放到 <安装目录>\extension,
|
||||
/// 「工具 → 安装谷歌插件」:写 Chrome/Edge 企业策略(UAC 一次),重启浏览器后自动安装
|
||||
///
|
||||
/// 扩展 ID 从后端 `/download/extension/updates.xml` 读(由打包私钥决定),
|
||||
/// 这里不写死 —— 换私钥/换域名都不用改客户端。
|
||||
/// </summary>
|
||||
private async void InstallExtension_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var confirm = MessageBox.Show(this,
|
||||
"将为 Chrome 和 Edge 写入企业策略,重启浏览器后自动安装「云仓视频溯源 · 单号注入」插件。\n\n"
|
||||
+ "· 需要允许一次管理员权限(UAC);\n"
|
||||
+ "· 装好后插件由浏览器自己更新,不用再手动「加载已解压」;\n"
|
||||
+ "· 想撤销:同一菜单「卸载谷歌插件」。\n\n继续吗?",
|
||||
"安装谷歌插件", MessageBoxButton.OKCancel, MessageBoxImage.Question);
|
||||
if (confirm != MessageBoxResult.OK) return;
|
||||
|
||||
try
|
||||
{
|
||||
var result = await ExtensionInstaller.InstallAsync(_settings.ServerBaseUrl).ConfigureAwait(true);
|
||||
AppLog.Write($"[extension] 插件策略已写入:{string.Join("、", result.Targets)}(id={result.Id})");
|
||||
|
||||
MessageBox.Show(this,
|
||||
$"已为 {string.Join("、", result.Targets)} 写入策略。\n\n"
|
||||
+ $"扩展 ID:{result.Id}\n更新地址:{result.UpdateUrl}\n\n"
|
||||
+ "请完全退出并重新打开浏览器;在 chrome://extensions 里应能看到该插件,并显示「由你的组织管理」。",
|
||||
"安装谷歌插件", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
MessageBox.Show(this, "已取消管理员授权,浏览器策略没有改动。",
|
||||
"安装谷歌插件", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[extension] 安装插件失败:{ex.Message}");
|
||||
MessageBox.Show(this,
|
||||
$"安装失败:{ex.Message}\n\n"
|
||||
+ "没有管理员权限的机器只能走开发者模式:用「工具 → 复制插件路径(开发者模式)」手动加载。",
|
||||
"安装谷歌插件", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>「工具 → 卸载谷歌插件」:删掉我们写的那几条策略(UAC 一次)</summary>
|
||||
private async void UninstallExtension_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var confirm = MessageBox.Show(this,
|
||||
"将移除 Chrome / Edge 里由本软件写入的插件策略,重启浏览器后插件会被卸载。\n\n继续吗?",
|
||||
"卸载谷歌插件", MessageBoxButton.OKCancel, MessageBoxImage.Question);
|
||||
if (confirm != MessageBoxResult.OK) return;
|
||||
|
||||
try
|
||||
{
|
||||
var result = await ExtensionInstaller.UninstallAsync(_settings.ServerBaseUrl).ConfigureAwait(true);
|
||||
AppLog.Write($"[extension] 插件策略已移除:{(result.Targets.Count == 0 ? "没有找到" : string.Join("、", result.Targets))}");
|
||||
|
||||
MessageBox.Show(this,
|
||||
result.Targets.Count == 0
|
||||
? "没有找到本软件写入的插件策略(可能本来就没装)。"
|
||||
: "已移除插件策略,重启浏览器后插件会被卸载。",
|
||||
"卸载谷歌插件", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
MessageBox.Show(this, "已取消管理员授权,浏览器策略没有改动。",
|
||||
"卸载谷歌插件", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[extension] 卸载插件失败:{ex.Message}");
|
||||
MessageBox.Show(this, $"卸载失败:{ex.Message}", "卸载谷歌插件", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 「工具 → 复制插件路径(开发者模式)」:插件随安装包释放到 <安装目录>\extension,
|
||||
/// 复制这个 Windows 路径,再到 chrome://extensions「加载已解压的扩展程序」里粘进去。
|
||||
/// </summary>
|
||||
private void CopyExtensionPath_Click(object sender, RoutedEventArgs e)
|
||||
@ -1114,6 +1193,7 @@ public partial class MainWindow : Window
|
||||
_validateCts?.Cancel();
|
||||
_validateCts = null;
|
||||
_validatedStreams = Array.Empty<PackStream>();
|
||||
_cloudDownload = false;
|
||||
PreviewButton.Visibility = Visibility.Collapsed;
|
||||
DownloadButton.Visibility = Visibility.Collapsed;
|
||||
|
||||
@ -1278,6 +1358,9 @@ public partial class MainWindow : Window
|
||||
_validateCts = new CancellationTokenSource();
|
||||
var ct = _validateCts.Token;
|
||||
|
||||
// 每次重新选路前先按「本机可达」算,云端校验通过才置为跨网
|
||||
_cloudDownload = false;
|
||||
|
||||
var lines = new List<string> { $"正在校验 {streams.Count} 路回放…" };
|
||||
ShowPlayback(string.Join(Environment.NewLine, lines));
|
||||
|
||||
@ -1308,6 +1391,8 @@ public partial class MainWindow : Window
|
||||
if (cloud is { State: "ok", HasVideo: { } hasVideo })
|
||||
{
|
||||
_validatedStreams = hasVideo ? streams : Array.Empty<PackStream>();
|
||||
// 本机连不到仓库的 NVR → 下载必须走云端中转(本机直连只会 ffmpeg −138)
|
||||
_cloudDownload = hasVideo;
|
||||
|
||||
// 跨网只给下载:预览要实时拉流,云端中转成本高且体验差
|
||||
SetRouteButtons(showPreview: false, showDownload: hasVideo);
|
||||
@ -1466,6 +1551,13 @@ public partial class MainWindow : Window
|
||||
var streams = _validatedStreams.ToList();
|
||||
if (streams.Count == 0) return;
|
||||
|
||||
// 跨网:本机连不到仓库的 NVR(直连只会让 ffmpeg 报 −138),交给云端转给仓库设备代取
|
||||
if (_cloudDownload)
|
||||
{
|
||||
await DownloadViaCloudAsync(query).ConfigureAwait(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_playback.Available)
|
||||
{
|
||||
ShowPlayback("没有找到 ffmpeg,无法下载录像。把 ffmpeg.exe 放到安装目录 native\\ffmpeg\\ 后再试。");
|
||||
@ -1604,6 +1696,66 @@ public partial class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跨网下载:云端建任务 → 仓库设备(能访问 NVR 的那台)拉流合并并上传 → 本机取回落盘。
|
||||
///
|
||||
/// 查询机到仓库 NVR 的 8000/554 都不通,所以这里**不回落**本机直连。
|
||||
/// </summary>
|
||||
private async Task DownloadViaCloudAsync(PackQuery query)
|
||||
{
|
||||
var service = _server.PlaybackDownload;
|
||||
if (service is null)
|
||||
{
|
||||
ShowPlayback("本机服务还没就绪,稍后重试(或重启软件)。");
|
||||
return;
|
||||
}
|
||||
|
||||
var scanTime = query.Records.Count > 0 ? query.Records[0].ScanTime.LocalDateTime : DateTime.Now;
|
||||
|
||||
_playbackCts?.Cancel();
|
||||
_playbackCts = new CancellationTokenSource();
|
||||
var ct = _playbackCts.Token;
|
||||
|
||||
DownloadButton.IsEnabled = false;
|
||||
OpenFolderButton.Visibility = Visibility.Collapsed;
|
||||
ShowPlayback("跨网下载:正在联系仓库设备(要等它拉完流并上传)…");
|
||||
|
||||
// 进度也要落日志:云端为什么没接单(无在线设备/无密码/上传超时)只能从这里看出来
|
||||
var progress = new Progress<string>(text =>
|
||||
{
|
||||
AppLog.Write($"[playback] 跨网:{text}");
|
||||
ShowPlayback($"跨网下载:{text}");
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
var result = await service.DownloadViaCloudAsync(query.Code, scanTime, progress, ct)
|
||||
.ConfigureAwait(true);
|
||||
|
||||
_lastOutputFolder = result.Folder;
|
||||
OpenFolderButton.Visibility = Visibility.Visible;
|
||||
|
||||
var saved = result.Merged ?? result.Segments.FirstOrDefault() ?? result.Folder;
|
||||
var text = new List<string> { $"已保存:{saved}", "(跨网:仓库设备代取)" };
|
||||
text.AddRange(result.Warnings);
|
||||
ShowPlayback(string.Join(Environment.NewLine, text));
|
||||
AppLog.Write($"[playback] 跨网下载完成:{saved}");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
ShowPlayback("已取消");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowPlayback($"跨网下载失败:{ex.Message}");
|
||||
AppLog.Write($"[playback] 跨网下载失败:{ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
DownloadButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>合并失败时把片段从临时目录搬到用户目录(不丢数据),再清临时目录</summary>
|
||||
private void MoveSegmentsOut(List<(PackStream Stream, PlaybackClip Clip)> done, string folder, string workDir)
|
||||
{
|
||||
|
||||
@ -191,19 +191,31 @@ dotnet publish -c Release -r win-x64 --self-contained true `
|
||||
开发阶段想让 `bin\Debug` 的 exe 也能直接双击,两个办法:装官方 SDK/Desktop Runtime 到标准位置,
|
||||
或者每次用发布产物验证唤起。
|
||||
|
||||
## 打安装包(MSI)+ 自动更新
|
||||
## 打安装包(MSI / EXE)+ 自动更新
|
||||
|
||||
`desktop/installer/` 下是安装包定义(**WiX 5**,免费;WiX v6+ 需要 OSMF 付费协议,别装最新版)。
|
||||
`desktop/installer/` 下有两套安装包定义,产物一样(perUser、装到同一个目录、注册同一个 `yuncang://` 协议):
|
||||
|
||||
- **MSI**(`Product.wxs`,**WiX 5**,免费;WiX v6+ 需要 OSMF 付费协议,别装最新版);
|
||||
- **EXE**(`YuncangTrace.iss`,**Inno Setup 6**)——**完全不依赖 Windows Installer**。
|
||||
|
||||
> 为什么要 EXE:现场有电脑装不了 MSI(Windows Installer 服务被禁用 / 安全软件拦 MSI / 组策略禁止)。
|
||||
> 这类机器用 EXE 版;装过旧 MSI 的机器再装 EXE 时,EXE 会先静默卸载旧 MSI,不会在「应用和功能」里留两个条目
|
||||
> (旧 MSI 的卸载会把文件删掉,必须清掉)。MSI 卸载失败(正是 MSI 坏掉的现场)时,EXE 会尽量移除它的卸载项
|
||||
> (HKLM 下的条目要管理员权限,删不掉只记日志)—— 避免以后误点「卸载」把新装的文件删了。
|
||||
|
||||
```powershell
|
||||
# 工具只需装一次
|
||||
dotnet tool install --global wix --version 5.0.2
|
||||
dotnet tool install --global wix --version 5.0.2 # MSI
|
||||
winget install --id JRSoftware.InnoSetup # EXE(提供 ISCC.exe)
|
||||
|
||||
cd desktop\installer
|
||||
|
||||
.\build.ps1 # 开发环境(默认),版本取 csproj(1.0.0)
|
||||
.\build.ps1 # 开发环境(默认),版本取 csproj,MSI + EXE 都打
|
||||
.\build.ps1 -Target Exe # 只打 EXE
|
||||
.\build.ps1 -Target Msi # 只打 MSI(老流程)
|
||||
.\build.ps1 -Version 1.0.1 # 指定版本
|
||||
.\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "修复若干问题"
|
||||
.\build.ps1 -Target Exe -SkipDeploy # 只在 out\ 出包,不复制到后端(调打包用)
|
||||
```
|
||||
|
||||
### 环境与域名(`package.config.json`)
|
||||
@ -223,23 +235,40 @@ cd desktop\installer
|
||||
缺 `publish\native\ffmpeg\ffmpeg.exe` 会直接报错中止;
|
||||
2. `wix build` 生成 MSI(`Product.wxs` 用 `<Files Include="..\publish\native\**" />`、`<Files Include="..\publish\extension\**" />`
|
||||
递归收集,保持目录结构;`extension\test` / `extension\tools` 这类调试文件不打进包);
|
||||
3. 算 MD5 → 写 `version.json`;
|
||||
4. 复制到后端:MSI → `backend/app/public/download/desktop/`,`version.json` → `backend/app/public/version/desktop/`;
|
||||
5. 本地 `out/` 与后端目录**各只保留最近 5 个**安装包(`keepVersions` 可配)。
|
||||
`ISCC` 生成 EXE(`YuncangTrace.iss` 把 `publish\` 下的 exe / `native\**` / `extension\**` 打进单个安装包);
|
||||
3. 算 MD5 → 写 `version.json`(MSI 一份、EXE 一份);
|
||||
4. 复制到后端:安装包 → `backend/app/public/download/desktop/`,`version.json` → `backend/app/public/version/desktop/`;
|
||||
5. 本地 `out/` 与后端目录**各只保留最近 5 个**安装包(`.msi` / `.exe` 分别算,`keepVersions` 可配)。
|
||||
|
||||
> 安装包与版本信息都归到后端 `desktop` 子目录:下载地址 `<域名>/download/desktop/YuncangTraceSetup-x.y.z.msi`,
|
||||
> 版本信息仍是 `<域名>/download/version.json`(老客户端写死了这个地址,不能改)。
|
||||
> 安装包与版本信息都归到后端 `desktop` 子目录:下载地址 `<域名>/download/desktop/YuncangTraceSetup-x.y.z.exe`(新客户端)
|
||||
> 和 `.msi`(老客户端),版本信息仍是 `<域名>/download/version.json`(老客户端写死了这个地址,不能改)。
|
||||
|
||||
### 谷歌浏览器插件随包安装
|
||||
### 谷歌浏览器插件
|
||||
|
||||
仓库根目录的 `extension/` 会一起打进 MSI,安装后固定在 **`<安装目录>\extension`**
|
||||
(perUser 安装即 `%LOCALAPPDATA%\Programs\YuncangTrace\extension`):
|
||||
仓库根目录的 `extension/` 会一起打进 MSI / EXE,安装后固定在 **`<安装目录>\extension`**
|
||||
(perUser 安装即 `%LOCALAPPDATA%\Programs\YuncangTrace\extension`)。
|
||||
|
||||
- 菜单「工具 → 复制谷歌插件地址」直接把该目录的 **Windows 路径**(如 `C:\Users\xxx\AppData\Local\Programs\YuncangTrace\extension`)复制到剪贴板;
|
||||
**推荐:企业策略安装(零开发者模式)** —— `Services/ExtensionInstaller.cs`:
|
||||
|
||||
- 菜单「工具 → **安装谷歌插件(Chrome / Edge)**」:先拉后端 `/download/extension/updates.xml`
|
||||
读出扩展 ID,再生成 `.reg` 文件、**runas 执行 `reg import`** 写 HKLM 策略(Chrome + Edge),
|
||||
最后**读注册表**确认结果(不依赖子进程回传,早期用「提权起自己 + 临时文件回传」现场踩过
|
||||
「退出码 0 但结果文件没写」的坑):
|
||||
- `ExtensionInstallForcelist = <ID>;https://<域名>/download/extension/updates.xml`
|
||||
- `ExtensionInstallSources = https://<域名>/download/extension/*`
|
||||
- 重启浏览器后自动装好,之后由 `updates.xml` 自己升级;`chrome://extensions` 里显示「由你的组织管理」;
|
||||
- 菜单「工具 → **卸载谷歌插件**」:只删值里带 `/download/extension/` 的那几条,不影响别人写的策略;
|
||||
- 前提:发布端已执行过 `cd backend && npm run extension:publish`(产出 `.crx` + `updates.xml`);
|
||||
扩展 ID 由 `extension/keys/key.pem` 决定,**换私钥 = 换 ID = 已下发策略失效**,私钥务必备份;
|
||||
- 提权失败(没有管理员权限)时提示用户走下面的开发者模式。
|
||||
|
||||
**兜底:开发者模式** ——
|
||||
|
||||
- 菜单「工具 → 复制插件路径(开发者模式)」直接把该目录的 **Windows 路径**(如 `C:\Users\xxx\AppData\Local\Programs\YuncangTrace\extension`)复制到剪贴板;
|
||||
写剪贴板会重试(WPF → WinForms,各 3 次 ×150ms),被输入法/剪贴板工具/远程桌面占用时不会直接报 `CLIPBRD_E_CANT_OPEN`;
|
||||
仍然失败会提示原因,并可以选「打开记事本」把路径显示出来手动抄写;
|
||||
- 用户打开 `chrome://extensions` → 打开「开发者模式」→「加载已解压的扩展程序」→ 粘贴路径即可;
|
||||
- 卸载时该目录随 MSI 组件一起删除;
|
||||
- 卸载时该目录随安装包一起删除;
|
||||
|
||||
### 自动更新怎么工作
|
||||
|
||||
@ -248,13 +277,19 @@ cd desktop\installer
|
||||
→ version.json 的 version 比当前程序集版本新
|
||||
→ 软件内弹窗:新版本号 / 更新说明 / 安装包大小
|
||||
→ 点「立即更新」→ **软件内下载(进度条)**→ MD5 校验
|
||||
→ 自动静默安装(msiexec /passive)→ 软件退出 → 装完自动重新打开
|
||||
→ 自动静默安装(EXE 走 /VERYSILENT /SUPPRESSMSGBOXES /NORESTART;MSI 走 msiexec /passive)
|
||||
→ 软件退出 → 装完自动重新打开
|
||||
```
|
||||
|
||||
- **不跳浏览器**:下载、进度、校验、安装都在软件里完成。
|
||||
- 下载落在 `%TEMP%\YuncangTraceUpdate\`,文件名取 downloadUrl 里的真实文件名。
|
||||
- 下载落在 `%TEMP%\YuncangTraceUpdate\`,文件名取下载地址里的真实文件名。
|
||||
- 安装前会等 3 秒(让本进程先退出,否则 exe 被占用换不掉);perUser 安装不需要管理员。
|
||||
- **版本一致性防护**:若 `downloadUrl` 里的包版本(`YuncangTraceSetup-x.y.z.msi`)不比当前版本新,
|
||||
- **优先 EXE 包**:`version.json` 有 `downloadUrlExe` 就下 EXE(不依赖 Windows Installer,现场装不了 MSI 的机器也能升);
|
||||
- **校验值必须成对取**:下 EXE 用 `md5Exe` / `sizeExe`,下 MSI 用 `md5` / `size`。
|
||||
(`≤1.0.151` 的旧客户端两个都取 `md5`,于是下 EXE 拿 MSI 的哈希去比 → 必然「MD5 不一致」;
|
||||
给这些机器的第一个修复版要只发 MSI,见 backend/README 的 `--target=Msi`);
|
||||
没有该字段才退回 `downloadUrl`(MSI)。老客户端只认 `downloadUrl`,所以打包脚本**默认两个包都出**。
|
||||
- **版本一致性防护**:若下载地址里的包版本(`YuncangTraceSetup-x.y.z.msi` / `.exe`)不比当前版本新,
|
||||
直接忽略 —— 防止 version.json 配错/漏传包导致「装完还是旧版 → 无限弹窗」。
|
||||
- 回归测试可用环境变量 `YUNCANG_AUTO_UPDATE=1` 让弹窗出现后自动开始下载(无需手点)。
|
||||
|
||||
@ -265,7 +300,10 @@ cd desktop\installer
|
||||
"version": "1.0.1",
|
||||
"downloadUrl": "https://正式域名/download/desktop/YuncangTraceSetup-1.0.1.msi",
|
||||
"md5": "7a93b4…",
|
||||
"size": 56786944,
|
||||
"size": 141578240,
|
||||
"downloadUrlExe": "https://正式域名/download/desktop/YuncangTraceSetup-1.0.1.exe",
|
||||
"md5Exe": "d5c75e…",
|
||||
"sizeExe": 118886550,
|
||||
"publishedAt": "2026-10-17T12:00:58+08:00",
|
||||
"buildId": "20261017120058",
|
||||
"environment": "Production",
|
||||
@ -273,6 +311,8 @@ cd desktop\installer
|
||||
}
|
||||
```
|
||||
|
||||
> `downloadUrl`(MSI)是给老客户端的,**不能删**;`downloadUrlExe` 是新增字段,新客户端优先用它。
|
||||
|
||||
### ⚠️ 缓存(这里最容易踩坑)
|
||||
|
||||
Egg 的 `static` 在生产默认**强缓存一年**。如果 `version.json` 也被缓存,软件永远检测不到更新。
|
||||
@ -303,13 +343,16 @@ Egg 的 `static` 在生产默认**强缓存一年**。如果 `version.json` 也
|
||||
| --- | --- |
|
||||
| 安装范围 | **perUser**(免管理员、无 UAC),装到 `%LOCALAPPDATA%\Programs\YuncangTrace` |
|
||||
| 启动协议 | **安装即注册** `yuncang://`(HKCU),不需要先启动软件 |
|
||||
| 卸载 | MSI 自动删除 exe、协议注册、开始菜单 —— 即「取消注册」 |
|
||||
| 升级 | `MajorUpgrade`:装新版会替换旧版;降级被拦 |
|
||||
| 卸载 | MSI 由 Windows Installer 删除;EXE 由安装目录下的 `unins000.exe` 删除。两者都会清掉 exe、协议注册、开始菜单 —— 即「取消注册」 |
|
||||
| 升级 | MSI:`MajorUpgrade`(装新版替换旧版、拦降级);EXE:同一个 `AppId` 覆盖安装;**EXE ↔ MSI 可互相顶替**(装 EXE 时会先静默卸载旧 MSI) |
|
||||
| 用户数据 | `%LOCALAPPDATA%\YuncangTrace\{settings,session}.json` 卸载**不删**(重装后仍保持设置/登录) |
|
||||
|
||||
```powershell
|
||||
msiexec /i out\YuncangTraceSetup-1.0.1.msi # 安装
|
||||
msiexec /x out\YuncangTraceSetup-1.0.1.msi # 卸载
|
||||
msiexec /i out\YuncangTraceSetup-1.0.1.msi # MSI 安装
|
||||
msiexec /x out\YuncangTraceSetup-1.0.1.msi # MSI 卸载
|
||||
|
||||
.\out\YuncangTraceSetup-1.0.1.exe # EXE 安装(双击即可,免管理员)
|
||||
.\out\YuncangTraceSetup-1.0.1.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- # EXE 静默安装
|
||||
```
|
||||
|
||||
> 需要「本机所有用户都能用」时:`Product.wxs` 里 `Scope` 改 `perMachine`、注册表根改 `HKLM`,
|
||||
@ -487,7 +530,7 @@ HKEY_CURRENT_USER\Software\Classes\yuncang
|
||||
- **每次启动都会自动把注册项校正到「当前这个 exe」**(幂等)。这一点很关键:
|
||||
换目录安装、从 `bin\Debug` 换成发布版、重新装一遍之后,注册表里残留的旧路径会让网页
|
||||
唤起一个不存在 / 缺运行时的 exe(典型现象就是弹「You must install .NET」或干脆没反应)。
|
||||
- **界面上完全不展示协议**:注册由安装包完成、卸载时 MSI 自动删除,启动时自动校正到当前 exe;
|
||||
- **界面上完全不展示协议**:注册由安装包完成、卸载时自动删除,启动时自动校正到当前 exe;
|
||||
用户不需要知道 `yuncang://` 这回事(排障看日志或注册表即可)。
|
||||
- 手工注册/排查:
|
||||
|
||||
@ -563,6 +606,11 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
> 不需要把每一路都验完,也不需要用户手动点「校验」。
|
||||
> 预览和下载仍按**全部**流处理:没录像的那几路在下载时自己跳过,保证多路合并不会退化成单路。
|
||||
>
|
||||
> **跨网(查询机和录像机不在同一张网里)**:局域网找不到「设备管理服务」时改问云端,由**能访问
|
||||
> 录像机的仓库扫码服务**校验;这种查询只给「下载录像」,而且下载**走云端中转**(云端建任务 →
|
||||
> 仓库设备拉流合并并上传 → 本机把成片取回),不再让本机直连录像机 —— 查询机到仓库 NVR 的
|
||||
> 8000/554 本来就不通,直连只会让 ffmpeg 报 `退出码 -138`(RTSP 连接超时,`AVERROR(ETIMEDOUT)`)。
|
||||
>
|
||||
> **回放时间按录像机时钟对齐**:扫码时间来自本机时钟,回放是按录像机本地时间定位的。
|
||||
> 每次校验/预览/下载前会读一次录像机时间(8000 私有协议),把请求窗口整体平移,
|
||||
> 日志里能看到 `[playback] 录像机 … 与本机时钟相差 X 秒`。本机时间不准(比如 Windows
|
||||
|
||||
@ -362,8 +362,11 @@ public static class ServiceInstaller
|
||||
/// <summary>
|
||||
/// 放行局域网发现端口(TCP 取流健康端点 + UDP 询问应答)。
|
||||
///
|
||||
/// 只对**域/专用网络**放行:公用网络(咖啡厅 WiFi)不暴露这些端口。
|
||||
/// 现场若把办公网识别成「公用」,需要手动改成「专用」或加同名规则。
|
||||
/// ⚠️ 必须是 <c>profile=any</c>:仓库/公司的网卡经常被 Windows 判成「**公用网络**」
|
||||
/// (插网线、连 WiFi、没加域都是 Public),而 `domain,private` 的规则在公用网络下
|
||||
/// **完全不生效** —— 2026-10-31 现场复现:同一局域网,别的查询机永远探测不到这台,
|
||||
/// 只有本机自测能通(loopback 不受防火墙过滤)。
|
||||
/// 端口本身有身份校验(主体令牌,且只回同主体/同后端的询问),不靠防火墙档位兜底。
|
||||
/// </summary>
|
||||
private static void EnsureFirewallRules()
|
||||
{
|
||||
@ -377,8 +380,15 @@ public static class ServiceInstaller
|
||||
RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}");
|
||||
var result = RunTool("netsh.exe", "advfirewall", "firewall", "add", "rule",
|
||||
$"name={name}", "dir=in", "action=allow", $"protocol={protocol}", $"localport={port}",
|
||||
"profile=domain,private");
|
||||
if (result.Code != 0) AppLog.Write($"[agent] 添加防火墙规则失败({name}):{result.Output}");
|
||||
"profile=any");
|
||||
if (result.Code != 0)
|
||||
{
|
||||
AppLog.Write($"[agent] 添加防火墙规则失败({name}):{result.Output}");
|
||||
}
|
||||
else
|
||||
{
|
||||
AppLog.Write($"[agent] 防火墙规则已更新:{name}({protocol} {port},profile=any)");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RemoveFirewallRules()
|
||||
|
||||
@ -137,6 +137,12 @@ public sealed class ApiClient
|
||||
/// <summary>长轮询专用:挂起时间比 15 秒长,必须用不限时的客户端</summary>
|
||||
private static readonly HttpClient LongPollHttp = new() { Timeout = Timeout.InfiniteTimeSpan };
|
||||
|
||||
/// <summary>
|
||||
/// 慢接口专用:云端建跨网下载任务时会**同步等仓库设备传完**(服务端最长挂 120 秒),
|
||||
/// 用 15 秒的客户端必然先超时(现场表现:「云端中转不可用」)。这里留 30 秒余量。
|
||||
/// </summary>
|
||||
private static readonly HttpClient SlowHttp = new() { Timeout = TimeSpan.FromSeconds(150) };
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
@ -461,8 +467,10 @@ public sealed class ApiClient
|
||||
public async Task<(string State, string? TaskId, string? Message)> EdgeDownloadCreateAsync(
|
||||
string token, int subjectId, string code, CancellationToken ct = default)
|
||||
{
|
||||
// 云端这个接口是**同步等设备传完**才返回的(最长 120 秒)→ 必须用慢接口客户端
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Post, "/api/web/edge/download",
|
||||
token, subjectId, JsonSerializer.Serialize(new { code }), "云端下载录像", ct).ConfigureAwait(false);
|
||||
token, subjectId, JsonSerializer.Serialize(new { code }), "云端下载录像(等仓库设备上传)", ct, SlowHttp)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var (data, _) = ReadEnvelope(response, text);
|
||||
@ -864,7 +872,7 @@ public sealed class ApiClient
|
||||
|
||||
/// <summary>带用户令牌 + 主体 header 的请求</summary>
|
||||
private Task<HttpResponseMessage> SendAuthorizedAsync(HttpMethod method, string path, string token, int subjectId,
|
||||
string? jsonBody, string action, CancellationToken ct)
|
||||
string? jsonBody, string action, CancellationToken ct, HttpClient? client = null)
|
||||
{
|
||||
return SendAsync(() =>
|
||||
{
|
||||
@ -873,7 +881,7 @@ public sealed class ApiClient
|
||||
if (subjectId > 0) request.Headers.TryAddWithoutValidation("X-Subject-Id", subjectId.ToString());
|
||||
if (jsonBody is not null) request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
|
||||
return request;
|
||||
}, action, ct);
|
||||
}, action, ct, client);
|
||||
}
|
||||
|
||||
/// <summary>带设备令牌的请求(POST,body 为 JSON)</summary>
|
||||
@ -899,12 +907,12 @@ public sealed class ApiClient
|
||||
|
||||
/// <summary>发请求:连不上时翻成「无法连接服务器」这种能看懂的提示</summary>
|
||||
private async Task<HttpResponseMessage> SendAsync(
|
||||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct)
|
||||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct, HttpClient? client = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = createRequest();
|
||||
return await Http.SendAsync(request, ct).ConfigureAwait(false);
|
||||
return await (client ?? Http).SendAsync(request, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
|
||||
@ -60,7 +60,7 @@ public static class EdgeDiscoveryClient
|
||||
var ownServer = HikWorkerDiscovery.NormalizeServer(server);
|
||||
if (ownServer.Length == 0)
|
||||
{
|
||||
AppLog.Write("[edge] 本机后端地址未知,跳过局域网询问");
|
||||
AppLog.Write($"[edge] 本机后端地址未知(设置里的服务器地址是「{server}」),跳过局域网询问");
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -70,12 +70,23 @@ public static class EdgeDiscoveryClient
|
||||
var payload = BuildQuery(subjectId, ownServer, nvrs);
|
||||
var bytes = Encoding.UTF8.GetBytes(payload);
|
||||
|
||||
foreach (var target in DeviceScanner.BroadcastTargets())
|
||||
var targets = DeviceScanner.BroadcastTargets();
|
||||
var wait = nvrs is { Count: > 0 } ? ProbeWait : QuickWait;
|
||||
|
||||
// 排障用:对端只回「同主体 + 同后端地址 + 能连上 NVR」的询问,
|
||||
// 三条里任何一条不满足都是**静默丢弃**,现场根本看不出为什么找不到。
|
||||
AppLog.Write($"[edge] 局域网询问:主体 {subjectId},后端 {ownServer},"
|
||||
+ $"NVR {(nvrs is { Count: > 0 } ? string.Join("、", nvrs.Select(item => $"{item.Host}:{item.Port}")) : "(不带)")}"
|
||||
+ $" → UDP {HikWorkerPorts.UdpQuery} 广播 {string.Join("、", targets)},等 {wait.TotalSeconds:0.#} 秒");
|
||||
|
||||
var sent = 0;
|
||||
foreach (var target in targets)
|
||||
{
|
||||
try
|
||||
{
|
||||
await udp.SendAsync(bytes, bytes.Length, new IPEndPoint(target, HikWorkerPorts.UdpQuery))
|
||||
.WaitAsync(ct).ConfigureAwait(false);
|
||||
sent++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -83,11 +94,13 @@ public static class EdgeDiscoveryClient
|
||||
}
|
||||
}
|
||||
|
||||
var wait = nvrs is { Count: > 0 } ? ProbeWait : QuickWait;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(wait);
|
||||
|
||||
var peers = new List<EdgePeer>();
|
||||
var logged = new HashSet<string>(StringComparer.Ordinal);
|
||||
var datagrams = 0;
|
||||
var ignored = 0;
|
||||
|
||||
while (!timeout.IsCancellationRequested)
|
||||
{
|
||||
@ -106,25 +119,54 @@ public static class EdgeDiscoveryClient
|
||||
break;
|
||||
}
|
||||
|
||||
var peer = TryParseReply(received.Buffer, received.RemoteEndPoint.Address, subjectId, ownServer);
|
||||
if (peer is null) continue;
|
||||
datagrams++;
|
||||
|
||||
var peer = TryParseReply(received.Buffer, received.RemoteEndPoint.Address, subjectId, ownServer,
|
||||
out var reason);
|
||||
if (peer is null)
|
||||
{
|
||||
ignored++;
|
||||
AppLog.Write($"[edge] 忽略 {received.RemoteEndPoint.Address} 的报文:{reason}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 带了 NVR 询问时,对端必须确认能连通其中至少一台(它已经自己筛过,这里再兜一层)
|
||||
if (nvrs is { Count: > 0 } && !HasAnyReachable(peer, nvrs)) continue;
|
||||
if (nvrs is { Count: > 0 } && !HasAnyReachable(peer, nvrs))
|
||||
{
|
||||
ignored++;
|
||||
AppLog.Write($"[edge] 忽略 {peer.Sn}({peer.Host})的应答:它连不上询问的 NVR"
|
||||
+ $"(它能连:{(peer.Reachable.Count == 0 ? "无" : string.Join("、", peer.Reachable))})");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 同一台机器会因为「广播 + 定向广播」回多次,日志只记第一次
|
||||
if (logged.Add(peer.Sn + "|" + peer.Host))
|
||||
{
|
||||
AppLog.Write($"[edge] 收到应答:{peer.Sn}({peer.Host}:{peer.Port}),"
|
||||
+ $"可服务 {(peer.Reachable.Count == 0 ? "(未询问 NVR)" : string.Join("、", peer.Reachable))}");
|
||||
}
|
||||
|
||||
peers.Add(peer);
|
||||
}
|
||||
|
||||
if (peers.Count == 0) return null;
|
||||
if (peers.Count == 0)
|
||||
{
|
||||
AppLog.Write($"[edge] 局域网询问无结果:发出 {sent}/{targets.Count} 个广播,"
|
||||
+ $"收到 {datagrams} 个报文(被忽略 {ignored} 个)");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 同一台机器会因为我们发了「广播 + 各网段定向广播」而回多次,先按 (SN, 主机) 去重
|
||||
return peers
|
||||
var best = peers
|
||||
.GroupBy(item => item.Sn + "|" + item.Host, StringComparer.Ordinal)
|
||||
.Select(group => group.First())
|
||||
// 多台都能服务时优先本机(自己就在这台机器上,省一次跨机转发)
|
||||
.OrderByDescending(item => IsLocalAddress(item.Host))
|
||||
.ThenBy(item => item.Sn, StringComparer.Ordinal)
|
||||
.First();
|
||||
|
||||
AppLog.Write($"[edge] 局域网询问结果:选 {best.Display}(收到 {datagrams} 个报文)");
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool IsLocalAddress(string host)
|
||||
@ -172,18 +214,26 @@ public static class EdgeDiscoveryClient
|
||||
}, HikWorkerJson.Options);
|
||||
}
|
||||
|
||||
private static EdgePeer? TryParseReply(byte[] buffer, IPAddress from, int expectedSubject, string expectedServer)
|
||||
/// <param name="reason">被丢弃的原因(成功时为空)——现场排障只靠它</param>
|
||||
private static EdgePeer? TryParseReply(byte[] buffer, IPAddress from, int expectedSubject, string expectedServer,
|
||||
out string reason)
|
||||
{
|
||||
reason = string.Empty;
|
||||
try
|
||||
{
|
||||
var text = Encoding.UTF8.GetString(buffer).TrimStart();
|
||||
if (text.Length == 0 || text[0] != '{') return null;
|
||||
if (text.Length == 0 || text[0] != '{')
|
||||
{
|
||||
reason = $"不是 JSON:{Brief(text)}";
|
||||
return null;
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var root = doc.RootElement;
|
||||
|
||||
if (!root.TryGetProperty("type", out var type) || type.GetString() != HikWorkerDiscovery.ReplyType)
|
||||
{
|
||||
reason = $"不是 {HikWorkerDiscovery.ReplyType} 报文:{Brief(text)}";
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -192,12 +242,18 @@ public static class EdgeDiscoveryClient
|
||||
|| !subjectElement.TryGetInt32(out var subjectId)
|
||||
|| subjectId != expectedSubject)
|
||||
{
|
||||
reason = root.TryGetProperty("subjectId", out var rawSubject)
|
||||
? $"主体不同:应答 {rawSubject.GetRawText()} ≠ 本机 {expectedSubject}"
|
||||
: $"应答里没有 subjectId:{Brief(text)}";
|
||||
return null;
|
||||
}
|
||||
|
||||
// 还要同环境:主体 id 在各环境都从 1 开始,光比主体会把别环境的机器招进来
|
||||
if (!string.Equals(GetString(root, "server"), expectedServer, StringComparison.Ordinal))
|
||||
var replyServer = GetString(root, "server");
|
||||
if (!string.Equals(replyServer, expectedServer, StringComparison.Ordinal))
|
||||
{
|
||||
reason = $"环境不同:应答 {replyServer} ≠ 本机 {expectedServer}"
|
||||
+ "(设置里的「服务器地址」要和对方完全一致:协议/域名/端口)";
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -224,12 +280,17 @@ public static class EdgeDiscoveryClient
|
||||
reachable,
|
||||
GetString(root, "version") ?? "");
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
reason = $"解析失败:{ex.Message}";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>报文摘要:日志只要一眼能认出来,不要整段刷屏</summary>
|
||||
private static string Brief(string text)
|
||||
=> text.Length <= 120 ? text : text[..120] + "…";
|
||||
|
||||
private static string? GetString(JsonElement element, string name)
|
||||
=> element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
|
||||
? value.GetString()
|
||||
|
||||
@ -44,7 +44,14 @@ public sealed class StreamGateway
|
||||
if (subjectId <= 0) return null;
|
||||
|
||||
var key = BuildKey(subjectId, nvrs);
|
||||
if (TryGetCached(key, out var cached)) return cached;
|
||||
if (TryGetCached(key, out var cached))
|
||||
{
|
||||
// 缓存命中就不再广播了:不记一行的话,现场会以为「探测根本没跑」
|
||||
AppLog.Write(cached is null
|
||||
? "[edge] 局域网探测(15 秒缓存):没有可用的设备管理服务"
|
||||
: $"[edge] 局域网探测(15 秒缓存):{cached.Display}");
|
||||
return cached;
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
|
||||
393
desktop/Services/ExtensionInstaller.cs
Normal file
393
desktop/Services/ExtensionInstaller.cs
Normal file
@ -0,0 +1,393 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 「工具 → 安装谷歌插件」:用**企业策略**把 Chrome / Edge 的扩展装上
|
||||
///
|
||||
/// 为什么不能像以前那样「复制解压目录 + 加载已解压」:
|
||||
/// - 那只在开发者模式生效,每台机器要人手动点,Chrome 每次启动还会提示「请停用以开发者模式运行的扩展程序」;
|
||||
/// - 策略安装(<c>ExtensionInstallForcelist</c>)只认 `<扩展ID>;<update_url>`,update_url 必须是
|
||||
/// 一个可访问的 XML(我们自己的 `/download/extension/updates.xml`),**不认本地目录**。
|
||||
///
|
||||
/// 实现方式(**不依赖进程间回传结果**):
|
||||
/// 1. 去后端拉 `updates.xml` 读出扩展 ID;
|
||||
/// 2. 生成一个 `.reg` 文件(写 HKLM 策略);
|
||||
/// 3. runas 执行 `reg.exe import`(一次 UAC);
|
||||
/// 4. **直接读注册表**确认写没写进去 —— 成功与否以注册表为准,不看子进程输出。
|
||||
///
|
||||
/// ⚠️ 早期版本用「runas 起自己 + 临时文件回传结果」,现场出现过
|
||||
/// 「提权进程退出码 0 但结果文件没写」→ 装不上。reg import 只有一步动作、没有 IPC,稳得多。
|
||||
/// </summary>
|
||||
public static class ExtensionInstaller
|
||||
{
|
||||
/// <summary>更新清单路径(相对后端地址)</summary>
|
||||
private const string UpdatePath = "/download/extension/updates.xml";
|
||||
|
||||
/// <summary>允许安装来源的匹配串(非商店 CRX 必须放行,否则 Chrome 直接拒绝)</summary>
|
||||
private const string SourcesSuffix = "/download/extension/*";
|
||||
|
||||
/// <summary>我们写的策略以后都带这个特征,卸载时按它精确匹配,不误删别人的策略</summary>
|
||||
private const string OurMarker = "/download/extension/";
|
||||
|
||||
/// <summary>Chrome / Edge 的策略根(都支持 ExtensionInstallForcelist + ExtensionInstallSources)</summary>
|
||||
private static readonly string[] BrowserPolicyRoots =
|
||||
{
|
||||
@"SOFTWARE\Policies\Google\Chrome",
|
||||
@"SOFTWARE\Policies\Microsoft\Edge",
|
||||
};
|
||||
|
||||
/// <summary>用户点了 UAC 的「否」</summary>
|
||||
private const int ErrorCancelled = 1223;
|
||||
|
||||
public sealed class HelperResult
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
public string? Error { get; set; }
|
||||
public string? Id { get; set; }
|
||||
public string? UpdateUrl { get; set; }
|
||||
public List<string> Targets { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 装插件(**会弹一次 UAC**)
|
||||
/// </summary>
|
||||
/// <exception cref="OperationCanceledException">用户取消了 UAC 授权</exception>
|
||||
/// <exception cref="InvalidOperationException">拉不到更新清单 / 策略没写进去</exception>
|
||||
public static async Task<HelperResult> InstallAsync(string serverBaseUrl, CancellationToken ct = default)
|
||||
{
|
||||
var baseUrl = NormalizeBase(serverBaseUrl);
|
||||
var id = await FetchExtensionIdAsync(baseUrl, ct).ConfigureAwait(false);
|
||||
return await ApplyAsync(baseUrl, id, install: true, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>卸插件(**会弹一次 UAC**):只删带我们 URL 特征的那几条策略</summary>
|
||||
public static Task<HelperResult> UninstallAsync(string serverBaseUrl, CancellationToken ct = default)
|
||||
=> ApplyAsync(NormalizeBase(serverBaseUrl), string.Empty, install: false, ct);
|
||||
|
||||
/// <summary>更新清单地址(失败提示里要给用户看)</summary>
|
||||
public static string UpdateUrlOf(string serverBaseUrl) => NormalizeBase(serverBaseUrl) + UpdatePath;
|
||||
|
||||
private static string NormalizeBase(string serverBaseUrl)
|
||||
{
|
||||
var value = (serverBaseUrl ?? string.Empty).Trim().TrimEnd('/');
|
||||
if (value.Length == 0) throw new InvalidOperationException("后端地址为空,无法安装插件");
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>拉 updates.xml,读 `<app appid="...">`</summary>
|
||||
private static async Task<string> FetchExtensionIdAsync(string baseUrl, CancellationToken ct)
|
||||
{
|
||||
var url = baseUrl + UpdatePath;
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
|
||||
string xml;
|
||||
try
|
||||
{
|
||||
xml = await http.GetStringAsync(url, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"拿不到插件更新清单({url}):{ex.Message}\n\n"
|
||||
+ "服务端还没发布过插件包?先执行 backend 的 npm run extension:publish。", ex);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var id = XDocument.Parse(xml)
|
||||
.Descendants()
|
||||
.FirstOrDefault(element => element.Name.LocalName == "app")
|
||||
?.Attribute("appid")?.Value?.Trim();
|
||||
|
||||
if (string.IsNullOrEmpty(id) || id.Length != 32)
|
||||
{
|
||||
throw new InvalidOperationException($"更新清单里没有有效的 appid({url})");
|
||||
}
|
||||
return id;
|
||||
}
|
||||
catch (Exception ex) when (ex is not InvalidOperationException)
|
||||
{
|
||||
throw new InvalidOperationException($"解析插件更新清单失败({url}):{ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>生成 .reg → runas 执行 reg import → 读注册表确认</summary>
|
||||
private static async Task<HelperResult> ApplyAsync(string baseUrl, string id, bool install, CancellationToken ct)
|
||||
{
|
||||
var regFile = Path.Combine(Path.GetTempPath(), $"yuncang_ext_{Guid.NewGuid():N}.reg");
|
||||
var regText = BuildReg(baseUrl, id, install);
|
||||
|
||||
if (regText.Length == 0)
|
||||
{
|
||||
// 卸载时没有任何我们写的值:直接算成功
|
||||
AppLog.Write("[extension] 没有找到本软件写入的策略,无需提权");
|
||||
return new HelperResult { Ok = true, Id = id, UpdateUrl = baseUrl + UpdatePath };
|
||||
}
|
||||
|
||||
File.WriteAllText(regFile, regText, Encoding.Unicode);
|
||||
|
||||
var regExe = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "reg.exe");
|
||||
var psi = new ProcessStartInfo(regExe, $"import \"{regFile}\"")
|
||||
{
|
||||
UseShellExecute = true, // runas 只能走 ShellExecute
|
||||
Verb = "runas",
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
|
||||
AppLog.Write($"[extension] 提权导入策略({(install ? "安装" : "卸载")}):{psi.FileName} {psi.Arguments}");
|
||||
|
||||
try
|
||||
{
|
||||
using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException("提权进程启动失败");
|
||||
|
||||
await process.WaitForExitAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// 以注册表实际状态为准(reg 的退出码在不同系统上不完全可靠)
|
||||
var ok = install ? HasExactPolicy(id, baseUrl) : !HasAnyOfOurPolicy();
|
||||
if (!ok)
|
||||
{
|
||||
AppLog.Write($"[extension] reg import 退出码 {process.ExitCode},但注册表未生效({regText})");
|
||||
throw new InvalidOperationException(
|
||||
$"策略没有写进注册表(reg import 退出码 {process.ExitCode})。\n\n"
|
||||
+ "可能被安全软件拦截了注册表写入;也可以手动导入下面这个文件后重试:\n"
|
||||
+ regFile);
|
||||
}
|
||||
|
||||
return new HelperResult
|
||||
{
|
||||
Ok = true,
|
||||
Id = id,
|
||||
UpdateUrl = baseUrl + UpdatePath,
|
||||
Targets = BrowserPolicyRoots.Select(root => root.EndsWith("Chrome", StringComparison.OrdinalIgnoreCase) ? "Chrome" : "Edge").ToList(),
|
||||
};
|
||||
}
|
||||
catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
|
||||
{
|
||||
throw new OperationCanceledException("已取消管理员授权,浏览器策略没有改动");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDelete(regFile);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>拼 .reg 文本(空文本 = 没有要改的东西)</summary>
|
||||
private static string BuildReg(string baseUrl, string id, bool install)
|
||||
{
|
||||
var updateUrl = baseUrl + UpdatePath;
|
||||
var sources = baseUrl + SourcesSuffix;
|
||||
|
||||
var builder = new StringBuilder();
|
||||
var hasContent = false;
|
||||
|
||||
foreach (var root in BrowserPolicyRoots)
|
||||
{
|
||||
var forcelistPath = root + @"\ExtensionInstallForcelist";
|
||||
var sourcesPath = root + @"\ExtensionInstallSources";
|
||||
|
||||
var forcelistLines = BuildValueLines(forcelistPath, $"{id};{updateUrl}", install);
|
||||
var sourcesLines = BuildValueLines(sourcesPath, sources, install);
|
||||
|
||||
if (forcelistLines.Count == 0 && sourcesLines.Count == 0) continue;
|
||||
|
||||
if (!hasContent)
|
||||
{
|
||||
builder.AppendLine("Windows Registry Editor Version 5.00");
|
||||
hasContent = true;
|
||||
}
|
||||
|
||||
if (forcelistLines.Count > 0)
|
||||
{
|
||||
builder.AppendLine();
|
||||
builder.AppendLine($"[HKEY_LOCAL_MACHINE\\{forcelistPath}]");
|
||||
foreach (var line in forcelistLines) builder.AppendLine(line);
|
||||
}
|
||||
|
||||
if (sourcesLines.Count > 0)
|
||||
{
|
||||
builder.AppendLine();
|
||||
builder.AppendLine($"[HKEY_LOCAL_MACHINE\\{sourcesPath}]");
|
||||
foreach (var line in sourcesLines) builder.AppendLine(line);
|
||||
}
|
||||
}
|
||||
|
||||
return hasContent ? builder.ToString() : string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成某个策略键要写的行(安装 = 写入/复用值名;卸载 = 删除我们写的值)
|
||||
///
|
||||
/// 安装时**复用已有的值名**(值就是我们想要的,或值是旧的我们 URL),
|
||||
/// 顺手把重复的历史值删掉 —— 否则每点一次「安装」都会多出一条一样的策略。
|
||||
/// </summary>
|
||||
private static List<string> BuildValueLines(string policyPath, string desiredValue, bool install)
|
||||
{
|
||||
var existing = PolicyValues(policyPath);
|
||||
|
||||
if (!install)
|
||||
{
|
||||
return existing
|
||||
.Where(item => item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
|
||||
.Select(item => $"\"{item.Key}\"=-")
|
||||
.ToList();
|
||||
}
|
||||
|
||||
var lines = new List<string>();
|
||||
|
||||
// ① 已经是目标值 → 直接用这个值名
|
||||
var target = existing
|
||||
.FirstOrDefault(item => string.Equals(item.Value.Trim(), desiredValue, StringComparison.OrdinalIgnoreCase))
|
||||
.Key;
|
||||
|
||||
// ② 否则复用「我们写的旧值」那个名字(比如域名换过)
|
||||
if (target is null)
|
||||
{
|
||||
target = existing
|
||||
.FirstOrDefault(item => item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
|
||||
.Key;
|
||||
}
|
||||
|
||||
// ③ 都没有才找一个空号(默认 "1",被别人占了就顺延)
|
||||
target ??= PickFreeValueName(existing.Keys);
|
||||
|
||||
lines.Add($"\"{target}\"=\"{Escape(desiredValue)}\"");
|
||||
|
||||
// 清掉重复的历史条目(同一个扩展我们可能写过多条)
|
||||
foreach (var item in existing)
|
||||
{
|
||||
if (string.Equals(item.Key, target, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (!item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
lines.Add($"\"{item.Key}\"=-");
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>该策略键下的「值名 → 值」(读不到返回空字典)</summary>
|
||||
private static Dictionary<string, string> PolicyValues(string policyPath)
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
|
||||
using var key = baseKey.OpenSubKey(policyPath);
|
||||
if (key is null) return result;
|
||||
|
||||
foreach (var name in key.GetValueNames())
|
||||
{
|
||||
if (key.GetValue(name) is string text) result[name] = text;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 读不到就当没有
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>找一个没被占用的值名</summary>
|
||||
private static string PickFreeValueName(IEnumerable<string> used)
|
||||
{
|
||||
var taken = new HashSet<string>(used, StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 1; i < 100; i++)
|
||||
{
|
||||
if (!taken.Contains(i.ToString())) return i.ToString();
|
||||
}
|
||||
return Guid.NewGuid().ToString("N");
|
||||
}
|
||||
|
||||
/// <summary>装成功后该有的那条 forcelist 值在不在(读 HKLM 不需要管理员)</summary>
|
||||
private static bool HasExactPolicy(string id, string baseUrl)
|
||||
{
|
||||
if (id.Length == 0) return false;
|
||||
var expected = $"{id};{baseUrl}{UpdatePath}";
|
||||
|
||||
foreach (var root in BrowserPolicyRoots)
|
||||
{
|
||||
foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 })
|
||||
{
|
||||
try
|
||||
{
|
||||
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
|
||||
using var key = baseKey.OpenSubKey(root + @"\ExtensionInstallForcelist");
|
||||
if (key is null) continue;
|
||||
|
||||
foreach (var name in key.GetValueNames())
|
||||
{
|
||||
if (key.GetValue(name) is string text
|
||||
&& string.Equals(text.Trim(), expected, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 读不到就当没有
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>还有没有我们写的策略(卸载后应为 false)</summary>
|
||||
private static bool HasAnyOfOurPolicy()
|
||||
{
|
||||
foreach (var root in BrowserPolicyRoots)
|
||||
{
|
||||
foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 })
|
||||
{
|
||||
try
|
||||
{
|
||||
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
|
||||
using var key = baseKey.OpenSubKey(root + @"\ExtensionInstallForcelist");
|
||||
if (key is null) continue;
|
||||
|
||||
foreach (var name in key.GetValueNames())
|
||||
{
|
||||
if (key.GetValue(name) is string text
|
||||
&& text.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 读不到就当没有
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>.reg 字符串里的转义(反斜杠、引号)</summary>
|
||||
private static string Escape(string value)
|
||||
=> value.Replace("\\", "\\\\").Replace("\"", "\\\"");
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 临时文件删不掉不影响业务
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -143,6 +143,26 @@ public sealed class PlaybackDownloadService
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跨网下载:**只走云端中转**,不回落本机直连。
|
||||
///
|
||||
/// 桌面主窗的「下载录像」在跨网时用它 —— 查询机连不到仓库的 NVR,
|
||||
/// 本机直连只会让 ffmpeg 报 −138(RTSP 连接超时)。
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">云端不可用 / 没有在线设备 / 设备代取失败</exception>
|
||||
public async Task<PlaybackDownloadResult> DownloadViaCloudAsync(string code, DateTime scanTime,
|
||||
IProgress<string>? progress = null, CancellationToken ct = default)
|
||||
{
|
||||
var result = await TryDownloadViaCloudAsync(code, scanTime, progress, ct).ConfigureAwait(false);
|
||||
if (result is null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"云端中转不可用(没有在线的扫码服务,或云端任务创建失败,详见上方提示)");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跨公司路径:云端建任务 → 仓库设备拉流并上传 → 本机把成片取回落盘。
|
||||
///
|
||||
|
||||
@ -9,7 +9,10 @@ namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>发现的新版本(来自后端静态 `version.json`)</summary>
|
||||
/// <param name="Version">新版本号(如 1.0.1)</param>
|
||||
/// <param name="DownloadUrl">安装包地址(一般是后端 `/download/YuncangTraceSetup-x.y.z.msi`)</param>
|
||||
/// <param name="DownloadUrl">
|
||||
/// 安装包地址:优先 EXE(`/download/desktop/YuncangTraceSetup-x.y.z.exe`),
|
||||
/// 没有 EXE 字段时退回 MSI(老客户端的唯一格式)
|
||||
/// </param>
|
||||
/// <param name="Md5">安装包 MD5(可用于下载后校验)</param>
|
||||
/// <param name="Size">安装包字节数(0 = 未知)</param>
|
||||
/// <param name="Notes">更新说明(可为空)</param>
|
||||
@ -37,13 +40,13 @@ public static class UpdateChecker
|
||||
=> serverBaseUrl.TrimEnd('/') + "/download/version.json";
|
||||
|
||||
/// <summary>
|
||||
/// 从下载地址里解析安装包版本:`.../YuncangTraceSetup-1.0.3.msi` → <c>1.0.3</c>;解析不到返回 null。
|
||||
/// 从下载地址里解析安装包版本:`.../YuncangTraceSetup-1.0.3.msi` / `.exe` → <c>1.0.3</c>;解析不到返回 null。
|
||||
/// </summary>
|
||||
public static Version? PackageVersionOf(string? downloadUrl)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(downloadUrl)) return null;
|
||||
|
||||
var match = Regex.Match(downloadUrl, @"YuncangTraceSetup-(\d+(?:\.\d+){1,3})\.msi", RegexOptions.IgnoreCase);
|
||||
var match = Regex.Match(downloadUrl, @"YuncangTraceSetup-(\d+(?:\.\d+){1,3})\.(?:msi|exe)", RegexOptions.IgnoreCase);
|
||||
return match.Success && Version.TryParse(match.Groups[1].Value, out var version) ? version : null;
|
||||
}
|
||||
|
||||
@ -78,18 +81,46 @@ public static class UpdateChecker
|
||||
if (!Version.TryParse(text.Trim(), out var remote)) return null;
|
||||
if (remote <= current) return null;
|
||||
|
||||
var downloadUrl = root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null;
|
||||
// 优先 EXE 安装包:MSI 依赖 Windows Installer,现场有电脑装不了(服务禁用/安全软件拦截)。
|
||||
// 老客户端不认 downloadUrlExe,仍走 downloadUrl(= MSI),两条路都能升级。
|
||||
var useExe = root.TryGetProperty("downloadUrlExe", out var exeUrl)
|
||||
&& !string.IsNullOrWhiteSpace(exeUrl.GetString());
|
||||
var downloadUrl = useExe
|
||||
? exeUrl.GetString()
|
||||
: root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null;
|
||||
|
||||
// 防御:version.json 的 version 可能和下载包本身不一致(配错、或发版时漏传包)。
|
||||
// 若包里的版本并不比当前新,提示了也装不上去 → 会无限弹窗,直接忽略。
|
||||
var packageVersion = PackageVersionOf(downloadUrl);
|
||||
if (packageVersion is not null && packageVersion <= current) return null;
|
||||
|
||||
// ⚠️ 校验值必须跟**实际下载的那个包**对应:
|
||||
// version.json 里 `md5`/`size` 是 MSI 的,`md5Exe`/`sizeExe` 才是 EXE 的;
|
||||
// 以前不管下哪个都取 `md5`,于是下 EXE、拿 MSI 的哈希去比 → 每次升级都报「MD5 不一致」。
|
||||
var md5 = useExe
|
||||
? GetString(root, "md5Exe") ?? null
|
||||
: GetString(root, "md5") ?? null;
|
||||
var size = useExe
|
||||
? GetLong(root, "sizeExe") ?? 0
|
||||
: GetLong(root, "size") ?? 0;
|
||||
|
||||
return new UpdateInfo(
|
||||
text.Trim(),
|
||||
downloadUrl,
|
||||
root.TryGetProperty("md5", out var m) ? m.GetString() : null,
|
||||
root.TryGetProperty("size", out var s) && s.TryGetInt64(out var size) ? size : 0,
|
||||
md5,
|
||||
size,
|
||||
root.TryGetProperty("releaseNotes", out var n) ? n.GetString() : null);
|
||||
}
|
||||
|
||||
/// <summary>读字符串字段(不存在/类型不对返回 null)</summary>
|
||||
private static string? GetString(JsonElement root, string name)
|
||||
=> root.TryGetProperty(name, out var element)
|
||||
&& element.ValueKind == JsonValueKind.String
|
||||
&& !string.IsNullOrWhiteSpace(element.GetString())
|
||||
? element.GetString()
|
||||
: null;
|
||||
|
||||
/// <summary>读整数字段(不存在/类型不对返回 null)</summary>
|
||||
private static long? GetLong(JsonElement root, string name)
|
||||
=> root.TryGetProperty(name, out var element) && element.TryGetInt64(out var value) ? value : null;
|
||||
}
|
||||
|
||||
@ -15,7 +15,8 @@ namespace YuncangTrace.LocalService;
|
||||
///
|
||||
/// 为什么不在浏览器里打开下载链接:
|
||||
/// 用户还要自己找文件、自己双击、自己处理"文件被占用";
|
||||
/// 这里直接下到临时目录、校验、`msiexec /passive` 安装,装完自动把新版拉起来。
|
||||
/// 这里直接下到临时目录、校验,再静默安装(EXE 走 `/VERYSILENT`,MSI 走 `msiexec /passive`),
|
||||
/// 装完自动把新版拉起来。
|
||||
/// </summary>
|
||||
public partial class UpdateWindow : Window
|
||||
{
|
||||
@ -91,6 +92,17 @@ public partial class UpdateWindow : Window
|
||||
Progress.Value = 100;
|
||||
StatusText.Text = "下载完成,正在校验安装包…";
|
||||
|
||||
// 先比大小:下载被截断时这里就能看出来,比 MD5 的报错更直白
|
||||
var length = new FileInfo(file).Length;
|
||||
if (_info.Size > 0 && length != _info.Size)
|
||||
{
|
||||
TryDelete(file);
|
||||
AppLog.Write($"安装包大小不符:实际 {length},期望 {_info.Size}({file})");
|
||||
StatusText.Text = "安装包不完整(大小不符),请稍后重试。";
|
||||
ResetButtons();
|
||||
return;
|
||||
}
|
||||
|
||||
var actual = await Task.Run(() => ComputeMd5(file));
|
||||
if (!string.IsNullOrWhiteSpace(_info.Md5)
|
||||
&& !actual.Equals(_info.Md5.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
@ -137,9 +149,11 @@ public partial class UpdateWindow : Window
|
||||
|
||||
// 文件名优先用下载地址里的真实文件名(避免 version.json 的 version 与包不一致时名字骗人)
|
||||
var fileName = Path.GetFileName(new Uri(url).LocalPath);
|
||||
if (string.IsNullOrWhiteSpace(fileName) || !fileName.EndsWith(".msi", StringComparison.OrdinalIgnoreCase))
|
||||
if (string.IsNullOrWhiteSpace(fileName)
|
||||
|| !(fileName.EndsWith(".msi", StringComparison.OrdinalIgnoreCase)
|
||||
|| fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
fileName = $"YuncangTraceSetup-{_info.Version}.msi";
|
||||
fileName = $"YuncangTraceSetup-{_info.Version}.exe";
|
||||
}
|
||||
|
||||
var file = Path.Combine(dir, fileName);
|
||||
@ -182,24 +196,33 @@ public partial class UpdateWindow : Window
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动安装:先等本进程退出(exe 被占用时 MSI 换不掉),再 /passive 安装,
|
||||
/// 装完自动把新版拉起来。perUser 安装,不需要管理员权限。
|
||||
/// 启动安装:先等本进程退出(exe 被占用时换不掉),再静默安装,装完自动把新版拉起来。
|
||||
/// perUser 安装,不需要管理员权限。
|
||||
///
|
||||
/// - `.exe`(Inno Setup):`/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-`;
|
||||
/// - `.msi`(老安装包 / 老版本更新):`msiexec /i ... /passive /norestart`。
|
||||
/// </summary>
|
||||
private static void LaunchInstaller(string msiPath)
|
||||
private static void LaunchInstaller(string packagePath)
|
||||
{
|
||||
var exe = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"Programs", "YuncangTrace", "YuncangTrace.LocalService.exe");
|
||||
|
||||
var command = $"/c timeout /t 3 /nobreak >nul & msiexec /i \"{msiPath}\" /passive /norestart";
|
||||
var isMsi = packagePath.EndsWith(".msi", StringComparison.OrdinalIgnoreCase);
|
||||
var install = isMsi
|
||||
? $"msiexec /i \"{packagePath}\" /passive /norestart"
|
||||
: $"\"{packagePath}\" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-";
|
||||
|
||||
// 安装程序(setup loader)会等真正的安装进程结束才退出,所以这里能顺序等到装完再拉起软件
|
||||
var command = $"/c timeout /t 3 /nobreak >nul & {install}";
|
||||
if (File.Exists(exe))
|
||||
{
|
||||
// ⚠️ 用 explorer 拉起:从提权 cmd “start” 子进程会继续以管理员身份运行,
|
||||
// 而普通权限的协议唤起无法把参数送进管理员实例(表现为“唤起没反应”)。
|
||||
command += $" & explorer.exe \"{exe}\"";
|
||||
command += $" & timeout /t 2 /nobreak >nul & explorer.exe \"{exe}\"";
|
||||
}
|
||||
|
||||
AppLog.Write($"启动安装程序(软件退出后执行):{msiPath}");
|
||||
AppLog.Write($"启动安装程序(软件退出后执行):{packagePath}");
|
||||
|
||||
Process.Start(new ProcessStartInfo("cmd.exe", command)
|
||||
{
|
||||
|
||||
@ -99,11 +99,15 @@
|
||||
|
||||
<!--
|
||||
谷歌浏览器插件(仓库根目录 extension\):随程序输出到 native 同级的 extension\,
|
||||
安装后位于 <安装目录>\extension,菜单「工具 → 复制谷歌插件地址」直接给出该 Windows 路径;
|
||||
用户在 chrome://extensions 里「加载已解压的扩展程序」即可。
|
||||
开发调试文件(test\ / tools\)不打进安装包。
|
||||
安装后位于 <安装目录>\extension,菜单「工具 → 复制插件路径(开发者模式)」给出该 Windows 路径;
|
||||
正式分发走企业策略(菜单「工具 → 安装谷歌插件」),crx/updates.xml 由 npm run extension:publish 发布。
|
||||
⚠️ 这些**绝对不能**打进安装包:
|
||||
· keys\ 扩展签名私钥(泄漏 = 别人能签一个"官方更新"推给我们的客户)
|
||||
· out\ 打包产物(crx/updates.xml,客户端从服务器拉)
|
||||
· test\ tools\ 开发调试文件
|
||||
-->
|
||||
<Content Include="..\extension\**\*" Exclude="..\extension\test\**;..\extension\tools\**">
|
||||
<Content Include="..\extension\**\*"
|
||||
Exclude="..\extension\test\**;..\extension\tools\**;..\extension\keys\**;..\extension\out\**">
|
||||
<Link>extension\%(RecursiveDir)%(Filename)%(Extension)</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# 云仓视频溯源 · 单号注入扩展
|
||||
# 云仓视频溯源 · 单号注入扩展
|
||||
|
||||
Chrome / Edge 扩展(**Manifest V3 + 原生 JS,零构建**)。
|
||||
|
||||
@ -22,11 +22,48 @@ Chrome / Edge 扩展(**Manifest V3 + 原生 JS,零构建**)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 配置从哪来(1.1.0 起)
|
||||
|
||||
**插件只拉取并执行,不提供本地配置**:
|
||||
|
||||
- 后台(`平台管理 → 插件配置`)维护**单号前缀**(`YT` / `SF` / `32`…)、**生效站点**、跳转模板、安装包地址;
|
||||
单号正则由服务端拼好(`\b(?:YT|SF|…)\d{10,16}\b`)一起下发,插件端**不展示、不可改**;
|
||||
- 插件每 **5 分钟**自动拉一次 `GET https://pack.wms.gztbyc.com/api/web/extension/config`
|
||||
(`chrome.alarms`;浏览器启动/扩展安装时也会立刻拉一次),选项页/弹窗里还有「立即同步」;
|
||||
- **版本没变就不写存储**(避免整页重扫);**拉取失败保留旧配置**(断网照常工作),错误显示在选项页;
|
||||
- 插件里不再有:规则编辑、正则输入、试跑、导入导出、使用说明 —— 这些都在后台维护。
|
||||
|
||||
---
|
||||
|
||||
## 0.1 打包与分发(企业策略安装)
|
||||
|
||||
浏览器**不认「加载已解压」之外的本地目录**,所以正式分发必须打包成签名好的 `.crx`:
|
||||
|
||||
```powershell
|
||||
cd backend
|
||||
npm run extension:build # 只打包(extension/out/ 下产出 .crx / updates.xml / extension-id.txt)
|
||||
npm run extension:publish # 打包 + 上传到服务器 /download/extension/ + 刷新 nginx
|
||||
```
|
||||
|
||||
- 私钥 `extension/keys/key.pem`(首次运行自动生成,**务必单独备份**):它决定**扩展 ID**,
|
||||
换了私钥 = 换了 ID = 已经下发到客户机的策略全部失效;
|
||||
- 服务器上:`/download/extension/updates.xml`(**不缓存**,浏览器靠它自动升级)、
|
||||
`/download/extension/YuncangTraceExtension-<version>.crx`(文件名带版本号,长缓存);
|
||||
- 客户机:桌面端「工具 → **安装谷歌插件**」→ 允许一次 UAC → 写 HKLM 策略:
|
||||
```
|
||||
Chrome/Edge ExtensionInstallForcelist = <扩展ID>;https://<域名>/download/extension/updates.xml
|
||||
Chrome/Edge ExtensionInstallSources = https://<域名>/download/extension/*
|
||||
```
|
||||
重启浏览器即自动装好(`chrome://extensions` 里显示「由你的组织管理」)。
|
||||
「工具 → 卸载谷歌插件」只会删掉值里带 `/download/extension/` 的那几条,不动别的策略。
|
||||
|
||||
没有管理员权限的机器仍可用「工具 → 复制插件路径(开发者模式)」手动加载。
|
||||
|
||||
## 1. 安装
|
||||
|
||||
### 客户机:从桌面端安装包直接加载(推荐)
|
||||
|
||||
桌面端 MSI 已经把这个 `extension/` 目录一起装好,路径固定为
|
||||
桌面端安装包(MSI / EXE)已经把这个 `extension/` 目录一起装好,路径固定为
|
||||
`%LOCALAPPDATA%\Programs\YuncangTrace\extension`:
|
||||
|
||||
1. 桌面端软件菜单「**工具 → 复制谷歌插件地址**」(复制的是 Windows 路径,可直接粘进选择框)。
|
||||
@ -47,15 +84,15 @@ Chrome / Edge 扩展(**Manifest V3 + 原生 JS,零构建**)。
|
||||
|
||||
```
|
||||
extension/
|
||||
├── manifest.json # MV3 声明;权限只有 "storage"
|
||||
├── manifest.json # MV3 声明;permissions = storage + alarms,host_permissions 含后端域名
|
||||
├── icons/ # 16/32/48/128,由 tools/make-icons.ps1 生成
|
||||
├── src/
|
||||
│ ├── lib/rules.js # ★ 规则引擎(配置归一化 / 正则编译 / DOM 加工 / 地址拼接)
|
||||
│ ├── lib/rules.js # ★ 规则引擎(配置归一化 / 服务器配置合并 / DOM 加工 / 地址拼接)
|
||||
│ ├── content.js # 注入脚本:扫描 + 加工 + 点击拦截 + MutationObserver 补标
|
||||
│ ├── content.css # 注入样式(全部 .pst- 前缀 + !important)
|
||||
│ ├── background.js # service worker:只负责把算好的地址打开(小窗 / 新标签页)
|
||||
│ ├── popup.html/.css/.js # 工具栏弹窗:开关、本页命中清单、重新扫描
|
||||
│ └── options.html/.css/.js # ★ 规则配置页:基本设置 / 规则编辑 / 试跑 / 导入导出
|
||||
│ ├── background.js # service worker:打开目标地址 + **每 5 分钟拉取服务器配置**
|
||||
│ ├── popup.html/.css/.js # 工具栏弹窗:配置版本、本页命中清单、重新扫描、立即同步
|
||||
│ └── options.html/.js # ★ 只读状态页:同步状态 / 生效站点 / 前缀(不可编辑)
|
||||
├── test/wms-mock.html # 自测页:按真实结构复刻的表格
|
||||
└── tools/make-icons.ps1 # 生成图标(纯 ASCII,见文件头说明)
|
||||
```
|
||||
@ -92,7 +129,8 @@ extension/
|
||||
| **从属性抽(推荐)** | `a[href*="postNum="]` | `href` | `postNum=([0-9A-Za-z_-]+)` | 不依赖链接文字,文字被改成「查看轨迹」也照样能取到编号 |
|
||||
| 取链接文字 | `a[href*="postNum="]` | *(空)* | *(空)* | 简单;引擎会对取到的文本 `trim()`,那一大串换行/制表符会被去掉 |
|
||||
|
||||
内置示例规则不再默认带着这种结构(2026-10-17 已移除);真要处理 旧版 JSP 轨迹链接,在配置页自己加一条规则(下表两种写法都行)。
|
||||
内置示例规则不再默认带着这种结构(2026-10-17 已移除)。当前版本只下发**一条**文本规则(前缀 + 位数),
|
||||
所以下表这种「按选择器/属性抽编号」的写法暂时用不上 —— 它属于 `rules.js` 引擎仍然支持、但插件端不再暴露的能力。
|
||||
因为是 `button` 加工方式,按钮插在 `<a>` **之后**,`<a>` 自己那个 `javascript:MM_openTrace(...)` 照旧能用。
|
||||
|
||||
**加工(找到之后干什么)**
|
||||
@ -113,36 +151,30 @@ extension/
|
||||
- `text` 正则 + `button`:因为要把按钮放到「命中位置的旁边」,必须包一层**纯定位**的
|
||||
`<span class="pst-trace-anchor">`(无任何视觉、不带可点类名、不拦点击);它是原文照抄的,
|
||||
所以被匹配到的那段文字没变。
|
||||
- 按钮文案在**基本设置**里配(默认「查看打包视频」);全局和单条规则都能设 `actionMode`,规则留空则跟随全局。
|
||||
- 按钮文案是固定的默认值「查看打包视频」(`DEFAULT_BUTTON_TEXT`);`actionMode` 由 `defaultConfig()` 决定,插件端不提供入口。
|
||||
- 提醒:按钮是真实 DOM,所以**容器元素的 `textContent` 会多出按钮文案** —— 这是插入 UI 的必然结果,
|
||||
被匹配的那段文字本身没有被改动。
|
||||
|
||||
### 内置规则
|
||||
### 识别规则(服务器下发,唯一一条)
|
||||
|
||||
**只内置一条**(实测这一条就能盖住真实页面的单号):
|
||||
**只有一条文本规则**,内容由服务器按后台维护的**前缀**拼出来:
|
||||
|
||||
| id | 说明 | 生效站点 | 默认 |
|
||||
| --- | --- | --- | --- |
|
||||
| `express` | 文本规则 `\b(?:YT\|SF\|JD\|ZTO\|YTO\|STO\|EMS\|DBL\|32\|77)\d{10,16}\b`(`gi`) | 全部 | 开 |
|
||||
| `remote` | `\b(?:YT\|SF\|JD\|ZTO\|YTO\|STO\|EMS\|DBL\|32\|77)\d{10,16}\b`(flags `g`) | 后台配的生效站点 | 由后台开关控制 |
|
||||
|
||||
- **前缀表就是唯一要维护的地方**:在 `src/lib/rules.js` 的 `EXPRESS_PREFIXES` 里往数组里追加新前缀即可
|
||||
(以前没出现过、又确实出现在单号开头的就加进去)—— 正则会跟着拼出来,**不用改正则本身**:
|
||||
```js
|
||||
const EXPRESS_PREFIXES = [ 'YT', 'SF', 'JD', 'ZTO', 'YTO', 'STO', 'EMS', 'DBL', '32', '77' ];
|
||||
const EXPRESS_PATTERN = '\\b(?:' + EXPRESS_PREFIXES.join('|') + ')\\d{10,16}\\b';
|
||||
```
|
||||
- 前缀后面必须跟 **10~16 位数字**(`\d{10,16}`):所以 `321408064481776`(WMS 运单号,`32` 开头)会被命中,
|
||||
- **只维护前缀**:后台「平台管理 → 插件配置」里加/删前缀(`YT`、`SF`、`32`…),
|
||||
正则由后端 `buildPattern()` 拼好一起下发;插件端 `applyRemote()` 只把它当成一条 `text` 规则,**不解析、不展示**。
|
||||
- 前缀后面必须跟 **10~16 位数字**(后台也可调,默认 10~16):所以 `321408064481776`(`32` 开头)会被命中,
|
||||
而同一行的波次号 `E2026101600069`、发货单号 `JY2026101619599`、平台交易单号、17 开头的毫秒时间戳都不会;
|
||||
- ⚠️ **数字前缀(`32` / `77`)最容易被内部 ID、订单号一起点亮** —— 发现误标就把那个前缀拿掉,或者给规则加 `exclude`;
|
||||
- 其它匹配方式(CSS 选择器 / 从 `href` 抽编号 / 按 `data-*` 取值)**不再内置示例**,需要时在配置页自己加一条即可,写法见上面的例子;
|
||||
- **升级迁移(config version 1 → 2)**:扩展升级后第一次打开配置页/页面时,会
|
||||
① 把已移除的示例规则(`wms-waybill` / `numeric` / `legacy-postnum` / `dom-attr`)从你的规则里剔掉,
|
||||
② 内置的 `express` 如果还是老正则(说明你没改过它)就换成带新前缀表的正则 ——
|
||||
**你自己加的规则、以及你改过的 `express` 都不动**(见 `upgradeRules()`)。
|
||||
- ⚠️ **数字前缀(`32` / `77`)最容易被内部 ID、订单号一起点亮** —— 发现误标就在后台把那个前缀删掉。
|
||||
- 规则是**区分大小写**的(flags 只有 `g`):前缀统一存成大写,`yt1234…` 不会被点亮。
|
||||
- `src/lib/rules.js` 里仍保留一条内置的 `express` 规则,**只作兜底**:首次安装还没同步成功时用它,
|
||||
同步成功后会被服务器那条 `remote` 整个替换掉。
|
||||
|
||||
## 4. 目标地址模板
|
||||
|
||||
在**基本设置**里改一处即可切到真实打包视频页,占位符:
|
||||
在后台「插件配置」里改(网页模板 / 唤起协议),占位符:
|
||||
|
||||
| 占位符 | 含义 |
|
||||
| --- | --- |
|
||||
@ -155,20 +187,28 @@ extension/
|
||||
将来:https://video.example.com/trace?keyword={code}&from=wms
|
||||
```
|
||||
|
||||
单条规则还可以设**专属地址**(留空则用全局模板)。点击后按「打开方式」呈现:
|
||||
**独立小窗**(默认)或**新标签页**。
|
||||
点击后按本地偏好呈现:**独立小窗**或**新标签页**(`openMode`,不再由服务器下发,避免每台机器行为不一致)。
|
||||
|
||||
## 5. 调规则:别刷页面,用「试跑」
|
||||
## 5. 配置同步与排障
|
||||
|
||||
配置页里的 **规则试跑** 用的是**当前表单里还没保存**的规则,所以可以边调边看:
|
||||
| 触发 | 频率 |
|
||||
| --- | --- |
|
||||
| 定时(`chrome.alarms`) | 每 5 分钟 |
|
||||
| 扩展安装 / 浏览器启动 | 立刻一次 |
|
||||
| 选项页 / 弹窗「立即同步」 | 手动 |
|
||||
|
||||
- 输入类型选 `HTML 片段`,粘一段真实 DOM,点「试跑」;
|
||||
- 它会模拟一个站点(默认 `wms.wms.gztbyc.com`,用于校验规则的「生效站点」),
|
||||
列出**命中的编号 + 最终目标地址**,并给出**二次加工后的 HTML**;
|
||||
- 0 命中时会把每条启用规则的「生效站点 / 选择器 / 正则」列出来,方便判断是**站点被过滤了**还是**没匹配上**;
|
||||
- 点「填入 WMS 取样」可以一键载入内置样例。
|
||||
- 拉的是 `GET https://pack.wms.gztbyc.com/api/web/extension/config`(可用
|
||||
`chrome.storage.local.pstConfigUrl` 覆盖,联调环境用);
|
||||
- **安装包地址不用后台配**:每次同步还会读一次 `GET https://pack.wms.gztbyc.com/download/version.json`,
|
||||
取里面的 `downloadUrl` 写进配置(和网页顶栏「下载桌面端」同一份,永远是最新发布版本);
|
||||
只有 version.json 拉不到时才退回后台配置里那个值、再退回上一次的值;
|
||||
- 返回 `{ ok, data: { version, enabled, hosts, prefixes, pattern, flags, urlTemplate, appUrlTemplate, downloadUrl } }`;
|
||||
- **版本相同不写存储**:`pstConfig.remote.version` 与服务器一致就跳过,页面不会被无谓重扫;
|
||||
- **失败保留旧配置**(断网/后端挂了照常工作),错误写进 `chrome.storage.local.pstSyncState`,选项页显示;
|
||||
- 写配置后会触发 `chrome.storage.onChanged`,content script 自己 `unmark()` + 重扫,**不用刷新页面**。
|
||||
|
||||
工具栏弹窗则用来确认**线上是否真的生效**:显示「本页命中 N」+ 编号清单(点一条可直接打开)。
|
||||
排障入口:选项页(同步状态/上次错误/生效站点/前缀)→ 弹窗(本页命中清单)→ `chrome://extensions` 的
|
||||
「Service Worker → 检查」里看 `syncConfig()` 的报错。
|
||||
|
||||
## 6. 自测页
|
||||
|
||||
@ -190,7 +230,7 @@ npx --yes http-server extension/test -p 7310 # → http://127.0.0.1:7310/wms
|
||||
按住 <kbd>Ctrl</kbd> / <kbd>⌘</kbd> / <kbd>Alt</kbd> / <kbd>Shift</kbd> 点击就不拦,交还给页面原本的行为。
|
||||
- **SPA 友好**:`MutationObserver`(默认 400ms 防抖)盯着新增节点和文本变化自动补标;
|
||||
自己也写了 DOM 会触发观察器,用 `quietUntil` 时间窗把这类回声挡掉,避免无限重扫。
|
||||
- **完整可撤销**:关掉总开关、改规则、或当前站点不在生效范围时会 `unmark()`——
|
||||
- **完整可撤销**:后台停用插件、配置变更、或当前站点不在生效范围时会 `unmark()`——
|
||||
wrap 模式把 `<span>` 换回纯文本,selector 模式把类名 / `data-pst-*` / 被覆盖的 `title` / 加过的 `tabindex` 全部还原。
|
||||
- **上限保护**:单次扫描最多看 `maxNodes`(默认 5000)个文本节点、单页最多标 `maxMarks`(默认 400)处,
|
||||
超了会截断并在弹窗里显示 `N+`。
|
||||
@ -199,11 +239,14 @@ npx --yes http-server extension/test -p 7310 # → http://127.0.0.1:7310/wms
|
||||
|
||||
| 权限 | 用途 |
|
||||
| --- | --- |
|
||||
| `storage` | 存规则配置(优先 `storage.sync`,超 8KB 单项配额自动退到 `storage.local` 并提示) |
|
||||
| `storage` | 存下发下来的配置(优先 `storage.sync`,超 8KB 自动退到 `storage.local`) |
|
||||
| `alarms` | 每 5 分钟定时拉配置(MV3 的 service worker 会被回收,不能用 `setInterval`) |
|
||||
| `host_permissions: https://pack.wms.gztbyc.com/*` | 拉 `GET /api/web/extension/config` |
|
||||
| `host_permissions: http(s)://localhost:17300/*` | 探测本机软件是否在跑(协议唤起兜底) |
|
||||
| content script `matches: http(s)://*/*` | 需要注入任意第三方系统,无法预先枚举域名 |
|
||||
|
||||
- 不请求 `tabs` / `scripting` / `cookies`,**不读页面 cookie,不发任何请求**:
|
||||
点击只是把算好的 URL 交给 `chrome.tabs.create` / `chrome.windows.create`。
|
||||
- 不请求 `tabs` / `scripting` / `cookies`,**不读页面 cookie**;唯一的出站请求就是上面那个配置接口
|
||||
(以及本机 17300 的探测)。点击只是把算好的 URL 交给 `chrome.tabs.create` / `chrome.windows.create`。
|
||||
- 注入走隔离世界(ISOLATED),不注入页面上下文,不受宿主页 CSP 影响。
|
||||
- 想收窄范围:改 `manifest.json` 里 `content_scripts[0].matches` 为具体域名(如 `https://wms.wms.gztbyc.com/*`),
|
||||
重新加载扩展即可;规则层面的范围由「生效站点」控制。
|
||||
|
||||
36
extension/keys/README.md
Normal file
36
extension/keys/README.md
Normal file
@ -0,0 +1,36 @@
|
||||
# extension/keys —— 扩展签名私钥(**已入库**)
|
||||
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `key.pem` | Chrome 扩展签名私钥。**决定扩展 ID**,`npm run extension:publish` 用它对 `.crx` 签名 |
|
||||
|
||||
**当前扩展 ID**:`lkeibbccgdddjamahnkibopcpidhgggk`
|
||||
(= 公钥 SHA256 前 16 字节按 `a~p` 映射;可用 `extension/out/extension-id.txt` 核对)
|
||||
|
||||
## 为什么入库
|
||||
|
||||
桌面端「工具 → 安装谷歌插件」会在客户机写一条企业策略:
|
||||
|
||||
```
|
||||
HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallForcelist
|
||||
1 = lkeibbccgdddjamahnkibopcpidhgggk;https://<域名>/download/extension/updates.xml
|
||||
```
|
||||
|
||||
策略里写死了**扩展 ID**,而 ID 由这把私钥唯一决定:
|
||||
|
||||
- 私钥在 → 每次发布都是同一个 ID,客户机策略长期有效;
|
||||
- 私钥丢 → 重新生成 → **ID 变了** → 已下发到所有客户机的策略全部失效(要重新点一次安装)。
|
||||
|
||||
所以按「宁可入库也别丢」处理。⚠️ 代价是:**仓库必须保持私有**,能读这个仓库的人等于能签发
|
||||
一个"官方更新"推给所有客户机(Chrome 信任这个私钥签的包)。
|
||||
|
||||
## 绝对不能随安装包发给客户
|
||||
|
||||
`desktop/YuncangTrace.LocalService.csproj` 已经把 `extension/keys/**` 和 `extension/out/**`
|
||||
从输出/发布/安装包里排除了;改那个 `Content Include` 的 `Exclude` 时**别把这两条删掉**。
|
||||
|
||||
## 换机器 / 重建
|
||||
|
||||
- 正常:`git clone` 下来就有 `key.pem`,直接 `npm run extension:publish` 即可;
|
||||
- 想换一把新的(**会让扩展 ID 变化**):删掉 `key.pem` 再发布,脚本会自动生成;
|
||||
之后客户机需要重新执行一次「工具 → 安装谷歌插件」(旧的 forcelist 值会被同名校验覆盖)。
|
||||
28
extension/keys/key.pem
Normal file
28
extension/keys/key.pem
Normal file
@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCT8TSlPr8EW0v7
|
||||
z26h1Uv5sEPtM8x5Ya6VKFnMVAbXXfybLL4pMMtfKJjGXIpVbOO7Mh9VI0LEw6nl
|
||||
fOJ1zqTO85BE8goZliw+3uzl6O/3Wjz4zunAH116BSJoUoVYXQVnCsQytmzIbThB
|
||||
sk0MqJi2BVMkQj/c0vv81K1rMkOcv0VTwOVqWxmSScv7JPTKJq6ZdIjwQW4nXNif
|
||||
ARlJ1ChXEQTUlfVUUzT1BEC44lN4rEa+/3UBL7zPC28lQBO1C2CRMeSR//9pRwlW
|
||||
KmUjVq0lxpy3j2T6xq9ijSKdGI+x5Dk41f2r2/82D38Fa15S2UFKumtOIKA0EQ0B
|
||||
63pOjjetAgMBAAECggEAFFmWAx2gmzdPD49m1ED+/JTCoI1tqiFbKUOjJ92ZEU/p
|
||||
hZN/1tz85JU01U2jw6trn0jTkYZSUrboFwajhKP3p0tOmYVCXrxO+sOhtOBiqH9+
|
||||
VT/qXGs+vvWXgt/IXYbHeEySqg0jj+WiMDtCqPlErv5dg5EksA9KP+rQrfxR25d9
|
||||
pimapOPaL3/J9nj8M3KQ30SV9/dfvd/AMhUeNByuxv4oxUOeYQBhsYitfPV54bmb
|
||||
5vwgpam5AZBgvJm+reIQETg8+iOPl4LL0SXUmsfw+4kV8oWoJFW+/S13mXsPptSo
|
||||
XlKQtDSWqbNBfTWfoXtsBMP9btDlcTUFRiFQu698+wKBgQDDJCW9NmTKx3luqe7Q
|
||||
cIlt/jL2izgc7haNVnmfA8H+Tal4kuxRioz/8ELmwR/zM2VfgsV0sU7rvnUqHP1q
|
||||
c9ePFOLiL+b/vtsV2OgTtZQg3RdyeZakPhpAUv3mKLMT3hcpHJgiLsI4YY+RIuol
|
||||
qEbPDip/UQ/XPV/px/eAJNYnxwKBgQDCFL6DSxZfDdodjp4+KSL7Yx/p9385HdaD
|
||||
pd0EdHAlBQJm9o3Vni5jRXGr+LnPKZR/BwcIfeQLYXPbfQIjdKDfE0ao2BzIgYhC
|
||||
TcYln0nzLb9EV1eO+Gp50PGnjZl4pl7GaNdnFXNRdFVbFYvcXcFDs6NTc44KKC49
|
||||
PTO4NtKs6wKBgQC+rMJneQ/RiEniVQ9yApR2sqzPdMd2lTnaDwY113El8HLIyx84
|
||||
qd4Oc5Cbc1epxq2mPtx7ookQFwDbDoqcCuc0+t6azt2zRaVDWreiEonT9tTjWWVV
|
||||
xQzXj4Bh9aDNp/QPis4okHHcr4+d7HTIKP5PcXMbBnUpBuKCR49SWiwbnwKBgH9Q
|
||||
OlVIOWmrXYyMFNQ0CgWcVcAWIffm0eRUNrMIatRt/9BpJkueU1G9qT6lj8YMwaO+
|
||||
iWeRpbmteOHflDqL9EfBjlWORvtktWzBNh1R66HBPbnoDcD0xmwYm51NLwLNKFjB
|
||||
R6QQlzA0vxVcAf5R5kiyG47Pu7p/9y0m67mJBRR3AoGBAJ3ll6Tczm98CJTWVRtB
|
||||
oLw4+XV2BguaCfrvCvcCPQgjrnDLK69qq6guXsGsII+NqAoxT9kLeWd9psISJMeC
|
||||
TJ/Mr7/cw8HlRhJUb6ckOZ0evCrtvwviott88gTb/iYbi4vyc4oTMTJ3Ok4FOsVp
|
||||
z6eDfMp49uqmhMGi2J/dn6Yn
|
||||
-----END PRIVATE KEY-----
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "云仓视频溯源 · 单号注入",
|
||||
"version": "1.0.0",
|
||||
"description": "在第三方 WMS / 后台页面里按规则识别单号,就地加工成可点击的溯源入口;点击后打开溯源页面(默认演示地址可用 ?keyword={code} 承接)。",
|
||||
"version": "1.1.0",
|
||||
"description": "在第三方 WMS / 后台页面里识别单号,就地加工成可点击的溯源入口;识别前缀与生效站点由管理员在后台统一维护,插件每小时自动同步。",
|
||||
"minimum_chrome_version": "96",
|
||||
|
||||
"icons": {
|
||||
@ -12,11 +12,12 @@
|
||||
"128": "icons/icon128.png"
|
||||
},
|
||||
|
||||
"permissions": ["storage"],
|
||||
"permissions": ["storage", "alarms"],
|
||||
|
||||
"host_permissions": [
|
||||
"http://localhost:17300/*",
|
||||
"http://127.0.0.1:17300/*"
|
||||
"http://127.0.0.1:17300/*",
|
||||
"https://pack.wms.gztbyc.com/*"
|
||||
],
|
||||
|
||||
"action": {
|
||||
|
||||
@ -2,6 +2,37 @@
|
||||
/**
|
||||
* 云仓视频溯源 · background(MV3 service worker)
|
||||
*
|
||||
* 两件事:
|
||||
* 1. 把 content script 算好的目标地址打开(见下);
|
||||
* 2. **拉取服务器下发配置**:每小时一次 + 插件启动/安装时一次 + 用户点「立即同步」。
|
||||
* 识别前缀、生效站点、跳转模板全由后台维护,插件只负责执行(不提供编辑/试跑/导入导出)。
|
||||
*/
|
||||
importScripts('lib/rules.js');
|
||||
|
||||
/** 服务器配置接口(可用 chrome.storage.local.pstConfigUrl 临时覆盖,调试用) */
|
||||
const CONFIG_URL = 'https://pack.wms.gztbyc.com/api/web/extension/config';
|
||||
|
||||
/**
|
||||
* 桌面端安装包版本信息(和网页顶栏「下载桌面端」同一份)
|
||||
*
|
||||
* 后台**不需要维护安装包地址**:每次同步都读一次这个文件,永远是最新发布版本;
|
||||
* 后台配置里的 `downloadUrl` 非空时才作为覆盖值(例如临时指到内网镜像)。
|
||||
*/
|
||||
const VERSION_URL = 'https://pack.wms.gztbyc.com/download/version.json';
|
||||
|
||||
/**
|
||||
* 定时拉取的 alarm 名 + 周期(分钟)
|
||||
*
|
||||
* 5 分钟:后台一改配置,最多 5 分钟就生效(服务端对配置结果缓存 1 小时,
|
||||
* 后台保存时会立刻删缓存,所以这里拉得勤不会把数据库打垮)。
|
||||
*/
|
||||
const SYNC_ALARM = 'pst:config-sync';
|
||||
const SYNC_PERIOD_MINUTES = 5;
|
||||
|
||||
/** 同步状态(选项页/弹窗展示用;与配置分开存,免得改配置时把错误信息冲掉) */
|
||||
const SYNC_STATE_KEY = 'pstSyncState';
|
||||
|
||||
/**
|
||||
* 只干一件事:把 content script 算好的目标地址打开。
|
||||
*
|
||||
* 为什么把「打开」放在这里而不是 content script 里?
|
||||
@ -21,6 +52,14 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 手动同步配置(选项页 / 弹窗的「立即同步」)
|
||||
if (msg.type === 'pst:sync') {
|
||||
syncConfig('manual').then(sendResponse, err => {
|
||||
sendResponse({ ok: false, error: String((err && err.message) || err) });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg.type !== 'pst:open') return;
|
||||
|
||||
openTarget(msg, sender).then(sendResponse, err => {
|
||||
@ -79,3 +118,136 @@ async function openTarget(msg, sender) {
|
||||
|
||||
return { ok: true, url, mode };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 配置同步 */
|
||||
|
||||
const R = globalThis.PSTRules;
|
||||
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
ensureSyncAlarm();
|
||||
void syncConfig('installed');
|
||||
});
|
||||
|
||||
chrome.runtime.onStartup.addListener(() => {
|
||||
ensureSyncAlarm();
|
||||
void syncConfig('startup');
|
||||
});
|
||||
|
||||
chrome.alarms.onAlarm.addListener(alarm => {
|
||||
if (alarm.name === SYNC_ALARM) void syncConfig('alarm');
|
||||
});
|
||||
|
||||
/**
|
||||
* alarm 不会自动续命:浏览器重启 / 扩展更新后要重新建。
|
||||
* `delayInMinutes: 1` 让安装后一分钟内就有第一次定时同步(上面另外还会立刻拉一次)。
|
||||
*/
|
||||
function ensureSyncAlarm() {
|
||||
chrome.alarms.get(SYNC_ALARM, current => {
|
||||
// 同名 create 会覆盖:周期改过(比如 60 → 5 分钟)时要重建,否则老用户升级后还是旧周期
|
||||
if (current && current.periodInMinutes === SYNC_PERIOD_MINUTES) return;
|
||||
chrome.alarms.create(SYNC_ALARM, { delayInMinutes: 1, periodInMinutes: SYNC_PERIOD_MINUTES });
|
||||
});
|
||||
}
|
||||
|
||||
/** 配置接口地址(允许用 storage 覆盖,方便联调环境) */
|
||||
async function resolveConfigUrl() {
|
||||
try {
|
||||
const stored = await chrome.storage.local.get('pstConfigUrl');
|
||||
const custom = stored && stored.pstConfigUrl;
|
||||
if (custom) return String(custom);
|
||||
} catch (_) { /* 读不到就用默认 */ }
|
||||
return CONFIG_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读最新桌面端安装包地址(`/download/version.json`,不是 `{ok,data}` 包装,直接是 JSON)
|
||||
*
|
||||
* 失败一律返回 null:安装包地址拿不到不该影响配置同步本身。
|
||||
*/
|
||||
async function resolveLatestInstaller() {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const res = await fetch(VERSION_URL, { cache: 'no-store', signal: controller.signal });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
const url = data && typeof data.downloadUrl === 'string' ? data.downloadUrl.trim() : '';
|
||||
if (!url) return null;
|
||||
return { url, version: String((data && data.version) || '') };
|
||||
} catch (_) {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function readSyncState() {
|
||||
try {
|
||||
const stored = await chrome.storage.local.get(SYNC_STATE_KEY);
|
||||
return (stored && stored[SYNC_STATE_KEY]) || {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function writeSyncState(patch) {
|
||||
const next = Object.assign({}, await readSyncState(), patch);
|
||||
try {
|
||||
await chrome.storage.local.set({ [SYNC_STATE_KEY]: next });
|
||||
} catch (_) { /* 状态写不进去不影响配置 */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉一次服务器配置
|
||||
*
|
||||
* - 版本没变就**不写 storage**(避免每小时让所有页面重扫一遍);
|
||||
* - 失败**保留旧配置**(断网也照常工作),错误写进同步状态给选项页看;
|
||||
* - 成功后内容脚本会收到 storage 变更通知,自己重扫当前页面。
|
||||
*/
|
||||
async function syncConfig(reason) {
|
||||
const url = await resolveConfigUrl();
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 8000);
|
||||
|
||||
try {
|
||||
const res = await fetch(url, { cache: 'no-store', signal: controller.signal });
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
|
||||
const payload = await res.json();
|
||||
const remote = payload && payload.data ? payload.data : payload;
|
||||
if (!remote || typeof remote !== 'object') throw new Error('服务器返回的配置格式不对');
|
||||
if (!remote.pattern) throw new Error('服务器返回的配置缺少 pattern(后台还没配前缀?)');
|
||||
|
||||
const previous = await R.loadConfig();
|
||||
|
||||
// 安装包地址:**优先用最新发布版本**(/download/version.json,和网页顶栏同一份),
|
||||
// 版本号没变但发了新包时也能跟上;拿不到(断网/还没发布过)才退回后台配置值、再退回上次的值,
|
||||
// 免得把「下载安装」按钮弄没了。
|
||||
const latest = await resolveLatestInstaller();
|
||||
const downloadUrl = (latest && latest.url)
|
||||
|| String(remote.downloadUrl || '').trim()
|
||||
|| String(previous.downloadUrl || '');
|
||||
|
||||
const known = (previous.remote && previous.remote.version) || 0;
|
||||
const sameConfig = known && Number(remote.version) === Number(known);
|
||||
const sameInstaller = String(previous.downloadUrl || '') === downloadUrl;
|
||||
|
||||
if (sameConfig && sameInstaller) {
|
||||
await writeSyncState({ at: new Date().toISOString(), error: '', reason, version: Number(remote.version) });
|
||||
return { ok: true, unchanged: true, version: Number(remote.version), at: previous.remote.syncedAt };
|
||||
}
|
||||
|
||||
const next = R.applyRemote(previous, Object.assign({}, remote, { downloadUrl }));
|
||||
const saved = await R.saveConfig(next);
|
||||
if (!saved.ok) throw new Error(saved.message || '配置保存失败');
|
||||
|
||||
await writeSyncState({ at: next.remote.syncedAt, error: '', reason, version: next.remote.version });
|
||||
return { ok: true, version: next.remote.version, at: next.remote.syncedAt, unchanged: false };
|
||||
} catch (err) {
|
||||
const message = String((err && err.message) || err);
|
||||
await writeSyncState({ at: new Date().toISOString(), error: message, reason });
|
||||
return { ok: false, error: message };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
@ -119,6 +119,7 @@
|
||||
cfg.appUrlTemplate = String(cfg.appUrlTemplate || '').trim() || DEFAULT_APP_URL_TEMPLATE;
|
||||
cfg.fallbackUrl = String(cfg.fallbackUrl || '').trim() || DEFAULT_FALLBACK_URL;
|
||||
cfg.downloadUrl = String(cfg.downloadUrl || '').trim();
|
||||
cfg.remote = normalizeRemote(cfg.remote);
|
||||
cfg.openMode = OPEN_MODES.indexOf(cfg.openMode) >= 0 ? cfg.openMode : 'app';
|
||||
|
||||
// v3 把「协议模板」当成了 urlTemplate 的默认值(当时没有 openMode=app 这个概念);
|
||||
@ -167,6 +168,63 @@
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------- 服务器下发(集中配置) */
|
||||
|
||||
/**
|
||||
* 服务器下发信息(只做展示/版本判断,不参与识别)
|
||||
*
|
||||
* `version` 用来判断"配置变没变":相同就不重写 storage,页面不会被无谓地重扫一遍。
|
||||
*/
|
||||
function normalizeRemote(raw) {
|
||||
const src = raw && typeof raw === 'object' ? raw : {};
|
||||
return {
|
||||
version: Number(src.version) || 0,
|
||||
syncedAt: String(src.syncedAt || ''),
|
||||
updatedAt: src.updatedAt ? String(src.updatedAt) : null,
|
||||
prefixes: toStrArray(src.prefixes, []),
|
||||
minDigits: Number(src.minDigits) || 0,
|
||||
maxDigits: Number(src.maxDigits) || 0,
|
||||
error: String(src.error || ''),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 把服务器配置合并进本地配置(插件**只执行**,不提供编辑)
|
||||
*
|
||||
* 服务端已经拼好正则(`pattern`),这里直接当成唯一一条 `text` 规则:
|
||||
* - 前缀/位数变了 → pattern 变 → 规则变;
|
||||
* - `hosts` 决定"在哪些站点工作";
|
||||
* - `openMode` 这类本机偏好保持原值,不被覆盖。
|
||||
*/
|
||||
function applyRemote(prev, remote) {
|
||||
const base = normalizeConfig(prev || {});
|
||||
const pattern = String((remote && remote.pattern) || '').trim();
|
||||
const hosts = toStrArray(remote && remote.hosts, ['*']);
|
||||
|
||||
const rules = pattern
|
||||
? [ {
|
||||
id: 'remote',
|
||||
name: '单号(服务器下发)',
|
||||
enabled: true,
|
||||
match: 'text',
|
||||
pattern,
|
||||
flags: String((remote && remote.flags) || 'g'),
|
||||
exclude: '',
|
||||
urlTemplate: '',
|
||||
} ]
|
||||
: [];
|
||||
|
||||
return normalizeConfig(Object.assign({}, base, {
|
||||
enabled: !(remote && remote.enabled === false),
|
||||
hosts,
|
||||
urlTemplate: String((remote && remote.urlTemplate) || '').trim() || DEFAULT_URL_TEMPLATE,
|
||||
appUrlTemplate: String((remote && remote.appUrlTemplate) || '').trim() || DEFAULT_APP_URL_TEMPLATE,
|
||||
downloadUrl: String((remote && remote.downloadUrl) || '').trim(),
|
||||
rules,
|
||||
remote: Object.assign({}, normalizeRemote(remote), { syncedAt: new Date().toISOString(), error: '' }),
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeRule(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return {
|
||||
@ -747,6 +805,8 @@
|
||||
MARK_STYLES,
|
||||
defaultConfig,
|
||||
normalizeConfig,
|
||||
normalizeRemote,
|
||||
applyRemote,
|
||||
normalizeRule,
|
||||
compileRules,
|
||||
matchText,
|
||||
|
||||
@ -1,208 +0,0 @@
|
||||
:root {
|
||||
--bg: #f2f5f7;
|
||||
--card: #fff;
|
||||
--fg: #1f2328;
|
||||
--muted: #6b7280;
|
||||
--border: #d9dee5;
|
||||
--brand: #0b7d7c;
|
||||
--brand-2: #0ea5a4;
|
||||
--danger: #b42318;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 13px/1.6 "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.wrap { max-width: 1080px; margin: 0 auto; padding: 20px 20px 90px; }
|
||||
|
||||
code, .mono {
|
||||
font-family: Consolas, "Courier New", monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
code { background: #eef1f4; padding: 0 4px; border-radius: 3px; }
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
.page-head { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head .logo { width: 40px; height: 40px; flex: none; }
|
||||
h1 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; max-width: 78ch; font-size: 12.5px; }
|
||||
|
||||
.card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.card h2 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.card h2 small { font-weight: 400; font-size: 12px; }
|
||||
|
||||
/* ---------- 表单 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 10px 14px;
|
||||
}
|
||||
.f { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.f.wide { grid-column: 1 / -1; }
|
||||
.f > span { font-size: 12px; color: var(--muted); }
|
||||
.f .hint { font-size: 11.5px; color: var(--brand); font-style: normal; word-break: break-all; }
|
||||
|
||||
input[type="text"], input:not([type]), select, textarea, .rule input, .rule select {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--fg);
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
}
|
||||
input.mono, textarea.mono, .rid { font-family: Consolas, "Courier New", monospace; }
|
||||
textarea { resize: vertical; }
|
||||
input:focus, select:focus, textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--brand-2);
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 164, .15);
|
||||
}
|
||||
|
||||
.row-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
|
||||
|
||||
button {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--fg);
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { border-color: var(--brand-2); color: var(--brand); }
|
||||
button.primary { background: var(--brand); border-color: var(--brand); color: #fff; }
|
||||
button.primary:hover { background: var(--brand-2); border-color: var(--brand-2); color: #fff; }
|
||||
button.danger { color: var(--danger); }
|
||||
button.danger:hover { border-color: var(--danger); color: var(--danger); }
|
||||
button.big { padding: 9px 26px; font-size: 13.5px; }
|
||||
|
||||
/* ---------- 规则卡片 ---------- */
|
||||
.rules { display: flex; flex-direction: column; gap: 10px; }
|
||||
.rule {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
background: #fbfcfd;
|
||||
}
|
||||
.rule-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
||||
.rule-head .rname { flex: 1 1 auto; font-weight: 600; }
|
||||
.rule-head .rid { flex: none; color: var(--muted); font-size: 11px; background: none; padding: 0; }
|
||||
.rule-actions { display: flex; gap: 4px; flex: none; }
|
||||
.rule-actions button {
|
||||
padding: 2px 8px;
|
||||
line-height: 1.5;
|
||||
font-size: 12px;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
.rule-actions button:hover { background: #eef6f6; }
|
||||
.rule.is-off { opacity: .62; }
|
||||
.rule.is-off .grid { opacity: .9; }
|
||||
|
||||
/* 开关(小号) */
|
||||
.sw { position: relative; display: inline-block; width: 36px; height: 20px; flex: none; }
|
||||
.sw.small { width: 32px; height: 18px; }
|
||||
.sw input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.sw span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #cbd5e1;
|
||||
border-radius: 999px;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.sw span::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px; left: 2px;
|
||||
width: 16px; height: 16px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
transition: transform .15s ease;
|
||||
}
|
||||
.sw.small span::after { width: 14px; height: 14px; }
|
||||
.sw input:checked + span { background: var(--brand-2); }
|
||||
.sw input:checked + span::after { transform: translateX(16px); }
|
||||
.sw.small input:checked + span::after { transform: translateX(14px); }
|
||||
|
||||
.note { margin: 12px 0 0; font-size: 12px; }
|
||||
|
||||
/* ---------- 试跑 ---------- */
|
||||
.test-result { margin-top: 12px; }
|
||||
.test-result table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.test-result th, .test-result td {
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 5px 8px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
word-break: break-all;
|
||||
}
|
||||
.test-result th { color: var(--muted); font-weight: 500; }
|
||||
.test-result td.mono { font-family: Consolas, "Courier New", monospace; }
|
||||
.test-result .snippet {
|
||||
margin-top: 10px;
|
||||
padding: 8px 10px;
|
||||
background: #f6f8fa;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
font-family: Consolas, "Courier New", monospace;
|
||||
font-size: 11.5px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.test-result .bad { color: var(--danger); }
|
||||
.test-result .good { color: var(--brand); }
|
||||
|
||||
.steps { margin: 0; padding-left: 20px; font-size: 12.5px; }
|
||||
.steps li { margin-bottom: 5px; }
|
||||
|
||||
/* ---------- 底部条 / 提示 ---------- */
|
||||
.page-foot {
|
||||
position: fixed;
|
||||
left: 0; right: 0; bottom: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 24px;
|
||||
background: rgba(255, 255, 255, .96);
|
||||
border-top: 1px solid var(--border);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 14px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 20;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
background: #1f2328;
|
||||
color: #fff;
|
||||
font-size: 12.5px;
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, .18);
|
||||
max-width: 76ch;
|
||||
}
|
||||
.toast.bad { background: var(--danger); }
|
||||
@ -2,300 +2,164 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>云仓视频溯源 · 规则配置</title>
|
||||
<link rel="stylesheet" href="options.css">
|
||||
<title>云仓视频溯源 · 插件配置</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f6f7f9;
|
||||
--card: #fff;
|
||||
--border: #e2e6ec;
|
||||
--text: #1f2937;
|
||||
--muted: #6b7280;
|
||||
--ok: #15803d;
|
||||
--warn: #b45309;
|
||||
--error: #b91c1c;
|
||||
--mono: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 28px 20px 48px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
.wrap { max-width: 760px; margin: 0 auto; }
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
header h1 { margin: 0; font-size: 18px; }
|
||||
|
||||
.badge {
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
background: #eef2ff;
|
||||
color: #3730a3;
|
||||
}
|
||||
|
||||
.badge.err { background: #fef2f2; color: var(--error); }
|
||||
|
||||
.card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 16px 18px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
h2 { margin: 0 0 10px; font-size: 14px; }
|
||||
|
||||
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 6px 0; }
|
||||
|
||||
.label { color: var(--muted); min-width: 88px; }
|
||||
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
.chips { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
|
||||
.chip {
|
||||
padding: 1px 8px;
|
||||
border-radius: 6px;
|
||||
background: #f1f5f9;
|
||||
border: 1px solid var(--border);
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.chip.host { background: #eef4ff; border-color: #dbe6ff; color: #1d4ed8; }
|
||||
|
||||
code {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
background: #f1f5f9;
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
|
||||
|
||||
button {
|
||||
height: 32px;
|
||||
padding: 0 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: #fff;
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary { background: #2563eb; border-color: #2563eb; color: #fff; }
|
||||
|
||||
button:disabled { opacity: .55; cursor: default; }
|
||||
|
||||
.err { color: var(--error); }
|
||||
|
||||
.ok { color: var(--ok); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<h1>云仓视频溯源 · 插件配置</h1>
|
||||
<span class="badge" id="version">v—</span>
|
||||
<span class="badge err" id="badge-error" style="display:none">同步失败</span>
|
||||
</header>
|
||||
|
||||
<header class="page-head">
|
||||
<img class="logo" src="../icons/icon48.png" alt="">
|
||||
<div>
|
||||
<h1>云仓视频溯源 · 页面注入配置</h1>
|
||||
<p class="muted">
|
||||
在第三方 WMS / 后台页面里按规则识别单号,就地加工成可点击元素;
|
||||
点击后按「打开方式」直接<b>唤起本机软件</b>(协议),或打开网页并把编号塞进 <code>{code}</code> 占位符。
|
||||
改完保存即生效,已打开的页面会自动重新扫描,<b>不需要刷新</b>。
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
|
||||
<!-- ============================ 基本设置 ============================ -->
|
||||
<section class="card">
|
||||
<h2>基本设置</h2>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>总开关</span>
|
||||
<select id="enabled">
|
||||
<option value="true">开启</option>
|
||||
<option value="false">关闭</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>点击后打开方式</span>
|
||||
<select id="openMode">
|
||||
<option value="app">直接唤起本机软件(协议)</option>
|
||||
<option value="window">独立小窗(网页)</option>
|
||||
<option value="tab">新标签页(网页)</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>加工方式</span>
|
||||
<select id="actionMode">
|
||||
<option value="button">在旁边加按钮(不碰原元素)</option>
|
||||
<option value="chip">命中元素本身可点</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>按钮文案(加工方式 = 在旁边加按钮时生效)</span>
|
||||
<input id="buttonText" placeholder="查看打包视频">
|
||||
<em class="hint" id="btnPreview">预览:—</em>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>标记样式(仅「命中元素本身可点」时生效)</span>
|
||||
<select id="markStyle">
|
||||
<option value="underline">下划线(不改变布局)</option>
|
||||
<option value="highlight">淡青高亮</option>
|
||||
<option value="chip">胶囊</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>显示播放角标(同上,仅元素本身可点时生效)</span>
|
||||
<select id="showIcon">
|
||||
<option value="true">显示</option>
|
||||
<option value="false">不显示</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>生效站点(glob,一行/逗号分隔,<code>*</code> = 全部站点)</span>
|
||||
<textarea id="hosts" rows="2" class="mono" placeholder="wms.wms.gztbyc.com *.gztbyc.com"></textarea>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>
|
||||
唤本机软件的协议模板 占位符同上(仅在「直接唤起本机软件」时生效)
|
||||
</span>
|
||||
<input id="appUrlTemplate" class="mono" placeholder="yuncang://open?code={code}">
|
||||
<em class="hint">
|
||||
默认 <code>yuncang://open?code={code}</code>;协议名必须与软件安装时注册的一致。
|
||||
唤不起时(约 8 秒内探测不到本机服务)会弹兜底卡片(见下方「唤不起时的兜底页」)。
|
||||
</em>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>
|
||||
网页地址模板 占位符:<code>{code}</code>=编号(URL 编码)、<code>{rawcode}</code>=编号原样、<code>{host}</code>=当前站点
|
||||
(仅在「独立小窗 / 新标签页」时生效)
|
||||
</span>
|
||||
<input id="urlTemplate" class="mono" placeholder="http://localhost:7301/local?code={code}">
|
||||
<em class="hint" id="urlPreview">预览:—</em>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>唤不起时的兜底页(协议没注册 / 没安装时弹的「在网页中查看」)</span>
|
||||
<input id="fallbackUrl" class="mono" placeholder="http://localhost:7301/local?code={code}">
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>软件下载地址(留空 = 兜底卡片不显示「下载安装」,只给「在网页中查看」)</span>
|
||||
<input id="downloadUrl" class="mono" placeholder="https://…/download">
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>DOM 变动后延迟重扫(毫秒)</span>
|
||||
<input id="scanDelay" type="number" min="0" max="5000" step="50">
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>单页最多标记多少处</span>
|
||||
<input id="maxMarks" type="number" min="1" max="5000" step="10">
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>单次扫描最多看多少个文本节点</span>
|
||||
<input id="maxNodes" type="number" min="100" max="50000" step="100">
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============================== 规则 ============================== -->
|
||||
<section class="card">
|
||||
<h2>
|
||||
识别规则
|
||||
<small class="muted">默认规则已按 <code>https://wms.wms.gztbyc.com/order/orderManagement</code> 的真实结构取样</small>
|
||||
</h2>
|
||||
|
||||
<div id="rules" class="rules"></div>
|
||||
|
||||
<div class="row-actions">
|
||||
<button type="button" id="add-rule">+ 添加规则</button>
|
||||
</div>
|
||||
|
||||
<p class="note muted">
|
||||
两种匹配方式:<br>
|
||||
· <b>CSS 选择器</b>:直接命中元素本身(例如 Element-Plus 表格里的 <code>[title*="快递单号"]</code>),
|
||||
取它的文本或某个属性(<code>attr</code>)当编号;<b>属性里的值必须用这种</b> —— 文本扫描只走文本节点,拿不到属性。<br>
|
||||
· <b>文本正则</b>:遍历页面文本,把命中的子串包起来(原文照抄,页面读 textContent / 复制粘贴不受影响)。<br>
|
||||
· <b>正则与模式的关系</b>:文本模式下正则必填(用来找编号);选择器模式下正则<b>可选</b>,
|
||||
填了就用来从取到的属性值/文本里<b>再抽一次</b>编号。<br>
|
||||
例:<code><a href="javascript:MM_openTrace('../system/view-trace!viewTrace.jspb?postNum=202610101621&wareHouseId=5400')"></code>
|
||||
→ 选择器 <code>a[href*="postNum="]</code> + 属性 <code>href</code> + 正则 <code>postNum=([0-9A-Za-z_-]+)</code>。
|
||||
</p>
|
||||
|
||||
<p class="note muted">
|
||||
两种加工方式:<br>
|
||||
· <b>在旁边加按钮</b>(默认):宿主元素<b>一个字都不改</b>(不加类名、不改 title、不接管点击),
|
||||
只在它旁边插一个「查看打包视频」兄弟按钮 —— 页面自己原来的点击行为照旧。<br>
|
||||
· <b>命中元素本身可点</b>:元素自己变成可点(会加类名 / 改写 title / 接管点击),
|
||||
适合页面上本来就是个普通文字的场景。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- ============================= 试跑 ============================= -->
|
||||
<section class="card">
|
||||
<h2>规则试跑 <small class="muted">用当前<b>还没保存</b>的规则试,方便调正则</small></h2>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>模拟站点(用于校验规则的「生效站点」)</span>
|
||||
<input id="testHost" class="mono" placeholder="wms.wms.gztbyc.com">
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>输入类型</span>
|
||||
<select id="testMode">
|
||||
<option value="html">HTML 片段</option>
|
||||
<option value="text">纯文本</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<textarea id="testInput" rows="5" class="mono"></textarea>
|
||||
|
||||
<div class="row-actions">
|
||||
<button type="button" id="run-test" class="primary">试跑</button>
|
||||
<button type="button" id="fill-sample">填入 WMS 取样</button>
|
||||
</div>
|
||||
|
||||
<div id="testResult" class="test-result"></div>
|
||||
</section>
|
||||
|
||||
<!-- ========================== 导入导出/重置 ========================== -->
|
||||
<section class="card">
|
||||
<h2>导入 / 导出</h2>
|
||||
<textarea id="json" rows="4" class="mono" placeholder="点「导出」把当前配置贴到这里,或粘贴一段配置后点「导入」"></textarea>
|
||||
<div class="row-actions">
|
||||
<button type="button" id="export">导出</button>
|
||||
<button type="button" id="import">导入</button>
|
||||
<button type="button" id="reset" class="danger">恢复默认</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============================ 使用说明 ============================ -->
|
||||
<section class="card">
|
||||
<h2>使用说明</h2>
|
||||
<ol class="steps">
|
||||
<li>打开 <code>chrome://extensions</code> → 右上角打开「开发者模式」→「加载已解压的扩展程序」→ 选择本项目的 <code>extension/</code> 目录。</li>
|
||||
<li>进入 WMS 页面(<code>https://wms.wms.gztbyc.com/order/orderManagement</code>),运单号<b>旁边</b>会出现「查看打包视频」按钮。</li>
|
||||
<li>点这个按钮 → 直接用 <code>yuncang://open?code=<运单号></code> <b>唤起本机软件</b>并定位到这个单号(浏览器第一次会问「要打开吗」,点允许即可)。没安装或协议没注册时,约 8 秒后(探测不到本机服务)会在右下角弹出「在网页中查看 / 下载安装」的兜底提示。</li>
|
||||
<li>想让它在浏览器里看,把「目标地址模板」换成 <code>http://…/local?code={code}</code>(本机软件公共页,<b>不需要登录</b>:一次查询就能知道软件在不在、要不要唤起登录)。</li>
|
||||
<li>运单号本身(<code>点击复制二维码</code>)不受影响,点它还是原来的复制行为。</li>
|
||||
<li>调规则时优先用下面的「规则试跑」,不要反复刷页面。工具栏图标上的弹窗能看到「本页命中」清单,用来确认注入是否生效。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<footer class="page-foot">
|
||||
<button type="button" id="save" class="primary big">保存配置</button>
|
||||
<span id="savedAt" class="muted"></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<template id="rule-tpl">
|
||||
<div class="rule" data-rule>
|
||||
<div class="rule-head">
|
||||
<label class="sw small" title="启用这条规则">
|
||||
<input type="checkbox" data-field="enabled">
|
||||
<span></span>
|
||||
</label>
|
||||
<input class="rname" data-field="name" placeholder="规则名称">
|
||||
<code class="rid" data-id></code>
|
||||
<div class="rule-actions">
|
||||
<button type="button" data-act="up" title="上移">↑</button>
|
||||
<button type="button" data-act="down" title="下移">↓</button>
|
||||
<button type="button" data-act="dup" title="复制">⧉</button>
|
||||
<button type="button" data-act="del" title="删除" class="danger">✕</button>
|
||||
<div class="card">
|
||||
<h2>同步状态</h2>
|
||||
<div class="row"><span class="label">配置来源</span><span id="source" class="muted">—</span></div>
|
||||
<div class="row"><span class="label">上次同步</span><span id="last-sync" class="muted">—</span></div>
|
||||
<div class="row"><span class="label">自动同步</span><span class="muted">每小时一次(插件启动时也会同步)</span></div>
|
||||
<div class="row" id="error-row" style="display:none">
|
||||
<span class="label">上次错误</span><span id="sync-error" class="err"></span>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button id="sync-now" class="primary" type="button">立即同步</button>
|
||||
<button id="download" type="button" style="display:none">下载桌面端</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>匹配方式</span>
|
||||
<select data-field="match">
|
||||
<option value="text">文本正则</option>
|
||||
<option value="selector">CSS 选择器</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>加工方式</span>
|
||||
<select data-field="actionMode">
|
||||
<option value="">跟随全局</option>
|
||||
<option value="button">在旁边加按钮</option>
|
||||
<option value="chip">元素本身可点</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>标记样式(仅 chip 时生效)</span>
|
||||
<select data-field="style">
|
||||
<option value="">跟随全局</option>
|
||||
<option value="underline">下划线</option>
|
||||
<option value="highlight">淡青高亮</option>
|
||||
<option value="chip">胶囊</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f wide" data-when="selector">
|
||||
<span>CSS 选择器</span>
|
||||
<input data-field="selector" class="mono" placeholder="[title*="快递单号"]">
|
||||
</label>
|
||||
<label class="f" data-when="selector">
|
||||
<span>取哪个属性(留空 = 取元素文本)</span>
|
||||
<input data-field="attr" class="mono" placeholder="href">
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>正则表达式 <em class="hint" data-hint="pattern"></em></span>
|
||||
<input data-field="pattern" class="mono">
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>flags</span>
|
||||
<input data-field="flags" class="mono" placeholder="gi">
|
||||
</label>
|
||||
<label class="f wide">
|
||||
<span>排除正则(抽出的编号命中即跳过,可留空)</span>
|
||||
<input data-field="exclude" class="mono">
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>生效站点(glob,一行/逗号分隔,<code>*</code> = 全部)</span>
|
||||
<input data-field="hostPatterns" class="mono" placeholder="*">
|
||||
</label>
|
||||
<label class="f wide">
|
||||
<span>专属目标地址(留空 = 用全局模板)</span>
|
||||
<input data-field="urlTemplate" class="mono" placeholder="https://video.example.com/play?keyword={code}">
|
||||
</label>
|
||||
<div class="card">
|
||||
<h2>生效站点</h2>
|
||||
<p class="muted" style="margin:0 0 8px">
|
||||
插件只在这些域名下识别单号(支持 <code>*.abc-wms.com</code> 这种通配)。由管理员统一维护。
|
||||
</p>
|
||||
<div id="hosts" class="chips"></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script src="lib/rules.js"></script>
|
||||
<script src="options.js"></script>
|
||||
<div class="card">
|
||||
<h2>单号识别</h2>
|
||||
<p class="muted" style="margin:0 0 8px">
|
||||
只认这些前缀;正则与位数由服务器下发,本地不提供修改。
|
||||
</p>
|
||||
<div id="prefixes" class="chips"></div>
|
||||
<div class="row" style="margin-top:10px">
|
||||
<span class="label">单号位数</span>
|
||||
<span id="digits" class="muted">—</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>跳转</h2>
|
||||
<div class="row"><span class="label">唤起软件</span><code id="app-url">—</code></div>
|
||||
<div class="row"><span class="label">网页查看</span><code id="web-url">—</code></div>
|
||||
</div>
|
||||
|
||||
<p class="muted" id="foot">
|
||||
本插件只拉取并执行后台下发的配置:要改前缀或生效站点,请在网页后台「平台管理 → 插件配置」里修改。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script src="lib/rules.js"></script>
|
||||
<script src="options.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@ -1,425 +1,140 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · 规则配置页
|
||||
* 云仓视频溯源 · 选项页(**只读状态页**)
|
||||
*
|
||||
* 说明:
|
||||
* - 页面上所有读写都围绕「配置对象」,最终由 PSTRules.normalizeConfig 兜底(缺字段/非法值都不会写坏)。
|
||||
* - 「试跑」用的是**当前表单里还没保存**的规则,方便边调正则边看结果。
|
||||
* - 试跑里渲染 HTML 一律走 PSTRules.escapeHtml,不把外来 HTML 直接 innerHTML 进本页(杜绝 onerror 之类)。
|
||||
* 插件不再提供规则编辑 / 试跑 / 导入导出 / 使用说明:
|
||||
* 识别前缀、生效站点、跳转模板全部由后台「平台管理 → 插件配置」维护,
|
||||
* 插件每小时自动同步(后台 background.js),这里只展示状态 + 提供「立即同步」。
|
||||
*/
|
||||
(function () {
|
||||
const R = globalThis.PSTRules;
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
/** 取样自 https://wms.wms.gztbyc.com/order/orderManagement 的一整行(已精简掉无关列) */
|
||||
const SAMPLE_HTML = [
|
||||
'<table><tbody><tr>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制发货单号">JY2026101619599</span></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制并查看快递单号二维码">321408064481776</span>',
|
||||
' <button type="button" class="click-copy-toggle" title="展开查看全部">+1</button></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制波次号">E2026101600069</span></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制平台交易单号">6930529169563286869</span></td>',
|
||||
' <td><span class="ut-status-text ut-status-text--success">已打包</span></td>',
|
||||
' <td><span>2026-10-16 13:26:22</span></td>',
|
||||
'</tr></tbody></table>',
|
||||
].join('\n');
|
||||
const SYNC_STATE_KEY = 'pstSyncState';
|
||||
const CONFIG_SOURCE = 'https://pack.wms.gztbyc.com/api/web/extension/config';
|
||||
|
||||
let cfg = R.defaultConfig();
|
||||
init();
|
||||
|
||||
boot();
|
||||
|
||||
async function boot() {
|
||||
cfg = await R.loadConfig();
|
||||
fillBase(cfg);
|
||||
renderRules(cfg.rules);
|
||||
|
||||
$('testHost').value = 'wms.wms.gztbyc.com';
|
||||
$('testInput').value = SAMPLE_HTML;
|
||||
|
||||
bind();
|
||||
updateUrlPreview();
|
||||
runTest();
|
||||
async function init() {
|
||||
$('sync-now').addEventListener('click', onSyncNow);
|
||||
$('download').addEventListener('click', onDownload);
|
||||
await render();
|
||||
}
|
||||
|
||||
/* ============================== 基本设置 ============================== */
|
||||
|
||||
function fillBase(c) {
|
||||
$('enabled').value = String(c.enabled);
|
||||
$('openMode').value = c.openMode;
|
||||
$('actionMode').value = c.actionMode;
|
||||
$('buttonText').value = c.buttonText;
|
||||
$('markStyle').value = c.markStyle;
|
||||
$('showIcon').value = String(c.showIcon);
|
||||
$('hosts').value = (c.hosts || []).join('\n');
|
||||
$('urlTemplate').value = c.urlTemplate;
|
||||
$('appUrlTemplate').value = c.appUrlTemplate || '';
|
||||
$('fallbackUrl').value = c.fallbackUrl || '';
|
||||
$('downloadUrl').value = c.downloadUrl || '';
|
||||
$('scanDelay').value = c.scanDelay;
|
||||
$('maxMarks').value = c.maxMarks;
|
||||
$('maxNodes').value = c.maxNodes;
|
||||
updateBtnPreview();
|
||||
}
|
||||
|
||||
function readBase() {
|
||||
return {
|
||||
enabled: $('enabled').value === 'true',
|
||||
openMode: $('openMode').value,
|
||||
actionMode: $('actionMode').value,
|
||||
buttonText: $('buttonText').value,
|
||||
markStyle: $('markStyle').value,
|
||||
showIcon: $('showIcon').value === 'true',
|
||||
hosts: $('hosts').value,
|
||||
urlTemplate: $('urlTemplate').value,
|
||||
appUrlTemplate: $('appUrlTemplate').value,
|
||||
fallbackUrl: $('fallbackUrl').value,
|
||||
downloadUrl: $('downloadUrl').value,
|
||||
scanDelay: $('scanDelay').value,
|
||||
maxMarks: $('maxMarks').value,
|
||||
maxNodes: $('maxNodes').value,
|
||||
};
|
||||
}
|
||||
|
||||
/** 表单 → 合法配置对象(同时用于保存和试跑) */
|
||||
function readForm() {
|
||||
return R.normalizeConfig(Object.assign(readBase(), { rules: readRules() }));
|
||||
}
|
||||
|
||||
/* ================================ 规则 ================================ */
|
||||
|
||||
const field = (card, name) => card.querySelector('[data-field="' + name + '"]');
|
||||
|
||||
function renderRules(rules) {
|
||||
const box = $('rules');
|
||||
box.textContent = '';
|
||||
for (const rule of rules) box.appendChild(ruleCard(rule));
|
||||
}
|
||||
|
||||
function ruleCard(rule) {
|
||||
const card = $('rule-tpl').content.firstElementChild.cloneNode(true);
|
||||
card.dataset.id = rule.id;
|
||||
field(card, 'enabled').checked = !!rule.enabled;
|
||||
field(card, 'name').value = rule.name;
|
||||
field(card, 'match').value = rule.match;
|
||||
field(card, 'actionMode').value = rule.actionMode || '';
|
||||
field(card, 'style').value = rule.style || '';
|
||||
field(card, 'pattern').value = rule.pattern;
|
||||
field(card, 'flags').value = rule.flags;
|
||||
field(card, 'exclude').value = rule.exclude;
|
||||
field(card, 'selector').value = rule.selector;
|
||||
field(card, 'attr').value = rule.attr;
|
||||
field(card, 'hostPatterns').value = (rule.hostPatterns || []).join(' ');
|
||||
field(card, 'urlTemplate').value = rule.urlTemplate;
|
||||
card.querySelector('[data-id]').textContent = rule.id;
|
||||
updateWhen(card);
|
||||
updateOff(card);
|
||||
return card;
|
||||
}
|
||||
|
||||
function readRules() {
|
||||
return Array.prototype.slice.call($('rules').querySelectorAll('.rule')).map(card => ({
|
||||
id: card.dataset.id,
|
||||
enabled: field(card, 'enabled').checked,
|
||||
name: field(card, 'name').value.trim(),
|
||||
match: field(card, 'match').value,
|
||||
actionMode: field(card, 'actionMode').value,
|
||||
style: field(card, 'style').value,
|
||||
pattern: field(card, 'pattern').value,
|
||||
flags: field(card, 'flags').value,
|
||||
exclude: field(card, 'exclude').value,
|
||||
selector: field(card, 'selector').value,
|
||||
attr: field(card, 'attr').value.trim(),
|
||||
hostPatterns: field(card, 'hostPatterns').value,
|
||||
urlTemplate: field(card, 'urlTemplate').value.trim(),
|
||||
}));
|
||||
}
|
||||
|
||||
/** 正则输入框的提示随匹配方式变:文本模式必填,选择器模式是可选的「再抽一次」 */
|
||||
const PATTERN_TIP = {
|
||||
text: {
|
||||
hint: '(必填:用来在页面文本里找编号;第 1 个捕获组 = 编号,没写就用整个匹配)',
|
||||
placeholder: '\\b(?:YT|SF|JD)\\d{10,16}\\b',
|
||||
},
|
||||
selector: {
|
||||
hint: '(可选:填了就从上面取到的属性/文本里再抽一次编号;第 1 个捕获组 = 编号)',
|
||||
placeholder: 'postNum=([0-9A-Za-z_-]+)',
|
||||
},
|
||||
};
|
||||
|
||||
function updateWhen(card) {
|
||||
const mode = field(card, 'match').value;
|
||||
for (const el of card.querySelectorAll('[data-when]')) {
|
||||
el.style.display = el.getAttribute('data-when') === mode ? '' : 'none';
|
||||
async function render() {
|
||||
let cfg;
|
||||
try {
|
||||
cfg = await R.loadConfig();
|
||||
} catch (_) {
|
||||
cfg = R.defaultConfig();
|
||||
}
|
||||
const tip = PATTERN_TIP[mode] || PATTERN_TIP.text;
|
||||
field(card, 'pattern').placeholder = tip.placeholder;
|
||||
const hint = card.querySelector('[data-hint="pattern"]');
|
||||
if (hint) hint.textContent = tip.hint;
|
||||
}
|
||||
|
||||
function updateOff(card) {
|
||||
card.classList.toggle('is-off', !field(card, 'enabled').checked);
|
||||
}
|
||||
const state = await readSyncState();
|
||||
const remote = cfg.remote || {};
|
||||
|
||||
function newRule() {
|
||||
// 借 normalizeRule 生成一个不重复的 id,顺便把字段补齐
|
||||
return R.normalizeRule({
|
||||
name: '新规则',
|
||||
enabled: true,
|
||||
match: 'text',
|
||||
pattern: '\\b[A-Z]{2}\\d{10,16}\\b',
|
||||
flags: 'gi',
|
||||
hostPatterns: ['*'],
|
||||
});
|
||||
}
|
||||
$('version').textContent = 'v' + (remote.version || '—');
|
||||
$('source').textContent = CONFIG_SOURCE;
|
||||
|
||||
function onRulesClick(e) {
|
||||
const btn = e.target.closest('button[data-act]');
|
||||
if (!btn) return;
|
||||
const card = btn.closest('.rule');
|
||||
const rules = $('rules');
|
||||
const act = btn.dataset.act;
|
||||
if (state.error) {
|
||||
$('badge-error').style.display = '';
|
||||
$('error-row').style.display = '';
|
||||
$('sync-error').textContent = state.error;
|
||||
} else {
|
||||
$('badge-error').style.display = 'none';
|
||||
$('error-row').style.display = 'none';
|
||||
}
|
||||
|
||||
if (act === 'del') {
|
||||
if (!confirm('删除规则「' + field(card, 'name').value + '」?(记得点保存才会生效)')) return;
|
||||
card.remove();
|
||||
} else if (act === 'up' && card.previousElementSibling) {
|
||||
rules.insertBefore(card, card.previousElementSibling);
|
||||
} else if (act === 'down' && card.nextElementSibling) {
|
||||
rules.insertBefore(card.nextElementSibling, card);
|
||||
} else if (act === 'dup') {
|
||||
const src = readRules().find(r => r.id === card.dataset.id);
|
||||
if (!src) return;
|
||||
const copy = R.normalizeRule(Object.assign({}, src, {
|
||||
id: newRule().id,
|
||||
name: (src.name || '规则') + ' 副本',
|
||||
}));
|
||||
rules.insertBefore(ruleCard(copy), card.nextElementSibling);
|
||||
$('last-sync').textContent = remote.syncedAt
|
||||
? formatTime(remote.syncedAt) + (state.reason === 'manual' ? '(手动)' : '(自动)')
|
||||
: '还没同步过(点「立即同步」)';
|
||||
|
||||
renderChips($('hosts'), cfg.hosts, 'host', '不限制(所有站点)');
|
||||
renderChips($('prefixes'), remote.prefixes && remote.prefixes.length ? remote.prefixes : [], '', '等待服务器下发');
|
||||
|
||||
$('digits').textContent = remote.minDigits
|
||||
? remote.minDigits + ' ~ ' + remote.maxDigits + ' 位'
|
||||
: '—';
|
||||
|
||||
$('app-url').textContent = cfg.appUrlTemplate || '—';
|
||||
$('web-url').textContent = cfg.urlTemplate || '—';
|
||||
|
||||
const download = $('download');
|
||||
if (cfg.downloadUrl) {
|
||||
download.style.display = '';
|
||||
download.title = cfg.downloadUrl;
|
||||
} else {
|
||||
download.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================ 试跑 ================================ */
|
||||
|
||||
function runTest() {
|
||||
const form = readForm();
|
||||
const compiled = R.compileRules(form.rules);
|
||||
const simHost = $('testHost').value.trim();
|
||||
const mode = $('testMode').value;
|
||||
const raw = $('testInput').value;
|
||||
const box = $('testResult');
|
||||
function renderChips(box, list, extraClass, emptyText) {
|
||||
box.textContent = '';
|
||||
|
||||
if (!raw.trim()) {
|
||||
box.appendChild(el('p', 'muted', '先粘一段 HTML / 文本再试跑。'));
|
||||
if (!list || !list.length) {
|
||||
const span = document.createElement('span');
|
||||
span.className = 'muted';
|
||||
span.textContent = emptyText;
|
||||
box.appendChild(span);
|
||||
return;
|
||||
}
|
||||
for (const item of list) {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'chip' + (extraClass ? ' ' + extraClass : '');
|
||||
chip.textContent = item;
|
||||
box.appendChild(chip);
|
||||
}
|
||||
}
|
||||
|
||||
let items = [];
|
||||
let marks = [];
|
||||
let truncated = false;
|
||||
async function onSyncNow() {
|
||||
const button = $('sync-now');
|
||||
button.disabled = true;
|
||||
button.textContent = '同步中…';
|
||||
try {
|
||||
const result = await sendSync();
|
||||
if (result && result.ok) {
|
||||
$('foot').className = 'ok';
|
||||
$('foot').textContent = result.unchanged
|
||||
? '已是最新配置(v' + result.version + ')'
|
||||
: '已更新到 v' + result.version + ',页面会自动重新扫描';
|
||||
} else {
|
||||
$('foot').className = 'err';
|
||||
$('foot').textContent = '同步失败:' + ((result && result.error) || '未知错误');
|
||||
}
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = '立即同步';
|
||||
await render();
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'html') {
|
||||
const doc = new DOMParser().parseFromString(raw, 'text/html');
|
||||
const res = R.applyMarks(doc.body, compiled, {
|
||||
markClass: 'pst-trace-mark',
|
||||
maxNodes: 3000,
|
||||
maxMarks: 200,
|
||||
defaultStyle: form.markStyle,
|
||||
defaultActionMode: form.actionMode,
|
||||
buttonText: form.buttonText,
|
||||
showIcon: form.showIcon,
|
||||
urlTemplate: form.urlTemplate,
|
||||
appUrlTemplate: form.appUrlTemplate,
|
||||
openMode: form.openMode,
|
||||
hostname: simHost,
|
||||
host: simHost,
|
||||
function sendSync() {
|
||||
return new Promise(resolve => {
|
||||
chrome.runtime.sendMessage({ type: 'pst:sync' }, res => {
|
||||
const err = chrome.runtime.lastError;
|
||||
resolve(err ? { ok: false, error: err.message } : res);
|
||||
});
|
||||
items = res.items;
|
||||
marks = res.marks;
|
||||
truncated = res.truncated;
|
||||
} else {
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
for (const m of R.matchText(line, compiled, 20)) {
|
||||
items.push({
|
||||
ruleId: m.rule.id,
|
||||
ruleName: m.rule.name,
|
||||
code: m.code,
|
||||
url: form.openMode === 'app'
|
||||
? R.buildUrl(form.appUrlTemplate, m.code, simHost)
|
||||
: R.buildUrl(m.rule.urlTemplate || form.urlTemplate, m.code, simHost),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 概览 ----
|
||||
const head = el('p', 'muted');
|
||||
head.innerHTML = '启用规则 <b>' + compiled.rules.length + '</b> 条'
|
||||
+ ' · 命中 <b class="' + (items.length ? 'good' : 'bad') + '">' + items.length + '</b> 条'
|
||||
+ (truncated ? ' · <span class="bad">已达上限,可能有遗漏</span>' : '')
|
||||
+ ' · 模拟站点 <code>' + R.escapeHtml(simHost || '(空)') + '</code>';
|
||||
box.appendChild(head);
|
||||
async function onDownload() {
|
||||
const cfg = await R.loadConfig();
|
||||
if (!cfg.downloadUrl) return;
|
||||
chrome.tabs.create({ url: cfg.downloadUrl });
|
||||
}
|
||||
|
||||
for (const err of compiled.errors) {
|
||||
box.appendChild(el('p', 'bad', '规则「' + err.name + '」无效:' + err.message));
|
||||
}
|
||||
|
||||
// ---- 命中表 ----
|
||||
if (items.length) {
|
||||
const table = document.createElement('table');
|
||||
table.innerHTML = '<thead><tr><th>规则</th><th>提取的编号</th><th>目标地址</th></tr></thead>';
|
||||
const tbody = document.createElement('tbody');
|
||||
for (const it of items) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = '<td>' + R.escapeHtml(it.ruleName || it.ruleId) + '</td>'
|
||||
+ '<td class="mono">' + R.escapeHtml(it.code) + '</td>'
|
||||
+ '<td class="mono">' + R.escapeHtml(it.url) + '</td>';
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
box.appendChild(table);
|
||||
} else {
|
||||
// 0 命中时把「为什么没命中」说清楚:多半是生效站点把规则挡住了
|
||||
const enabled = form.rules.filter(r => r.enabled);
|
||||
if (enabled.length) {
|
||||
const box2 = el('div', 'snippet');
|
||||
box2.textContent = enabled.map(r => '· ' + r.name + ' 生效站点:' + r.hostPatterns.join(' / ')
|
||||
+ (r.match === 'selector' ? ' 选择器:' + r.selector : ' 正则:' + r.pattern)).join('\n')
|
||||
+ '\n(模拟站点不在「生效站点」里、或选择器/正则没命中,都会是 0 条)';
|
||||
box.appendChild(box2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 二次加工后的源码片段(转义显示,不执行)----
|
||||
if (marks.length) {
|
||||
const snippet = el('div', 'snippet');
|
||||
snippet.textContent = marks.slice(0, 3)
|
||||
.map(m => trim(m.el.outerHTML, 240))
|
||||
.join('\n\n');
|
||||
box.appendChild(el('p', 'muted', '二次加工后的 HTML(最多 3 段):'));
|
||||
box.appendChild(snippet);
|
||||
async function readSyncState() {
|
||||
try {
|
||||
const stored = await chrome.storage.local.get(SYNC_STATE_KEY);
|
||||
return (stored && stored[SYNC_STATE_KEY]) || {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================ 导入导出/重置 ============================ */
|
||||
|
||||
async function reset() {
|
||||
if (!confirm('恢复为内置默认规则?当前配置会被覆盖。')) return;
|
||||
await save(R.defaultConfig());
|
||||
}
|
||||
|
||||
/* ================================ 保存 ================================ */
|
||||
|
||||
async function save(value) {
|
||||
const res = await R.saveConfig(value || readForm());
|
||||
if (!res.ok) {
|
||||
toast('保存失败:' + (res.message || ''), true);
|
||||
return;
|
||||
}
|
||||
cfg = await R.loadConfig();
|
||||
fillBase(cfg);
|
||||
renderRules(cfg.rules);
|
||||
updateUrlPreview();
|
||||
$('savedAt').textContent = '最后保存 ' + new Date().toLocaleTimeString();
|
||||
toast(res.warning ? '已保存(' + res.warning + ')' : '已保存 —— 已打开的页面会自动重新扫描');
|
||||
}
|
||||
|
||||
function updateUrlPreview() {
|
||||
const host = $('testHost').value.trim() || 'wms.wms.gztbyc.com';
|
||||
$('urlPreview').textContent = '预览:' + R.buildUrl($('urlTemplate').value, '321408064481776', host);
|
||||
}
|
||||
|
||||
function updateBtnPreview() {
|
||||
const text = $('buttonText').value.trim() || '查看打包视频';
|
||||
$('btnPreview').textContent = '预览:' + text + ' (加工方式 = ' + $('actionMode').value + ')';
|
||||
}
|
||||
|
||||
/* ================================ 绑定 ================================ */
|
||||
|
||||
function bind() {
|
||||
$('save').addEventListener('click', () => save());
|
||||
$('add-rule').addEventListener('click', () => {
|
||||
$('rules').appendChild(ruleCard(newRule()));
|
||||
});
|
||||
|
||||
const rulesBox = $('rules');
|
||||
rulesBox.addEventListener('click', onRulesClick);
|
||||
rulesBox.addEventListener('change', e => {
|
||||
const card = e.target.closest('.rule');
|
||||
if (!card) return;
|
||||
const name = e.target.getAttribute('data-field');
|
||||
if (name === 'match') updateWhen(card);
|
||||
if (name === 'enabled') updateOff(card);
|
||||
// 规则改了就顺手重跑一遍试跑,$('testInput') 里没东西时不会报错
|
||||
if (name) runTest();
|
||||
});
|
||||
|
||||
$('run-test').addEventListener('click', runTest);
|
||||
$('fill-sample').addEventListener('click', () => {
|
||||
$('testMode').value = 'html';
|
||||
$('testInput').value = SAMPLE_HTML;
|
||||
runTest();
|
||||
});
|
||||
|
||||
$('urlTemplate').addEventListener('input', updateUrlPreview);
|
||||
$('testHost').addEventListener('input', updateUrlPreview);
|
||||
$('buttonText').addEventListener('input', () => { updateBtnPreview(); runTest(); });
|
||||
$('actionMode').addEventListener('change', () => { updateBtnPreview(); runTest(); });
|
||||
$('testInput').addEventListener('input', debounce(runTest, 350));
|
||||
|
||||
$('export').addEventListener('click', () => {
|
||||
$('json').value = JSON.stringify(readForm(), null, 2);
|
||||
toast('已导出到下面的文本框,复制走即可');
|
||||
});
|
||||
$('import').addEventListener('click', async () => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse($('json').value);
|
||||
} catch (e) {
|
||||
toast('JSON 解析失败:' + e.message, true);
|
||||
return;
|
||||
}
|
||||
await save(parsed);
|
||||
});
|
||||
$('reset').addEventListener('click', reset);
|
||||
|
||||
window.addEventListener('keydown', e => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ================================ 小工具 ================================ */
|
||||
|
||||
function el(tag, cls, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (cls) node.className = cls;
|
||||
if (text != null) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(message, bad) {
|
||||
const box = $('toast');
|
||||
box.textContent = message;
|
||||
box.className = 'toast' + (bad ? ' bad' : '');
|
||||
box.hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => { box.hidden = true; }, bad ? 6000 : 2600);
|
||||
}
|
||||
|
||||
function trim(s, max) {
|
||||
const t = String(s || '');
|
||||
return t.length > max ? t.slice(0, max) + ' …(' + t.length + ' 字符)' : t;
|
||||
}
|
||||
|
||||
function debounce(fn, ms) {
|
||||
let t = null;
|
||||
return function () {
|
||||
clearTimeout(t);
|
||||
t = setTimeout(fn, ms);
|
||||
};
|
||||
function formatTime(iso) {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return iso;
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
|
||||
+ ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes());
|
||||
}
|
||||
})();
|
||||
|
||||
@ -12,10 +12,7 @@
|
||||
<h1>云仓视频溯源</h1>
|
||||
<p id="host" class="muted">—</p>
|
||||
</div>
|
||||
<label class="sw" title="总开关">
|
||||
<input type="checkbox" id="enabled">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="badge" id="version" title="服务器下发的配置版本">v—</span>
|
||||
</header>
|
||||
|
||||
<section class="card" id="state">
|
||||
@ -33,7 +30,8 @@
|
||||
|
||||
<div class="actions">
|
||||
<button id="rescan" type="button">重新扫描</button>
|
||||
<button id="open-options" type="button" class="primary">规则配置</button>
|
||||
<button id="sync" type="button">立即同步</button>
|
||||
<button id="open-options" type="button" class="primary">设置</button>
|
||||
</div>
|
||||
|
||||
<script src="lib/rules.js"></script>
|
||||
|
||||
@ -22,10 +22,11 @@
|
||||
} catch (_) {
|
||||
cfg = R.defaultConfig();
|
||||
}
|
||||
$('enabled').checked = !!cfg.enabled;
|
||||
// 配置由服务器下发:这里只展示版本,不提供本地开关(避免每小时同步时被冲掉、两处打架)
|
||||
$('version').textContent = 'v' + ((cfg.remote && cfg.remote.version) || '—');
|
||||
|
||||
$('enabled').addEventListener('change', onToggle);
|
||||
$('rescan').addEventListener('click', onRescan);
|
||||
$('sync').addEventListener('click', onSyncNow);
|
||||
$('open-options').addEventListener('click', () => chrome.runtime.openOptionsPage());
|
||||
|
||||
try {
|
||||
@ -53,8 +54,8 @@
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge warn">未注入</span>'
|
||||
+ '<span class="muted">这个页面还没有脚本,刷新一下即可</span></div>';
|
||||
} else if (!status.enabled) {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge off">已关闭</span>'
|
||||
+ '<span class="muted">总开关处于关闭状态</span></div>';
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge off">已停用</span>'
|
||||
+ '<span class="muted">管理员在后台关闭了插件</span></div>';
|
||||
} else if (!status.hostAllowed && !status.active) {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge off">不在生效范围</span></div>'
|
||||
+ '<div class="row"><span class="muted">生效站点:' + R.escapeHtml((status.hosts || []).join(' / ')) + '</span></div>';
|
||||
@ -98,20 +99,33 @@
|
||||
|
||||
/* ------------------------------------------------------------ 交互 */
|
||||
|
||||
async function onToggle() {
|
||||
const next = $('enabled').checked;
|
||||
cfg.enabled = next;
|
||||
const res = await R.saveConfig(cfg);
|
||||
if (!res.ok) {
|
||||
$('enabled').checked = !next;
|
||||
$('state').innerHTML = '<div class="row"><span class="badge warn">保存失败</span>'
|
||||
+ '<span class="muted">' + R.escapeHtml(res.message || '') + '</span></div>';
|
||||
return;
|
||||
/** 手动同步服务器配置(成功后 content script 会自己重扫,这里只刷展示) */
|
||||
async function onSyncNow() {
|
||||
const button = $('sync');
|
||||
button.disabled = true;
|
||||
button.textContent = '同步中…';
|
||||
try {
|
||||
const res = await new Promise(resolve => {
|
||||
chrome.runtime.sendMessage({ type: 'pst:sync' }, value => {
|
||||
const err = chrome.runtime.lastError;
|
||||
resolve(err ? { ok: false, error: err.message } : value);
|
||||
});
|
||||
});
|
||||
|
||||
if (!res || !res.ok) {
|
||||
$('state').innerHTML = '<div class="row"><span class="badge warn">同步失败</span>'
|
||||
+ '<span class="muted">' + R.escapeHtml(String((res && res.error) || '未知错误')) + '</span></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
cfg = await R.loadConfig();
|
||||
$('version').textContent = 'v' + ((cfg.remote && cfg.remote.version) || '—');
|
||||
status = tab ? await send(tab.id, { type: 'pst:status' }) : null;
|
||||
render();
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = '立即同步';
|
||||
}
|
||||
cfg = await R.loadConfig();
|
||||
// content script 收到 storage 变更会自己重新扫描,这里刷一下展示
|
||||
status = tab ? await send(tab.id, { type: 'pst:status' }) : null;
|
||||
render();
|
||||
}
|
||||
|
||||
async function onRescan() {
|
||||
|
||||
46
frontend/src/api/extension.ts
Normal file
46
frontend/src/api/extension.ts
Normal file
@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Chrome 插件集中配置(平台管理员维护)
|
||||
*
|
||||
* 后端:
|
||||
* - `GET/PUT /api/web/admin/extension` —— 管理端(平台管理员)
|
||||
* - `GET /api/web/extension/config` —— 插件读的公开只读接口(这里用不到)
|
||||
*
|
||||
* 后台**只维护单号前缀**(`YT` / `SF` / `32`…),单号正则由服务端拼好放在 `pattern` 里,
|
||||
* 前端只做只读预览、不接受修改。
|
||||
*/
|
||||
import { api } from '@/api/client';
|
||||
|
||||
export interface ExtensionConfig {
|
||||
/** 每次保存 +1;插件靠它判断配置有没有变 */
|
||||
version: number;
|
||||
enabled: boolean;
|
||||
/** 插件允许工作的站点(glob:`*.abc.com`、`192.168.11.206`、`*`) */
|
||||
hosts: string[];
|
||||
/** 单号前缀(大写字母/数字) */
|
||||
prefixes: string[];
|
||||
minDigits: number;
|
||||
maxDigits: number;
|
||||
/** 网页跳转模板,必须含 `{code}` */
|
||||
urlTemplate: string;
|
||||
/** 唤起本机软件的协议模板,必须含 `{code}` */
|
||||
appUrlTemplate: string;
|
||||
/** 桌面端安装包地址;留空时插件回落到 /download/version.json */
|
||||
downloadUrl: string;
|
||||
updatedAt?: string | null;
|
||||
/** 服务端生成:`\b(?:YT|SF|…)\d{10,16}\b`(只读) */
|
||||
pattern: string;
|
||||
flags: string;
|
||||
}
|
||||
|
||||
/** 保存时能改的字段(version / pattern / flags / updatedAt 由服务端算) */
|
||||
export type ExtensionConfigInput = Omit<ExtensionConfig, 'version' | 'updatedAt' | 'pattern' | 'flags'>;
|
||||
|
||||
/** 读当前配置 */
|
||||
export function fetchExtensionConfig(): Promise<ExtensionConfig> {
|
||||
return api.get('/api/web/admin/extension');
|
||||
}
|
||||
|
||||
/** 保存配置(成功后 version +1,插件下次拉取即生效) */
|
||||
export function saveExtensionConfig(body: ExtensionConfigInput): Promise<ExtensionConfig> {
|
||||
return api.put('/api/web/admin/extension', body);
|
||||
}
|
||||
@ -13,7 +13,7 @@ import {
|
||||
subjectsLoaded,
|
||||
} from '@/composables/useSubject';
|
||||
import { clearPlatformAdmin, ensurePlatformAdmin, isPlatformAdmin } from '@/composables/usePlatformAdmin';
|
||||
import { fetchInstallerVersion, formatSize, type InstallerVersion } from '@/api/download';
|
||||
import { fetchInstallerVersion, formatSize, preferredDownloadUrl, type InstallerVersion } from '@/api/download';
|
||||
|
||||
/**
|
||||
* fill = true:列表页用 —— 内容区不滚动,卡片吃掉剩余高度,只有表格内部滚动(表头吸顶、分页贴底)
|
||||
@ -61,6 +61,7 @@ const platformMenus = [
|
||||
{ to: '/admin/subjects', label: '主体管理' },
|
||||
{ to: '/admin/orders', label: '订单管理' },
|
||||
{ to: '/admin/members', label: '管理员' },
|
||||
{ to: '/admin/extension', label: '插件配置' },
|
||||
];
|
||||
|
||||
/** 当前主体(用于右上角展示 / 过期提示) */
|
||||
@ -85,7 +86,7 @@ const androidPkg = ref<InstallerVersion | null>(null);
|
||||
function packageTitle(label: string, pkg: InstallerVersion | null): string {
|
||||
if (!pkg) return `${label}:还没有发布过安装包`;
|
||||
const parts = [ `${label} v${pkg.version || '?'}` ];
|
||||
const size = formatSize(pkg.size);
|
||||
const size = formatSize(pkg.sizeExe || pkg.size);
|
||||
if (size) parts.push(size);
|
||||
if (pkg.publishedAt) parts.push(`发布 ${pkg.publishedAt.slice(0, 10)}`);
|
||||
parts.push('点击下载');
|
||||
@ -94,7 +95,7 @@ function packageTitle(label: string, pkg: InstallerVersion | null): string {
|
||||
|
||||
/** 还没发布时按钮置灰、点了给个提示(不让浏览器跳到 404) */
|
||||
function guardDownload(event: MouseEvent, pkg: InstallerVersion | null, label: string) {
|
||||
if (pkg && pkg.downloadUrl) return;
|
||||
if (preferredDownloadUrl(pkg)) return;
|
||||
event.preventDefault();
|
||||
window.alert(`${label}还没有发布安装包,请稍后再试。`);
|
||||
}
|
||||
@ -165,7 +166,7 @@ onMounted(() => {
|
||||
<a
|
||||
class="download-btn"
|
||||
:class="{ 'is-missing': !desktopPkg }"
|
||||
:href="desktopPkg?.downloadUrl || undefined"
|
||||
:href="preferredDownloadUrl(desktopPkg)"
|
||||
:title="packageTitle('桌面端(Windows)', desktopPkg)"
|
||||
rel="noopener"
|
||||
@click="guardDownload($event, desktopPkg, '桌面端')"
|
||||
|
||||
@ -60,6 +60,13 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('@/views/AdminMembersView.vue'),
|
||||
meta: { allowNoSubject: true, platformAdmin: true },
|
||||
},
|
||||
// Chrome 插件:集中维护单号前缀 / 生效站点 / 跳转模板(插件只拉取执行)
|
||||
{
|
||||
path: '/admin/extension',
|
||||
name: 'admin-extension',
|
||||
component: () => import('@/views/AdminExtensionView.vue'),
|
||||
meta: { allowNoSubject: true, platformAdmin: true },
|
||||
},
|
||||
// 测试页只在开发构建里存在:生产包不包含该路由,也不会产出它的 chunk
|
||||
...(import.meta.env.DEV
|
||||
? [{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue'), meta: { adminOnly: true } } as RouteRecordRaw]
|
||||
|
||||
394
frontend/src/views/AdminExtensionView.vue
Normal file
394
frontend/src/views/AdminExtensionView.vue
Normal file
@ -0,0 +1,394 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 平台管理 · Chrome 插件配置
|
||||
*
|
||||
* 接口:`GET/PUT /api/web/admin/extension`(平台管理员)
|
||||
*
|
||||
* 这里只维护**能用一句话说清的东西**:
|
||||
* - 单号前缀(`YT` / `SF` / `32`…):单号正则由服务端拼,页面只读预览;
|
||||
* - 生效站点(插件允许在哪些域名工作,支持 `*.abc.com` 这种通配);
|
||||
* - 跳转模板与桌面端安装包地址。
|
||||
*
|
||||
* 插件端不提供任何编辑/试跑/导入导出:它每小时拉一次 `GET /api/web/extension/config`,
|
||||
* 版本号变了就换配置并重新扫描页面。
|
||||
*/
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { fetchExtensionConfig, saveExtensionConfig, type ExtensionConfig } from '@/api/extension';
|
||||
import { formatTime } from '@/utils/format';
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
|
||||
/** 服务端算出来的只读信息 */
|
||||
const meta = reactive({ version: 0, updatedAt: '' as string, pattern: '', flags: 'g' });
|
||||
|
||||
const form = reactive({
|
||||
enabled: true,
|
||||
hosts: [] as string[],
|
||||
prefixes: [] as string[],
|
||||
minDigits: 10,
|
||||
maxDigits: 16,
|
||||
urlTemplate: '',
|
||||
appUrlTemplate: '',
|
||||
downloadUrl: '',
|
||||
});
|
||||
|
||||
const hostInput = ref('');
|
||||
const prefixInput = ref('');
|
||||
|
||||
const patternPreview = ref('');
|
||||
|
||||
/** 错误文案带上 HTTP 状态码:404 = 后端没重启/没这个接口,422 = 校验不过,500 = 服务器异常 */
|
||||
function describe(err: unknown, fallback: string): string {
|
||||
if (err instanceof ApiError) return err.status ? `${err.message}(HTTP ${err.status})` : err.message;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function applyConfig(cfg: ExtensionConfig) {
|
||||
form.enabled = cfg.enabled;
|
||||
form.hosts = [...cfg.hosts];
|
||||
form.prefixes = [...cfg.prefixes];
|
||||
form.minDigits = cfg.minDigits;
|
||||
form.maxDigits = cfg.maxDigits;
|
||||
form.urlTemplate = cfg.urlTemplate;
|
||||
form.appUrlTemplate = cfg.appUrlTemplate;
|
||||
form.downloadUrl = cfg.downloadUrl || '';
|
||||
meta.version = cfg.version;
|
||||
meta.updatedAt = cfg.updatedAt || '';
|
||||
meta.pattern = cfg.pattern;
|
||||
meta.flags = cfg.flags;
|
||||
patternPreview.value = cfg.pattern;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
applyConfig(await fetchExtensionConfig());
|
||||
} catch (err) {
|
||||
error.value = describe(err, '加载失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function addHost() {
|
||||
const value = hostInput.value.trim();
|
||||
if (!value) return;
|
||||
// 粘 URL 时只留主机名:https://abc.com/xx → abc.com
|
||||
const cleaned = value.replace(/^[a-z]+:\/\//i, '').split('/')[0].trim().toLowerCase();
|
||||
if (cleaned && !form.hosts.includes(cleaned)) form.hosts.push(cleaned);
|
||||
hostInput.value = '';
|
||||
}
|
||||
|
||||
function removeHost(index: number) {
|
||||
form.hosts.splice(index, 1);
|
||||
}
|
||||
|
||||
function addPrefix() {
|
||||
// 支持一次粘一串:`YT SF JD` 或 `YT,SF,JD`
|
||||
const parts = prefixInput.value.split(/[\s,,、]+/).map(item => item.trim().toUpperCase()).filter(Boolean);
|
||||
for (const item of parts) {
|
||||
if (!/^[A-Z0-9]{1,8}$/.test(item)) {
|
||||
error.value = `前缀「${item}」不合法:只能是大写字母或数字,1~8 位`;
|
||||
return;
|
||||
}
|
||||
if (!form.prefixes.includes(item)) form.prefixes.push(item);
|
||||
}
|
||||
prefixInput.value = '';
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
function removePrefix(index: number) {
|
||||
form.prefixes.splice(index, 1);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
ok.value = '';
|
||||
error.value = '';
|
||||
|
||||
if (form.prefixes.length === 0) {
|
||||
error.value = '至少要有一个单号前缀';
|
||||
return;
|
||||
}
|
||||
if (!(form.minDigits >= 4 && form.maxDigits <= 24) || form.minDigits > form.maxDigits) {
|
||||
error.value = '单号位数要在 4~24 之间,且最小位数不能大于最大位数';
|
||||
return;
|
||||
}
|
||||
if (!form.urlTemplate.includes('{code}')) {
|
||||
error.value = '网页跳转模板必须包含 {code}';
|
||||
return;
|
||||
}
|
||||
if (!form.appUrlTemplate.includes('{code}')) {
|
||||
error.value = '唤起协议模板必须包含 {code}';
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
applyConfig(await saveExtensionConfig({
|
||||
enabled: form.enabled,
|
||||
hosts: form.hosts,
|
||||
prefixes: form.prefixes,
|
||||
minDigits: form.minDigits,
|
||||
maxDigits: form.maxDigits,
|
||||
urlTemplate: form.urlTemplate.trim(),
|
||||
appUrlTemplate: form.appUrlTemplate.trim(),
|
||||
downloadUrl: form.downloadUrl.trim(),
|
||||
}));
|
||||
ok.value = `已保存(v${meta.version})。插件每小时自动拉一次,也可以在插件里点「立即同步」。`;
|
||||
} catch (err) {
|
||||
error.value = describe(err, '保存失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 表单页**不能用 fill**:fill 是给列表页的(内容区不滚动),长表单会被截断、保存按钮点不到 -->
|
||||
<AppLayout>
|
||||
<template #title>插件配置</template>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<div v-if="ok" class="alert alert-ok">{{ ok }}</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>
|
||||
Chrome 插件(单号注入)
|
||||
<span class="badge badge-ok">v{{ meta.version }}</span>
|
||||
<span v-if="meta.updatedAt" class="cell-sub inline">上次保存 {{ formatTime(meta.updatedAt) }}</span>
|
||||
</h3>
|
||||
<p class="hint">
|
||||
插件**只拉取执行**:这里保存后,插件每小时自动同步一次(插件里也能点「立即同步」)。
|
||||
插件端不提供正则编辑、试跑、导入导出。
|
||||
</p>
|
||||
|
||||
<div class="row">
|
||||
<label class="switch">
|
||||
<input v-model="form.enabled" type="checkbox" />
|
||||
<span>启用插件(关掉后所有站点都不识别单号)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<h4>生效站点</h4>
|
||||
<p class="hint">插件只在这些域名下工作,支持通配:<code>*.abc-wms.com</code>、<code>192.168.11.206</code>。留空 = 不限制。</p>
|
||||
<div class="tag-box">
|
||||
<span v-for="(host, index) in form.hosts" :key="host" class="tag">
|
||||
{{ host }}
|
||||
<button type="button" class="tag-x" @click="removeHost(index)">×</button>
|
||||
</span>
|
||||
<input
|
||||
v-model="hostInput"
|
||||
class="tag-input"
|
||||
placeholder="输入域名后回车,例如 *.abc-wms.com"
|
||||
@keyup.enter="addHost"
|
||||
@blur="addHost"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h4>单号前缀</h4>
|
||||
<p class="hint">
|
||||
只维护前缀,单号正则由服务端生成(可一次粘贴多个:<code>YT SF JD</code>)。
|
||||
前缀只能是大写字母或数字(<code>32</code> / <code>77</code> 这类数字前缀也支持)。
|
||||
</p>
|
||||
<div class="tag-box">
|
||||
<span v-for="(prefix, index) in form.prefixes" :key="prefix" class="tag tag-prefix">
|
||||
{{ prefix }}
|
||||
<button type="button" class="tag-x" @click="removePrefix(index)">×</button>
|
||||
</span>
|
||||
<input
|
||||
v-model="prefixInput"
|
||||
class="tag-input"
|
||||
placeholder="输入前缀后回车"
|
||||
@keyup.enter="addPrefix"
|
||||
@blur="addPrefix"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<label>单号位数</label>
|
||||
<input v-model.number="form.minDigits" type="number" min="4" max="24" class="num" />
|
||||
<span class="hint">~</span>
|
||||
<input v-model.number="form.maxDigits" type="number" min="4" max="24" class="num" />
|
||||
<span class="hint">位(默认 10 ~ 16)</span>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<label>生成的单号正则</label>
|
||||
<code class="pattern">{{ patternPreview || '(没有前缀,不会识别任何单号)' }}</code>
|
||||
<span class="hint">只读 · flags={{ meta.flags }} · 插件端不展示</span>
|
||||
</div>
|
||||
|
||||
<h4>跳转地址</h4>
|
||||
<div class="field">
|
||||
<label>网页模板</label>
|
||||
<input v-model="form.urlTemplate" placeholder="http://localhost:7301/local?code={code}" />
|
||||
<span class="hint">没装本机软件时点单号打开的页面,必须含 <code>{code}</code></span>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>唤起协议</label>
|
||||
<input v-model="form.appUrlTemplate" placeholder="yuncang://open?code={code}" />
|
||||
<span class="hint">与桌面端注册的协议一致,必须含 <code>{code}</code></span>
|
||||
</div>
|
||||
<p class="hint">
|
||||
桌面端安装包地址**不用配**:插件同步时会自己读 <code>/download/version.json</code>,
|
||||
永远用最新发布版本(和网页顶栏「下载桌面端」是同一份)。
|
||||
</p>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn" :disabled="saving || loading" @click="save">{{ saving ? '保存中…' : '保存并下发' }}</button>
|
||||
<button class="btn btn-plain" :disabled="saving || loading" @click="load">放弃修改</button>
|
||||
</div>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card h4 {
|
||||
margin: 18px 0 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.card h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.inline {
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.row label {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tag-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
min-height: 38px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 6px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: #eef4ff;
|
||||
color: #1d4ed8;
|
||||
font-size: 12px;
|
||||
font-family: var(--mono, ui-monospace, Consolas, monospace);
|
||||
}
|
||||
|
||||
.tag-prefix {
|
||||
background: #f1f5f9;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.tag-x {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.tag-input {
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
border: 0;
|
||||
outline: none;
|
||||
font-size: 13px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.num {
|
||||
width: 72px;
|
||||
}
|
||||
|
||||
.pattern {
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.inline-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.inline-row input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.hint code {
|
||||
background: #f1f5f9;
|
||||
padding: 0 3px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 18px;
|
||||
padding: 12px 0;
|
||||
background: linear-gradient(to bottom, rgba(255, 255, 255, .85), #fff 40%);
|
||||
}
|
||||
</style>
|
||||
Loading…
x
Reference in New Issue
Block a user