Compare commits
31
Commits
1.1.0
...
10c39b5116
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10c39b5116 | ||
|
|
a4cd855b0c | ||
|
|
9c0b677d38 | ||
|
|
6890f13aa9 | ||
|
|
8f2f23682f | ||
|
|
2bd5c7057f | ||
|
|
74ff4701d6 | ||
|
|
9465c98859 | ||
|
|
5582aadc09 | ||
|
|
6867a3cb01 | ||
|
|
9b4667cab5 | ||
|
|
bf7a5a0449 | ||
|
|
dae14a8a10 | ||
|
|
9ace2c8aca | ||
|
|
fa559101b9 | ||
|
|
e10afb180d | ||
|
|
082c487cf8 | ||
|
|
1466e24c83 | ||
|
|
c17b7d5ad9 | ||
|
|
84a2d3db01 | ||
|
|
64715a2c9e | ||
|
|
21542c88d7 | ||
|
|
3cb4053ab5 | ||
|
|
91e9b027e8 | ||
|
|
b6e56f5f9a | ||
|
|
b2982ae8f7 | ||
|
|
9d766a0b58 | ||
|
|
605c09c88a | ||
|
|
5014376b81 | ||
|
|
bb8a0afeac | ||
|
|
4dccc4d96b |
@@ -51,6 +51,7 @@ BUILD_DIR_RETENTION_HOURS=24
|
|||||||
|
|
||||||
# 打包超时时间(小时),超时自动标记失败
|
# 打包超时时间(小时),超时自动标记失败
|
||||||
BUILD_TIMEOUT_HOURS=1
|
BUILD_TIMEOUT_HOURS=1
|
||||||
|
DOWNLOAD_URL_EXPIRE_SECONDS=600
|
||||||
|
|
||||||
# ---- Watchdog 健康监测 ----
|
# ---- Watchdog 健康监测 ----
|
||||||
# 健康检查间隔(秒)
|
# 健康检查间隔(秒)
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ __pycache__/
|
|||||||
|
|
||||||
# 运行时数据
|
# 运行时数据
|
||||||
backend/data/*.bak
|
backend/data/*.bak
|
||||||
|
# 运行时配置:网页 UI 改配置、每次 App_Store 打包都会写盘,不纳入版本控制。
|
||||||
|
# 结构参见仓库根目录的 config.example.json;首次部署可 cp 一份作为初始种子。
|
||||||
config.json
|
config.json
|
||||||
|
backend/data/config.json
|
||||||
ReadoorBranches/
|
ReadoorBranches/
|
||||||
build/
|
build/
|
||||||
|
|
||||||
|
|||||||
@@ -25,11 +25,14 @@ FastAPI + Vue 3 iOS app auto-packaging service. Supports Ad_Hoc and App_Store bu
|
|||||||
- `backend/deps.py` — JWT auth dependency used by all protected routes
|
- `backend/deps.py` — JWT auth dependency used by all protected routes
|
||||||
- `backend/config.py` — loads .env, defines all config constants
|
- `backend/config.py` — loads .env, defines all config constants
|
||||||
- `frontend/src/views/` — BuildView, HistoryView, ConfigView
|
- `frontend/src/views/` — BuildView, HistoryView, ConfigView
|
||||||
- `config.json` — runtime config (apps, schemes, servers, upload, branches) managed via web UI
|
- `config.json` — runtime config (apps, schemes, servers, upload, branches, versions) managed via web UI
|
||||||
|
- Multi-project: `config.json` is `{"projects": {pid: {definition + data}}, "upload": {...}}`; `backend/projects.py` holds project definitions (git, source_dir, xcode, copy_items, patcher `readoor`/`generic`, patch_rules, app_fields/server_fields, obfuscation). Requests pick the project via `X-Project` header (or `?project=`), bound in a ContextVar by middleware; `load_config()` returns the current project's data plus `upload` and `_project`. Legacy flat config auto-migrates to project `readoor` (uses `.env` Git settings). Tasks store `project_id`; build dirs are `build_{pid}_{task_id}`
|
||||||
|
- Versions are per-branch (within each project): every branch owns a track in `config["versions"]["tracks"]`, named after the branch (master/main keeps the historical name `release`); `config["branch_track"]` maps branch → track name, and each track's `kind` is `release` (build number auto-increments on App_Store) or `feature` (never increments)
|
||||||
|
- Tags are buildable refs too: `config["tags"]` (names never collide with branches), tracked in `branch_track` like branches (default kind `release`); tasks store the name in `branch` plus `ref_type` (`branch`/`tag`), and tag builds check out `refs/tags/<tag>` detached
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
- All backend routes require JWT auth except `/api/auth/login` and `/api/health`
|
- All backend routes require JWT auth except `/api/auth/login` and `/api/health`
|
||||||
- Admin-only routes: user management (`/api/users/*`)
|
- Admin-only routes: user management (`/api/users/*`) and all of `/api/config/*` except `/api/config/apps*` (incl. project CRUD `/api/config/projects*`); `GET /api/projects` is the public project list for any logged-in user
|
||||||
- Config stored in `config.json` (apps/schemes/servers), `.env` (infra), SQLite `build_config` table (build settings)
|
- Config stored in `config.json` (apps/schemes/servers), `.env` (infra), SQLite `build_config` table (build settings)
|
||||||
- Chinese UI and documentation throughout
|
- Chinese UI and documentation throughout
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
- [Watchdog 健康监测](#watchdog-健康监测)
|
- [Watchdog 健康监测](#watchdog-健康监测)
|
||||||
- [macOS 开机自启](#macos-开机自启)
|
- [macOS 开机自启](#macos-开机自启)
|
||||||
- [开发模式](#开发模式)
|
- [开发模式](#开发模式)
|
||||||
|
- [推送代码到 Git 服务器](#推送代码到-git-服务器)
|
||||||
- [自动化测试](#自动化测试)
|
- [自动化测试](#自动化测试)
|
||||||
- [项目结构](#项目结构)
|
- [项目结构](#项目结构)
|
||||||
- [常见问题](#常见问题)
|
- [常见问题](#常见问题)
|
||||||
@@ -63,11 +64,24 @@ ADMIN_PASSWORD=your_secure_password
|
|||||||
|
|
||||||
### 3. 构建与启动
|
### 3. 构建与启动
|
||||||
|
|
||||||
|
推荐一键部署(构建 + 启动 + 健康监测,一步到位):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 一键部署:build + start + watchdog(强制重来)
|
||||||
|
./deploy.sh up
|
||||||
|
```
|
||||||
|
|
||||||
|
`up` 会自动构建前端、(强制)重启后端并**轮询 `/api/health` 直到就绪**才返回,再拉起 watchdog,最后打印状态。适合首次部署和更新代码后重新上线。
|
||||||
|
|
||||||
|
> ⚠️ `up`/`start` 采用「强制重来」语义:若检测到旧服务会先停再起,正在进行的打包任务会被中断。
|
||||||
|
|
||||||
|
也可以分步执行:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 一键构建(安装依赖 + 构建前端)
|
# 一键构建(安装依赖 + 构建前端)
|
||||||
./deploy.sh build
|
./deploy.sh build
|
||||||
|
|
||||||
# 启动服务
|
# 启动服务(等待就绪;端口被非本项目进程占用时会明确报错)
|
||||||
./deploy.sh start
|
./deploy.sh start
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -156,19 +170,93 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
|||||||
|
|
||||||
### Web 管理配置
|
### Web 管理配置
|
||||||
|
|
||||||
以下配置通过管理后台 Web 界面管理(存储在 `config.json`):
|
以下配置通过管理后台 Web 界面管理(存储在 `backend/data/config.json`):
|
||||||
|
|
||||||
首次部署时,如果项目根目录下存在 `config.json`,系统会自动导入其中的 `apps` 和 `schemes` 作为初始配置;导入后即可继续在后台增删改。
|
> ⚠️ `config.json` 是**运行时数据文件**(网页改配置、每次 App_Store 打包写入构建号都会改写它),**不纳入版本控制**,`git pull` 不会覆盖它。仓库仅提供结构模板 `config.example.json`。
|
||||||
|
>
|
||||||
|
> 首次部署时,若项目根目录下存在 `config.json`,系统会自动将其复制为 `backend/data/config.json` 作为初始配置。可从模板起步:
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> cp config.example.json config.json # 按需填入真实的 apps / servers / upload 等,再启动
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> 导入后即可继续在后台增删改。
|
||||||
|
|
||||||
|
> 旧的单项目 `config.json`(顶层直接是 apps / servers …)启动后自动迁移为项目 `readoor`,原文件备份为 `config.json.bak`。
|
||||||
|
|
||||||
| 配置项 | 说明 |
|
| 配置项 | 说明 |
|
||||||
|--------|------|
|
|--------|------|
|
||||||
|
| 项目管理 | 多项目:每个项目独立的 Git 仓库、Xcode 工程、配置替换方式;见下「多项目」 |
|
||||||
| App 管理 | 应用名称、Scheme、服务器环境、upload_key 等 |
|
| App 管理 | 应用名称、Scheme、服务器环境、upload_key 等 |
|
||||||
| Scheme 管理 | 打包 Scheme 配置 |
|
| Scheme 管理 | 打包 Scheme 配置 |
|
||||||
| 服务器环境 | 测试/正式/自定义环境的 API 地址、Universal Link 等 |
|
| 服务器环境 | 测试/正式/自定义环境的 API 地址、Universal Link 等 |
|
||||||
| 分支管理 | 可打包的代码分支列表 |
|
| 分支管理 | 可打包的代码分支和 Tag 列表,以及各自的版本轨道类型(上架 / 自测);Tag 打包时以游离 HEAD 检出 `refs/tags/<tag>` |
|
||||||
| 版本号 | 服务端统一管理 App_Ver 和 Build_Ver,不修改分支源码 |
|
| 版本号 | 服务端统一管理 App_Ver 和 Build_Ver,不修改分支源码;按版本轨道分开管理(见下) |
|
||||||
| 上传配置 | 服务端内置 OSS / WebDAV 分发,生成 IPA、manifest、下载页和二维码 |
|
| 上传配置 | 服务端内置 OSS / WebDAV 分发,生成 IPA、manifest、下载页和二维码 |
|
||||||
|
|
||||||
|
### 多项目
|
||||||
|
|
||||||
|
`config.json` 顶层为 `{"projects": {"<项目 ID>": {...}}, "upload": {...}}`:每个项目的 Apps、Schemes、服务器环境、分支/Tag、版本轨道互相独立,上传配置所有项目共用。页面顶部切换当前项目,前端每个请求带 `X-Project` 请求头(下载链接等用 `?project=`)。
|
||||||
|
|
||||||
|
管理员在「项目管理」维护项目定义:
|
||||||
|
|
||||||
|
| 字段 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `git` | `remote_url` / `username` / `password`(Token);`use_env: true` 时未填项回退到 `.env` 的 `GIT_*`(迁移出的 `readoor` 项目即如此) |
|
||||||
|
| `source_dir` | 共享源码工作目录,留空为 `<服务目录>/sources/<项目 ID>`。打包时会 `git reset --hard` + `git clean`,**不要指向本地开发的工作副本** |
|
||||||
|
| `xcode` | `workspace`(有 CocoaPods 时)或 `project`;无 Podfile 时跳过 `pod install` |
|
||||||
|
| `copy_items` | 拷贝到打包目录的条目,留空拷贝整个仓库 |
|
||||||
|
| `patcher` | `readoor`:原阅门户专用替换逻辑;`generic`:通用替换(pbxproj 中的版本号、Bundle ID、签名)+ `patch_rules` |
|
||||||
|
| `app_fields` / `server_fields` | App / 服务器环境的自定义字段 `[{key, label, required}]`,表单中显示 |
|
||||||
|
| `patch_rules` | `{"type": "define", "file", "name", "value"}` 替换所有未注释的 `#define name` 行;`{"type": "replace_line", "file", "keyword", "line"}` 整行替换。值可用 `${app.字段}`、`${server.字段}`、`${VERSION}` 等 |
|
||||||
|
| `obfuscation` | 是否支持代码混淆 |
|
||||||
|
|
||||||
|
示例(DyAuction:按环境切换 `ISDEV`,`APPID` 按 App 配置):
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"dyauction": {
|
||||||
|
"name": "多云选",
|
||||||
|
"git": { "remote_url": "https://git.example.com/trn/triduoyunxuan", "username": "...", "password": "<Token>" },
|
||||||
|
"xcode": { "project": "DyAuction.xcodeproj" },
|
||||||
|
"patcher": "generic",
|
||||||
|
"obfuscation": false,
|
||||||
|
"app_fields": [{ "key": "APPID", "label": "APPID", "required": true }],
|
||||||
|
"server_fields": [{ "key": "ISDEV", "label": "ISDEV(1=开发环境,0=正式环境)", "required": true }],
|
||||||
|
"patch_rules": [
|
||||||
|
{ "type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "ISDEV", "value": "${server.ISDEV}" },
|
||||||
|
{ "type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "APPID", "value": "@\"${app.APPID}\"" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 版本号与版本轨道
|
||||||
|
|
||||||
|
**每个分支各有一条版本轨道(track)**,App_Ver 与构建号完全独立、互不影响。轨道名即分支名(master / main 沿用历史名称 `release`),轨道类型 `kind` 决定构建号行为:
|
||||||
|
|
||||||
|
| 轨道类型 | 默认适用分支 | 构建号行为 |
|
||||||
|
|----------|--------------|-----------|
|
||||||
|
| `release`(上架) | master、main、develop、dev、release-*、hotfix-* | App_Store 打包时按当前 App_Ver 自动 +1 |
|
||||||
|
| `feature`(自测) | 其余分支 | 永不自增,始终使用配置页填写的值(默认 `.0`) |
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"versions": {
|
||||||
|
"tracks": {
|
||||||
|
"release": { "kind": "release", "app_ver": "2.195.0", "build_map": { "2.195.0": 7 } }, // master
|
||||||
|
"develop": { "kind": "release", "app_ver": "2.196.0", "build_map": {} },
|
||||||
|
"feature/login": { "kind": "feature", "app_ver": "2.100.0", "build_map": {} }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"branch_track": { "master": "release", "develop": "develop", "feature/login": "feature/login" }
|
||||||
|
```
|
||||||
|
|
||||||
|
- 新增分支时自动建一条同名轨道,类型按分支名推断,可在「分支管理」页逐个改(只改构建号是否自增,版本号仍各自独立)。
|
||||||
|
- Tag 存在 `config["tags"]`,与分支不可重名,同样在 `branch_track` 中各有一条同名轨道,新增时默认为上架轨。
|
||||||
|
- 「打包设置」页按分支分块填写版本号。
|
||||||
|
- 每条轨道内的构建号按 App_Ver 独立记录(`build_map`),回退到打过包的旧版本号时会从它自己的最大值继续,不会与 App Store Connect 上已传构建号冲突。
|
||||||
|
- App Store 的构建号唯一性按 App_Ver 全局判定,因此两个上架分支若临时用了同一个 App_Ver,递增时会跨轨道取最大值 +1,避免重号被拒。
|
||||||
|
- 旧配置(master/develop 共用的 `release` 轨、各自测分支共用的 `feature` 轨)首次启动时自动拆开:master 留在 `release` 轨,其余分支新建同名轨道并复制一份已用构建号。
|
||||||
|
- 需要两个分支共用同一条版本线时,可直接把 `branch_track` 里的值指向另一条轨道名。
|
||||||
|
|
||||||
### 服务端自动化资源
|
### 服务端自动化资源
|
||||||
|
|
||||||
项目内的 `backend/automation/` 是 Web 打包服务唯一使用的自动化资源:默认皮肤和混淆工具都在此处维护。分支源码中的 `AutoPacking/` 不会被复制、执行或修改,仍可供开发者手动打包使用。
|
项目内的 `backend/automation/` 是 Web 打包服务唯一使用的自动化资源:默认皮肤和混淆工具都在此处维护。分支源码中的 `AutoPacking/` 不会被复制、执行或修改,仍可供开发者手动打包使用。
|
||||||
@@ -179,6 +267,9 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
|||||||
|------|--------|------|
|
|------|--------|------|
|
||||||
| `WATCHDOG_INTERVAL` | `30` | 健康检查间隔(秒) |
|
| `WATCHDOG_INTERVAL` | `30` | 健康检查间隔(秒) |
|
||||||
| `WATCHDOG_TIMEOUT` | `10` | HTTP 健康检查超时(秒) |
|
| `WATCHDOG_TIMEOUT` | `10` | HTTP 健康检查超时(秒) |
|
||||||
|
| `WATCHDOG_STARTUP_GRACE` | `10` | 首次检查前的宽限(秒),避开服务正常启动窗口,防止误重启 |
|
||||||
|
| `STARTUP_READY_TIMEOUT` | `20` | `start` 后等待 `/api/health` 就绪的最长时间(秒) |
|
||||||
|
| `WATCHDOG_RESTART_MODE` | `nohup` | 重启方式:`nohup`(PID 文件托管)或 `launchd`(用 `launchctl kickstart` 交回 launchd 托管,避免与 KeepAlive 抢端口) |
|
||||||
| `MAX_RESTART_ATTEMPTS` | `3` | 连续重启上限,超过后进入冷却 |
|
| `MAX_RESTART_ATTEMPTS` | `3` | 连续重启上限,超过后进入冷却 |
|
||||||
| `COOLDOWN_SECONDS` | `300` | 冷却时间(秒) |
|
| `COOLDOWN_SECONDS` | `300` | 冷却时间(秒) |
|
||||||
|
|
||||||
@@ -196,8 +287,9 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
|||||||
|
|
||||||
| 命令 | 说明 |
|
| 命令 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
|
| `up` | **一键部署**:build + start + watchdog(强制重来),启动后等待就绪 |
|
||||||
| `build` | 构建前端、创建 Python 虚拟环境、安装所有依赖 |
|
| `build` | 构建前端、创建 Python 虚拟环境、安装所有依赖 |
|
||||||
| `start` | 后台启动服务 |
|
| `start` | 后台启动服务(强制重启并等待 `/api/health` 就绪;端口被非本项目进程占用会报错) |
|
||||||
| `stop` | 停止服务和 watchdog |
|
| `stop` | 停止服务和 watchdog |
|
||||||
| `restart` | 重启服务 |
|
| `restart` | 重启服务 |
|
||||||
| `status` | 查看服务和 watchdog 运行状态 |
|
| `status` | 查看服务和 watchdog 运行状态 |
|
||||||
@@ -209,18 +301,17 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
|||||||
### 常用操作
|
### 常用操作
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 首次部署
|
# 首次部署(一键:build + start + watchdog)
|
||||||
./deploy.sh build && ./deploy.sh start
|
./deploy.sh up
|
||||||
|
|
||||||
# 查看状态
|
# 查看状态
|
||||||
./deploy.sh status
|
./deploy.sh status
|
||||||
|
|
||||||
# 更新代码后重新部署
|
# 更新代码后重新部署
|
||||||
git pull
|
git pull
|
||||||
./deploy.sh build
|
./deploy.sh up
|
||||||
./deploy.sh restart
|
|
||||||
|
|
||||||
# 启用健康监测
|
# 单独启用健康监测
|
||||||
./deploy.sh watchdog
|
./deploy.sh watchdog
|
||||||
|
|
||||||
# 停止所有服务
|
# 停止所有服务
|
||||||
@@ -252,7 +343,7 @@ logs/
|
|||||||
| 角色 | 权限 |
|
| 角色 | 权限 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| 管理员 | 所有功能 + 用户管理(增删改查、角色切换) |
|
| 管理员 | 所有功能 + 用户管理(增删改查、角色切换) |
|
||||||
| 普通用户 | 打包、查看历史、查看配置(不可修改配置、不可管理用户) |
|
| 普通用户 | 打包、查看历史、管理 Apps 配置(不可修改版本号及其余配置、不可管理用户) |
|
||||||
|
|
||||||
### 管理用户
|
### 管理用户
|
||||||
|
|
||||||
@@ -370,6 +461,31 @@ launchctl load ~/Library/LaunchAgents/com.readoor.buildserver.watchdog.plist
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 推送代码到 Git 服务器
|
||||||
|
|
||||||
|
本项目托管在自建 Git 服务(`origin` 走 HTTPS),推送需要账号凭据:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 提交改动
|
||||||
|
git add -A
|
||||||
|
git commit -m "feat: 描述你的改动"
|
||||||
|
|
||||||
|
# 推送到远程 main
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
首次推送会提示输入用户名和密码/访问令牌。若不想每次都输入,可启用 macOS 钥匙串缓存凭据(只需配置一次):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config --global credential.helper osxkeychain
|
||||||
|
```
|
||||||
|
|
||||||
|
配置后,下一次 `git push` 输入的账号密码会被安全保存到钥匙串,后续免输入。
|
||||||
|
|
||||||
|
> 若 Git 服务使用**访问令牌**认证:用户名填账号、密码填令牌即可。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 自动化测试
|
## 自动化测试
|
||||||
|
|
||||||
### 运行测试
|
### 运行测试
|
||||||
|
|||||||
+18
-14
@@ -57,27 +57,29 @@ GIT_USERNAME = os.getenv("GIT_USERNAME", "")
|
|||||||
GIT_PASSWORD = os.getenv("GIT_PASSWORD", "")
|
GIT_PASSWORD = os.getenv("GIT_PASSWORD", "")
|
||||||
|
|
||||||
|
|
||||||
def get_git_remote_url(with_credentials: bool = False) -> str:
|
def inject_git_credentials(url: str, username: str, password: str = "") -> str:
|
||||||
"""获取 Git 远程地址,可选注入用户名密码"""
|
"""向 http(s) 形式的 Git 地址注入用户名密码;已带凭证或非 URL 形式时原样返回"""
|
||||||
if not with_credentials or not GIT_REMOTE_URL or not GIT_USERNAME:
|
if not url or not username or "://" not in url:
|
||||||
return GIT_REMOTE_URL
|
return url
|
||||||
if "://" not in GIT_REMOTE_URL:
|
|
||||||
return GIT_REMOTE_URL
|
|
||||||
|
|
||||||
parts = urlsplit(GIT_REMOTE_URL)
|
parts = urlsplit(url)
|
||||||
if "@" in parts.netloc:
|
if "@" in parts.netloc:
|
||||||
return GIT_REMOTE_URL
|
return url
|
||||||
|
|
||||||
username = quote(GIT_USERNAME, safe="")
|
auth = quote(username, safe="")
|
||||||
if GIT_PASSWORD:
|
if password:
|
||||||
password = quote(GIT_PASSWORD, safe="")
|
auth = f"{auth}:{quote(password, safe='')}"
|
||||||
auth = f"{username}:{password}"
|
|
||||||
else:
|
|
||||||
auth = username
|
|
||||||
netloc = f"{auth}@{parts.netloc}"
|
netloc = f"{auth}@{parts.netloc}"
|
||||||
return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment))
|
return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment))
|
||||||
|
|
||||||
|
|
||||||
|
def get_git_remote_url(with_credentials: bool = False) -> str:
|
||||||
|
"""获取 .env 中的 Git 远程地址,可选注入用户名密码"""
|
||||||
|
if not with_credentials:
|
||||||
|
return GIT_REMOTE_URL
|
||||||
|
return inject_git_credentials(GIT_REMOTE_URL, GIT_USERNAME, GIT_PASSWORD)
|
||||||
|
|
||||||
|
|
||||||
def mask_git_remote_url(url: str) -> str:
|
def mask_git_remote_url(url: str) -> str:
|
||||||
"""对 Git 远程地址中的凭证做脱敏"""
|
"""对 Git 远程地址中的凭证做脱敏"""
|
||||||
if not url or "://" not in url:
|
if not url or "://" not in url:
|
||||||
@@ -146,6 +148,8 @@ ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123")
|
|||||||
JWT_SECRET = os.getenv("JWT_SECRET", "ios-build-server-secret-key-change-in-production")
|
JWT_SECRET = os.getenv("JWT_SECRET", "ios-build-server-secret-key-change-in-production")
|
||||||
JWT_ALGORITHM = "HS256"
|
JWT_ALGORITHM = "HS256"
|
||||||
JWT_EXPIRE_HOURS = 24
|
JWT_EXPIRE_HOURS = 24
|
||||||
|
# 受控 IPA 下载链接的 OSS 签名有效期(秒)。
|
||||||
|
DOWNLOAD_URL_EXPIRE_SECONDS = int(os.getenv("DOWNLOAD_URL_EXPIRE_SECONDS", "600"))
|
||||||
|
|
||||||
|
|
||||||
def validate_production_security() -> None:
|
def validate_production_security() -> None:
|
||||||
|
|||||||
@@ -1,455 +0,0 @@
|
|||||||
{
|
|
||||||
"apps": {
|
|
||||||
"100": {
|
|
||||||
"name": "阅门户测试App",
|
|
||||||
"server": "测试环境",
|
|
||||||
"AppGuid": "647372741900537856",
|
|
||||||
"API": "https://api3-dev.readoor.cn",
|
|
||||||
"AssDom": "applinks:dev-data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://dev-data1.readoor.cn",
|
|
||||||
"weixinlogin": "wx30847bd529fe856c",
|
|
||||||
"weixinpay": "wx30847bd529fe856c",
|
|
||||||
"tencent": "tencent1105839866",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.touchv.a4YX061",
|
|
||||||
"pro": "a4YX061_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "0e6b269a",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"101": {
|
|
||||||
"name": "申学",
|
|
||||||
"server": "测试环境",
|
|
||||||
"AppGuid": "571681541265068032",
|
|
||||||
"API": "https://api3-dev.readoor.cn",
|
|
||||||
"AssDom": "applinks:dev-data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://dev-data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx30847bd529fe856c",
|
|
||||||
"weixinpay": "wx30847bd529fe856c",
|
|
||||||
"tencent": "tencent1105839866",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.kingsunsoft.CollectionBooks.Xinhua",
|
|
||||||
"pro": "TouchLinked_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "c843d672",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"102": {
|
|
||||||
"name": "英汉大词典测试",
|
|
||||||
"server": "测试环境",
|
|
||||||
"AppGuid": "1593413622",
|
|
||||||
"API": "https://api3-dev.readoor.cn",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.yiwen.ecdstandalone",
|
|
||||||
"pro": "TouchLinked_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "weread"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "9b470281",
|
|
||||||
"skins": [
|
|
||||||
"weread.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"103": {
|
|
||||||
"name": "英汉大词典",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "1607584582",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.yiwen.ecdstandalone",
|
|
||||||
"pro": "ecdstandalone_Adhoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai Translation Publishing House (8S29652W62)",
|
|
||||||
"theme": ""
|
|
||||||
},
|
|
||||||
"App_Store": {
|
|
||||||
"name": "com.yiwen.ecdstandalone",
|
|
||||||
"pro": "ecdstandalone_provisioning_profiles",
|
|
||||||
"cer": "iPhone Distribution: Shanghai Translation Publishing House (8S29652W62)",
|
|
||||||
"theme": ""
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "2e743ca9"
|
|
||||||
},
|
|
||||||
"201": {
|
|
||||||
"name": "3.1版测试",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "447445078487633920",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "",
|
|
||||||
"weixinpay": "",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc1": {
|
|
||||||
"name": "cn.touchv.a0yny24",
|
|
||||||
"pro": "a0yny24_adhoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
},
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.touchv.a4YX061",
|
|
||||||
"pro": "a4YX061_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "2522c9bb",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"202": {
|
|
||||||
"name": "北教辅学",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "416182063440367616",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx1416817fa79df772",
|
|
||||||
"weixinpay": "wx1416817fa79df772",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"App_Store": {
|
|
||||||
"name": "cn.touchv.adsATM4",
|
|
||||||
"pro": "beijiaofuxue",
|
|
||||||
"cer": "iPhone Distribution: Jingban Beijing Education Culture Media Corporation Limited (343SD396U6)",
|
|
||||||
"theme": "bj"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "ca03a41b",
|
|
||||||
"skins": [
|
|
||||||
"bj.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"203": {
|
|
||||||
"name": "智慧云学",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "576814720200249344",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "",
|
|
||||||
"weixinpay": "",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.touchv.a4YX061",
|
|
||||||
"pro": "a4YX061_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "689c69a2",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"204": {
|
|
||||||
"name": "北洋学堂",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "559336679295455232",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx1df85bf317e35171",
|
|
||||||
"weixinpay": "wx1df85bf317e35171",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"App_Store": {
|
|
||||||
"name": "cn.tjdxcbs.aBEM0B3",
|
|
||||||
"pro": "beiyangxuetang",
|
|
||||||
"cer": "iPhone Distribution: Tianjin University Press Co., Ltd.. (D3NDDP8CZU)",
|
|
||||||
"theme": "byxt"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "27fb0395",
|
|
||||||
"skins": [
|
|
||||||
"byxt.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"205": {
|
|
||||||
"name": "交我学",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "119822865246760960",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "",
|
|
||||||
"weixinpay": "",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.touchv.a4YX061",
|
|
||||||
"pro": "a4YX061_adHoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "0718cd13",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"206": {
|
|
||||||
"name": "上财云津",
|
|
||||||
"server": "正式环境",
|
|
||||||
"AppGuid": "389000208056356864",
|
|
||||||
"API": "https://api3.readoor.cn",
|
|
||||||
"AssDom": "applinks:data1.readoor.cn",
|
|
||||||
"UniversalLink": "https://data1.readoor.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx6f1163efcb202265",
|
|
||||||
"weixinpay": "wx6f1163efcb202265",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.shcj.aGh0UB2",
|
|
||||||
"pro": "aGh0UB2_adhoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai University of Finance and Economics Press Co., Ltd. (8S29L934WG)",
|
|
||||||
"theme": "shangcai"
|
|
||||||
},
|
|
||||||
"App_Store": {
|
|
||||||
"name": "cn.shcj.aGh0UB2",
|
|
||||||
"pro": "aGh0UB2_dis",
|
|
||||||
"cer": "iPhone Distribution: Shanghai University of Finance and Economics Press Co., Ltd. (8S29L934WG)",
|
|
||||||
"theme": "shangcai"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "8e326070",
|
|
||||||
"skins": [
|
|
||||||
"shangcai.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"301": {
|
|
||||||
"name": "教育汇",
|
|
||||||
"server": "华师大环境",
|
|
||||||
"AppGuid": "152115765687226368",
|
|
||||||
"API": "https://api3.ecnupress.com.cn",
|
|
||||||
"AssDom": "applinks:data1.ecnupress.com.cn",
|
|
||||||
"UniversalLink": "https://data1.ecnupress.com.cn",
|
|
||||||
"AlivcLicenseKey": "jPtBO1QJzkkHLu3F896a0569e78de46979050fb2605a6a2a5",
|
|
||||||
"weixinlogin": "wx9e23021f7f4313c0",
|
|
||||||
"weixinpay": "wx9e23021f7f4313c0",
|
|
||||||
"tencent": "tencent1105919518",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.ecnup.aSCLdl2",
|
|
||||||
"pro": "aSCLdl2_adhoc",
|
|
||||||
"cer": "iPhone Distribution: East China Normal University Press Ltd (Q659D4XU6T)",
|
|
||||||
"theme": "hsd"
|
|
||||||
},
|
|
||||||
"App_Store": {
|
|
||||||
"name": "com.ecnup.aSCLdl2",
|
|
||||||
"pro": "com-ecnup-aSCLdl2_Distribution",
|
|
||||||
"cer": "iPhone Distribution: East China Normal University Press Ltd (Q659D4XU6T)",
|
|
||||||
"theme": "hsd"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "f6fe827d",
|
|
||||||
"skins": [
|
|
||||||
"hsd.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"302": {
|
|
||||||
"name": "教育汇测试",
|
|
||||||
"server": "华师大环境",
|
|
||||||
"AppGuid": "335068450529882112",
|
|
||||||
"API": "https://api3.ecnupress.com.cn",
|
|
||||||
"AssDom": "applinks:data1.ecnupress.com.cn",
|
|
||||||
"UniversalLink": "https://data1.ecnupress.com.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx9e23021f7f4313c0",
|
|
||||||
"weixinpay": "wx9e23021f7f4313c0",
|
|
||||||
"tencent": "tencent1105919518",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.ecnup.a4PBPk",
|
|
||||||
"pro": "a4PBPk_adhoc",
|
|
||||||
"cer": "iPhone Distribution: East China Normal University Press Ltd (Q659D4XU6T)",
|
|
||||||
"theme": "hsd"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "4f9c7953",
|
|
||||||
"skins": [
|
|
||||||
"hsd.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"303": {
|
|
||||||
"name": "大夏书系",
|
|
||||||
"server": "华师大环境",
|
|
||||||
"AppGuid": "639419713965142016",
|
|
||||||
"API": "https://api3.ecnupress.com.cn",
|
|
||||||
"AssDom": "applinks:data1.ecnupress.com.cn",
|
|
||||||
"UniversalLink": "https://data1.ecnupress.com.cn",
|
|
||||||
"AlivcLicenseKey": "jPtBO1QJzkkHLu3F896a0569e78de46979050fb2605a6a2a5",
|
|
||||||
"weixinlogin": "wx1d95492fee2ce298",
|
|
||||||
"weixinpay": "wx1d95492fee2ce298",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "com.ecnup.aaS16d3",
|
|
||||||
"pro": "aaS16d3_adhoc",
|
|
||||||
"cer": "iPhone Distribution: East China Normal University Press Ltd (Q659D4XU6T)",
|
|
||||||
"theme": "dxsx"
|
|
||||||
},
|
|
||||||
"App_Store": {
|
|
||||||
"name": "com.ecnup.aaS16d3",
|
|
||||||
"pro": "aaS16d3_dis",
|
|
||||||
"cer": "iPhone Distribution: East China Normal University Press Ltd (Q659D4XU6T)",
|
|
||||||
"theme": "dxsx"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "a29091d9",
|
|
||||||
"skins": [
|
|
||||||
"dxsx.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"304": {
|
|
||||||
"name": "HSD测试App",
|
|
||||||
"server": "华师大环境",
|
|
||||||
"AppGuid": "470235916070694912",
|
|
||||||
"API": "https://api3.ecnupress.com.cn",
|
|
||||||
"AssDom": "applinks:data1.ecnupress.com.cn",
|
|
||||||
"UniversalLink": "https://data1.ecnupress.com.cn",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx9e23021f7f4313c0",
|
|
||||||
"weixinpay": "wx9e23021f7f4313c0",
|
|
||||||
"tencent": "tencent1105919518",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.touchv.aO3pOM",
|
|
||||||
"pro": "aO3pOM_adhoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai TouchLinked Info & Tech Co.,Ltd. (MG4Z7FU83W)",
|
|
||||||
"theme": "ymh"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "86bfb114",
|
|
||||||
"skins": [
|
|
||||||
"ymh.zip"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"401": {
|
|
||||||
"name": "WE Read",
|
|
||||||
"server": "外教环境",
|
|
||||||
"AppGuid": "631907986336071680",
|
|
||||||
"API": "https://weread-api3.sflep.com/api3",
|
|
||||||
"AssDom": "applinks:wereadossda.sflep.com",
|
|
||||||
"UniversalLink": "https://wereadossda.sflep.com",
|
|
||||||
"AlivcLicenseKey": "",
|
|
||||||
"weixinlogin": "wx6d6c63f4df7e5720",
|
|
||||||
"weixinpay": "",
|
|
||||||
"tencent": "",
|
|
||||||
"certificates": {
|
|
||||||
"Ad_Hoc": {
|
|
||||||
"name": "cn.sflep.aSiLjn",
|
|
||||||
"pro": "cn_sflep_aSiLjn_adhoc",
|
|
||||||
"cer": "iPhone Distribution: Shanghai Foreign Language Education Press Co.,Ltd. (G4X56AY2VB)",
|
|
||||||
"theme": "weread"
|
|
||||||
},
|
|
||||||
"App_Store": {
|
|
||||||
"name": "cn.sflep.aSiLjn",
|
|
||||||
"pro": "cn-sflep-aSiLjn",
|
|
||||||
"cer": "iPhone Distribution: Shanghai Foreign Language Education Press Co.,Ltd. (G4X56AY2VB)",
|
|
||||||
"theme": "weread"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"upload_key": "87e7656f",
|
|
||||||
"skins": [
|
|
||||||
"weread.zip"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"schemes": {
|
|
||||||
"1": {
|
|
||||||
"name": "readoor31",
|
|
||||||
"ossFloder": "readoor"
|
|
||||||
},
|
|
||||||
"2": {
|
|
||||||
"name": "readoor31OtherPay",
|
|
||||||
"ossFloder": "readoor"
|
|
||||||
},
|
|
||||||
"3": {
|
|
||||||
"name": "readoorShenXue",
|
|
||||||
"ossFloder": "readoor"
|
|
||||||
},
|
|
||||||
"4": {
|
|
||||||
"name": "readoorDict",
|
|
||||||
"ossFloder": "ecdict"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"servers": {
|
|
||||||
"测试环境": {
|
|
||||||
"api": "https://api3-dev.readoor.cn",
|
|
||||||
"assDom": "applinks:dev-data1.readoor.cn",
|
|
||||||
"universalLink": "https://dev-data1.readoor.cn"
|
|
||||||
},
|
|
||||||
"正式环境": {
|
|
||||||
"api": "https://api3.readoor.cn",
|
|
||||||
"assDom": "applinks:data1.readoor.cn",
|
|
||||||
"universalLink": "https://data1.readoor.cn"
|
|
||||||
},
|
|
||||||
"华师大环境": {
|
|
||||||
"api": "https://api3.ecnupress.com.cn",
|
|
||||||
"assDom": "applinks:data1.ecnupress.com.cn",
|
|
||||||
"universalLink": "https://data1.ecnupress.com.cn"
|
|
||||||
},
|
|
||||||
"外教环境": {
|
|
||||||
"api": "https://weread-api3.sflep.com/api3",
|
|
||||||
"assDom": "applinks:wereadossda.sflep.com",
|
|
||||||
"universalLink": "https://wereadossda.sflep.com"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"branches": [
|
|
||||||
"master",
|
|
||||||
"develop",
|
|
||||||
"feature"
|
|
||||||
],
|
|
||||||
"upload": {
|
|
||||||
"mode": "webdav",
|
|
||||||
"oss": {
|
|
||||||
"access_key_id": "",
|
|
||||||
"access_key_secret": "",
|
|
||||||
"endpoint": "oss-cn-beijing.aliyuncs.com",
|
|
||||||
"bucket_name": "",
|
|
||||||
"base_url": ""
|
|
||||||
},
|
|
||||||
"webdav": {
|
|
||||||
"server_url": "http://192.168.21.200:5005",
|
|
||||||
"username": "slcydia",
|
|
||||||
"password": "S9rr9359p:4o)nfel?W",
|
|
||||||
"base_path": "/APPBuildInfo",
|
|
||||||
"public_url": "http://192.168.21.200:5005/APPBuildInfo"
|
|
||||||
},
|
|
||||||
"dingtalk": {
|
|
||||||
"enabled": false,
|
|
||||||
"webhook_url": "",
|
|
||||||
"secret": ""
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"versions": {
|
|
||||||
"app_ver": "2.195.0",
|
|
||||||
"build_ver": "2.195.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,7 +23,11 @@ def _migrate_db():
|
|||||||
"""简单的数据库迁移:为旧表添加缺失的列"""
|
"""简单的数据库迁移:为旧表添加缺失的列"""
|
||||||
migrations = [
|
migrations = [
|
||||||
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
||||||
|
("tasks", "ref_type", "VARCHAR DEFAULT 'branch'"),
|
||||||
("tasks", "error_category", "VARCHAR"),
|
("tasks", "error_category", "VARCHAR"),
|
||||||
|
("tasks", "superseded_at", "TIMESTAMP"),
|
||||||
|
("tasks", "dsym_url", "VARCHAR"),
|
||||||
|
("tasks", "project_id", "VARCHAR DEFAULT 'readoor'"),
|
||||||
]
|
]
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
for table, column, col_type in migrations:
|
for table, column, col_type in migrations:
|
||||||
|
|||||||
+16
-2
@@ -8,10 +8,11 @@ from fastapi.staticfiles import StaticFiles
|
|||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
from .database import init_db
|
from .database import init_db
|
||||||
from .routers import config, apps, tasks, auth, users
|
from .routers import config, apps, tasks, auth, users, operations
|
||||||
from .services.log_streamer import log_streamer
|
from .services.log_streamer import log_streamer
|
||||||
from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security
|
from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security
|
||||||
from .deps import decode_current_user
|
from .deps import decode_current_user
|
||||||
|
from .projects import PROJECT_HEADER, current_project_id
|
||||||
|
|
||||||
STATIC_DIR = Path(__file__).parent / "static"
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
|
||||||
@@ -37,17 +38,30 @@ if CORS_ALLOWED_ORIGINS:
|
|||||||
allow_origins=CORS_ALLOWED_ORIGINS,
|
allow_origins=CORS_ALLOWED_ORIGINS,
|
||||||
allow_credentials=False,
|
allow_credentials=False,
|
||||||
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
||||||
allow_headers=["Authorization", "Content-Type"],
|
allow_headers=["Authorization", "Content-Type", PROJECT_HEADER],
|
||||||
)
|
)
|
||||||
|
|
||||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=TRUSTED_HOSTS)
|
app.add_middleware(TrustedHostMiddleware, allowed_hosts=TRUSTED_HOSTS)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def bind_project(request: Request, call_next):
|
||||||
|
"""按请求头 X-Project(下载链接等无法带请求头时用 ?project=)确定本次请求操作的项目。"""
|
||||||
|
project_id = request.headers.get(PROJECT_HEADER) or request.query_params.get("project") or None
|
||||||
|
token = current_project_id.set(project_id)
|
||||||
|
try:
|
||||||
|
return await call_next(request)
|
||||||
|
finally:
|
||||||
|
current_project_id.reset(token)
|
||||||
|
|
||||||
|
|
||||||
# 路由
|
# 路由
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(users.router)
|
app.include_router(users.router)
|
||||||
app.include_router(config.router)
|
app.include_router(config.router)
|
||||||
app.include_router(apps.router)
|
app.include_router(apps.router)
|
||||||
app.include_router(tasks.router)
|
app.include_router(tasks.router)
|
||||||
|
app.include_router(operations.router)
|
||||||
|
|
||||||
|
|
||||||
@app.websocket("/ws/tasks/{task_id}")
|
@app.websocket("/ws/tasks/{task_id}")
|
||||||
|
|||||||
+25
-1
@@ -9,13 +9,15 @@ class Task(Base):
|
|||||||
__tablename__ = "tasks"
|
__tablename__ = "tasks"
|
||||||
|
|
||||||
id = Column(String, primary_key=True)
|
id = Column(String, primary_key=True)
|
||||||
|
project_id = Column(String, default="readoor") # 所属项目,见 projects.py
|
||||||
app_id = Column(String, nullable=False)
|
app_id = Column(String, nullable=False)
|
||||||
app_name = Column(String, nullable=False)
|
app_name = Column(String, nullable=False)
|
||||||
build_type = Column(String, nullable=False)
|
build_type = Column(String, nullable=False)
|
||||||
scheme_id = Column(String, nullable=False)
|
scheme_id = Column(String, nullable=False)
|
||||||
scheme_name = Column(String, nullable=False)
|
scheme_name = Column(String, nullable=False)
|
||||||
obfuscation = Column(Boolean, default=False)
|
obfuscation = Column(Boolean, default=False)
|
||||||
branch = Column(String, default="main")
|
branch = Column(String, default="main") # 分支名或 Tag 名,由 ref_type 区分
|
||||||
|
ref_type = Column(String, default="branch") # branch/tag
|
||||||
|
|
||||||
# 状态
|
# 状态
|
||||||
status = Column(String, default="pending") # pending/running/completed/failed/cancelled
|
status = Column(String, default="pending") # pending/running/completed/failed/cancelled
|
||||||
@@ -25,11 +27,14 @@ class Task(Base):
|
|||||||
created_at = Column(TIMESTAMP, default=datetime.utcnow)
|
created_at = Column(TIMESTAMP, default=datetime.utcnow)
|
||||||
started_at = Column(TIMESTAMP)
|
started_at = Column(TIMESTAMP)
|
||||||
completed_at = Column(TIMESTAMP)
|
completed_at = Column(TIMESTAMP)
|
||||||
|
# 同一 OSS 对象被后续成功打包覆盖时标记;默认历史列表不展示。
|
||||||
|
superseded_at = Column(TIMESTAMP)
|
||||||
|
|
||||||
# 产物
|
# 产物
|
||||||
ipa_path = Column(String)
|
ipa_path = Column(String)
|
||||||
oss_url = Column(String)
|
oss_url = Column(String)
|
||||||
dsym_path = Column(String)
|
dsym_path = Column(String)
|
||||||
|
dsym_url = Column(String)
|
||||||
obfuscation_maps_path = Column(String)
|
obfuscation_maps_path = Column(String)
|
||||||
qr_code_path = Column(String)
|
qr_code_path = Column(String)
|
||||||
build_dir = Column(String)
|
build_dir = Column(String)
|
||||||
@@ -60,3 +65,22 @@ class User(Base):
|
|||||||
password_hash = Column(String, nullable=False)
|
password_hash = Column(String, nullable=False)
|
||||||
is_admin = Column(Boolean, default=False)
|
is_admin = Column(Boolean, default=False)
|
||||||
created_at = Column(TIMESTAMP, default=datetime.utcnow)
|
created_at = Column(TIMESTAMP, default=datetime.utcnow)
|
||||||
|
|
||||||
|
|
||||||
|
class OperationLog(Base):
|
||||||
|
"""用户关键操作的审计与统计记录。"""
|
||||||
|
__tablename__ = "operation_logs"
|
||||||
|
|
||||||
|
id = Column(String, primary_key=True)
|
||||||
|
created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
|
||||||
|
username = Column(String, nullable=False)
|
||||||
|
is_admin = Column(Boolean, default=False, nullable=False)
|
||||||
|
action = Column(String, nullable=False)
|
||||||
|
task_id = Column(String)
|
||||||
|
app_id = Column(String)
|
||||||
|
app_name = Column(String)
|
||||||
|
resource_type = Column(String)
|
||||||
|
resource_name = Column(String)
|
||||||
|
detail_json = Column(Text)
|
||||||
|
client_ip = Column(String)
|
||||||
|
user_agent = Column(String)
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""多项目定义:每个项目的源码仓库、Xcode 工程、配置替换方式等。
|
||||||
|
|
||||||
|
config.json 结构:
|
||||||
|
{
|
||||||
|
"projects": {
|
||||||
|
"<项目 ID>": {
|
||||||
|
# —— 项目定义(管理员在「项目管理」维护)——
|
||||||
|
"name": "显示名称",
|
||||||
|
"git": {"remote_url": "", "username": "", "password": "", "use_env": false},
|
||||||
|
"source_dir": "", # 共享源码工作目录,留空为 <服务目录>/sources/<项目 ID>
|
||||||
|
"xcode": {"workspace": "", "project": "X.xcodeproj"},
|
||||||
|
"copy_items": [], # 拷贝到打包目录的条目,留空拷贝整个仓库
|
||||||
|
"patcher": "generic", # readoor(阅门户专用)/ generic(通用 + patch_rules)
|
||||||
|
"patch_rules": [], # generic 的额外替换规则,见 project_patcher
|
||||||
|
"app_fields": [], # App 的项目自定义字段 [{key, label, required}]
|
||||||
|
"server_fields": [], # 服务器环境的项目自定义字段
|
||||||
|
"obfuscation": false, # 是否支持代码混淆
|
||||||
|
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||||
|
# 本项目钉钉 @ 名单,为空则用 upload.dingtalk 的全局名单
|
||||||
|
# —— 项目数据(与原单项目时的顶层字段相同)——
|
||||||
|
"apps": {}, "schemes": {}, "servers": {}, "branches": [], "tags": [],
|
||||||
|
"versions": {}, "branch_track": {}, "next_app_id_prefix": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"upload": {...} # 上传与钉钉通知,所有项目共用
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .config import (
|
||||||
|
COPY_ITEMS,
|
||||||
|
GIT_PASSWORD,
|
||||||
|
GIT_REMOTE_URL,
|
||||||
|
GIT_SOURCE_BASE,
|
||||||
|
GIT_SOURCE_DIR,
|
||||||
|
GIT_USERNAME,
|
||||||
|
SERVER_ROOT,
|
||||||
|
inject_git_credentials,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 升级前的单项目配置迁移为这个项目,并沿用 .env 中的 Git 配置。
|
||||||
|
LEGACY_PROJECT_ID = "readoor"
|
||||||
|
|
||||||
|
PATCHER_READOOR = "readoor"
|
||||||
|
PATCHER_GENERIC = "generic"
|
||||||
|
PATCHERS = (PATCHER_READOOR, PATCHER_GENERIC)
|
||||||
|
|
||||||
|
# 项目定义字段;其余字段(apps、schemes、versions 等)都是项目数据。
|
||||||
|
DEFINITION_KEYS = (
|
||||||
|
"name", "git", "source_dir", "xcode", "copy_items", "patcher",
|
||||||
|
"patch_rules", "app_fields", "server_fields", "obfuscation", "dingtalk_at",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 原单项目(阅门户)的定义,迁移旧配置时写入。
|
||||||
|
LEGACY_PROJECT_DEFINITION = {
|
||||||
|
"name": "Readoor",
|
||||||
|
"git": {"remote_url": "", "username": "", "password": "", "use_env": True},
|
||||||
|
"source_dir": "",
|
||||||
|
"xcode": {"workspace": "readoor.xcworkspace", "project": "readoor.xcodeproj"},
|
||||||
|
"copy_items": list(COPY_ITEMS),
|
||||||
|
"patcher": PATCHER_READOOR,
|
||||||
|
"patch_rules": [],
|
||||||
|
"app_fields": [],
|
||||||
|
"server_fields": [],
|
||||||
|
"obfuscation": True,
|
||||||
|
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 当前请求操作的项目,由 main.py 的中间件按请求头 X-Project 设置;
|
||||||
|
# load_config() 未显式指定项目时使用它,未设置则取第一个项目。
|
||||||
|
PROJECT_HEADER = "X-Project"
|
||||||
|
current_project_id: ContextVar = ContextVar("current_project_id", default=None)
|
||||||
|
|
||||||
|
_PROJECT_ID_PATTERN = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_project_id(project_id: str) -> bool:
|
||||||
|
"""项目 ID 会用于目录名和请求头,只允许小写字母开头的短标识。"""
|
||||||
|
return bool(_PROJECT_ID_PATTERN.fullmatch(project_id or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def default_definition(project_id: str) -> dict:
|
||||||
|
"""项目定义缺省值:旧项目沿用原有行为,新项目为通用配置。"""
|
||||||
|
if project_id == LEGACY_PROJECT_ID:
|
||||||
|
return LEGACY_PROJECT_DEFINITION
|
||||||
|
return {
|
||||||
|
"name": project_id,
|
||||||
|
"git": {"remote_url": "", "username": "", "password": "", "use_env": False},
|
||||||
|
"source_dir": "",
|
||||||
|
"xcode": {"workspace": "", "project": ""},
|
||||||
|
"copy_items": [],
|
||||||
|
"patcher": PATCHER_GENERIC,
|
||||||
|
"patch_rules": [],
|
||||||
|
"app_fields": [],
|
||||||
|
"server_fields": [],
|
||||||
|
"obfuscation": False,
|
||||||
|
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_definition(project_id: str, project: dict) -> dict:
|
||||||
|
"""取项目定义,缺失字段用缺省值补齐(只读,不写回配置)。"""
|
||||||
|
defaults = default_definition(project_id)
|
||||||
|
definition = {key: project.get(key, defaults[key]) for key in DEFINITION_KEYS}
|
||||||
|
definition["git"] = {**defaults["git"], **(definition.get("git") or {})}
|
||||||
|
definition["xcode"] = {**defaults["xcode"], **(definition.get("xcode") or {})}
|
||||||
|
definition["dingtalk_at"] = {**defaults["dingtalk_at"], **(definition.get("dingtalk_at") or {})}
|
||||||
|
if definition["patcher"] not in PATCHERS:
|
||||||
|
definition["patcher"] = PATCHER_GENERIC
|
||||||
|
return definition
|
||||||
|
|
||||||
|
|
||||||
|
def public_definition(project_id: str, project: dict) -> dict:
|
||||||
|
"""打包页和配置页渲染所需的项目信息,不含 Git 凭据。"""
|
||||||
|
definition = get_definition(project_id, project)
|
||||||
|
return {
|
||||||
|
"id": project_id,
|
||||||
|
"name": definition["name"],
|
||||||
|
"patcher": definition["patcher"],
|
||||||
|
"obfuscation": bool(definition["obfuscation"]),
|
||||||
|
"app_fields": definition["app_fields"],
|
||||||
|
"server_fields": definition["server_fields"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectSource:
|
||||||
|
"""项目源码的获取方式。"""
|
||||||
|
|
||||||
|
def __init__(self, remote_url: str, remote_url_with_credentials: str,
|
||||||
|
shared_dir: Path, manual_base: Path = None):
|
||||||
|
self.remote_url = remote_url
|
||||||
|
self.remote_url_with_credentials = remote_url_with_credentials
|
||||||
|
# 配置远程仓库时,所有分支共用的源码工作目录
|
||||||
|
self.shared_dir = shared_dir
|
||||||
|
# 未配置远程仓库时,按 <manual_base>/<branch> 读取人工维护的分支目录(仅旧项目支持)
|
||||||
|
self.manual_base = manual_base
|
||||||
|
|
||||||
|
|
||||||
|
def get_project_source(project_id: str, project: dict) -> ProjectSource:
|
||||||
|
definition = get_definition(project_id, project)
|
||||||
|
git = definition["git"]
|
||||||
|
use_env = bool(git.get("use_env"))
|
||||||
|
|
||||||
|
remote_url = (git.get("remote_url") or "").strip() or (GIT_REMOTE_URL if use_env else "")
|
||||||
|
username = git.get("username") or (GIT_USERNAME if use_env else "")
|
||||||
|
password = git.get("password") or (GIT_PASSWORD if use_env else "")
|
||||||
|
|
||||||
|
source_dir = (definition.get("source_dir") or "").strip()
|
||||||
|
if source_dir:
|
||||||
|
shared_dir = Path(source_dir).expanduser()
|
||||||
|
if not shared_dir.is_absolute():
|
||||||
|
shared_dir = SERVER_ROOT / shared_dir
|
||||||
|
elif use_env:
|
||||||
|
shared_dir = GIT_SOURCE_DIR
|
||||||
|
else:
|
||||||
|
shared_dir = SERVER_ROOT / "sources" / project_id
|
||||||
|
|
||||||
|
return ProjectSource(
|
||||||
|
remote_url=remote_url,
|
||||||
|
remote_url_with_credentials=inject_git_credentials(remote_url, username, password),
|
||||||
|
shared_dir=shared_dir,
|
||||||
|
manual_base=GIT_SOURCE_BASE if use_env else None,
|
||||||
|
)
|
||||||
+24
-5
@@ -1,7 +1,9 @@
|
|||||||
"""打包选择 API"""
|
"""打包选择 API"""
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
from .config import load_config
|
from ..deps import get_current_user
|
||||||
|
from ..projects import PATCHER_READOOR, get_definition, public_definition
|
||||||
|
from .config import get_tags, load_config, load_projects
|
||||||
|
|
||||||
router = APIRouter(prefix="/api", tags=["apps"])
|
router = APIRouter(prefix="/api", tags=["apps"])
|
||||||
|
|
||||||
@@ -15,11 +17,22 @@ _APP_SCHEME_RULES = {
|
|||||||
_DEFAULT_SCHEME_NAMES = ("readoor31", "readoor31OtherPay")
|
_DEFAULT_SCHEME_NAMES = ("readoor31", "readoor31OtherPay")
|
||||||
|
|
||||||
|
|
||||||
def get_allowed_scheme_names(app: dict) -> tuple[str, ...]:
|
def get_allowed_scheme_names(app: dict, config: dict) -> tuple[str, ...]:
|
||||||
"""返回 App 可使用的 Scheme 名称。"""
|
"""返回 App 可使用的 Scheme 名称;空元组表示不限制。
|
||||||
|
|
||||||
|
按 App 名称限定 Scheme 是 Readoor 项目的规则,其它项目不限制。
|
||||||
|
"""
|
||||||
|
if get_definition(config["_project"], config)["patcher"] != PATCHER_READOOR:
|
||||||
|
return ()
|
||||||
return _APP_SCHEME_RULES.get(app.get("name", ""), _DEFAULT_SCHEME_NAMES)
|
return _APP_SCHEME_RULES.get(app.get("name", ""), _DEFAULT_SCHEME_NAMES)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/projects", dependencies=[Depends(get_current_user)])
|
||||||
|
async def get_projects():
|
||||||
|
"""获取项目列表(供切换项目,不含 Git 凭据)"""
|
||||||
|
return [public_definition(project_id, project) for project_id, project in load_projects().items()]
|
||||||
|
|
||||||
|
|
||||||
@router.get("/apps")
|
@router.get("/apps")
|
||||||
async def get_apps_for_build():
|
async def get_apps_for_build():
|
||||||
"""获取 apps 列表(供打包选择)"""
|
"""获取 apps 列表(供打包选择)"""
|
||||||
@@ -27,7 +40,7 @@ async def get_apps_for_build():
|
|||||||
apps = {}
|
apps = {}
|
||||||
for app_id, app in config.get("apps", {}).items():
|
for app_id, app in config.get("apps", {}).items():
|
||||||
app_data = app.copy()
|
app_data = app.copy()
|
||||||
app_data["allowed_scheme_names"] = list(get_allowed_scheme_names(app))
|
app_data["allowed_scheme_names"] = list(get_allowed_scheme_names(app, config))
|
||||||
apps[app_id] = app_data
|
apps[app_id] = app_data
|
||||||
return apps
|
return apps
|
||||||
|
|
||||||
@@ -44,3 +57,9 @@ async def get_branches_for_build():
|
|||||||
"""获取分支列表(供打包选择)"""
|
"""获取分支列表(供打包选择)"""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
return config.get("branches", ["main"])
|
return config.get("branches", ["main"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tags")
|
||||||
|
async def get_tags_for_build():
|
||||||
|
"""获取 Tag 列表(供打包选择)"""
|
||||||
|
return get_tags(load_config())
|
||||||
|
|||||||
+792
-60
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,103 @@
|
|||||||
|
"""操作日志与统计 API(仅管理员)。"""
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..database import get_db
|
||||||
|
from ..deps import get_current_user
|
||||||
|
from ..models import OperationLog, Task
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/operations", tags=["operations"])
|
||||||
|
|
||||||
|
|
||||||
|
def _require_admin(user: dict):
|
||||||
|
if not user.get("is_admin"):
|
||||||
|
raise HTTPException(status_code=403, detail="需要管理员权限")
|
||||||
|
|
||||||
|
|
||||||
|
def _query_logs(db: Session, days: int, username: str = "", action: str = ""):
|
||||||
|
since = datetime.utcnow() - timedelta(days=max(1, min(days, 365)))
|
||||||
|
query = db.query(OperationLog).filter(OperationLog.created_at >= since)
|
||||||
|
if username:
|
||||||
|
query = query.filter(OperationLog.username == username)
|
||||||
|
if action:
|
||||||
|
query = query.filter(OperationLog.action == action)
|
||||||
|
return query
|
||||||
|
|
||||||
|
|
||||||
|
def _task_versions(db: Session, task_ids: set[str]) -> dict[str, str]:
|
||||||
|
versions = {}
|
||||||
|
if not task_ids:
|
||||||
|
return versions
|
||||||
|
for task_id, config_json in db.query(Task.id, Task.config_json).filter(Task.id.in_(task_ids)).all():
|
||||||
|
try:
|
||||||
|
config = json.loads(config_json or "{}")
|
||||||
|
versions[task_id] = config.get("VERSION", "") if isinstance(config, dict) else ""
|
||||||
|
except (TypeError, json.JSONDecodeError):
|
||||||
|
versions[task_id] = ""
|
||||||
|
return versions
|
||||||
|
|
||||||
|
|
||||||
|
def _log_detail(log: OperationLog) -> dict:
|
||||||
|
try:
|
||||||
|
detail = json.loads(log.detail_json or "{}")
|
||||||
|
except (TypeError, json.JSONDecodeError):
|
||||||
|
return {}
|
||||||
|
return detail if isinstance(detail, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/summary")
|
||||||
|
async def operation_summary(days: int = Query(30, ge=1, le=365), user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
|
_require_admin(user)
|
||||||
|
query = _query_logs(db, days)
|
||||||
|
total = query.count()
|
||||||
|
action_counts = dict(query.with_entities(OperationLog.action, func.count()).group_by(OperationLog.action).all())
|
||||||
|
users = query.with_entities(OperationLog.username, func.count()).group_by(OperationLog.username).order_by(func.count().desc()).limit(10).all()
|
||||||
|
apps = query.filter(OperationLog.app_name.isnot(None)).with_entities(OperationLog.app_name, func.count()).group_by(OperationLog.app_name).order_by(func.count().desc()).limit(10).all()
|
||||||
|
return {"days": days, "total": total, "action_counts": action_counts,
|
||||||
|
"top_users": [{"name": name, "count": count} for name, count in users],
|
||||||
|
"top_apps": [{"name": name, "count": count} for name, count in apps]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_operations(days: int = Query(30, ge=1, le=365), username: str = "", action: str = "", limit: int = Query(100, ge=1, le=500), user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
|
_require_admin(user)
|
||||||
|
logs = _query_logs(db, days, username, action).order_by(OperationLog.created_at.desc()).limit(limit).all()
|
||||||
|
task_ids = {log.task_id for log in logs if log.action == "ipa_download_requested" and log.task_id}
|
||||||
|
task_versions = _task_versions(db, task_ids)
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for log in logs:
|
||||||
|
detail = _log_detail(log)
|
||||||
|
item = {"id": log.id, "created_at": log.created_at, "username": log.username,
|
||||||
|
"action": log.action, "app_name": log.app_name, "task_id": log.task_id,
|
||||||
|
"resource_type": log.resource_type, "resource_name": log.resource_name,
|
||||||
|
"detail": detail}
|
||||||
|
if log.action == "ipa_download_requested":
|
||||||
|
item["version"] = detail.get("version") or task_versions.get(log.task_id, "")
|
||||||
|
result.append(item)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/export")
|
||||||
|
async def export_operations(days: int = Query(30, ge=1, le=365), user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
|
_require_admin(user)
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.writer(output)
|
||||||
|
writer.writerow(["时间", "用户", "操作", "App", "资源类型", "资源名称", "版本", "详情"])
|
||||||
|
logs = _query_logs(db, days).order_by(OperationLog.created_at.desc()).all()
|
||||||
|
task_ids = {log.task_id for log in logs if log.action == "ipa_download_requested" and log.task_id}
|
||||||
|
task_versions = _task_versions(db, task_ids)
|
||||||
|
for log in logs:
|
||||||
|
detail = _log_detail(log)
|
||||||
|
version = ""
|
||||||
|
if log.action == "ipa_download_requested":
|
||||||
|
version = detail.get("version") or task_versions.get(log.task_id, "")
|
||||||
|
writer.writerow([log.created_at, log.username, log.action, log.app_name or "", log.resource_type or "", log.resource_name or "", version, log.detail_json or ""])
|
||||||
|
return StreamingResponse(iter(["\ufeff" + output.getvalue()]), media_type="text/csv", headers={"Content-Disposition": "attachment; filename=operation-logs.csv"})
|
||||||
+130
-15
@@ -3,10 +3,11 @@ import os
|
|||||||
import json
|
import json
|
||||||
import shutil
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import List
|
from typing import List
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
from starlette.background import BackgroundTask
|
from starlette.background import BackgroundTask
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
@@ -18,9 +19,13 @@ from ..deps import get_current_user
|
|||||||
|
|
||||||
router = APIRouter(prefix="/api/tasks", tags=["tasks"], dependencies=[Depends(get_current_user)])
|
router = APIRouter(prefix="/api/tasks", tags=["tasks"], dependencies=[Depends(get_current_user)])
|
||||||
|
|
||||||
|
# 同一用户对同一任务连击下载按钮时,短时间内只记一次操作日志,避免刷屏
|
||||||
|
_DOWNLOAD_LOG_DEBOUNCE_SECONDS = 5
|
||||||
|
_recent_download_logs: dict[str, float] = {}
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=TaskResponse)
|
@router.post("", response_model=TaskResponse)
|
||||||
async def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
async def create_task(task: TaskCreate, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
"""创建打包任务"""
|
"""创建打包任务"""
|
||||||
from .config import load_config
|
from .config import load_config
|
||||||
|
|
||||||
@@ -43,16 +48,26 @@ async def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
|||||||
raise HTTPException(status_code=400, detail=f"该 App 未配置 {task.build_type} 证书")
|
raise HTTPException(status_code=400, detail=f"该 App 未配置 {task.build_type} 证书")
|
||||||
|
|
||||||
from .apps import get_allowed_scheme_names
|
from .apps import get_allowed_scheme_names
|
||||||
allowed_scheme_names = get_allowed_scheme_names(app)
|
allowed_scheme_names = get_allowed_scheme_names(app, config)
|
||||||
if allowed_scheme_names and scheme_name not in allowed_scheme_names:
|
if allowed_scheme_names and scheme_name not in allowed_scheme_names:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail=f"该 App 只能使用 Scheme: {', '.join(allowed_scheme_names)}",
|
detail=f"该 App 只能使用 Scheme: {', '.join(allowed_scheme_names)}",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
project_id = config["_project"]
|
||||||
|
from ..projects import get_definition
|
||||||
|
if task.obfuscation and not get_definition(project_id, config)["obfuscation"]:
|
||||||
|
raise HTTPException(status_code=400, detail="该项目不支持代码混淆")
|
||||||
|
|
||||||
|
# 分支与 Tag 不允许重名,按名字即可确定要检出的引用类型
|
||||||
|
from .config import get_ref_type
|
||||||
|
ref_type = get_ref_type(config, task.branch)
|
||||||
|
|
||||||
task_id = str(uuid.uuid4())
|
task_id = str(uuid.uuid4())
|
||||||
db_task = Task(
|
db_task = Task(
|
||||||
id=task_id,
|
id=task_id,
|
||||||
|
project_id=project_id,
|
||||||
app_id=task.app_id,
|
app_id=task.app_id,
|
||||||
app_name=app.get("name", ""),
|
app_name=app.get("name", ""),
|
||||||
build_type=task.build_type,
|
build_type=task.build_type,
|
||||||
@@ -60,9 +75,13 @@ async def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
|||||||
scheme_name=scheme.get("displayName") or scheme_name,
|
scheme_name=scheme.get("displayName") or scheme_name,
|
||||||
obfuscation=task.obfuscation,
|
obfuscation=task.obfuscation,
|
||||||
branch=task.branch,
|
branch=task.branch,
|
||||||
|
ref_type=ref_type,
|
||||||
status="pending",
|
status="pending",
|
||||||
)
|
)
|
||||||
db.add(db_task)
|
db.add(db_task)
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
record_operation(db, user, "build_created", request=request, task=db_task,
|
||||||
|
detail={"branch": task.branch, "ref_type": ref_type, "build_type": task.build_type})
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(db_task)
|
db.refresh(db_task)
|
||||||
|
|
||||||
@@ -100,12 +119,20 @@ def _enrich_tasks(tasks):
|
|||||||
@router.get("", response_model=List[TaskResponse])
|
@router.get("", response_model=List[TaskResponse])
|
||||||
async def list_tasks(
|
async def list_tasks(
|
||||||
status: str = None,
|
status: str = None,
|
||||||
|
include_superseded: bool = False,
|
||||||
limit: int = 20,
|
limit: int = 20,
|
||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
|
user: dict = Depends(get_current_user),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""获取任务列表"""
|
"""获取当前项目的任务列表"""
|
||||||
query = db.query(Task)
|
from .config import load_config
|
||||||
|
query = db.query(Task).filter(Task.project_id == load_config()["_project"])
|
||||||
|
if include_superseded:
|
||||||
|
if not user.get("is_admin"):
|
||||||
|
raise HTTPException(status_code=403, detail="需要管理员权限")
|
||||||
|
else:
|
||||||
|
query = query.filter(Task.superseded_at.is_(None))
|
||||||
if status:
|
if status:
|
||||||
query = query.filter(Task.status == status)
|
query = query.filter(Task.status == status)
|
||||||
tasks = query.order_by(Task.created_at.desc()).offset(offset).limit(limit).all()
|
tasks = query.order_by(Task.created_at.desc()).offset(offset).limit(limit).all()
|
||||||
@@ -122,7 +149,7 @@ async def get_task(task_id: str, db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{task_id}")
|
@router.delete("/{task_id}")
|
||||||
async def cancel_task(task_id: str, db: Session = Depends(get_db)):
|
async def cancel_task(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
"""取消任务"""
|
"""取消任务"""
|
||||||
task = db.query(Task).filter(Task.id == task_id).first()
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
if not task:
|
if not task:
|
||||||
@@ -132,6 +159,8 @@ async def cancel_task(task_id: str, db: Session = Depends(get_db)):
|
|||||||
raise HTTPException(status_code=400, detail="任务已完成或已取消")
|
raise HTTPException(status_code=400, detail="任务已完成或已取消")
|
||||||
|
|
||||||
task.status = "cancelled"
|
task.status = "cancelled"
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
record_operation(db, user, "build_cancelled", request=request, task=task)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
# 尝试取消运行中的任务
|
# 尝试取消运行中的任务
|
||||||
@@ -153,7 +182,7 @@ async def cancel_task(task_id: str, db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{task_id}/delete")
|
@router.delete("/{task_id}/delete")
|
||||||
async def delete_task(task_id: str, db: Session = Depends(get_db)):
|
async def delete_task(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
"""删除打包记录"""
|
"""删除打包记录"""
|
||||||
import shutil
|
import shutil
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -178,16 +207,35 @@ async def delete_task(task_id: str, db: Session = Depends(get_db)):
|
|||||||
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端文件")
|
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端文件")
|
||||||
try:
|
try:
|
||||||
build_config = json.loads(task.config_json)
|
build_config = json.loads(task.config_json)
|
||||||
from .config import load_config
|
from .config import load_upload_config
|
||||||
from ..services.distribution import DistributionError, delete_published_artifacts
|
from ..services.distribution import DistributionError, delete_published_artifacts
|
||||||
delete_published_artifacts(
|
delete_published_artifacts(
|
||||||
build_config,
|
build_config,
|
||||||
load_config().get("upload", {}),
|
load_upload_config(),
|
||||||
task.oss_url,
|
task.oss_url,
|
||||||
)
|
)
|
||||||
except (json.JSONDecodeError, DistributionError) as exc:
|
except (json.JSONDecodeError, DistributionError) as exc:
|
||||||
raise HTTPException(status_code=502, detail=f"远端产物删除失败,记录未删除:{exc}") from exc
|
raise HTTPException(status_code=502, detail=f"远端产物删除失败,记录未删除:{exc}") from exc
|
||||||
|
|
||||||
|
# dSYM 压缩包的远端对象键与 IPA 独立,同一版本/分支重复打包会复用并覆盖同一个远端文件,
|
||||||
|
# 仍有其他历史记录引用时不能删除。
|
||||||
|
has_shared_dsym = bool(
|
||||||
|
task.dsym_url and db.query(Task).filter(
|
||||||
|
Task.id != task.id,
|
||||||
|
Task.dsym_url == task.dsym_url,
|
||||||
|
).first()
|
||||||
|
)
|
||||||
|
if task.dsym_url and not has_shared_dsym:
|
||||||
|
if not task.config_json:
|
||||||
|
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端 dSYM 文件")
|
||||||
|
try:
|
||||||
|
build_config = json.loads(task.config_json)
|
||||||
|
from .config import load_upload_config
|
||||||
|
from ..services.distribution import DistributionError, delete_published_dsym
|
||||||
|
delete_published_dsym(build_config, load_upload_config(), task.dsym_url)
|
||||||
|
except (json.JSONDecodeError, DistributionError) as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=f"远端 dSYM 删除失败,记录未删除:{exc}") from exc
|
||||||
|
|
||||||
# 删除日志文件
|
# 删除日志文件
|
||||||
log_path = Path(__file__).parent.parent / "logs" / f"{task_id}.log"
|
log_path = Path(__file__).parent.parent / "logs" / f"{task_id}.log"
|
||||||
if log_path.exists():
|
if log_path.exists():
|
||||||
@@ -199,6 +247,8 @@ async def delete_task(task_id: str, db: Session = Depends(get_db)):
|
|||||||
if build_path.exists():
|
if build_path.exists():
|
||||||
shutil.rmtree(build_path, ignore_errors=True)
|
shutil.rmtree(build_path, ignore_errors=True)
|
||||||
|
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
record_operation(db, user, "task_deleted", request=request, task=task)
|
||||||
db.delete(task)
|
db.delete(task)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
@@ -243,9 +293,48 @@ async def get_build_log(task_id: str, db: Session = Depends(get_db)):
|
|||||||
return {"log": ""}
|
return {"log": ""}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}/download-link")
|
||||||
|
async def get_download_link(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
|
"""记录已登录用户发起 IPA 下载,并返回 OSS 公开链接。"""
|
||||||
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="任务不存在")
|
||||||
|
if not task.oss_url:
|
||||||
|
raise HTTPException(status_code=404, detail="下载文件不存在")
|
||||||
|
try:
|
||||||
|
from .config import load_upload_config
|
||||||
|
from ..config import DOWNLOAD_URL_EXPIRE_SECONDS
|
||||||
|
from ..services.distribution import DistributionError, get_published_download_url
|
||||||
|
task_config = json.loads(task.config_json or "{}")
|
||||||
|
download_url = get_published_download_url(
|
||||||
|
task_config,
|
||||||
|
load_upload_config(),
|
||||||
|
task.oss_url,
|
||||||
|
)
|
||||||
|
except (json.JSONDecodeError, DistributionError) as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=f"生成下载链接失败:{exc}") from exc
|
||||||
|
|
||||||
|
debounce_key = f"{user.get('username')}:{task_id}"
|
||||||
|
now = time.monotonic()
|
||||||
|
last = _recent_download_logs.get(debounce_key)
|
||||||
|
if last is None or now - last > _DOWNLOAD_LOG_DEBOUNCE_SECONDS:
|
||||||
|
if len(_recent_download_logs) > 500:
|
||||||
|
cutoff = now - _DOWNLOAD_LOG_DEBOUNCE_SECONDS
|
||||||
|
for key, ts in list(_recent_download_logs.items()):
|
||||||
|
if ts < cutoff:
|
||||||
|
del _recent_download_logs[key]
|
||||||
|
_recent_download_logs[debounce_key] = now
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
record_operation(db, user, "ipa_download_requested", request=request, task=task,
|
||||||
|
resource_type="ipa", resource_name=task.oss_url,
|
||||||
|
detail={"controlled": True, "version": task_config.get("VERSION", "")})
|
||||||
|
db.commit()
|
||||||
|
return {"url": download_url, "expires_in": DOWNLOAD_URL_EXPIRE_SECONDS}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{task_id}/dsym")
|
@router.get("/{task_id}/dsym")
|
||||||
async def download_dsym(task_id: str, db: Session = Depends(get_db)):
|
async def download_dsym(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
"""下载 dSYM 文件"""
|
"""下载 dSYM 文件:本地文件已被清理时回退到构建时上传保存的远端地址"""
|
||||||
import shutil
|
import shutil
|
||||||
import zipfile
|
import zipfile
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -253,13 +342,35 @@ async def download_dsym(task_id: str, db: Session = Depends(get_db)):
|
|||||||
task = db.query(Task).filter(Task.id == task_id).first()
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
if not task:
|
if not task:
|
||||||
raise HTTPException(status_code=404, detail="任务不存在")
|
raise HTTPException(status_code=404, detail="任务不存在")
|
||||||
if not task.dsym_path:
|
|
||||||
raise HTTPException(status_code=404, detail="dSYM 文件不存在")
|
|
||||||
|
|
||||||
dsym_path = task.dsym_path
|
dsym_path = task.dsym_path
|
||||||
if not os.path.exists(dsym_path):
|
local_exists = bool(dsym_path) and os.path.exists(dsym_path)
|
||||||
|
if not local_exists and not task.dsym_url:
|
||||||
|
if not dsym_path:
|
||||||
|
raise HTTPException(status_code=404, detail="dSYM 文件不存在")
|
||||||
raise HTTPException(status_code=404, detail="dSYM 文件已被清理")
|
raise HTTPException(status_code=404, detail="dSYM 文件已被清理")
|
||||||
|
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
resource_name = os.path.basename(dsym_path) if dsym_path else os.path.basename(task.dsym_url)
|
||||||
|
record_operation(db, user, "dsym_downloaded", request=request, task=task,
|
||||||
|
resource_type="dsym", resource_name=resource_name)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
if not local_exists:
|
||||||
|
# dSYM 需要携带认证信息才能访问该接口,浏览器无法直接跳转到本接口的
|
||||||
|
# 302 目标,因此改为返回 JSON 让前端自行发起下载。
|
||||||
|
try:
|
||||||
|
from .config import load_upload_config
|
||||||
|
from ..services.distribution import DistributionError, get_published_dsym_url
|
||||||
|
download_url = get_published_dsym_url(
|
||||||
|
json.loads(task.config_json or "{}"),
|
||||||
|
load_upload_config(),
|
||||||
|
task.dsym_url,
|
||||||
|
)
|
||||||
|
except (json.JSONDecodeError, DistributionError) as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=f"生成下载链接失败:{exc}") from exc
|
||||||
|
return {"url": download_url}
|
||||||
|
|
||||||
# .dSYM 是目录(macOS bundle),需要压缩为 zip 再下载
|
# .dSYM 是目录(macOS bundle),需要压缩为 zip 再下载
|
||||||
if os.path.isdir(dsym_path):
|
if os.path.isdir(dsym_path):
|
||||||
zip_path = os.path.join(tempfile.gettempdir(), os.path.basename(dsym_path) + ".zip")
|
zip_path = os.path.join(tempfile.gettempdir(), os.path.basename(dsym_path) + ".zip")
|
||||||
@@ -275,13 +386,17 @@ async def download_dsym(task_id: str, db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{task_id}/obfuscation-maps")
|
@router.get("/{task_id}/obfuscation-maps")
|
||||||
async def download_obfuscation_maps(task_id: str, db: Session = Depends(get_db)):
|
async def download_obfuscation_maps(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
"""下载混淆映射表"""
|
"""下载混淆映射表"""
|
||||||
task = db.query(Task).filter(Task.id == task_id).first()
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
if not task:
|
if not task:
|
||||||
raise HTTPException(status_code=404, detail="任务不存在")
|
raise HTTPException(status_code=404, detail="任务不存在")
|
||||||
if not task.obfuscation_maps_path:
|
if not task.obfuscation_maps_path:
|
||||||
raise HTTPException(status_code=404, detail="混淆映射表不存在")
|
raise HTTPException(status_code=404, detail="混淆映射表不存在")
|
||||||
|
from ..services.audit_log import record_operation
|
||||||
|
record_operation(db, user, "obfuscation_maps_downloaded", request=request, task=task,
|
||||||
|
resource_type="obfuscation_maps", resource_name=os.path.basename(task.obfuscation_maps_path))
|
||||||
|
db.commit()
|
||||||
|
|
||||||
maps_path = task.obfuscation_maps_path
|
maps_path = task.obfuscation_maps_path
|
||||||
if not os.path.exists(maps_path):
|
if not os.path.exists(maps_path):
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ class TaskCreate(BaseModel):
|
|||||||
|
|
||||||
class TaskResponse(BaseModel):
|
class TaskResponse(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
|
project_id: Optional[str] = "readoor"
|
||||||
app_id: str
|
app_id: str
|
||||||
app_name: str
|
app_name: str
|
||||||
build_type: str
|
build_type: str
|
||||||
@@ -22,14 +23,17 @@ class TaskResponse(BaseModel):
|
|||||||
scheme_name: str
|
scheme_name: str
|
||||||
obfuscation: bool
|
obfuscation: bool
|
||||||
branch: str
|
branch: str
|
||||||
|
ref_type: Optional[str] = "branch"
|
||||||
status: str
|
status: str
|
||||||
current_step: Optional[str]
|
current_step: Optional[str]
|
||||||
created_at: Optional[datetime]
|
created_at: Optional[datetime]
|
||||||
started_at: Optional[datetime]
|
started_at: Optional[datetime]
|
||||||
completed_at: Optional[datetime]
|
completed_at: Optional[datetime]
|
||||||
|
superseded_at: Optional[datetime] = None
|
||||||
ipa_path: Optional[str]
|
ipa_path: Optional[str]
|
||||||
oss_url: Optional[str]
|
oss_url: Optional[str]
|
||||||
dsym_path: Optional[str]
|
dsym_path: Optional[str]
|
||||||
|
dsym_url: Optional[str] = None
|
||||||
obfuscation_maps_path: Optional[str]
|
obfuscation_maps_path: Optional[str]
|
||||||
qr_code_path: Optional[str]
|
qr_code_path: Optional[str]
|
||||||
build_dir: Optional[str]
|
build_dir: Optional[str]
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""操作审计日志。"""
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from ..models import OperationLog
|
||||||
|
|
||||||
|
|
||||||
|
def record_operation(db, user: dict, action: str, *, request=None, task=None,
|
||||||
|
resource_type: str = "", resource_name: str = "", detail: dict | None = None):
|
||||||
|
"""将已登录用户的关键操作写入当前数据库事务。"""
|
||||||
|
client_ip = request.client.host if request and request.client else ""
|
||||||
|
user_agent = request.headers.get("user-agent", "")[:500] if request else ""
|
||||||
|
db.add(OperationLog(
|
||||||
|
id=str(uuid.uuid4()), created_at=datetime.utcnow(), username=user.get("username", ""),
|
||||||
|
is_admin=bool(user.get("is_admin")), action=action,
|
||||||
|
task_id=task.id if task else None,
|
||||||
|
app_id=task.app_id if task else None,
|
||||||
|
app_name=task.app_name if task else None,
|
||||||
|
resource_type=resource_type, resource_name=resource_name,
|
||||||
|
detail_json=json.dumps(detail or {}, ensure_ascii=False),
|
||||||
|
client_ip=client_ip, user_agent=user_agent,
|
||||||
|
))
|
||||||
@@ -3,28 +3,27 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import plistlib
|
import plistlib
|
||||||
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import zipfile
|
import zipfile
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from ..config import (
|
from ..config import (
|
||||||
BUILD_BASE_DIR,
|
BUILD_BASE_DIR,
|
||||||
COPY_ITEMS,
|
|
||||||
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
||||||
BUILD_TIMEOUT_HOURS,
|
BUILD_TIMEOUT_HOURS,
|
||||||
SKINS_DIR,
|
SKINS_DIR,
|
||||||
AUTOMATION_DIR,
|
AUTOMATION_DIR,
|
||||||
get_source_dir,
|
|
||||||
get_shared_source_dir,
|
|
||||||
get_git_remote_url,
|
get_git_remote_url,
|
||||||
mask_git_remote_url,
|
mask_git_remote_url,
|
||||||
)
|
)
|
||||||
|
from ..projects import LEGACY_PROJECT_ID, PATCHER_READOOR, get_definition, get_project_source
|
||||||
from .log_streamer import log_streamer
|
from .log_streamer import log_streamer
|
||||||
from .distribution import DistributionError, publish_ipa
|
from .distribution import DistributionError, publish_dsym, publish_ipa
|
||||||
from .notification import NotificationError, send_dingtalk_notification
|
from .notification import NotificationError, merge_project_at_mobiles, send_dingtalk_notification
|
||||||
from .project_patcher import ProjectPatchError, apply_project_config
|
from .project_patcher import ProjectPatchError, apply_project_config
|
||||||
|
|
||||||
|
|
||||||
@@ -37,9 +36,36 @@ class BuildError(Exception):
|
|||||||
self.detail = detail
|
self.detail = detail
|
||||||
|
|
||||||
|
|
||||||
# 共享源码目录只能同时被一个任务切换、清理和复制。
|
# 共享源码目录只能同时被一个任务切换、清理和复制,每个源码目录一把锁,
|
||||||
# 后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
|
# 不同项目的源码准备互不阻塞。后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
|
||||||
source_prepare_lock = asyncio.Lock()
|
_source_prepare_locks: dict = {}
|
||||||
|
|
||||||
|
# 打包目录名:build_<项目 ID>_<任务 ID>
|
||||||
|
_BUILD_DIR_PATTERN = re.compile(r"^build_[a-z][a-z0-9_-]{0,31}_.+")
|
||||||
|
|
||||||
|
|
||||||
|
def _source_prepare_lock(source_dir: Path) -> asyncio.Lock:
|
||||||
|
return _source_prepare_locks.setdefault(str(source_dir.resolve()), asyncio.Lock())
|
||||||
|
|
||||||
|
|
||||||
|
def _task_project_id(task) -> str:
|
||||||
|
project_id = getattr(task, "project_id", None)
|
||||||
|
return project_id if isinstance(project_id, str) and project_id else LEGACY_PROJECT_ID
|
||||||
|
|
||||||
|
|
||||||
|
def load_task_project(task) -> dict:
|
||||||
|
"""读取任务所属项目的配置视图(见 routers.config.load_config)。"""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from ..routers.config import load_config
|
||||||
|
try:
|
||||||
|
return load_config(_task_project_id(task))
|
||||||
|
except HTTPException as exc:
|
||||||
|
raise BuildError(str(exc.detail), category="config") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def get_task_definition(task) -> dict:
|
||||||
|
project_id = _task_project_id(task)
|
||||||
|
return get_definition(project_id, load_task_project(task))
|
||||||
|
|
||||||
|
|
||||||
def _patch_afnetworking_private_headers(build_dir: Path) -> int:
|
def _patch_afnetworking_private_headers(build_dir: Path) -> int:
|
||||||
@@ -214,14 +240,59 @@ def _cleanup_old_builds(db):
|
|||||||
|
|
||||||
base = BUILD_BASE_DIR
|
base = BUILD_BASE_DIR
|
||||||
if not base.exists():
|
if not base.exists():
|
||||||
|
_cleanup_superseded_tasks(db)
|
||||||
return
|
return
|
||||||
for d in base.iterdir():
|
for d in base.iterdir():
|
||||||
if d.is_dir() and d.name.startswith("build_readoor_"):
|
if d.is_dir() and _BUILD_DIR_PATTERN.match(d.name):
|
||||||
try:
|
try:
|
||||||
if d.stat().st_mtime < cutoff:
|
if d.stat().st_mtime < cutoff:
|
||||||
shutil.rmtree(d)
|
shutil.rmtree(d)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
_cleanup_superseded_tasks(db)
|
||||||
|
|
||||||
|
|
||||||
|
def _cleanup_superseded_tasks(db):
|
||||||
|
"""7 天后删除已被新 OSS 包覆盖的历史记录及仅本地保留的文件。"""
|
||||||
|
from ..models import Task
|
||||||
|
cutoff = datetime.utcnow() - timedelta(days=7)
|
||||||
|
tasks = db.query(Task).filter(
|
||||||
|
Task.superseded_at.isnot(None), Task.superseded_at < cutoff,
|
||||||
|
).all()
|
||||||
|
for task in tasks:
|
||||||
|
for path_value in (task.build_dir, task.dsym_path, task.obfuscation_maps_path):
|
||||||
|
if not path_value:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
path = Path(path_value)
|
||||||
|
if path.is_dir():
|
||||||
|
shutil.rmtree(path, ignore_errors=True)
|
||||||
|
elif path.exists():
|
||||||
|
path.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
log_path = Path(__file__).parent.parent / "logs" / f"{task.id}.log"
|
||||||
|
try:
|
||||||
|
log_path.unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
db.delete(task)
|
||||||
|
if tasks:
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _mark_superseded_tasks(db, latest_task):
|
||||||
|
"""标记同一 OSS 对象的旧成功记录;OSS 文件由最新任务覆盖。"""
|
||||||
|
if not latest_task.oss_url:
|
||||||
|
return
|
||||||
|
from ..models import Task
|
||||||
|
db.query(Task).filter(
|
||||||
|
Task.id != latest_task.id,
|
||||||
|
Task.status == "completed",
|
||||||
|
Task.oss_url == latest_task.oss_url,
|
||||||
|
Task.superseded_at.is_(None),
|
||||||
|
).update({Task.superseded_at: datetime.utcnow()}, synchronize_session=False)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
def _cleanup_old_logs():
|
def _cleanup_old_logs():
|
||||||
@@ -246,16 +317,21 @@ def _db_update(db, task, **fields):
|
|||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
async def update_source(task_id: str, source_dir: Path, branch: str):
|
async def update_source(task_id: str, source_dir: Path, branch: str, ref_type: str = "branch",
|
||||||
"""将共享源码工作目录强制同步到指定远程分支。"""
|
remote_url: str = None):
|
||||||
remote_url = get_git_remote_url(with_credentials=True)
|
"""将共享源码工作目录强制同步到指定远程分支或 Tag(ref_type="tag" 时 branch 为 Tag 名)。
|
||||||
|
|
||||||
|
remote_url 为带凭证的项目仓库地址,未传时使用 .env 中的 GIT_REMOTE_URL。
|
||||||
|
"""
|
||||||
|
if remote_url is None:
|
||||||
|
remote_url = get_git_remote_url(with_credentials=True)
|
||||||
remote_url_masked = mask_git_remote_url(remote_url)
|
remote_url_masked = mask_git_remote_url(remote_url)
|
||||||
git_env = _git_env()
|
git_env = _git_env()
|
||||||
|
|
||||||
cloned = not source_dir.exists()
|
cloned = not source_dir.exists()
|
||||||
if cloned:
|
if cloned:
|
||||||
if not remote_url:
|
if not remote_url:
|
||||||
raise Exception(f"源码目录不存在且未配置 GIT_REMOTE_URL: {source_dir}")
|
raise Exception(f"源码目录不存在且未配置 Git 仓库地址: {source_dir}")
|
||||||
source_dir.parent.mkdir(parents=True, exist_ok=True)
|
source_dir.parent.mkdir(parents=True, exist_ok=True)
|
||||||
await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}")
|
await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}")
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
@@ -276,7 +352,8 @@ async def update_source(task_id: str, source_dir: Path, branch: str):
|
|||||||
if not cloned and not (source_dir / ".git").exists():
|
if not cloned and not (source_dir / ".git").exists():
|
||||||
raise Exception(f"共享源码目录不是 Git 仓库: {source_dir}")
|
raise Exception(f"共享源码目录不是 Git 仓库: {source_dir}")
|
||||||
|
|
||||||
await log_streamer.emit(task_id, f"同步共享源码到分支: {branch}")
|
is_tag = ref_type == "tag"
|
||||||
|
await log_streamer.emit(task_id, f"同步共享源码到{'Tag' if is_tag else '分支'}: {branch}")
|
||||||
|
|
||||||
if remote_url:
|
if remote_url:
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
@@ -288,12 +365,22 @@ async def update_source(task_id: str, source_dir: Path, branch: str):
|
|||||||
if process.returncode != 0:
|
if process.returncode != 0:
|
||||||
raise Exception("git remote set-url 失败")
|
raise Exception("git remote set-url 失败")
|
||||||
|
|
||||||
commands = [
|
if is_tag:
|
||||||
(("git", "fetch", "origin"), "git fetch 失败"),
|
# Tag 检出为游离 HEAD;--force 让远端被移动过的 Tag 覆盖本地旧 Tag
|
||||||
(("git", "checkout", "-B", branch, f"origin/{branch}"), f"git checkout {branch} 失败"),
|
tag_ref = f"refs/tags/{branch}"
|
||||||
(("git", "reset", "--hard", f"origin/{branch}"), f"git reset {branch} 失败"),
|
commands = [
|
||||||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
(("git", "fetch", "origin", "--tags", "--force"), "git fetch 失败"),
|
||||||
]
|
(("git", "checkout", "--detach", tag_ref), f"git checkout Tag {branch} 失败"),
|
||||||
|
(("git", "reset", "--hard", tag_ref), f"git reset Tag {branch} 失败"),
|
||||||
|
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
commands = [
|
||||||
|
(("git", "fetch", "origin"), "git fetch 失败"),
|
||||||
|
(("git", "checkout", "-B", branch, f"origin/{branch}"), f"git checkout {branch} 失败"),
|
||||||
|
(("git", "reset", "--hard", f"origin/{branch}"), f"git reset {branch} 失败"),
|
||||||
|
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||||||
|
]
|
||||||
for command, error_message in commands:
|
for command, error_message in commands:
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
*_GIT_NO_CREDENTIAL_HELPER, *command[1:], env=git_env,
|
*_GIT_NO_CREDENTIAL_HELPER, *command[1:], env=git_env,
|
||||||
@@ -325,24 +412,34 @@ async def get_source_commit(source_dir: Path) -> str:
|
|||||||
|
|
||||||
|
|
||||||
async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]:
|
async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]:
|
||||||
"""准备任务独立源码快照;远程仓库模式下此过程全局串行。"""
|
"""准备任务独立源码快照;远程仓库模式下同一源码目录的准备过程串行。"""
|
||||||
if not get_git_remote_url():
|
project_id = _task_project_id(task)
|
||||||
source_dir = get_source_dir(task.branch)
|
project = load_task_project(task)
|
||||||
|
definition = get_definition(project_id, project)
|
||||||
|
source = get_project_source(project_id, project)
|
||||||
|
await log_streamer.emit(task_id, f"项目: {definition['name']}({project_id})")
|
||||||
|
|
||||||
|
if not source.remote_url:
|
||||||
|
if source.manual_base is None:
|
||||||
|
raise BuildError(f"项目 {definition['name']} 未配置 Git 仓库地址", category="config")
|
||||||
|
source_dir = source.manual_base / task.branch
|
||||||
if not source_dir.exists():
|
if not source_dir.exists():
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支代码,或配置 GIT_REMOTE_URL"
|
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支(或 Tag)代码,或配置 GIT_REMOTE_URL"
|
||||||
)
|
)
|
||||||
await log_streamer.emit(task_id, f"使用分支源码: {source_dir}")
|
await log_streamer.emit(task_id, f"使用分支源码: {source_dir}")
|
||||||
return await copy_source_code(task_id, task, source_dir), ""
|
return await copy_source_code(task_id, task, source_dir, definition), ""
|
||||||
|
|
||||||
source_dir = get_shared_source_dir()
|
source_dir = source.shared_dir
|
||||||
await log_streamer.emit(task_id, "等待共享源码准备队列...")
|
await log_streamer.emit(task_id, "等待共享源码准备队列...")
|
||||||
async with source_prepare_lock:
|
async with _source_prepare_lock(source_dir):
|
||||||
await log_streamer.emit(task_id, "开始准备共享源码快照")
|
await log_streamer.emit(task_id, "开始准备共享源码快照")
|
||||||
await update_source(task_id, source_dir, task.branch)
|
ref_type = "tag" if task.ref_type == "tag" else "branch"
|
||||||
|
await update_source(task_id, source_dir, task.branch, ref_type,
|
||||||
|
remote_url=source.remote_url_with_credentials)
|
||||||
commit = await get_source_commit(source_dir)
|
commit = await get_source_commit(source_dir)
|
||||||
await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}")
|
await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}")
|
||||||
build_dir = await copy_source_code(task_id, task, source_dir)
|
build_dir = await copy_source_code(task_id, task, source_dir, definition)
|
||||||
await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包")
|
await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包")
|
||||||
return build_dir, commit
|
return build_dir, commit
|
||||||
|
|
||||||
@@ -381,6 +478,7 @@ async def run_build_task(task_id: str):
|
|||||||
nonlocal build_dir
|
nonlocal build_dir
|
||||||
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
||||||
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
||||||
|
definition = await asyncio.to_thread(get_task_definition, task)
|
||||||
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
||||||
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
||||||
|
|
||||||
@@ -388,17 +486,18 @@ async def run_build_task(task_id: str):
|
|||||||
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
||||||
config_data = await generate_config(task_id, task, build_dir)
|
config_data = await generate_config(task_id, task, build_dir)
|
||||||
config_data["SOURCE_BRANCH"] = task.branch
|
config_data["SOURCE_BRANCH"] = task.branch
|
||||||
|
config_data["SOURCE_REF_TYPE"] = "tag" if task.ref_type == "tag" else "branch"
|
||||||
config_data["SOURCE_COMMIT"] = source_commit
|
config_data["SOURCE_COMMIT"] = source_commit
|
||||||
await asyncio.to_thread(_db_update, db, task,
|
await asyncio.to_thread(_db_update, db, task,
|
||||||
config_json=json.dumps(config_data, ensure_ascii=False))
|
config_json=json.dumps(config_data, ensure_ascii=False))
|
||||||
|
|
||||||
# 3. 替换项目配置
|
# 3. 替换项目配置
|
||||||
await asyncio.to_thread(_db_update, db, task, current_step="patch")
|
await asyncio.to_thread(_db_update, db, task, current_step="patch")
|
||||||
await patch_project(task_id, task, config_data, build_dir)
|
await patch_project(task_id, task, config_data, build_dir, definition)
|
||||||
|
|
||||||
# 3.5 安装依赖
|
# 3.5 安装依赖
|
||||||
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
||||||
await run_pod_install(task_id, build_dir)
|
await run_pod_install(task_id, build_dir, definition["xcode"])
|
||||||
|
|
||||||
# 4. 代码混淆(可选)
|
# 4. 代码混淆(可选)
|
||||||
if task.obfuscation:
|
if task.obfuscation:
|
||||||
@@ -407,10 +506,10 @@ async def run_build_task(task_id: str):
|
|||||||
|
|
||||||
# 5. 构建项目
|
# 5. 构建项目
|
||||||
await asyncio.to_thread(_db_update, db, task, current_step="build")
|
await asyncio.to_thread(_db_update, db, task, current_step="build")
|
||||||
ipa_path = await build_project(task_id, task, config_data, build_dir)
|
ipa_path = await build_project(task_id, task, config_data, build_dir, definition["xcode"])
|
||||||
|
|
||||||
# 查找 dSYM
|
# 查找 dSYM
|
||||||
dsym_path = await find_dsym(task_id, build_dir)
|
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
|
||||||
|
|
||||||
# 查找混淆映射表
|
# 查找混淆映射表
|
||||||
obf_maps_path = build_dir / "obfuscation_maps"
|
obf_maps_path = build_dir / "obfuscation_maps"
|
||||||
@@ -432,6 +531,13 @@ async def run_build_task(task_id: str):
|
|||||||
upload_fields["oss_url"] = oss_url
|
upload_fields["oss_url"] = oss_url
|
||||||
if qr_code_path:
|
if qr_code_path:
|
||||||
upload_fields["qr_code_path"] = qr_code_path
|
upload_fields["qr_code_path"] = qr_code_path
|
||||||
|
|
||||||
|
# dSYM 用于后续崩溃符号化,按上传配置一并保存到远端;失败不影响本次打包结果。
|
||||||
|
if dsym_path:
|
||||||
|
dsym_url = await upload_dsym(task_id, task, config_data, dsym_path, build_dir)
|
||||||
|
if dsym_url:
|
||||||
|
upload_fields["dsym_url"] = dsym_url
|
||||||
|
|
||||||
if upload_fields:
|
if upload_fields:
|
||||||
await asyncio.to_thread(_db_update, db, task, **upload_fields)
|
await asyncio.to_thread(_db_update, db, task, **upload_fields)
|
||||||
|
|
||||||
@@ -439,28 +545,33 @@ async def run_build_task(task_id: str):
|
|||||||
await asyncio.to_thread(_db_update, db, task,
|
await asyncio.to_thread(_db_update, db, task,
|
||||||
status="completed", completed_at=datetime.utcnow(),
|
status="completed", completed_at=datetime.utcnow(),
|
||||||
current_step=None)
|
current_step=None)
|
||||||
|
await asyncio.to_thread(_mark_superseded_tasks, db, task)
|
||||||
|
|
||||||
await log_streamer.emit_step(task_id, "打包完成")
|
await log_streamer.emit_step(task_id, "打包完成")
|
||||||
await log_streamer.emit(task_id, f"IPA: {ipa_path}")
|
await log_streamer.emit(task_id, f"IPA: {ipa_path}")
|
||||||
if task.oss_url:
|
if task.oss_url:
|
||||||
await log_streamer.emit(task_id, f"下载链接: {task.oss_url}")
|
await log_streamer.emit(task_id, f"下载链接: {task.oss_url}")
|
||||||
|
|
||||||
# App Store 仅提供 IPA 下载地址,不发送下载通知;Ad Hoc 才发送安装页二维码通知。
|
# Ad Hoc 发安装页二维码通知,App Store 发 IPA 下载地址通知;
|
||||||
if task.build_type == "Ad_Hoc":
|
# 两者标题与 @ 名单不同,均由 send_dingtalk_notification 按 BUILD_TYPE 区分;
|
||||||
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
|
# 项目配置了 @ 名单时覆盖全局名单。
|
||||||
dingtalk_config = config_data.get("_upload_config", {}).get("dingtalk", {})
|
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
|
||||||
try:
|
dingtalk_config = merge_project_at_mobiles(
|
||||||
notified = await asyncio.to_thread(
|
config_data.get("_upload_config", {}).get("dingtalk", {}),
|
||||||
send_dingtalk_notification,
|
definition.get("dingtalk_at"),
|
||||||
dingtalk_config,
|
)
|
||||||
config_data,
|
try:
|
||||||
task.oss_url or oss_url,
|
notified = await asyncio.to_thread(
|
||||||
task.qr_code_path or qr_code_path,
|
send_dingtalk_notification,
|
||||||
)
|
dingtalk_config,
|
||||||
if notified:
|
config_data,
|
||||||
await log_streamer.emit(task_id, "钉钉通知发送成功")
|
task.oss_url or oss_url,
|
||||||
except NotificationError as exc:
|
task.qr_code_path or qr_code_path,
|
||||||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
)
|
||||||
|
if notified:
|
||||||
|
await log_streamer.emit(task_id, "钉钉通知发送成功")
|
||||||
|
except NotificationError as exc:
|
||||||
|
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||||||
|
|
||||||
# 带超时执行打包
|
# 带超时执行打包
|
||||||
await asyncio.wait_for(_do_build(), timeout=timeout_seconds)
|
await asyncio.wait_for(_do_build(), timeout=timeout_seconds)
|
||||||
@@ -524,16 +635,36 @@ async def run_build_task(task_id: str):
|
|||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
async def copy_source_code(task_id: str, task, source_dir: Path) -> Path:
|
async def copy_source_code(task_id: str, task, source_dir: Path, definition: dict = None) -> Path:
|
||||||
"""从分支源码目录拷贝代码到打包目录"""
|
"""从分支源码目录拷贝代码到打包目录"""
|
||||||
await log_streamer.emit_step(task_id, "拷贝代码")
|
await log_streamer.emit_step(task_id, "拷贝代码")
|
||||||
|
|
||||||
build_dir = BUILD_BASE_DIR / f"build_readoor_{task_id}"
|
project_id = _task_project_id(task)
|
||||||
|
if definition is None:
|
||||||
|
definition = get_definition(project_id, {})
|
||||||
|
build_dir = BUILD_BASE_DIR / f"build_{project_id}_{task_id}"
|
||||||
if build_dir.exists():
|
if build_dir.exists():
|
||||||
shutil.rmtree(build_dir)
|
shutil.rmtree(build_dir)
|
||||||
build_dir.mkdir(parents=True)
|
|
||||||
|
|
||||||
for item in COPY_ITEMS:
|
# 未指定拷贝条目时拷贝整个仓库(不含 Git 数据和编译缓存)
|
||||||
|
copy_items = definition.get("copy_items") or []
|
||||||
|
if not copy_items:
|
||||||
|
await log_streamer.emit(task_id, "拷贝整个仓库")
|
||||||
|
root = str(source_dir)
|
||||||
|
|
||||||
|
def _ignore(directory, names):
|
||||||
|
ignored = {name for name in names if name in (".git", "DerivedData")}
|
||||||
|
# 仓库根目录的 build 与打包产物目录同名,不拷贝
|
||||||
|
if directory == root and "build" in names:
|
||||||
|
ignored.add("build")
|
||||||
|
return ignored
|
||||||
|
|
||||||
|
shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore)
|
||||||
|
await log_streamer.emit(task_id, "代码拷贝完成")
|
||||||
|
return build_dir
|
||||||
|
|
||||||
|
build_dir.mkdir(parents=True)
|
||||||
|
for item in copy_items:
|
||||||
src = source_dir / item
|
src = source_dir / item
|
||||||
# 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj
|
# 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj
|
||||||
# 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。
|
# 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。
|
||||||
@@ -555,35 +686,45 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
|||||||
"""生成打包配置"""
|
"""生成打包配置"""
|
||||||
await log_streamer.emit_step(task_id, "生成配置")
|
await log_streamer.emit_step(task_id, "生成配置")
|
||||||
|
|
||||||
from ..routers.config import load_config, _config_lock
|
from ..routers.config import (
|
||||||
|
load_config, _config_lock, get_track, get_track_name, track_build_ver,
|
||||||
|
is_release_track, next_build_no, _ensure_track,
|
||||||
|
)
|
||||||
|
|
||||||
config = load_config()
|
project_id = _task_project_id(task)
|
||||||
|
config = load_config(project_id)
|
||||||
apps = config.get("apps", {})
|
apps = config.get("apps", {})
|
||||||
schemes = config.get("schemes", {})
|
schemes = config.get("schemes", {})
|
||||||
versions = config.get("versions", {})
|
|
||||||
|
|
||||||
app = apps.get(task.app_id, {})
|
app = apps.get(task.app_id, {})
|
||||||
scheme = schemes.get(task.scheme_id, {})
|
scheme = schemes.get(task.scheme_id, {})
|
||||||
|
|
||||||
# 版本号由当前服务配置统一管理,不读取分支源码中的手动打包脚本。
|
# 版本号由当前服务配置统一管理,不读取分支源码中的手动打包脚本。
|
||||||
app_ver = versions.get("app_ver", "2.180.0")
|
# 按分支所属轨道取版本号:每个上架分支(master、develop 等)一条独立轨道,
|
||||||
build_ver = versions.get("build_ver", "2.180.0.0")
|
# 自测分支共用 feature 轨,各轨道的 App_Ver 互不影响。
|
||||||
|
track_name = get_track_name(config, task.branch)
|
||||||
|
track = get_track(config, track_name)
|
||||||
|
app_ver = track.get("app_ver") or "2.180.0"
|
||||||
|
|
||||||
# App_Store 打包时自动递增 Build_Ver 第四位版本号
|
# 构建号按版本号独立记录:build_map[app_ver] 为该版本号已用到的最大第四位。
|
||||||
if task.build_type == "App_Store":
|
build_ver = track_build_ver(track)
|
||||||
|
is_release = is_release_track(track)
|
||||||
|
await log_streamer.emit(
|
||||||
|
task_id,
|
||||||
|
f"版本轨道: {track_name}({'上架,App_Store 打包自增' if is_release else '自测,构建号不自增'})",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 上架轨的 App_Store 打包,在该版本号的构建号上 +1(回退到旧版本号也从它自己的最大值继续);
|
||||||
|
# feature 轨始终使用手动设定的构建号。
|
||||||
|
if is_release and task.build_type == "App_Store":
|
||||||
async with _config_lock:
|
async with _config_lock:
|
||||||
parts = build_ver.split(".")
|
config = load_config(project_id)
|
||||||
if len(parts) >= 4:
|
track = _ensure_track(config, track_name)
|
||||||
parts[3] = str(int(parts[3]) + 1)
|
track.setdefault("app_ver", app_ver)
|
||||||
else:
|
n = next_build_no(config["versions"]["tracks"], app_ver)
|
||||||
parts.append("1")
|
track.setdefault("build_map", {})[app_ver] = n
|
||||||
build_ver = ".".join(parts)
|
build_ver = f"{app_ver}.{n}"
|
||||||
|
|
||||||
config = load_config()
|
|
||||||
config["versions"] = {
|
|
||||||
"app_ver": app_ver,
|
|
||||||
"build_ver": build_ver,
|
|
||||||
}
|
|
||||||
from ..routers.config import save_config
|
from ..routers.config import save_config
|
||||||
save_config(config)
|
save_config(config)
|
||||||
|
|
||||||
@@ -591,6 +732,7 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
|||||||
|
|
||||||
# 构建配置
|
# 构建配置
|
||||||
config_data = {
|
config_data = {
|
||||||
|
"PROJECT_ID": project_id,
|
||||||
"VERSION": app_ver,
|
"VERSION": app_ver,
|
||||||
"BUILD_VERSION": build_ver,
|
"BUILD_VERSION": build_ver,
|
||||||
"SERVER": app.get("server", ""),
|
"SERVER": app.get("server", ""),
|
||||||
@@ -629,7 +771,12 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
|||||||
skin_extract_dir.mkdir(exist_ok=True)
|
skin_extract_dir.mkdir(exist_ok=True)
|
||||||
with zipfile.ZipFile(skin_zip, "r") as zf:
|
with zipfile.ZipFile(skin_zip, "r") as zf:
|
||||||
zf.extractall(skin_extract_dir)
|
zf.extractall(skin_extract_dir)
|
||||||
entries = list(skin_extract_dir.iterdir())
|
# 过滤掉 macOS 压缩产生的 __MACOSX 及隐藏文件,避免把它们
|
||||||
|
# 当成皮肤资源目录一起复制进 Images.xcassets。
|
||||||
|
entries = [
|
||||||
|
e for e in skin_extract_dir.iterdir()
|
||||||
|
if e.name != "__MACOSX" and not e.name.startswith(".")
|
||||||
|
]
|
||||||
if len(entries) == 1 and entries[0].is_dir():
|
if len(entries) == 1 and entries[0].is_dir():
|
||||||
config_data["THEME"] = str(entries[0])
|
config_data["THEME"] = str(entries[0])
|
||||||
else:
|
else:
|
||||||
@@ -655,10 +802,27 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
|||||||
|
|
||||||
# 关联域名等配置
|
# 关联域名等配置
|
||||||
config_data["ASSOCIATED_DOMAINS"] = app.get("AssDom", "")
|
config_data["ASSOCIATED_DOMAINS"] = app.get("AssDom", "")
|
||||||
for key in ["weixinlogin", "weixinpay", "tencent", "UniversalLink", "AlivcLicenseKey"]:
|
for key in ["weixinlogin", "weixinpay", "wxworkSchema", "tencent", "UniversalLink", "AlivcLicenseKey"]:
|
||||||
if key in app:
|
if key in app:
|
||||||
config_data[key] = app[key]
|
config_data[key] = app[key]
|
||||||
|
|
||||||
|
# 项目自定义字段,供通用替换规则以 ${app.X} / ${server.X} 引用
|
||||||
|
definition = get_definition(project_id, config)
|
||||||
|
server = config.get("servers", {}).get(app.get("server", ""), {})
|
||||||
|
config_data["APP_VARS"] = {
|
||||||
|
field["key"]: app.get(field["key"], "") for field in definition["app_fields"] if field.get("key")
|
||||||
|
}
|
||||||
|
# 通用项目没有 AppGuid:以第一个 App 字段(如 APPID)作为 App 标识,
|
||||||
|
# 用于产物文件名和通知;未配置 App 字段时用 upload_key。
|
||||||
|
if definition["patcher"] != PATCHER_READOOR:
|
||||||
|
id_field = next((field for field in definition["app_fields"] if field.get("key")), None)
|
||||||
|
app_ident = config_data["APP_VARS"].get(id_field["key"], "") if id_field else ""
|
||||||
|
config_data["APPID"] = app_ident or config_data["UPLOAD_KEY"]
|
||||||
|
config_data["APPID_LABEL"] = (id_field.get("label") or id_field["key"]) if app_ident else "App 标识"
|
||||||
|
config_data["SERVER_VARS"] = {
|
||||||
|
field["key"]: server.get(field["key"], "") for field in definition["server_fields"] if field.get("key")
|
||||||
|
}
|
||||||
|
|
||||||
# 写入配置文件
|
# 写入配置文件
|
||||||
config_output_path = build_dir / "config_output.json"
|
config_output_path = build_dir / "config_output.json"
|
||||||
with open(config_output_path, "w", encoding="utf-8") as f:
|
with open(config_output_path, "w", encoding="utf-8") as f:
|
||||||
@@ -668,12 +832,12 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
|||||||
return config_data
|
return config_data
|
||||||
|
|
||||||
|
|
||||||
async def patch_project(task_id: str, task, config_data: dict, build_dir: Path):
|
async def patch_project(task_id: str, task, config_data: dict, build_dir: Path, definition: dict = None):
|
||||||
"""替换项目配置"""
|
"""替换项目配置"""
|
||||||
await log_streamer.emit_step(task_id, "替换项目配置")
|
await log_streamer.emit_step(task_id, "替换项目配置")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
patch_lines = await asyncio.to_thread(apply_project_config, build_dir, config_data)
|
patch_lines = await asyncio.to_thread(apply_project_config, build_dir, config_data, definition)
|
||||||
except ProjectPatchError as exc:
|
except ProjectPatchError as exc:
|
||||||
raise BuildError(str(exc), category="config") from exc
|
raise BuildError(str(exc), category="config") from exc
|
||||||
(build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8")
|
(build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8")
|
||||||
@@ -682,13 +846,34 @@ async def patch_project(task_id: str, task, config_data: dict, build_dir: Path):
|
|||||||
await log_streamer.emit(task_id, "项目配置替换完成")
|
await log_streamer.emit(task_id, "项目配置替换完成")
|
||||||
|
|
||||||
|
|
||||||
async def run_pod_install(task_id: str, build_dir: Path):
|
def _pod_dir(build_dir: Path, xcode: dict = None) -> Path:
|
||||||
|
"""Podfile 所在目录:工程在仓库子目录时(如 sub/App.xcworkspace),优先取该子目录。"""
|
||||||
|
candidates = []
|
||||||
|
for key in ("workspace", "project"):
|
||||||
|
rel = ((xcode or {}).get(key) or "").strip()
|
||||||
|
if rel:
|
||||||
|
candidates.append(build_dir / Path(rel).parent)
|
||||||
|
candidates.append(build_dir)
|
||||||
|
for directory in candidates:
|
||||||
|
if (directory / "Podfile").is_file() or (directory / "podfile").is_file():
|
||||||
|
return directory
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||||
"""安装 CocoaPods 依赖"""
|
"""安装 CocoaPods 依赖"""
|
||||||
await log_streamer.emit_step(task_id, "安装依赖")
|
await log_streamer.emit_step(task_id, "安装依赖")
|
||||||
|
|
||||||
|
pod_dir = _pod_dir(build_dir, xcode)
|
||||||
|
if pod_dir is None:
|
||||||
|
await log_streamer.emit(task_id, "项目未使用 CocoaPods,跳过")
|
||||||
|
return
|
||||||
|
if pod_dir != build_dir:
|
||||||
|
await log_streamer.emit(task_id, f"Podfile 目录: {pod_dir.relative_to(build_dir)}")
|
||||||
|
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
"pod", "install",
|
"pod", "install",
|
||||||
cwd=str(build_dir),
|
cwd=str(pod_dir),
|
||||||
stdout=asyncio.subprocess.PIPE,
|
stdout=asyncio.subprocess.PIPE,
|
||||||
stderr=asyncio.subprocess.STDOUT,
|
stderr=asyncio.subprocess.STDOUT,
|
||||||
)
|
)
|
||||||
@@ -703,7 +888,7 @@ async def run_pod_install(task_id: str, build_dir: Path):
|
|||||||
if process.returncode != 0:
|
if process.returncode != 0:
|
||||||
raise BuildError("pod install 失败", category="config")
|
raise BuildError("pod install 失败", category="config")
|
||||||
|
|
||||||
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, build_dir)
|
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, pod_dir)
|
||||||
if patched_files:
|
if patched_files:
|
||||||
await log_streamer.emit(
|
await log_streamer.emit(
|
||||||
task_id,
|
task_id,
|
||||||
@@ -765,14 +950,21 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
|||||||
await log_streamer.emit(task_id, "代码混淆完成")
|
await log_streamer.emit(task_id, "代码混淆完成")
|
||||||
|
|
||||||
|
|
||||||
async def build_project(task_id: str, task, config_data: dict, build_dir: Path) -> Path:
|
async def build_project(task_id: str, task, config_data: dict, build_dir: Path, xcode: dict = None) -> Path:
|
||||||
"""构建项目"""
|
"""构建项目;xcode 为项目定义中的 {workspace, project},优先使用 workspace"""
|
||||||
await log_streamer.emit_step(task_id, "构建项目")
|
await log_streamer.emit_step(task_id, "构建项目")
|
||||||
|
|
||||||
scheme = config_data.get("SCHEME", "")
|
scheme = config_data.get("SCHEME", "")
|
||||||
export_path = build_dir / "build"
|
export_path = build_dir / "build"
|
||||||
archive_path = export_path / f"{scheme}.xcarchive"
|
archive_path = export_path / f"{scheme}.xcarchive"
|
||||||
workspace_path = build_dir / "readoor.xcworkspace"
|
if xcode is None:
|
||||||
|
xcode = get_definition(LEGACY_PROJECT_ID, {})["xcode"]
|
||||||
|
if xcode.get("workspace"):
|
||||||
|
container_args = ("-workspace", xcode["workspace"])
|
||||||
|
elif xcode.get("project"):
|
||||||
|
container_args = ("-project", xcode["project"])
|
||||||
|
else:
|
||||||
|
raise BuildError("项目未配置 Xcode workspace 或 project", category="config")
|
||||||
|
|
||||||
export_path.mkdir(parents=True, exist_ok=True)
|
export_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
@@ -780,7 +972,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
|||||||
await log_streamer.emit(task_id, "清理项目...")
|
await log_streamer.emit(task_id, "清理项目...")
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
"xcodebuild", "clean",
|
"xcodebuild", "clean",
|
||||||
"-workspace", workspace_path.name,
|
*container_args,
|
||||||
"-scheme", scheme,
|
"-scheme", scheme,
|
||||||
"-configuration", "Release",
|
"-configuration", "Release",
|
||||||
"-derivedDataPath", str(export_path / "derived_data"),
|
"-derivedDataPath", str(export_path / "derived_data"),
|
||||||
@@ -799,7 +991,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
|||||||
archive_output = []
|
archive_output = []
|
||||||
process = await asyncio.create_subprocess_exec(
|
process = await asyncio.create_subprocess_exec(
|
||||||
"xcodebuild", "archive",
|
"xcodebuild", "archive",
|
||||||
"-workspace", workspace_path.name,
|
*container_args,
|
||||||
"-scheme", scheme,
|
"-scheme", scheme,
|
||||||
"-configuration", "Release",
|
"-configuration", "Release",
|
||||||
"-archivePath", str(archive_path),
|
"-archivePath", str(archive_path),
|
||||||
@@ -854,15 +1046,22 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
|||||||
return ipa_path
|
return ipa_path
|
||||||
|
|
||||||
|
|
||||||
async def find_dsym(task_id: str, build_dir: Path) -> Path:
|
async def find_dsym(task_id: str, build_dir: Path, scheme: str = "") -> Path:
|
||||||
"""查找 dSYM 文件"""
|
"""查找当前 target(主 App)对应的 dSYM 文件,忽略 Extension/Framework 各自的 dSYM"""
|
||||||
derived_data = build_dir / "build" / "derived_data"
|
derived_data = build_dir / "build" / "derived_data"
|
||||||
if not derived_data.exists():
|
if not derived_data.exists():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
for dsym in derived_data.rglob("*.dSYM"):
|
dsyms = list(derived_data.rglob("*.dSYM"))
|
||||||
return dsym
|
if not dsyms:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
if scheme:
|
||||||
|
for dsym in dsyms:
|
||||||
|
if dsym.name == f"{scheme}.app.dSYM":
|
||||||
|
return dsym
|
||||||
|
|
||||||
|
return dsyms[0]
|
||||||
|
|
||||||
|
|
||||||
async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, build_dir: Path) -> tuple:
|
async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, build_dir: Path) -> tuple:
|
||||||
@@ -870,11 +1069,20 @@ async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, buil
|
|||||||
await log_streamer.emit_step(task_id, "上传分发平台")
|
await log_streamer.emit_step(task_id, "上传分发平台")
|
||||||
|
|
||||||
# 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。
|
# 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。
|
||||||
from ..routers.config import load_config
|
from ..routers.config import load_upload_config
|
||||||
full_config = load_config()
|
config_data["_upload_config"] = load_upload_config()
|
||||||
config_data["_upload_config"] = full_config.get("upload", {})
|
|
||||||
try:
|
try:
|
||||||
await log_streamer.emit(task_id, f"使用 {config_data['_upload_config'].get('mode', '')} 发布 IPA...")
|
await log_streamer.emit(task_id, f"使用 {config_data['_upload_config'].get('mode', '')} 发布 IPA...")
|
||||||
return await asyncio.to_thread(publish_ipa, config_data, ipa_path, build_dir)
|
return await asyncio.to_thread(publish_ipa, config_data, ipa_path, build_dir)
|
||||||
except DistributionError as exc:
|
except DistributionError as exc:
|
||||||
raise BuildError(str(exc), category="upload") from exc
|
raise BuildError(str(exc), category="upload") from exc
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_dsym(task_id: str, task, config_data: dict, dsym_path: Path, build_dir: Path) -> str:
|
||||||
|
"""上传 dSYM,返回下载 URL;上传失败仅记录警告,不影响已完成的打包结果"""
|
||||||
|
await log_streamer.emit_step(task_id, "上传 dSYM")
|
||||||
|
try:
|
||||||
|
return await asyncio.to_thread(publish_dsym, config_data, dsym_path, build_dir)
|
||||||
|
except DistributionError as exc:
|
||||||
|
await log_streamer.emit(task_id, f"dSYM 上传失败: {exc}", level="warn")
|
||||||
|
return ""
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ import plistlib
|
|||||||
import posixpath
|
import posixpath
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
from html import escape
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.parse import quote, unquote, urlparse
|
from urllib.parse import quote, unquote, urlparse
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
|
from ..config import DOWNLOAD_URL_EXPIRE_SECONDS
|
||||||
|
|
||||||
|
|
||||||
class DistributionError(Exception):
|
class DistributionError(Exception):
|
||||||
"""分发配置或上传过程失败。"""
|
"""分发配置或上传过程失败。"""
|
||||||
@@ -52,18 +55,149 @@ def _write_manifest(config: dict, manifest: Path, ipa_url: str):
|
|||||||
plistlib.dump(data, f)
|
plistlib.dump(data, f)
|
||||||
|
|
||||||
|
|
||||||
|
DOWNLOAD_PAGE_TEMPLATE = """<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="format-detection" content="telephone=no">
|
||||||
|
<title>{title} - 安装</title>
|
||||||
|
<style>
|
||||||
|
:root {{
|
||||||
|
--bg: #f2f3f7;
|
||||||
|
--card: #ffffff;
|
||||||
|
--text: #1c1c1e;
|
||||||
|
--muted: #8a8a8e;
|
||||||
|
--line: rgba(60, 60, 67, .12);
|
||||||
|
--brand: #50a0ff;
|
||||||
|
}}
|
||||||
|
@media (prefers-color-scheme: dark) {{
|
||||||
|
:root {{
|
||||||
|
--bg: #000000;
|
||||||
|
--card: #1c1c1e;
|
||||||
|
--text: #f5f5f7;
|
||||||
|
--muted: #98989d;
|
||||||
|
--line: rgba(255, 255, 255, .12);
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
* {{ box-sizing: border-box; }}
|
||||||
|
body {{
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 10vh 20px calc(32px + env(safe-area-inset-bottom));
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: flex-start;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font: 16px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", Arial, sans-serif;
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
}}
|
||||||
|
.card {{
|
||||||
|
width: 100%;
|
||||||
|
max-width: 420px;
|
||||||
|
background: var(--card);
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 28px 24px 24px;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, .08);
|
||||||
|
text-align: center;
|
||||||
|
}}
|
||||||
|
.name {{
|
||||||
|
margin: 0;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
word-break: break-word;
|
||||||
|
}}
|
||||||
|
.version {{
|
||||||
|
margin: 6px 0 22px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 15px;
|
||||||
|
}}
|
||||||
|
.install {{
|
||||||
|
display: block;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: var(--brand);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: none;
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
}}
|
||||||
|
.install:active {{ opacity: .75; }}
|
||||||
|
.meta {{
|
||||||
|
margin: 22px 0 0;
|
||||||
|
padding-top: 16px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
text-align: left;
|
||||||
|
font-size: 14px;
|
||||||
|
}}
|
||||||
|
.meta div {{
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 5px 0;
|
||||||
|
}}
|
||||||
|
.meta dt {{ color: var(--muted); flex: none; }}
|
||||||
|
.meta dd {{
|
||||||
|
margin: 0;
|
||||||
|
text-align: right;
|
||||||
|
word-break: break-all;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}}
|
||||||
|
.tips {{
|
||||||
|
margin: 18px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.7;
|
||||||
|
text-align: left;
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="card">
|
||||||
|
<h1 class="name">{title}</h1>
|
||||||
|
<p class="version">版本 {version}</p>
|
||||||
|
<a class="install" href="{install_url}">安装 App</a>
|
||||||
|
<dl class="meta">{meta}</dl>
|
||||||
|
<p class="tips">请使用 iPhone 自带的 Safari 浏览器打开本页面安装。<br>
|
||||||
|
安装后如提示“未受信任的开发者”,请前往「设置 → 通用 → VPN 与设备管理」信任该描述文件。</p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _write_download_page(config: dict, html: Path, manifest_url: str):
|
def _write_download_page(config: dict, html: Path, manifest_url: str):
|
||||||
install_url = f"itms-services://?action=download-manifest&url={quote(manifest_url, safe=':/?=&') }"
|
install_url = f"itms-services://?action=download-manifest&url={quote(manifest_url, safe=':/?=&')}"
|
||||||
title = config.get("APPID_NAME", "iOS App")
|
title = config.get("APPID_NAME") or "iOS App"
|
||||||
|
meta_items = [
|
||||||
|
("构建版本", config.get("BUILD_VERSION", "")),
|
||||||
|
("Bundle ID", config.get("BUNDLE_ID", "")),
|
||||||
|
("Tag" if config.get("SOURCE_REF_TYPE") == "tag" else "分支", config.get("SOURCE_BRANCH", "")),
|
||||||
|
]
|
||||||
|
meta = "".join(
|
||||||
|
f"<div><dt>{escape(label)}</dt><dd>{escape(str(value))}</dd></div>"
|
||||||
|
for label, value in meta_items
|
||||||
|
if value
|
||||||
|
)
|
||||||
html.write_text(
|
html.write_text(
|
||||||
"<!doctype html><html lang=\"zh-CN\"><meta charset=\"utf-8\">"
|
DOWNLOAD_PAGE_TEMPLATE.format(
|
||||||
f"<title>{title}</title><body><h2>{title}</h2>"
|
title=escape(title),
|
||||||
f"<p>版本 {config.get('VERSION', '')}</p><a href=\"{install_url}\">安装 App</a>"
|
version=escape(str(config.get("VERSION", ""))),
|
||||||
"</body></html>",
|
install_url=escape(install_url, quote=True),
|
||||||
|
meta=meta,
|
||||||
|
),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _dsym_remote_path(config: dict) -> str:
|
||||||
|
stem = _artifact_stem(config)
|
||||||
|
folder = config.get("OSS_FLODER", "ios-builds").strip("/") or "ios-builds"
|
||||||
|
return posixpath.join(folder, "iOS", f"{stem}.dSYM.zip")
|
||||||
|
|
||||||
|
|
||||||
def _remote_paths(config: dict) -> tuple[str, str, str, str]:
|
def _remote_paths(config: dict) -> tuple[str, str, str, str]:
|
||||||
stem = _artifact_stem(config)
|
stem = _artifact_stem(config)
|
||||||
folder = config.get("OSS_FLODER", "ios-builds").strip("/") or "ios-builds"
|
folder = config.get("OSS_FLODER", "ios-builds").strip("/") or "ios-builds"
|
||||||
@@ -82,12 +216,10 @@ def _delete_webdav(config: dict, remote_paths: list[str]):
|
|||||||
if not server_url or not webdav.get("username"):
|
if not server_url or not webdav.get("username"):
|
||||||
raise DistributionError("WebDAV 配置不完整")
|
raise DistributionError("WebDAV 配置不完整")
|
||||||
|
|
||||||
base_path = webdav.get("base_path", "/ios-builds").strip("/")
|
|
||||||
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
||||||
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
||||||
for relative_path in remote_paths:
|
for relative_path in remote_paths:
|
||||||
remote_path = posixpath.join(base_path, relative_path)
|
response = client.delete(f"{server_url}/{quote(relative_path, safe='/')}")
|
||||||
response = client.delete(f"{server_url}/{remote_path}")
|
|
||||||
# 404 代表文件已不存在,可视为清理完成。
|
# 404 代表文件已不存在,可视为清理完成。
|
||||||
if response.status_code not in (200, 202, 204, 404):
|
if response.status_code not in (200, 202, 204, 404):
|
||||||
raise DistributionError(f"WebDAV 删除失败: {relative_path} ({response.status_code})")
|
raise DistributionError(f"WebDAV 删除失败: {relative_path} ({response.status_code})")
|
||||||
@@ -124,15 +256,37 @@ def _remote_paths_from_published_url(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
remote_path = unquote(parsed.path).lstrip("/")
|
remote_path = unquote(parsed.path).lstrip("/")
|
||||||
# base_url 允许带路径前缀;该前缀是公开地址的一部分,不属于 OSS 对象键。
|
if any(segment == ".." for segment in remote_path.split("/")):
|
||||||
base_url = upload_config.get("oss", {}).get("base_url", "")
|
return None
|
||||||
|
# 公开地址允许带路径前缀;该前缀是下载路由的一部分,不属于远端文件路径。
|
||||||
|
mode = upload_config.get("mode")
|
||||||
|
if mode == "webdav":
|
||||||
|
webdav = upload_config.get("webdav", {})
|
||||||
|
base_url = webdav.get("public_url", "")
|
||||||
|
else:
|
||||||
|
base_url = upload_config.get("oss", {}).get("base_url", "")
|
||||||
base = urlparse(base_url)
|
base = urlparse(base_url)
|
||||||
if base_url and base.netloc == parsed.netloc:
|
if base_url and base.netloc == parsed.netloc:
|
||||||
base_path = unquote(base.path).strip("/")
|
base_path = unquote(base.path).strip("/")
|
||||||
if base_path and remote_path.startswith(f"{base_path}/"):
|
if base_path and remote_path.startswith(f"{base_path}/"):
|
||||||
remote_path = remote_path[len(base_path) + 1:]
|
remote_path = remote_path[len(base_path) + 1:]
|
||||||
|
|
||||||
|
# Historical WebDAV links may contain the configured directory twice, e.g.
|
||||||
|
# public_url=/iOS plus base_path=/iOS produced /iOS/iOS/file. If public_url
|
||||||
|
# was later corrected to the site root, the current prefix stripping above
|
||||||
|
# cannot remove the old extra segment. Files were still uploaded only once
|
||||||
|
# under base_path, so collapse that duplicated prefix when recovering the
|
||||||
|
# remote path for deletion.
|
||||||
|
if mode == "webdav":
|
||||||
|
configured_path = str(webdav.get("base_path") or "/").strip("/")
|
||||||
|
if configured_path:
|
||||||
|
duplicated_prefix = f"{configured_path}/{configured_path}/"
|
||||||
|
if remote_path.startswith(duplicated_prefix):
|
||||||
|
remote_path = remote_path[len(configured_path) + 1:]
|
||||||
|
|
||||||
path = Path(remote_path)
|
path = Path(remote_path)
|
||||||
|
if path.suffix == ".zip":
|
||||||
|
return [str(path)]
|
||||||
if path.suffix not in {".ipa", ".plist", ".html", ".png"}:
|
if path.suffix not in {".ipa", ".plist", ".html", ".png"}:
|
||||||
return None
|
return None
|
||||||
if build_config.get("BUILD_TYPE") == "App_Store":
|
if build_config.get("BUILD_TYPE") == "App_Store":
|
||||||
@@ -153,29 +307,105 @@ def delete_published_artifacts(
|
|||||||
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||||
|
|
||||||
remote_paths = None
|
remote_paths = None
|
||||||
if mode == "oss" and published_url:
|
if published_url:
|
||||||
remote_paths = _remote_paths_from_published_url(
|
remote_paths = _remote_paths_from_published_url(
|
||||||
build_config, upload_config, published_url,
|
build_config, upload_config, published_url,
|
||||||
)
|
)
|
||||||
if not remote_paths:
|
if not remote_paths:
|
||||||
ipa_remote, manifest_remote, html_remote, qr_remote = _remote_paths(build_config)
|
ipa_remote, manifest_remote, html_remote, qr_remote = _remote_paths(build_config)
|
||||||
remote_paths = [ipa_remote]
|
paths = [ipa_remote]
|
||||||
if build_config.get("BUILD_TYPE") != "App_Store":
|
if build_config.get("BUILD_TYPE") != "App_Store":
|
||||||
remote_paths.extend([manifest_remote, html_remote, qr_remote])
|
paths.extend([manifest_remote, html_remote, qr_remote])
|
||||||
|
if mode == "webdav":
|
||||||
|
remote_paths = [_webdav_remote_path(upload_config, Path(path).name) for path in paths]
|
||||||
|
else:
|
||||||
|
remote_paths = paths
|
||||||
|
|
||||||
deleter = _delete_oss if mode == "oss" else _delete_webdav
|
deleter = _delete_oss if mode == "oss" else _delete_webdav
|
||||||
deleter(upload_config, remote_paths)
|
deleter(upload_config, remote_paths)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_published_dsym(build_config: dict, upload_config: dict, published_url: str = ""):
|
||||||
|
"""删除任务对应的远端 dSYM 压缩包。
|
||||||
|
|
||||||
|
dSYM 的远端对象键完全由构建配置(APPID/版本/分支/构建类型)决定,
|
||||||
|
无需像 IPA 那样从已保存的下载链接反推,直接按命名规则删除即可。
|
||||||
|
"""
|
||||||
|
mode = upload_config.get("mode", "")
|
||||||
|
if mode not in {"oss", "webdav"}:
|
||||||
|
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||||
|
|
||||||
|
remote_paths = _remote_paths_from_published_url(build_config, upload_config, published_url) if published_url else None
|
||||||
|
if not remote_paths:
|
||||||
|
remote_path = _dsym_remote_path(build_config)
|
||||||
|
if mode == "webdav":
|
||||||
|
remote_path = _webdav_remote_path(upload_config, Path(remote_path).name)
|
||||||
|
remote_paths = [remote_path]
|
||||||
|
|
||||||
|
deleter = _delete_oss if mode == "oss" else _delete_webdav
|
||||||
|
deleter(upload_config, remote_paths)
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_oss_url(upload_config: dict, remote_path: str) -> str:
|
||||||
|
oss = upload_config.get("oss", {})
|
||||||
|
required = ["access_key_id", "access_key_secret", "endpoint", "bucket_name"]
|
||||||
|
if any(not oss.get(key) for key in required):
|
||||||
|
raise DistributionError("OSS 配置不完整")
|
||||||
|
try:
|
||||||
|
import oss2
|
||||||
|
except ImportError as exc:
|
||||||
|
raise DistributionError("未安装 oss2,请重新执行 ./deploy.sh build") from exc
|
||||||
|
|
||||||
|
bucket = oss2.Bucket(
|
||||||
|
oss2.Auth(oss["access_key_id"], oss["access_key_secret"]),
|
||||||
|
oss["endpoint"], oss["bucket_name"], connect_timeout=30,
|
||||||
|
)
|
||||||
|
return bucket.sign_url("GET", remote_path, DOWNLOAD_URL_EXPIRE_SECONDS, slash_safe=True)
|
||||||
|
|
||||||
|
|
||||||
|
def get_published_download_url(build_config: dict, upload_config: dict, published_url: str) -> str:
|
||||||
|
"""返回用于受控下载的短时链接;WebDAV 保持原公开链接。"""
|
||||||
|
if upload_config.get("mode") != "oss":
|
||||||
|
return published_url
|
||||||
|
|
||||||
|
remote_paths = _remote_paths_from_published_url(build_config, upload_config, published_url)
|
||||||
|
if not remote_paths:
|
||||||
|
raise DistributionError("无法识别 OSS 文件路径,无法生成受控下载链接")
|
||||||
|
return _sign_oss_url(upload_config, remote_paths[0])
|
||||||
|
|
||||||
|
|
||||||
|
def get_published_dsym_url(build_config: dict, upload_config: dict, dsym_url: str) -> str:
|
||||||
|
"""返回 dSYM 受控下载的短时链接;WebDAV 保持原公开链接。
|
||||||
|
|
||||||
|
dSYM 的远端对象键完全由构建配置决定,直接按命名规则重新计算即可,
|
||||||
|
不需要像 IPA 那样从已保存的下载链接反推。
|
||||||
|
"""
|
||||||
|
if upload_config.get("mode") != "oss":
|
||||||
|
return dsym_url
|
||||||
|
return _sign_oss_url(upload_config, _dsym_remote_path(build_config))
|
||||||
|
|
||||||
|
|
||||||
def _ensure_webdav_dirs(client: httpx.Client, server_url: str, remote_path: str):
|
def _ensure_webdav_dirs(client: httpx.Client, server_url: str, remote_path: str):
|
||||||
path = ""
|
path = ""
|
||||||
for segment in remote_path.strip("/").split("/")[:-1]:
|
for segment in remote_path.strip("/").split("/")[:-1]:
|
||||||
path = f"{path}/{segment}"
|
path = f"{path}/{segment}"
|
||||||
response = client.request("MKCOL", f"{server_url.rstrip('/')}{path}")
|
response = client.request("MKCOL", f"{server_url.rstrip('/')}{path}/")
|
||||||
if response.status_code not in (200, 201, 204, 301, 405):
|
if response.status_code not in (200, 201, 204, 301, 405):
|
||||||
raise DistributionError(f"创建 WebDAV 目录失败: {path} ({response.status_code})")
|
raise DistributionError(f"创建 WebDAV 目录失败: {path} ({response.status_code})")
|
||||||
|
|
||||||
|
|
||||||
|
def _webdav_remote_path(upload_config: dict, filename: str) -> str:
|
||||||
|
"""Return the exact WebDAV destination path configured in the admin UI."""
|
||||||
|
webdav = upload_config.get("webdav", {})
|
||||||
|
base_path = str(webdav.get("base_path") or "/").strip("/")
|
||||||
|
if any(segment in {".", ".."} for segment in base_path.split("/")):
|
||||||
|
raise DistributionError("WebDAV 远程路径不能包含 . 或 ..")
|
||||||
|
filename = Path(filename).name
|
||||||
|
if not filename or filename in {".", ".."}:
|
||||||
|
raise DistributionError("WebDAV 文件名无效")
|
||||||
|
return posixpath.join(base_path, filename) if base_path else filename
|
||||||
|
|
||||||
|
|
||||||
def _upload_webdav(config: dict, files: list[tuple[Path, str]]) -> dict[str, str]:
|
def _upload_webdav(config: dict, files: list[tuple[Path, str]]) -> dict[str, str]:
|
||||||
webdav = config.get("webdav", {})
|
webdav = config.get("webdav", {})
|
||||||
server_url = webdav.get("server_url", "").rstrip("/")
|
server_url = webdav.get("server_url", "").rstrip("/")
|
||||||
@@ -183,18 +413,18 @@ def _upload_webdav(config: dict, files: list[tuple[Path, str]]) -> dict[str, str
|
|||||||
if not server_url or not webdav.get("username"):
|
if not server_url or not webdav.get("username"):
|
||||||
raise DistributionError("WebDAV 配置不完整")
|
raise DistributionError("WebDAV 配置不完整")
|
||||||
|
|
||||||
base_path = webdav.get("base_path", "/ios-builds").strip("/")
|
|
||||||
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
||||||
urls = {}
|
urls = {}
|
||||||
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
||||||
for local_path, relative_path in files:
|
for local_path, _relative_path in files:
|
||||||
remote_path = posixpath.join(base_path, relative_path)
|
# WebDAV 的远程路径由后台配置;不沿用 OSS 的 ios-builds/iOS 对象键。
|
||||||
|
remote_path = _webdav_remote_path(config, local_path.name)
|
||||||
_ensure_webdav_dirs(client, server_url, remote_path)
|
_ensure_webdav_dirs(client, server_url, remote_path)
|
||||||
with local_path.open("rb") as f:
|
with local_path.open("rb") as f:
|
||||||
response = client.put(f"{server_url}/{remote_path}", content=f.read())
|
response = client.put(f"{server_url}/{quote(remote_path, safe='/')}", content=f.read())
|
||||||
if response.status_code not in (200, 201, 204):
|
if response.status_code not in (200, 201, 204):
|
||||||
raise DistributionError(f"WebDAV 上传失败: {local_path.name} ({response.status_code})")
|
raise DistributionError(f"WebDAV 上传失败: {local_path.name} ({response.status_code})")
|
||||||
urls[local_path.suffix] = f"{public_url}/{quote(remote_path)}"
|
urls[local_path.suffix] = f"{public_url}/{quote(remote_path, safe='/')}"
|
||||||
return urls
|
return urls
|
||||||
|
|
||||||
|
|
||||||
@@ -224,6 +454,22 @@ def _upload_oss(config: dict, files: list[tuple[Path, str]]) -> dict[str, str]:
|
|||||||
return urls
|
return urls
|
||||||
|
|
||||||
|
|
||||||
|
# 桌面端钉钉会把 Markdown 图片裁成约 1.4:1 的横向区域,正方形二维码上下被裁掉
|
||||||
|
# (手机端完整显示)。居中放到 3:2 的白底画布上:桌面端裁掉的只是空白,
|
||||||
|
# 手机端二维码仍占图片宽度的 2/3,不至于太小。
|
||||||
|
_QR_CANVAS_RATIO = 1.5
|
||||||
|
|
||||||
|
|
||||||
|
def _pad_to_wide(image):
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
image = image.convert("RGB")
|
||||||
|
width, height = image.size
|
||||||
|
canvas = Image.new("RGB", (round(height * _QR_CANVAS_RATIO), height), "white")
|
||||||
|
canvas.paste(image, ((canvas.width - width) // 2, 0))
|
||||||
|
return canvas
|
||||||
|
|
||||||
|
|
||||||
def publish_ipa(config: dict, ipa_path: Path, build_dir: Path) -> tuple[str, str]:
|
def publish_ipa(config: dict, ipa_path: Path, build_dir: Path) -> tuple[str, str]:
|
||||||
"""发布 IPA,返回下载 URL 与二维码公开 URL。"""
|
"""发布 IPA,返回下载 URL 与二维码公开 URL。"""
|
||||||
upload = config.get("_upload_config", {})
|
upload = config.get("_upload_config", {})
|
||||||
@@ -254,6 +500,28 @@ def publish_ipa(config: dict, ipa_path: Path, build_dir: Path) -> tuple[str, str
|
|||||||
import qrcode
|
import qrcode
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
raise DistributionError("未安装 qrcode,请重新执行 ./deploy.sh build") from exc
|
raise DistributionError("未安装 qrcode,请重新执行 ./deploy.sh build") from exc
|
||||||
qrcode.make(urls[".html"]).save(qr_path)
|
qr = qrcode.QRCode(box_size=5, border=4)
|
||||||
|
qr.add_data(urls[".html"])
|
||||||
|
qr.make(fit=True)
|
||||||
|
_pad_to_wide(qr.make_image(fill_color="black", back_color="white").get_image()).save(qr_path)
|
||||||
urls.update(uploader(upload, [(qr_path, qr_remote)]))
|
urls.update(uploader(upload, [(qr_path, qr_remote)]))
|
||||||
return urls[".html"], urls[".png"]
|
return urls[".html"], urls[".png"]
|
||||||
|
|
||||||
|
|
||||||
|
def publish_dsym(config: dict, dsym_path: Path, build_dir: Path) -> str:
|
||||||
|
"""压缩并上传主 target 的 dSYM,返回下载 URL。"""
|
||||||
|
upload = config.get("_upload_config", {})
|
||||||
|
mode = upload.get("mode", "")
|
||||||
|
if mode not in {"oss", "webdav"}:
|
||||||
|
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||||
|
|
||||||
|
output_dir = build_dir / "distribution"
|
||||||
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
zip_base = output_dir / f"{_artifact_stem(config)}.dSYM"
|
||||||
|
zip_path = Path(shutil.make_archive(
|
||||||
|
str(zip_base), "zip", root_dir=str(dsym_path.parent), base_dir=dsym_path.name,
|
||||||
|
))
|
||||||
|
|
||||||
|
uploader = _upload_oss if mode == "oss" else _upload_webdav
|
||||||
|
urls = uploader(upload, [(zip_path, _dsym_remote_path(config))])
|
||||||
|
return urls[".zip"]
|
||||||
|
|||||||
@@ -27,23 +27,66 @@ def _signed_webhook_url(webhook_url: str, secret: str) -> str:
|
|||||||
return f"{webhook_url}{separator}timestamp={timestamp}&sign={quote(base64.b64encode(signature))}"
|
return f"{webhook_url}{separator}timestamp={timestamp}&sign={quote(base64.b64encode(signature))}"
|
||||||
|
|
||||||
|
|
||||||
def build_dingtalk_payload(config_data: dict, download_url: str, qr_code_url: str = "") -> dict:
|
def normalize_mobiles(at_mobiles) -> list:
|
||||||
|
"""把手机号配置统一成去重、去空的字符串列表,兼容列表或逗号/换行分隔的字符串。"""
|
||||||
|
if not at_mobiles:
|
||||||
|
return []
|
||||||
|
if isinstance(at_mobiles, str):
|
||||||
|
raw = at_mobiles.replace("\n", ",").replace(",", ",").replace(" ", ",").split(",")
|
||||||
|
else:
|
||||||
|
raw = at_mobiles
|
||||||
|
seen = []
|
||||||
|
for item in raw:
|
||||||
|
mobile = str(item).strip()
|
||||||
|
if mobile and mobile not in seen:
|
||||||
|
seen.append(mobile)
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
# Ad_Hoc / App_Store 两份 @ 名单在配置中的键名
|
||||||
|
AT_MOBILES_KEYS = ("at_mobiles", "at_mobiles_app_store")
|
||||||
|
|
||||||
|
|
||||||
|
def merge_project_at_mobiles(dingtalk_config: dict, project_at: dict) -> dict:
|
||||||
|
"""项目配置了 @ 名单时覆盖全局名单(按打包类型分别覆盖),为空则沿用全局名单。"""
|
||||||
|
merged = dict(dingtalk_config or {})
|
||||||
|
for key in AT_MOBILES_KEYS:
|
||||||
|
mobiles = normalize_mobiles((project_at or {}).get(key))
|
||||||
|
if mobiles:
|
||||||
|
merged[key] = mobiles
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def build_dingtalk_payload(
|
||||||
|
config_data: dict,
|
||||||
|
download_url: str,
|
||||||
|
qr_code_url: str = "",
|
||||||
|
at_mobiles=None,
|
||||||
|
) -> dict:
|
||||||
"""生成与 AutoPacking/upload_iap.py 一致的钉钉 Markdown 内容。"""
|
"""生成与 AutoPacking/upload_iap.py 一致的钉钉 Markdown 内容。"""
|
||||||
|
mobiles = normalize_mobiles(at_mobiles)
|
||||||
|
# App_Store 包与 Ad Hoc 用不同标题,App_Store 只有 IPA 下载地址、无二维码。
|
||||||
|
# 标题必须保留「打包」二字:钉钉机器人启用了自定义关键词,缺少关键词会被拒收。
|
||||||
|
heading = "【iOS】App_Store 打包信息" if config_data.get("BUILD_TYPE") == "App_Store" else "【iOS】打包信息"
|
||||||
details = (
|
details = (
|
||||||
f"**环境:** {config_data.get('SERVER', '')}\n\n"
|
f"**环境:** {config_data.get('SERVER', '')}\n\n"
|
||||||
f"**版本:** {config_data.get('VERSION', '')}\n\n"
|
f"**版本:** {config_data.get('VERSION', '')}\n\n"
|
||||||
f"**APP名称:** {config_data.get('APPID_NAME', '')}\n\n"
|
f"**APP名称:** {config_data.get('APPID_NAME', '')}\n\n"
|
||||||
f"**包名:** {config_data.get('BUNDLE_ID', '')}\n\n"
|
f"**包名:** {config_data.get('BUNDLE_ID', '')}\n\n"
|
||||||
f"**App Guid:** {config_data.get('APPID', '')}"
|
f"**{config_data.get('APPID_LABEL', 'App Guid')}:** {config_data.get('APPID', '')}"
|
||||||
)
|
)
|
||||||
text = f"## 【iOS】打包信息\n\n{details}\n\n**iOS 下载链接:** {download_url}\n"
|
text = f"## {heading}\n\n{details}\n\n**iOS 下载链接:** {download_url}\n"
|
||||||
if qr_code_url:
|
if qr_code_url:
|
||||||
text += f"\n"
|
text += f"\n"
|
||||||
|
# 钉钉 markdown 消息必须在正文内出现 @手机号 才会真正 @ 到人,
|
||||||
|
# 仅靠 at.atMobiles 不生效。
|
||||||
|
if mobiles:
|
||||||
|
text += "\n\n" + " ".join(f"@{m}" for m in mobiles)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"msgtype": "markdown",
|
"msgtype": "markdown",
|
||||||
"markdown": {"title": "iOS应用下载", "text": text},
|
"markdown": {"title": "iOS应用下载", "text": text},
|
||||||
"at": {"atMobiles": [], "isAtAll": False},
|
"at": {"atMobiles": mobiles, "isAtAll": False},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -61,8 +104,11 @@ def send_dingtalk_notification(
|
|||||||
if not webhook_url:
|
if not webhook_url:
|
||||||
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
|
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
|
||||||
|
|
||||||
payload = build_dingtalk_payload(config_data, download_url, qr_code_url)
|
# Ad_Hoc 与 App_Store 使用各自的 @ 名单。
|
||||||
payload["at"]["atMobiles"] = dingtalk_config.get("at_mobiles", [])
|
mobiles_key = "at_mobiles_app_store" if config_data.get("BUILD_TYPE") == "App_Store" else "at_mobiles"
|
||||||
|
payload = build_dingtalk_payload(
|
||||||
|
config_data, download_url, qr_code_url, dingtalk_config.get(mobiles_key, [])
|
||||||
|
)
|
||||||
response = httpx.post(
|
response = httpx.post(
|
||||||
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
|
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
|
||||||
json=payload,
|
json=payload,
|
||||||
|
|||||||
@@ -35,11 +35,15 @@ def _update_plist(path: Path, config: dict):
|
|||||||
|
|
||||||
plist["CFBundleDisplayName"] = config.get("APPID_NAME", "")
|
plist["CFBundleDisplayName"] = config.get("APPID_NAME", "")
|
||||||
plist["AlivcLicenseKey"] = config.get("AlivcLicenseKey", "") or ""
|
plist["AlivcLicenseKey"] = config.get("AlivcLicenseKey", "") or ""
|
||||||
|
|
||||||
scheme = (config.get("BUNDLE_ID", "") or "").replace(".", "").lower()
|
scheme = (config.get("BUNDLE_ID", "") or "").replace(".", "").lower()
|
||||||
values = {
|
values = {
|
||||||
"weixinlogin": config.get("weixinlogin", ""),
|
"weixinlogin": config.get("weixinlogin", ""),
|
||||||
"wechatpay": config.get("weixinpay", ""),
|
"wechatpay": config.get("weixinpay", ""),
|
||||||
"tencent": config.get("tencent", ""),
|
"tencent": config.get("tencent", ""),
|
||||||
|
# 企业微信 Schema 与微信登录 AppID 同样存在 CFBundleURLTypes 中
|
||||||
|
# (CFBundleURLName == "wxwork"),未配置则整条移除。
|
||||||
|
"wxwork": (config.get("wxworkSchema", "") or "").strip(),
|
||||||
"readoorUrlScheme": scheme,
|
"readoorUrlScheme": scheme,
|
||||||
}
|
}
|
||||||
url_types = []
|
url_types = []
|
||||||
@@ -68,6 +72,9 @@ def _apply_theme(build_dir: Path, theme_dir: str, messages: list[str]):
|
|||||||
for item in source.iterdir():
|
for item in source.iterdir():
|
||||||
if not item.is_dir():
|
if not item.is_dir():
|
||||||
continue
|
continue
|
||||||
|
# 跳过 macOS 压缩包内的 __MACOSX 及隐藏目录,仅复制真实皮肤资源
|
||||||
|
if item.name == "__MACOSX" or item.name.startswith("."):
|
||||||
|
continue
|
||||||
destination = target_assets / item.name
|
destination = target_assets / item.name
|
||||||
if destination.exists():
|
if destination.exists():
|
||||||
shutil.rmtree(destination)
|
shutil.rmtree(destination)
|
||||||
@@ -128,8 +135,14 @@ def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str])
|
|||||||
messages.append("已替换词典版本配置")
|
messages.append("已替换词典版本配置")
|
||||||
|
|
||||||
|
|
||||||
def apply_project_config(build_dir: Path, config: dict) -> list[str]:
|
def apply_project_config(build_dir: Path, config: dict, definition: dict = None) -> list[str]:
|
||||||
"""写入项目配置,返回适合实时日志展示的变更说明。"""
|
"""写入项目配置,返回适合实时日志展示的变更说明。
|
||||||
|
|
||||||
|
definition 为项目定义(见 backend/projects.py),未传或 patcher 为 readoor 时按 Readoor 工程处理。
|
||||||
|
"""
|
||||||
|
if definition and definition.get("patcher") != "readoor":
|
||||||
|
return apply_generic_config(build_dir, config, definition)
|
||||||
|
|
||||||
messages: list[str] = []
|
messages: list[str] = []
|
||||||
if config.get("SCHEME") == "readoorDict":
|
if config.get("SCHEME") == "readoorDict":
|
||||||
_apply_dictionary_config(build_dir, config, messages)
|
_apply_dictionary_config(build_dir, config, messages)
|
||||||
@@ -183,3 +196,135 @@ def apply_project_config(build_dir: Path, config: dict) -> list[str]:
|
|||||||
_write_export_options(build_dir, config)
|
_write_export_options(build_dir, config)
|
||||||
messages.append("工程、签名、版本和分发配置已更新")
|
messages.append("工程、签名、版本和分发配置已更新")
|
||||||
return messages
|
return messages
|
||||||
|
|
||||||
|
|
||||||
|
# —— 通用工程(patcher = generic)——
|
||||||
|
|
||||||
|
_TEMPLATE_PATTERN = re.compile(r"\$\{([A-Za-z0-9_.]+)\}")
|
||||||
|
_BUILD_SETTINGS_PATTERN = re.compile(r"buildSettings = \{\n(.*?)\n\t*\};", re.DOTALL)
|
||||||
|
_PLAIN_PBX_VALUE = re.compile(r"^[A-Za-z0-9_.$/-]+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _render_template(template: str, config: dict) -> str:
|
||||||
|
"""替换 ${app.X}、${server.X}、${KEY}:分别取 App 字段、服务器环境字段和打包配置;值为空时报错。"""
|
||||||
|
def _lookup(match):
|
||||||
|
name = match.group(1)
|
||||||
|
if name.startswith("app."):
|
||||||
|
value = config.get("APP_VARS", {}).get(name[4:], "")
|
||||||
|
elif name.startswith("server."):
|
||||||
|
value = config.get("SERVER_VARS", {}).get(name[7:], "")
|
||||||
|
else:
|
||||||
|
value = config.get(name, "")
|
||||||
|
if value is None or str(value) == "":
|
||||||
|
raise ProjectPatchError(f"替换规则引用的 {name} 未配置")
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
return _TEMPLATE_PATTERN.sub(_lookup, template)
|
||||||
|
|
||||||
|
|
||||||
|
def _pbx_value(value: str) -> str:
|
||||||
|
return value if _PLAIN_PBX_VALUE.match(value) else '"' + value.replace('"', '\\"') + '"'
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_pbxproj(path: Path, settings: dict) -> dict:
|
||||||
|
"""在 App 目标的 buildSettings 中替换设置(含 [sdk=iphoneos*] 变体),返回每个设置的替换次数。
|
||||||
|
|
||||||
|
测试目标(含 TEST_HOST / TEST_TARGET_NAME)有自己的 Bundle ID 和签名,跳过。
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
raise ProjectPatchError(f"工程文件不存在: {path.parent.name}/{path.name}")
|
||||||
|
counts = {key: 0 for key in settings}
|
||||||
|
|
||||||
|
def _patch_block(match):
|
||||||
|
block = match.group(1)
|
||||||
|
if "TEST_HOST" in block or "TEST_TARGET_NAME" in block:
|
||||||
|
return match.group(0)
|
||||||
|
for key, value in settings.items():
|
||||||
|
pattern = re.compile(
|
||||||
|
rf'^(\s*)("?{re.escape(key)}(?:\[sdk=iphoneos\*\])?"?) = .*;$', re.MULTILINE
|
||||||
|
)
|
||||||
|
block, n = pattern.subn(lambda m: f"{m.group(1)}{m.group(2)} = {_pbx_value(value)};", block)
|
||||||
|
counts[key] += n
|
||||||
|
return match.group(0).replace(match.group(1), block, 1)
|
||||||
|
|
||||||
|
content = _BUILD_SETTINGS_PATTERN.sub(_patch_block, path.read_text(encoding="utf-8"))
|
||||||
|
path.write_text(content, encoding="utf-8")
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_define_rule(path: Path, name: str, value: str) -> int:
|
||||||
|
"""替换所有未注释的 #define NAME ... 行(#if/#else 各分支中的同名宏都会被替换)。"""
|
||||||
|
pattern = re.compile(rf"^([ \t]*#define[ \t]+{re.escape(name)})(?:[ \t].*)?$", re.MULTILINE)
|
||||||
|
content, count = pattern.subn(lambda m: f"{m.group(1)} {value}", path.read_text(encoding="utf-8"))
|
||||||
|
path.write_text(content, encoding="utf-8")
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_rule_file(build_dir: Path, file: str) -> Path:
|
||||||
|
path = (build_dir / file).resolve()
|
||||||
|
if not file or not path.is_relative_to(build_dir.resolve()):
|
||||||
|
raise ProjectPatchError(f"替换规则文件路径无效: {file}")
|
||||||
|
if not path.is_file():
|
||||||
|
raise ProjectPatchError(f"替换规则文件不存在: {file}")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def apply_generic_config(build_dir: Path, config: dict, definition: dict) -> list[str]:
|
||||||
|
"""通用工程:替换 pbxproj 的版本号与签名、生成 exportOptions.plist,再执行项目的 patch_rules。
|
||||||
|
|
||||||
|
patch_rules 每项:
|
||||||
|
{"type": "define", "file": "相对路径", "name": "宏名", "value": "模板"}
|
||||||
|
替换所有未注释的 #define 宏名 行
|
||||||
|
{"type": "replace_line", "file": "相对路径", "keyword": "关键字", "line": "模板"}
|
||||||
|
整行替换包含关键字且未注释的行
|
||||||
|
模板中的 ${app.X} / ${server.X} / ${KEY} 取 App 字段、服务器环境字段、打包配置。
|
||||||
|
"""
|
||||||
|
messages: list[str] = []
|
||||||
|
xcodeproj = (definition.get("xcode") or {}).get("project", "")
|
||||||
|
if not xcodeproj:
|
||||||
|
raise ProjectPatchError("项目未配置 Xcode project(.xcodeproj)")
|
||||||
|
|
||||||
|
settings = {
|
||||||
|
"MARKETING_VERSION": config.get("VERSION", ""),
|
||||||
|
"CURRENT_PROJECT_VERSION": config.get("BUILD_VERSION", ""),
|
||||||
|
}
|
||||||
|
if config.get("BUNDLE_ID"):
|
||||||
|
settings["PRODUCT_BUNDLE_IDENTIFIER"] = config["BUNDLE_ID"]
|
||||||
|
if not config.get("NO_CERT"):
|
||||||
|
if config.get("TEAM_ID"):
|
||||||
|
settings["DEVELOPMENT_TEAM"] = config["TEAM_ID"]
|
||||||
|
if config.get("PROVISIONING_NAME"):
|
||||||
|
settings["PROVISIONING_PROFILE_SPECIFIER"] = config["PROVISIONING_NAME"]
|
||||||
|
settings["CODE_SIGN_STYLE"] = "Manual"
|
||||||
|
settings["CODE_SIGN_IDENTITY"] = "iPhone Distribution"
|
||||||
|
|
||||||
|
counts = _patch_pbxproj(build_dir / xcodeproj / "project.pbxproj", settings)
|
||||||
|
missing = [key for key in ("MARKETING_VERSION", "CURRENT_PROJECT_VERSION") if counts[key] == 0]
|
||||||
|
if missing:
|
||||||
|
raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}")
|
||||||
|
messages.append(
|
||||||
|
f"工程配置已更新: 版本 {settings['MARKETING_VERSION']} ({settings['CURRENT_PROJECT_VERSION']})"
|
||||||
|
+ (f",Bundle ID {settings['PRODUCT_BUNDLE_IDENTIFIER']}" if "PRODUCT_BUNDLE_IDENTIFIER" in settings else "")
|
||||||
|
)
|
||||||
|
|
||||||
|
for index, rule in enumerate(definition.get("patch_rules") or [], start=1):
|
||||||
|
rule_type = rule.get("type")
|
||||||
|
path = _resolve_rule_file(build_dir, rule.get("file", ""))
|
||||||
|
if rule_type == "define":
|
||||||
|
name = rule.get("name", "")
|
||||||
|
value = _render_template(rule.get("value", ""), config)
|
||||||
|
if _apply_define_rule(path, name, value) == 0:
|
||||||
|
raise ProjectPatchError(f"{rule['file']} 中未找到 #define {name}")
|
||||||
|
messages.append(f"{rule['file']}: #define {name} {value}")
|
||||||
|
elif rule_type == "replace_line":
|
||||||
|
keyword = rule.get("keyword", "")
|
||||||
|
line = _render_template(rule.get("line", ""), config)
|
||||||
|
if not keyword or _replace_lines(path, keyword, line) == 0:
|
||||||
|
raise ProjectPatchError(f"{rule['file']} 中未找到包含 {keyword} 的行")
|
||||||
|
messages.append(f"{rule['file']}: {line.strip()}")
|
||||||
|
else:
|
||||||
|
raise ProjectPatchError(f"第 {index} 条替换规则类型无效: {rule_type}")
|
||||||
|
|
||||||
|
_write_export_options(build_dir, config)
|
||||||
|
messages.append("签名和分发配置已更新")
|
||||||
|
return messages
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"1": {
|
||||||
|
"name": "示例应用",
|
||||||
|
"server": "测试环境",
|
||||||
|
"API": "https://api3-dev.example.com",
|
||||||
|
"AppGuid": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"AssDom": "applinks:dev-data1.example.com",
|
||||||
|
"UniversalLink": "https://dev-data1.example.com",
|
||||||
|
"upload_key": "example_app",
|
||||||
|
"tencent": "",
|
||||||
|
"weixinlogin": "",
|
||||||
|
"weixinpay": "",
|
||||||
|
"wxworkSchema": "",
|
||||||
|
"skins": ["default.zip"],
|
||||||
|
"certificates": {
|
||||||
|
"Ad_Hoc": {
|
||||||
|
"name": "com.example.app",
|
||||||
|
"cer": "证书名称或标识",
|
||||||
|
"pro": "描述文件名称",
|
||||||
|
"theme": "default"
|
||||||
|
},
|
||||||
|
"App_Store": {
|
||||||
|
"name": "com.example.app",
|
||||||
|
"cer": "证书名称或标识",
|
||||||
|
"pro": "描述文件名称",
|
||||||
|
"theme": "default"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"schemes": {
|
||||||
|
"1": { "name": "readoor31", "ossFloder": "readoor" }
|
||||||
|
},
|
||||||
|
"servers": {
|
||||||
|
"测试环境": {
|
||||||
|
"api": "https://api3-dev.example.com",
|
||||||
|
"assDom": "applinks:dev-data1.example.com",
|
||||||
|
"universalLink": "https://dev-data1.example.com",
|
||||||
|
"app_id_prefix": 1
|
||||||
|
},
|
||||||
|
"正式环境": {
|
||||||
|
"api": "https://api3.example.com",
|
||||||
|
"assDom": "applinks:data1.example.com",
|
||||||
|
"universalLink": "https://data1.example.com",
|
||||||
|
"app_id_prefix": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"next_app_id_prefix": 3,
|
||||||
|
"branches": ["master", "develop", "feature/示例分支"],
|
||||||
|
"upload": {
|
||||||
|
"mode": "webdav",
|
||||||
|
"oss": {
|
||||||
|
"access_key_id": "",
|
||||||
|
"access_key_secret": "",
|
||||||
|
"endpoint": "",
|
||||||
|
"bucket_name": "",
|
||||||
|
"base_url": ""
|
||||||
|
},
|
||||||
|
"webdav": {
|
||||||
|
"server_url": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"base_path": "",
|
||||||
|
"public_url": ""
|
||||||
|
},
|
||||||
|
"dingtalk": {
|
||||||
|
"enabled": false,
|
||||||
|
"webhook_url": "",
|
||||||
|
"secret": "",
|
||||||
|
"at_mobiles": [],
|
||||||
|
"at_mobiles_app_store": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"versions": {
|
||||||
|
"tracks": {
|
||||||
|
"release": { "kind": "release", "app_ver": "2.180.0", "build_map": {} },
|
||||||
|
"develop": { "kind": "release", "app_ver": "2.180.0", "build_map": {} },
|
||||||
|
"feature/示例分支": { "kind": "feature", "app_ver": "2.180.0", "build_map": {} }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"branch_track": {
|
||||||
|
"master": "release",
|
||||||
|
"develop": "develop",
|
||||||
|
"feature/示例分支": "feature/示例分支"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# iOS 自动打包服务 — 部署与管理脚本
|
# iOS 自动打包服务 — 部署与管理脚本
|
||||||
# 用法: ./deploy.sh {build|start|stop|restart|status|watchdog|watchdog-stop}
|
# 用法: ./deploy.sh {up|build|start|stop|restart|status|watchdog|watchdog-stop}
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
@@ -23,6 +23,11 @@ WATCHDOG_INTERVAL="${WATCHDOG_INTERVAL:-30}" # 健康检查间隔(秒)
|
|||||||
WATCHDOG_TIMEOUT="${WATCHDOG_TIMEOUT:-10}" # 健康检查超时(秒)
|
WATCHDOG_TIMEOUT="${WATCHDOG_TIMEOUT:-10}" # 健康检查超时(秒)
|
||||||
MAX_RESTART_ATTEMPTS="${MAX_RESTART_ATTEMPTS:-3}" # 连续重启上限,超过则冷却
|
MAX_RESTART_ATTEMPTS="${MAX_RESTART_ATTEMPTS:-3}" # 连续重启上限,超过则冷却
|
||||||
COOLDOWN_SECONDS="${COOLDOWN_SECONDS:-300}" # 冷却时间(秒)
|
COOLDOWN_SECONDS="${COOLDOWN_SECONDS:-300}" # 冷却时间(秒)
|
||||||
|
WATCHDOG_STARTUP_GRACE="${WATCHDOG_STARTUP_GRACE:-10}" # watchdog 首次检查前的宽限(秒),避开正常启动窗口
|
||||||
|
STARTUP_READY_TIMEOUT="${STARTUP_READY_TIMEOUT:-20}" # 启动后等待 /api/health 就绪的最长时间(秒)
|
||||||
|
# 重启方式:nohup(默认,PID 文件托管)| launchd(交回 launchctl kickstart 托管,避免与 KeepAlive 抢端口)
|
||||||
|
WATCHDOG_RESTART_MODE="${WATCHDOG_RESTART_MODE:-nohup}"
|
||||||
|
APP_LAUNCHD_LABEL="${APP_LAUNCHD_LABEL:-com.readoor.buildserver}"
|
||||||
|
|
||||||
# ========== 颜色输出 ==========
|
# ========== 颜色输出 ==========
|
||||||
RED='\033[0;31m'
|
RED='\033[0;31m'
|
||||||
@@ -64,6 +69,52 @@ get_server_pid() {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 返回占用目标端口、但命令不属于本项目的进程 PID(若有),用于区分“端口冲突”与“本服务在跑”。
|
||||||
|
foreign_port_holder() {
|
||||||
|
local pid
|
||||||
|
for pid in $(lsof -tiTCP:"$BACKEND_PORT" -sTCP:LISTEN 2>/dev/null); do
|
||||||
|
if ! is_server_process "$pid"; then
|
||||||
|
echo "$pid"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 启动 uvicorn 后端进程(单点维护启动参数,供 start / watchdog 复用),PID 写入 PID_FILE。
|
||||||
|
_spawn_server() {
|
||||||
|
setup_venv
|
||||||
|
mkdir -p "$LOG_DIR"
|
||||||
|
nohup "$VENV_DIR/bin/python3" -m uvicorn backend.main:app \
|
||||||
|
--host "$BIND_HOST" \
|
||||||
|
--port "$BACKEND_PORT" \
|
||||||
|
--proxy-headers \
|
||||||
|
--forwarded-allow-ips 127.0.0.1 \
|
||||||
|
--workers 1 \
|
||||||
|
>> "$LOG_DIR/server.log" 2>&1 &
|
||||||
|
echo $! > "$PID_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 轮询 /api/health 直到返回 200 或超时;就绪返回 0,否则返回 1。
|
||||||
|
# 健康检查固定走 127.0.0.1(与 check_health 一致),不受 BIND_HOST 影响。
|
||||||
|
_wait_ready() {
|
||||||
|
local timeout="${1:-$STARTUP_READY_TIMEOUT}"
|
||||||
|
local deadline=$(( $(date +%s) + timeout ))
|
||||||
|
while [ "$(date +%s)" -lt "$deadline" ]; do
|
||||||
|
# 进程若已退出则无需再等
|
||||||
|
if [ -f "$PID_FILE" ] && ! kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
local code
|
||||||
|
code=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||||
|
--connect-timeout 2 --max-time 3 \
|
||||||
|
"http://127.0.0.1:$BACKEND_PORT/api/health" 2>/dev/null || echo "000")
|
||||||
|
[ "$code" = "200" ] && return 0
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
# 日志同时写文件和终端
|
# 日志同时写文件和终端
|
||||||
log_to_file() {
|
log_to_file() {
|
||||||
local level="$1"; shift
|
local level="$1"; shift
|
||||||
@@ -143,11 +194,23 @@ do_build() {
|
|||||||
do_start() {
|
do_start() {
|
||||||
check_env
|
check_env
|
||||||
|
|
||||||
|
# 端口被非本项目进程占用:明确报错,避免 uvicorn 静默绑定失败。
|
||||||
|
local foreign
|
||||||
|
foreign=$(foreign_port_holder || true)
|
||||||
|
if [ -n "$foreign" ]; then
|
||||||
|
error "端口 $BACKEND_PORT 被非本项目进程占用 (PID: $foreign):"
|
||||||
|
ps -p "$foreign" -o pid,command= 2>/dev/null | sed 's/^/ /'
|
||||||
|
error "请先释放该端口,或在 .env 修改 BACKEND_PORT"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 本项目实例已在运行:强制重来(用户选定语义)。
|
||||||
|
# 注意:这会中断正在进行的打包任务。
|
||||||
local existing_pid
|
local existing_pid
|
||||||
existing_pid=$(get_server_pid || true)
|
existing_pid=$(get_server_pid || true)
|
||||||
if [ -n "$existing_pid" ]; then
|
if [ -n "$existing_pid" ]; then
|
||||||
warn "服务已在运行 (PID: $existing_pid)"
|
warn "检测到旧服务 (PID: $existing_pid),强制重启(若有打包任务将被中断)..."
|
||||||
return 0
|
do_stop
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 确保前端已构建
|
# 确保前端已构建
|
||||||
@@ -156,28 +219,15 @@ do_start() {
|
|||||||
do_build
|
do_build
|
||||||
fi
|
fi
|
||||||
|
|
||||||
setup_venv
|
|
||||||
|
|
||||||
mkdir -p "$LOG_DIR"
|
|
||||||
|
|
||||||
info "启动后端服务 ($BIND_HOST:$BACKEND_PORT)..."
|
info "启动后端服务 ($BIND_HOST:$BACKEND_PORT)..."
|
||||||
nohup "$VENV_DIR/bin/python3" -m uvicorn backend.main:app \
|
_spawn_server
|
||||||
--host "$BIND_HOST" \
|
|
||||||
--port "$BACKEND_PORT" \
|
|
||||||
--proxy-headers \
|
|
||||||
--forwarded-allow-ips 127.0.0.1 \
|
|
||||||
--workers 1 \
|
|
||||||
> "$LOG_DIR/server.log" 2>&1 &
|
|
||||||
|
|
||||||
echo $! > "$PID_FILE"
|
if _wait_ready; then
|
||||||
sleep 1
|
info "服务已就绪 (PID: $(cat "$PID_FILE"))"
|
||||||
|
|
||||||
if kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
|
|
||||||
info "服务已启动 (PID: $(cat "$PID_FILE"))"
|
|
||||||
info "访问地址: http://$BIND_HOST:$BACKEND_PORT"
|
info "访问地址: http://$BIND_HOST:$BACKEND_PORT"
|
||||||
else
|
else
|
||||||
error "启动失败,请查看日志: $LOG_DIR/server.log"
|
error "服务启动后 ${STARTUP_READY_TIMEOUT}s 内未就绪,请查看日志: $LOG_DIR/server.log"
|
||||||
rm -f "$PID_FILE"
|
tail -20 "$LOG_DIR/server.log" 2>/dev/null | sed 's/^/ /'
|
||||||
return 1
|
return 1
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -252,12 +302,15 @@ check_health() {
|
|||||||
|
|
||||||
# ========== Watchdog(前台模式,用于调试) ==========
|
# ========== Watchdog(前台模式,用于调试) ==========
|
||||||
do_watchdog_fg() {
|
do_watchdog_fg() {
|
||||||
info "Watchdog 启动(前台模式),检查间隔: ${WATCHDOG_INTERVAL}s"
|
info "Watchdog 启动(前台模式),检查间隔: ${WATCHDOG_INTERVAL}s,启动宽限: ${WATCHDOG_STARTUP_GRACE}s"
|
||||||
info "按 Ctrl+C 停止"
|
info "按 Ctrl+C 停止"
|
||||||
|
|
||||||
local restart_count=0
|
local restart_count=0
|
||||||
local last_restart_time=0
|
local last_restart_time=0
|
||||||
|
|
||||||
|
# 启动宽限:避开服务正常启动/重启的就绪窗口,防止误判触发重启。
|
||||||
|
sleep "$WATCHDOG_STARTUP_GRACE"
|
||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
local result
|
local result
|
||||||
result=$(check_health)
|
result=$(check_health)
|
||||||
@@ -338,7 +391,10 @@ do_watchdog_loop() {
|
|||||||
local restart_count=0
|
local restart_count=0
|
||||||
local last_restart_time=0
|
local last_restart_time=0
|
||||||
|
|
||||||
log_to_file "INFO" "Watchdog started, interval=${WATCHDOG_INTERVAL}s"
|
log_to_file "INFO" "Watchdog started, interval=${WATCHDOG_INTERVAL}s, grace=${WATCHDOG_STARTUP_GRACE}s, mode=${WATCHDOG_RESTART_MODE}"
|
||||||
|
|
||||||
|
# 启动宽限:避开服务正常启动/重启的就绪窗口,防止误判触发重启。
|
||||||
|
sleep "$WATCHDOG_STARTUP_GRACE"
|
||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
local result
|
local result
|
||||||
@@ -366,35 +422,33 @@ do_watchdog_loop() {
|
|||||||
|
|
||||||
restart_count=$((restart_count + 1))
|
restart_count=$((restart_count + 1))
|
||||||
last_restart_time=$(date +%s)
|
last_restart_time=$(date +%s)
|
||||||
log_to_file "WARN" "Restarting service (attempt: $restart_count)"
|
log_to_file "WARN" "Restarting service (attempt: $restart_count, mode: $WATCHDOG_RESTART_MODE)"
|
||||||
|
|
||||||
# 停止旧进程
|
if [ "$WATCHDOG_RESTART_MODE" = "launchd" ]; then
|
||||||
if [ -f "$PID_FILE" ]; then
|
# launchd 托管模式:交回 launchctl 重启,避免与 KeepAlive 抢占端口。
|
||||||
local old_pid
|
if launchctl kickstart -k "gui/$(id -u)/$APP_LAUNCHD_LABEL" 2>/dev/null; then
|
||||||
old_pid=$(cat "$PID_FILE")
|
log_to_file "INFO" "launchctl kickstart issued for $APP_LAUNCHD_LABEL"
|
||||||
kill "$old_pid" 2>/dev/null
|
else
|
||||||
sleep 2
|
log_to_file "ERROR" "launchctl kickstart failed for $APP_LAUNCHD_LABEL"
|
||||||
kill -9 "$old_pid" 2>/dev/null || true
|
fi
|
||||||
rm -f "$PID_FILE"
|
else
|
||||||
|
# nohup 托管模式:停掉旧进程后重新拉起。
|
||||||
|
if [ -f "$PID_FILE" ]; then
|
||||||
|
local old_pid
|
||||||
|
old_pid=$(cat "$PID_FILE")
|
||||||
|
kill "$old_pid" 2>/dev/null
|
||||||
|
sleep 2
|
||||||
|
kill -9 "$old_pid" 2>/dev/null || true
|
||||||
|
rm -f "$PID_FILE"
|
||||||
|
fi
|
||||||
|
_spawn_server
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 重新启动
|
# 无论哪种模式,都等待 /api/health 就绪再继续,避免连锁误判。
|
||||||
setup_venv
|
if _wait_ready; then
|
||||||
mkdir -p "$LOG_DIR"
|
log_to_file "INFO" "Service restarted successfully (PID: $(cat "$PID_FILE" 2>/dev/null))"
|
||||||
nohup "$VENV_DIR/bin/python3" -m uvicorn backend.main:app \
|
|
||||||
--host "$BIND_HOST" \
|
|
||||||
--port "$BACKEND_PORT" \
|
|
||||||
--proxy-headers \
|
|
||||||
--forwarded-allow-ips 127.0.0.1 \
|
|
||||||
--workers 1 \
|
|
||||||
>> "$LOG_DIR/server.log" 2>&1 &
|
|
||||||
echo $! > "$PID_FILE"
|
|
||||||
|
|
||||||
sleep 3
|
|
||||||
if kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
|
|
||||||
log_to_file "INFO" "Service restarted successfully (PID: $(cat "$PID_FILE"))"
|
|
||||||
else
|
else
|
||||||
log_to_file "ERROR" "Service restart failed"
|
log_to_file "ERROR" "Service restart failed or not ready in ${STARTUP_READY_TIMEOUT}s"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -457,8 +511,21 @@ do_test() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ========== 一键部署(强制重来)==========
|
||||||
|
# build → start(强制重启并等待就绪)→ watchdog,最后打印状态。
|
||||||
|
do_up() {
|
||||||
|
info "一键部署(强制重来):build → start → watchdog"
|
||||||
|
do_watchdog_stop >/dev/null 2>&1 || true # 先停监听,避免它在重启窗口内干预
|
||||||
|
do_build
|
||||||
|
do_start # do_start 内部会强制停旧服务并等待 health 就绪
|
||||||
|
do_watchdog
|
||||||
|
echo ""
|
||||||
|
do_status
|
||||||
|
}
|
||||||
|
|
||||||
# ========== 主入口 ==========
|
# ========== 主入口 ==========
|
||||||
case "${1:-}" in
|
case "${1:-}" in
|
||||||
|
up) do_up ;;
|
||||||
build) do_build ;;
|
build) do_build ;;
|
||||||
start) do_start ;;
|
start) do_start ;;
|
||||||
stop) do_stop; do_watchdog_stop ;;
|
stop) do_stop; do_watchdog_stop ;;
|
||||||
@@ -470,10 +537,11 @@ case "${1:-}" in
|
|||||||
watchdog-fg) do_watchdog_fg ;;
|
watchdog-fg) do_watchdog_fg ;;
|
||||||
_watchdog_loop) do_watchdog_loop ;;
|
_watchdog_loop) do_watchdog_loop ;;
|
||||||
*)
|
*)
|
||||||
echo "用法: $0 {build|start|stop|restart|status|test|watchdog|watchdog-stop}"
|
echo "用法: $0 {up|build|start|stop|restart|status|test|watchdog|watchdog-stop}"
|
||||||
echo ""
|
echo ""
|
||||||
|
echo " up 一键部署:build + start + watchdog(强制重来)"
|
||||||
echo " build 构建前端、安装依赖"
|
echo " build 构建前端、安装依赖"
|
||||||
echo " start 启动服务(后台运行)"
|
echo " start 启动服务(强制重启并等待就绪;端口被占用会报错)"
|
||||||
echo " stop 停止服务(同时停止 watchdog)"
|
echo " stop 停止服务(同时停止 watchdog)"
|
||||||
echo " restart 重启服务"
|
echo " restart 重启服务"
|
||||||
echo " status 查看运行状态"
|
echo " status 查看运行状态"
|
||||||
@@ -485,6 +553,9 @@ case "${1:-}" in
|
|||||||
echo "环境变量(可在 .env 中配置):"
|
echo "环境变量(可在 .env 中配置):"
|
||||||
echo " WATCHDOG_INTERVAL 健康检查间隔(秒,默认 30)"
|
echo " WATCHDOG_INTERVAL 健康检查间隔(秒,默认 30)"
|
||||||
echo " WATCHDOG_TIMEOUT 健康检查超时(秒,默认 10)"
|
echo " WATCHDOG_TIMEOUT 健康检查超时(秒,默认 10)"
|
||||||
|
echo " WATCHDOG_STARTUP_GRACE watchdog 首次检查前宽限(秒,默认 10)"
|
||||||
|
echo " STARTUP_READY_TIMEOUT 启动后等待 health 就绪的最长时间(秒,默认 20)"
|
||||||
|
echo " WATCHDOG_RESTART_MODE 重启方式 nohup|launchd(默认 nohup)"
|
||||||
echo " MAX_RESTART_ATTEMPTS 连续重启上限(默认 3)"
|
echo " MAX_RESTART_ATTEMPTS 连续重启上限(默认 3)"
|
||||||
echo " COOLDOWN_SECONDS 超过重启上限后冷却时间(秒,默认 300)"
|
echo " COOLDOWN_SECONDS 超过重启上限后冷却时间(秒,默认 300)"
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
@@ -95,6 +95,8 @@ EOF
|
|||||||
<dict>
|
<dict>
|
||||||
<key>PATH</key>
|
<key>PATH</key>
|
||||||
<string>$VENV_DIR/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
<string>$VENV_DIR/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
||||||
|
<key>WATCHDOG_RESTART_MODE</key>
|
||||||
|
<string>launchd</string>
|
||||||
</dict>
|
</dict>
|
||||||
<key>RunAtLoad</key>
|
<key>RunAtLoad</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
|||||||
+49
-2
@@ -3,10 +3,19 @@
|
|||||||
<header class="header">
|
<header class="header">
|
||||||
<h1>iOS 自动打包服务</h1>
|
<h1>iOS 自动打包服务</h1>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
|
<select
|
||||||
|
v-if="isLoggedIn && projects.length > 1"
|
||||||
|
v-model="currentProject"
|
||||||
|
class="project-select"
|
||||||
|
title="切换项目"
|
||||||
|
>
|
||||||
|
<option v-for="p in projects" :key="p.id" :value="p.id">{{ p.name }}</option>
|
||||||
|
</select>
|
||||||
<nav v-if="isLoggedIn" class="nav">
|
<nav v-if="isLoggedIn" class="nav">
|
||||||
<router-link to="/build">打包</router-link>
|
<router-link to="/build">打包</router-link>
|
||||||
<router-link to="/history">历史</router-link>
|
<router-link to="/history">历史</router-link>
|
||||||
<router-link to="/admin">管理</router-link>
|
<router-link to="/admin">管理</router-link>
|
||||||
|
<router-link v-if="isAdmin" to="/operations">操作日志</router-link>
|
||||||
</nav>
|
</nav>
|
||||||
<div v-if="!isLoggedIn" class="user-info">
|
<div v-if="!isLoggedIn" class="user-info">
|
||||||
<button class="btn-login" @click="showLogin = true">登录</button>
|
<button class="btn-login" @click="showLogin = true">登录</button>
|
||||||
@@ -20,7 +29,8 @@
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<template v-if="isLoggedIn">
|
<template v-if="isLoggedIn">
|
||||||
<router-view />
|
<!-- 切换项目时重建页面,按新项目重新加载数据 -->
|
||||||
|
<router-view v-if="projectReady" :key="currentProject" />
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<div class="login-required">
|
<div class="login-required">
|
||||||
@@ -51,7 +61,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, provide } from 'vue'
|
import { ref, computed, onMounted, provide, watch } from 'vue'
|
||||||
|
|
||||||
const isLoggedIn = ref(false)
|
const isLoggedIn = ref(false)
|
||||||
const isAdmin = ref(false)
|
const isAdmin = ref(false)
|
||||||
@@ -66,6 +76,40 @@ provide('isAdmin', isAdmin)
|
|||||||
// 获取存储的 token
|
// 获取存储的 token
|
||||||
const getToken = () => localStorage.getItem('authToken') || ''
|
const getToken = () => localStorage.getItem('authToken') || ''
|
||||||
|
|
||||||
|
// 当前项目:所有接口请求通过 X-Project 请求头指定,记在本地以便下次打开沿用
|
||||||
|
const PROJECT_KEY = 'currentProject'
|
||||||
|
const readStoredProject = () => {
|
||||||
|
try { return localStorage.getItem(PROJECT_KEY) || '' } catch { return '' }
|
||||||
|
}
|
||||||
|
const projects = ref([])
|
||||||
|
const currentProject = ref(readStoredProject())
|
||||||
|
const projectReady = ref(false)
|
||||||
|
const currentProjectInfo = computed(() => projects.value.find(p => p.id === currentProject.value) || null)
|
||||||
|
|
||||||
|
watch(currentProject, (value) => {
|
||||||
|
try { localStorage.setItem(PROJECT_KEY, value) } catch { /* 忽略存储失败 */ }
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadProjects = async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/projects', { headers: { 'Authorization': `Bearer ${getToken()}` } })
|
||||||
|
if (res.ok) {
|
||||||
|
projects.value = await res.json()
|
||||||
|
if (!projects.value.some(p => p.id === currentProject.value)) {
|
||||||
|
currentProject.value = projects.value[0]?.id || ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 网络错误时沿用当前项目
|
||||||
|
}
|
||||||
|
projectReady.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
provide('projects', projects)
|
||||||
|
provide('currentProject', currentProject)
|
||||||
|
provide('currentProjectInfo', currentProjectInfo)
|
||||||
|
provide('reloadProjects', loadProjects)
|
||||||
|
|
||||||
// 对外暴露 token 获取方法,供 API 请求使用
|
// 对外暴露 token 获取方法,供 API 请求使用
|
||||||
provide('getToken', getToken)
|
provide('getToken', getToken)
|
||||||
|
|
||||||
@@ -82,6 +126,7 @@ const login = async () => {
|
|||||||
isAdmin.value = data.is_admin
|
isAdmin.value = data.is_admin
|
||||||
showLogin.value = false
|
showLogin.value = false
|
||||||
localStorage.setItem('authToken', data.token)
|
localStorage.setItem('authToken', data.token)
|
||||||
|
await loadProjects()
|
||||||
} else {
|
} else {
|
||||||
alert('用户名或密码错误')
|
alert('用户名或密码错误')
|
||||||
}
|
}
|
||||||
@@ -111,6 +156,7 @@ onMounted(async () => {
|
|||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
isLoggedIn.value = true
|
isLoggedIn.value = true
|
||||||
isAdmin.value = data.is_admin
|
isAdmin.value = data.is_admin
|
||||||
|
await loadProjects()
|
||||||
} else {
|
} else {
|
||||||
localStorage.removeItem('authToken')
|
localStorage.removeItem('authToken')
|
||||||
showLogin.value = true
|
showLogin.value = true
|
||||||
@@ -131,6 +177,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; b
|
|||||||
.nav a { color: #a0a0a0; text-decoration: none; padding: 8px 16px; border-radius: 6px; }
|
.nav a { color: #a0a0a0; text-decoration: none; padding: 8px 16px; border-radius: 6px; }
|
||||||
.nav a.router-link-active { background: #16213e; color: white; }
|
.nav a.router-link-active { background: #16213e; color: white; }
|
||||||
.nav a:hover { color: white; }
|
.nav a:hover { color: white; }
|
||||||
|
.project-select { background: #16213e; color: white; border: 1px solid #444; border-radius: 6px; padding: 6px 10px; font-size: 14px; cursor: pointer; }
|
||||||
.user-info { display: flex; align-items: center; gap: 10px; }
|
.user-info { display: flex; align-items: center; gap: 10px; }
|
||||||
.user-avatar { width: 32px; height: 32px; background: #1890ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; }
|
.user-avatar { width: 32px; height: 32px; background: #1890ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; }
|
||||||
.user-name { font-size: 14px; }
|
.user-name { font-size: 14px; }
|
||||||
|
|||||||
@@ -73,6 +73,46 @@ describe('BuildView.vue', () => {
|
|||||||
expect(branchSelect).toBeTruthy()
|
expect(branchSelect).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('分支和 Tag 分组显示,可选择 Tag 提交', async () => {
|
||||||
|
fetch.mockImplementation((url, opts) => {
|
||||||
|
if (url === '/api/tasks' && opts?.method === 'POST') {
|
||||||
|
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'tag-task', status: 'pending' }) })
|
||||||
|
}
|
||||||
|
const responses = {
|
||||||
|
'/api/apps': { '1': { name: '测试App', server: '测试环境', certificates: { Ad_Hoc: {} } } },
|
||||||
|
'/api/schemes': { '1': { name: 'testScheme' } },
|
||||||
|
'/api/branches': ['main', 'dev'],
|
||||||
|
'/api/tags': ['v3.2.0'],
|
||||||
|
'/api/tasks': [],
|
||||||
|
}
|
||||||
|
return Promise.resolve({ json: () => Promise.resolve(responses[url] || {}) })
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mountBuildView()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const groups = wrapper.findAll('optgroup')
|
||||||
|
expect(groups.map(g => g.attributes('label'))).toEqual(['分支', 'Tag'])
|
||||||
|
expect(groups[1].findAll('option').map(o => o.text())).toEqual(['v3.2.0'])
|
||||||
|
|
||||||
|
wrapper.vm.selectedServer = '测试环境'
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
wrapper.vm.form.app_id = '1'
|
||||||
|
wrapper.vm.form.branch = 'v3.2.0'
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
await wrapper.find('.btn-primary').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const post = fetch.mock.calls.find(([url, opts]) => url === '/api/tasks' && opts?.method === 'POST')
|
||||||
|
expect(JSON.parse(post[1].body).branch).toBe('v3.2.0')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('没有 Tag 时不显示 Tag 分组', async () => {
|
||||||
|
const wrapper = mountBuildView()
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.findAll('optgroup').map(g => g.attributes('label'))).toEqual(['分支'])
|
||||||
|
})
|
||||||
|
|
||||||
it('默认值正确', async () => {
|
it('默认值正确', async () => {
|
||||||
const wrapper = mountBuildView()
|
const wrapper = mountBuildView()
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|||||||
@@ -23,8 +23,19 @@ function mockFetch(url) {
|
|||||||
'/api/config/schemes': { '1': { name: 'testScheme', ossFloder: 'test' } },
|
'/api/config/schemes': { '1': { name: 'testScheme', ossFloder: 'test' } },
|
||||||
'/api/config/servers': { '测试环境': { api: 'https://test.com', assDom: '', universalLink: '' } },
|
'/api/config/servers': { '测试环境': { api: 'https://test.com', assDom: '', universalLink: '' } },
|
||||||
'/api/config/branches': ['main', 'dev'],
|
'/api/config/branches': ['main', 'dev'],
|
||||||
|
'/api/config/tags': ['v3.2.0'],
|
||||||
'/api/config/build': { max_concurrent_builds: 2, build_dir_retention_hours: 24, build_base_dir: '/tmp' },
|
'/api/config/build': { max_concurrent_builds: 2, build_dir_retention_hours: 24, build_base_dir: '/tmp' },
|
||||||
'/api/config/versions': { app_ver: '2.195.0', build_ver: '2.195.0.0' },
|
'/api/config/versions': {
|
||||||
|
app_ver: '2.195.0',
|
||||||
|
build_ver: '2.195.0.0',
|
||||||
|
primary_track: 'release',
|
||||||
|
tracks: {
|
||||||
|
release: { kind: 'release', app_ver: '2.195.0', build_ver: '2.195.0.0', build_map: {} },
|
||||||
|
dev: { kind: 'feature', app_ver: '2.100.0', build_ver: '2.100.0.0', build_map: {} },
|
||||||
|
'v3.2.0': { kind: 'release', app_ver: '3.2.0', build_ver: '3.2.0.0', build_map: {} },
|
||||||
|
},
|
||||||
|
branch_track: { main: 'release', dev: 'dev', 'v3.2.0': 'v3.2.0' },
|
||||||
|
},
|
||||||
'/api/config': { apps: {}, schemes: {}, branches: ['main'] },
|
'/api/config': { apps: {}, schemes: {}, branches: ['main'] },
|
||||||
}
|
}
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
@@ -168,19 +179,117 @@ describe('ConfigView.vue', () => {
|
|||||||
expect(window.alert).toHaveBeenCalledWith('设置已保存')
|
expect(window.alert).toHaveBeenCalledWith('设置已保存')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('普通账号可修改版本号但看不到打包参数', async () => {
|
it('普通账号只能管理 Apps,看不到打包设置与版本号', async () => {
|
||||||
const wrapper = mountConfigView({ admin: false })
|
const wrapper = mountConfigView({ admin: false })
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
const menuTexts = wrapper.findAll('.sidebar-menu li').map(li => li.text())
|
const menuTexts = wrapper.findAll('.sidebar-menu li').map(li => li.text())
|
||||||
expect(menuTexts).toEqual(['Apps 配置', '打包设置'])
|
expect(menuTexts).toEqual(['Apps 配置'])
|
||||||
|
|
||||||
|
expect(wrapper.text()).not.toContain('上架版本号')
|
||||||
|
expect(wrapper.text()).not.toContain('自测版本号')
|
||||||
|
expect(wrapper.text()).not.toContain('打包参数')
|
||||||
|
// 版本号接口为管理员专属,普通账号不再请求
|
||||||
|
expect(fetch).not.toHaveBeenCalledWith('/api/config/versions', expect.anything())
|
||||||
|
expect(fetch.mock.calls.map(c => c[0])).toEqual(['/api/config/apps'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('每个分支的版本号各自独立展示与保存', async () => {
|
||||||
|
const calls = []
|
||||||
|
fetch.mockImplementation((url, opts) => {
|
||||||
|
if (url === '/api/config/versions' && opts?.method === 'PUT') {
|
||||||
|
calls.push(JSON.parse(opts.body))
|
||||||
|
return Promise.resolve({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve({ app_ver: '2.101.0', build_ver: '2.101.0.0' }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return mockFetch(url)
|
||||||
|
})
|
||||||
|
window.alert = vi.fn()
|
||||||
|
|
||||||
|
const wrapper = mountConfigView()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
const buildMenu = wrapper.findAll('.sidebar-menu li').find(li => li.text() === '打包设置')
|
const buildMenu = wrapper.findAll('.sidebar-menu li').find(li => li.text() === '打包设置')
|
||||||
await buildMenu.trigger('click')
|
await buildMenu.trigger('click')
|
||||||
await wrapper.vm.$nextTick()
|
await wrapper.vm.$nextTick()
|
||||||
|
|
||||||
expect(wrapper.text()).toContain('应用版本号')
|
// 每个分支一块:main(上架,release 轨)、dev(自测,dev 轨)
|
||||||
expect(wrapper.text()).not.toContain('打包参数')
|
expect(wrapper.text()).toContain('上架版本号(main)')
|
||||||
expect(wrapper.findAll('input').length).toBe(1)
|
expect(wrapper.text()).toContain('自测版本号(dev)')
|
||||||
|
|
||||||
|
const inputs = wrapper.findAll('input[type="text"]')
|
||||||
|
expect(inputs[0].element.value).toBe('2.195.0') // main 分支 App_Ver
|
||||||
|
expect(inputs[2].element.value).toBe('2.100.0') // dev 分支 App_Ver
|
||||||
|
|
||||||
|
await inputs[2].setValue('2.101.0')
|
||||||
|
const saveBtn = wrapper.findAll('.btn-primary').find(b => b.text() === '保存 dev 版本号')
|
||||||
|
await saveBtn.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(calls).toEqual([{ track: 'dev', app_ver: '2.101.0', build_ver: '2.101.0.0' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('分支管理可切换版本轨道', async () => {
|
||||||
|
const calls = []
|
||||||
|
fetch.mockImplementation((url, opts) => {
|
||||||
|
if (url === '/api/config/branches/track' && opts?.method === 'PUT') {
|
||||||
|
calls.push(JSON.parse(opts.body))
|
||||||
|
return Promise.resolve({ ok: true, json: () => Promise.resolve({ message: 'ok' }) })
|
||||||
|
}
|
||||||
|
return mockFetch(url)
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mountConfigView()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const branchesMenu = wrapper.findAll('.sidebar-menu li').find(li => li.text() === '分支管理')
|
||||||
|
await branchesMenu.trigger('click')
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
|
||||||
|
const select = wrapper.find('.config-table select')
|
||||||
|
expect(select.element.value).toBe('release') // main → release 轨(上架)
|
||||||
|
await select.setValue('feature')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(calls).toEqual([{ branch: 'main', track: 'feature' }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('分支管理可添加和删除 Tag', async () => {
|
||||||
|
window.confirm = vi.fn(() => true)
|
||||||
|
const calls = []
|
||||||
|
fetch.mockImplementation((url, opts) => {
|
||||||
|
if (opts?.method === 'POST' || opts?.method === 'DELETE') {
|
||||||
|
calls.push([opts.method, url, opts.body && JSON.parse(opts.body)])
|
||||||
|
return Promise.resolve({ ok: true, json: () => Promise.resolve({ message: 'ok' }) })
|
||||||
|
}
|
||||||
|
return mockFetch(url)
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mountConfigView()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const branchesMenu = wrapper.findAll('.sidebar-menu li').find(li => li.text() === '分支管理')
|
||||||
|
await branchesMenu.trigger('click')
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
|
||||||
|
const rows = wrapper.findAll('.config-table tbody tr')
|
||||||
|
expect(rows.map(r => r.findAll('td').slice(0, 2).map(td => td.text()))).toEqual([
|
||||||
|
['main', '分支'], ['dev', '分支'], ['v3.2.0', 'Tag'],
|
||||||
|
])
|
||||||
|
|
||||||
|
await wrapper.find('select').setValue('tag')
|
||||||
|
await wrapper.find('input[placeholder="输入 Tag 名称"]').setValue('v3.3.0')
|
||||||
|
await wrapper.findAll('.btn-primary').find(b => b.text() === '添加 Tag').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
await rows[2].find('.action-btn.delete').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(calls).toEqual([
|
||||||
|
['POST', '/api/config/tags', { name: 'v3.3.0' }],
|
||||||
|
['DELETE', '/api/config/tags/v3.2.0', undefined],
|
||||||
|
])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -159,6 +159,18 @@ describe('HistoryView.vue', () => {
|
|||||||
expect(wrapper.text()).not.toContain('日志')
|
expect(wrapper.text()).not.toContain('日志')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('管理员可显示已覆盖记录', async () => {
|
||||||
|
const wrapper = mountHistory(true)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const toggle = wrapper.find('.superseded-toggle input')
|
||||||
|
expect(toggle.exists()).toBe(true)
|
||||||
|
await toggle.setValue(true)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenLastCalledWith('/api/tasks?limit=100&include_superseded=true', expect.any(Object))
|
||||||
|
})
|
||||||
|
|
||||||
it('空列表显示提示', async () => {
|
it('空列表显示提示', async () => {
|
||||||
fetch.mockResolvedValue({ json: () => Promise.resolve([]) })
|
fetch.mockResolvedValue({ json: () => Promise.resolve([]) })
|
||||||
const router = createMockRouter()
|
const router = createMockRouter()
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import OperationLogView from '../views/OperationLogView.vue'
|
||||||
|
|
||||||
|
global.fetch = vi.fn()
|
||||||
|
|
||||||
|
describe('OperationLogView.vue', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
fetch
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ total: 4, action_counts: { build_created: 2, ipa_download_requested: 1 }, top_users: [{ name: 'admin', count: 4 }], top_apps: [{ name: '测试App', count: 3 }] }) })
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([{ id: '1', created_at: '2026-07-22T08:00:00', username: 'admin', action: 'build_created', app_name: '测试App', resource_type: '', client_ip: '127.0.0.1' }]) })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('管理员可查看统计和操作明细', async () => {
|
||||||
|
const wrapper = mount(OperationLogView, { global: { provide: { isAdmin: ref(true), getToken: () => 'token' } } })
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('操作日志')
|
||||||
|
expect(wrapper.text()).toContain('操作总数')
|
||||||
|
expect(wrapper.text()).toContain('发起打包')
|
||||||
|
expect(wrapper.text()).toContain('测试App')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('普通用户不渲染操作日志页面', async () => {
|
||||||
|
const wrapper = mount(OperationLogView, { global: { provide: { isAdmin: ref(false) } } })
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('.panel').exists()).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -2,12 +2,14 @@ import { createRouter, createWebHistory } from 'vue-router'
|
|||||||
import BuildView from '../views/BuildView.vue'
|
import BuildView from '../views/BuildView.vue'
|
||||||
import HistoryView from '../views/HistoryView.vue'
|
import HistoryView from '../views/HistoryView.vue'
|
||||||
import ConfigView from '../views/ConfigView.vue'
|
import ConfigView from '../views/ConfigView.vue'
|
||||||
|
import OperationLogView from '../views/OperationLogView.vue'
|
||||||
|
|
||||||
const routes = [
|
const routes = [
|
||||||
{ path: '/', redirect: '/build' },
|
{ path: '/', redirect: '/build' },
|
||||||
{ path: '/build', name: 'Build', component: BuildView },
|
{ path: '/build', name: 'Build', component: BuildView },
|
||||||
{ path: '/history', name: 'History', component: HistoryView },
|
{ path: '/history', name: 'History', component: HistoryView },
|
||||||
{ path: '/admin', name: 'Admin', component: ConfigView },
|
{ path: '/admin', name: 'Admin', component: ConfigView },
|
||||||
|
{ path: '/operations', name: 'Operations', component: OperationLogView },
|
||||||
]
|
]
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
|
|||||||
@@ -41,12 +41,17 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>代码分支</label>
|
<label>代码分支 / Tag</label>
|
||||||
<select v-model="form.branch">
|
<select v-model="form.branch">
|
||||||
<option v-for="b in branches" :key="b" :value="b">{{ b }}</option>
|
<optgroup label="分支">
|
||||||
|
<option v-for="b in branches" :key="b" :value="b">{{ b }}</option>
|
||||||
|
</optgroup>
|
||||||
|
<optgroup v-if="tags.length" label="Tag">
|
||||||
|
<option v-for="t in tags" :key="`tag:${t}`" :value="t">{{ t }}</option>
|
||||||
|
</optgroup>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div v-if="supportsObfuscation" class="form-group">
|
||||||
<label>代码混淆</label>
|
<label>代码混淆</label>
|
||||||
<div class="checkbox-group">
|
<div class="checkbox-group">
|
||||||
<input type="checkbox" id="obfuscation" v-model="form.obfuscation">
|
<input type="checkbox" id="obfuscation" v-model="form.obfuscation">
|
||||||
@@ -156,17 +161,22 @@ import { useRoute } from 'vue-router'
|
|||||||
|
|
||||||
const getToken = inject('getToken')
|
const getToken = inject('getToken')
|
||||||
|
|
||||||
|
const currentProject = inject('currentProject', ref(''))
|
||||||
const authFetch = (url, options = {}) => {
|
const authFetch = (url, options = {}) => {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (token) {
|
if (token) {
|
||||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||||
}
|
}
|
||||||
|
if (currentProject.value) {
|
||||||
|
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||||
|
}
|
||||||
return fetch(url, options)
|
return fetch(url, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
const apps = ref({})
|
const apps = ref({})
|
||||||
const schemes = ref({})
|
const schemes = ref({})
|
||||||
const branches = ref(['main'])
|
const branches = ref(['main'])
|
||||||
|
const tags = ref([])
|
||||||
const tasks = ref([])
|
const tasks = ref([])
|
||||||
const selectedServer = ref('')
|
const selectedServer = ref('')
|
||||||
const serverEnvironments = computed(() => {
|
const serverEnvironments = computed(() => {
|
||||||
@@ -176,6 +186,9 @@ const filteredApps = computed(() => {
|
|||||||
return Object.entries(apps.value).filter(([, app]) => app.server === selectedServer.value)
|
return Object.entries(apps.value).filter(([, app]) => app.server === selectedServer.value)
|
||||||
})
|
})
|
||||||
const selectedApp = computed(() => apps.value[form.value.app_id] || null)
|
const selectedApp = computed(() => apps.value[form.value.app_id] || null)
|
||||||
|
const currentProjectInfo = inject('currentProjectInfo', ref(null))
|
||||||
|
// 未加载到项目信息时(旧版服务)保持原有行为
|
||||||
|
const supportsObfuscation = computed(() => currentProjectInfo.value?.obfuscation ?? true)
|
||||||
const availableBuildTypes = computed(() => {
|
const availableBuildTypes = computed(() => {
|
||||||
const certificates = selectedApp.value?.certificates || {}
|
const certificates = selectedApp.value?.certificates || {}
|
||||||
return ['Ad_Hoc', 'App_Store'].filter(buildType => Boolean(certificates[buildType]))
|
return ['Ad_Hoc', 'App_Store'].filter(buildType => Boolean(certificates[buildType]))
|
||||||
@@ -314,15 +327,18 @@ onUnmounted(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const [appsRes, schemesRes, branchesRes, tasksRes] = await Promise.all([
|
const [appsRes, schemesRes, branchesRes, tagsRes, tasksRes] = await Promise.all([
|
||||||
authFetch('/api/apps'),
|
authFetch('/api/apps'),
|
||||||
authFetch('/api/schemes'),
|
authFetch('/api/schemes'),
|
||||||
authFetch('/api/branches'),
|
authFetch('/api/branches'),
|
||||||
|
authFetch('/api/tags'),
|
||||||
authFetch('/api/tasks'),
|
authFetch('/api/tasks'),
|
||||||
])
|
])
|
||||||
apps.value = await appsRes.json()
|
apps.value = await appsRes.json()
|
||||||
schemes.value = await schemesRes.json()
|
schemes.value = await schemesRes.json()
|
||||||
branches.value = await branchesRes.json()
|
branches.value = await branchesRes.json()
|
||||||
|
const tagList = await tagsRes.json()
|
||||||
|
tags.value = Array.isArray(tagList) ? tagList : []
|
||||||
const allTasks = await tasksRes.json()
|
const allTasks = await tasksRes.json()
|
||||||
|
|
||||||
// 从历史页跳转过来时,读取 taskId 查询参数
|
// 从历史页跳转过来时,读取 taskId 查询参数
|
||||||
@@ -364,7 +380,7 @@ const submitTask = async () => {
|
|||||||
const res = await authFetch('/api/tasks', {
|
const res = await authFetch('/api/tasks', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(form.value),
|
body: JSON.stringify({ ...form.value, obfuscation: supportsObfuscation.value && form.value.obfuscation }),
|
||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const task = await res.json()
|
const task = await res.json()
|
||||||
@@ -436,7 +452,7 @@ const errorCategoryHint = (cat) => {
|
|||||||
provisioning: '描述文件问题:描述文件过期、不匹配或未安装',
|
provisioning: '描述文件问题:描述文件过期、不匹配或未安装',
|
||||||
compilation: '代码编译错误:请检查代码语法和类型引用',
|
compilation: '代码编译错误:请检查代码语法和类型引用',
|
||||||
dependency: '依赖问题:Pod 依赖缺失或版本不兼容',
|
dependency: '依赖问题:Pod 依赖缺失或版本不兼容',
|
||||||
git: '代码拉取失败:请检查分支是否存在',
|
git: '代码拉取失败:请检查分支或 Tag 是否存在',
|
||||||
config: '配置替换失败:请检查打包配置',
|
config: '配置替换失败:请检查打包配置',
|
||||||
build: '构建配置错误:请检查 Scheme 和 Workspace 配置',
|
build: '构建配置错误:请检查 Scheme 和 Workspace 配置',
|
||||||
unknown: '打包失败:请查看详细日志排查原因',
|
unknown: '打包失败:请查看详细日志排查原因',
|
||||||
@@ -497,7 +513,7 @@ const errorCategoryHint = (cat) => {
|
|||||||
.download-link { color: #1890ff; text-decoration: none; }
|
.download-link { color: #1890ff; text-decoration: none; }
|
||||||
.download-link:hover { text-decoration: underline; }
|
.download-link:hover { text-decoration: underline; }
|
||||||
.qr-section { text-align: center; padding: 16px; background: #fafafa; border-radius: 8px; }
|
.qr-section { text-align: center; padding: 16px; background: #fafafa; border-radius: 8px; }
|
||||||
.qr-image { width: 180px; height: 180px; border: 1px solid #f0f0f0; border-radius: 8px; }
|
.qr-image { width: 180px; height: 180px; object-fit: contain; border: 1px solid #f0f0f0; border-radius: 8px; }
|
||||||
.qr-hint { margin-top: 8px; font-size: 13px; color: #999; }
|
.qr-hint { margin-top: 8px; font-size: 13px; color: #999; }
|
||||||
.error-msg { color: #ff4d4f; font-size: 13px; word-break: break-all; }
|
.error-msg { color: #ff4d4f; font-size: 13px; word-break: break-all; }
|
||||||
|
|
||||||
|
|||||||
@@ -8,18 +8,52 @@
|
|||||||
<div v-else class="admin-page">
|
<div v-else class="admin-page">
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
<h3>配置管理</h3>
|
<h3>配置管理</h3>
|
||||||
|
<div v-if="currentProjectInfo" class="sidebar-project">当前项目:{{ currentProjectInfo.name }}</div>
|
||||||
<ul class="sidebar-menu">
|
<ul class="sidebar-menu">
|
||||||
|
<li v-if="isAdmin" :class="{ active: tab === 'projects' }" @click="tab = 'projects'">项目管理</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'users' }" @click="tab = 'users'">用户管理</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'users' }" @click="tab = 'users'">用户管理</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'servers' }" @click="tab = 'servers'">服务器环境</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'servers' }" @click="tab = 'servers'">服务器环境</li>
|
||||||
<li :class="{ active: tab === 'apps' }" @click="tab = 'apps'">Apps 配置</li>
|
<li :class="{ active: tab === 'apps' }" @click="tab = 'apps'">Apps 配置</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'schemes' }" @click="tab = 'schemes'">Schemes 配置</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'schemes' }" @click="tab = 'schemes'">Schemes 配置</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'branches' }" @click="tab = 'branches'">分支管理</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'branches' }" @click="tab = 'branches'">分支管理</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'upload' }" @click="tab = 'upload'">上传配置</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'upload' }" @click="tab = 'upload'">上传配置</li>
|
||||||
<li :class="{ active: tab === 'build' }" @click="tab = 'build'">打包设置</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'build' }" @click="tab = 'build'">打包设置</li>
|
||||||
<li v-if="isAdmin" :class="{ active: tab === 'json' }" @click="tab = 'json'">JSON 编辑</li>
|
<li v-if="isAdmin" :class="{ active: tab === 'json' }" @click="tab = 'json'">JSON 编辑</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div class="main-content">
|
<div class="main-content">
|
||||||
|
<!-- 项目管理 -->
|
||||||
|
<div v-if="tab === 'projects'">
|
||||||
|
<h2>项目管理</h2>
|
||||||
|
<p style="color: #666; margin-bottom: 16px; font-size: 14px;">每个项目有独立的源码仓库、Apps、Schemes、服务器环境、分支和版本号;上传配置所有项目共用。页面顶部切换当前项目。</p>
|
||||||
|
<button class="btn btn-primary" style="width: auto; margin-bottom: 16px;" @click="openProjectModal()">+ 新增项目</button>
|
||||||
|
<table class="config-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>名称</th>
|
||||||
|
<th>Git 仓库</th>
|
||||||
|
<th>Xcode</th>
|
||||||
|
<th>配置替换</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="p in projectDefinitions" :key="p.id">
|
||||||
|
<td>{{ p.id }}</td>
|
||||||
|
<td><strong>{{ p.name }}</strong></td>
|
||||||
|
<td>{{ p.git.remote_url || (p.git.use_env ? '.env 中的 GIT_REMOTE_URL' : '-') }}</td>
|
||||||
|
<td>{{ p.xcode.workspace || p.xcode.project }}</td>
|
||||||
|
<td>{{ p.patcher === 'readoor' ? 'Readoor 专用' : `通用(${p.patch_rules.length} 条规则)` }}</td>
|
||||||
|
<td class="action-btns">
|
||||||
|
<button class="action-btn" @click="openProjectModal(p)">编辑</button>
|
||||||
|
<button class="action-btn delete" @click="deleteProject(p)">删除</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 用户管理 -->
|
<!-- 用户管理 -->
|
||||||
<div v-if="tab === 'users'">
|
<div v-if="tab === 'users'">
|
||||||
<h2>用户管理</h2>
|
<h2>用户管理</h2>
|
||||||
@@ -65,20 +99,22 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>环境名称</th>
|
<th>环境名称</th>
|
||||||
<th>API 地址</th>
|
<th v-if="isReadoorProject">API 地址</th>
|
||||||
<th>App ID 前缀</th>
|
<th>App ID 前缀</th>
|
||||||
<th>Associated Domains</th>
|
<th v-if="isReadoorProject">Associated Domains</th>
|
||||||
<th>Universal Link</th>
|
<th v-if="isReadoorProject">Universal Link</th>
|
||||||
|
<th v-for="field in serverFields" :key="field.key">{{ field.label }}</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="(server, name) in servers" :key="name">
|
<tr v-for="(server, name) in servers" :key="name">
|
||||||
<td><strong>{{ name }}</strong></td>
|
<td><strong>{{ name }}</strong></td>
|
||||||
<td>{{ server.api }}</td>
|
<td v-if="isReadoorProject">{{ server.api }}</td>
|
||||||
<td>{{ server.app_id_prefix }}</td>
|
<td>{{ server.app_id_prefix }}</td>
|
||||||
<td>{{ server.assDom }}</td>
|
<td v-if="isReadoorProject">{{ server.assDom }}</td>
|
||||||
<td>{{ server.universalLink }}</td>
|
<td v-if="isReadoorProject">{{ server.universalLink }}</td>
|
||||||
|
<td v-for="field in serverFields" :key="field.key">{{ server[field.key] }}</td>
|
||||||
<td class="action-btns">
|
<td class="action-btns">
|
||||||
<button class="action-btn" @click="openServerModal(name, server)">编辑</button>
|
<button class="action-btn" @click="openServerModal(name, server)">编辑</button>
|
||||||
<button class="action-btn delete" @click="deleteServer(name)">删除</button>
|
<button class="action-btn delete" @click="deleteServer(name)">删除</button>
|
||||||
@@ -98,7 +134,8 @@
|
|||||||
<th>ID</th>
|
<th>ID</th>
|
||||||
<th>名称</th>
|
<th>名称</th>
|
||||||
<th>环境</th>
|
<th>环境</th>
|
||||||
<th>AppGuid</th>
|
<th v-if="isReadoorProject">AppGuid</th>
|
||||||
|
<th v-for="field in appFields" :key="field.key">{{ field.label }}</th>
|
||||||
<th>证书</th>
|
<th>证书</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -108,7 +145,8 @@
|
|||||||
<td>{{ id }}</td>
|
<td>{{ id }}</td>
|
||||||
<td>{{ app.name }}</td>
|
<td>{{ app.name }}</td>
|
||||||
<td>{{ app.server }}</td>
|
<td>{{ app.server }}</td>
|
||||||
<td>{{ app.AppGuid || app.AppId }}</td>
|
<td v-if="isReadoorProject">{{ app.AppGuid || app.AppId }}</td>
|
||||||
|
<td v-for="field in appFields" :key="field.key">{{ app[field.key] }}</td>
|
||||||
<td>{{ Object.keys(app.certificates || {}).join(', ') || '-' }}</td>
|
<td>{{ Object.keys(app.certificates || {}).join(', ') || '-' }}</td>
|
||||||
<td class="action-btns">
|
<td class="action-btns">
|
||||||
<button class="action-btn" @click="openAppModal(id, app)">编辑</button>
|
<button class="action-btn" @click="openAppModal(id, app)">编辑</button>
|
||||||
@@ -151,27 +189,43 @@
|
|||||||
<!-- 分支管理 -->
|
<!-- 分支管理 -->
|
||||||
<div v-if="tab === 'branches'">
|
<div v-if="tab === 'branches'">
|
||||||
<h2>分支管理</h2>
|
<h2>分支管理</h2>
|
||||||
<p style="color: #666; margin-bottom: 16px; font-size: 14px;">管理可打包的代码分支,打包时从对应分支目录获取源码</p>
|
<p style="color: #666; margin-bottom: 16px; font-size: 14px;">
|
||||||
|
管理可打包的代码分支和 Tag,打包时从对应分支或 Tag 获取源码。
|
||||||
|
每个分支 / Tag 各有一套独立的版本号,版本轨道决定构建号行为:上架(App_Store 打包构建号自增)、自测(构建号不自增)。新增 Tag 默认为上架。
|
||||||
|
</p>
|
||||||
<div style="display: flex; gap: 12px; margin-bottom: 16px;">
|
<div style="display: flex; gap: 12px; margin-bottom: 16px;">
|
||||||
<input v-model="newBranch" type="text" placeholder="输入分支名称" style="flex: 1; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px;">
|
<select v-model="newRefType" style="width: auto; padding: 10px 12px;">
|
||||||
<button class="btn btn-primary" style="width: auto; padding: 10px 24px;" @click="addBranch">添加分支</button>
|
<option value="branch">分支</option>
|
||||||
|
<option value="tag">Tag</option>
|
||||||
|
</select>
|
||||||
|
<input v-model="newBranch" type="text" :placeholder="newRefType === 'tag' ? '输入 Tag 名称' : '输入分支名称'" style="flex: 1; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px;">
|
||||||
|
<button class="btn btn-primary" style="width: auto; padding: 10px 24px;" @click="addBranch">{{ newRefType === 'tag' ? '添加 Tag' : '添加分支' }}</button>
|
||||||
</div>
|
</div>
|
||||||
<table class="config-table">
|
<table class="config-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>分支名称</th>
|
<th>名称</th>
|
||||||
|
<th>类型</th>
|
||||||
|
<th>版本轨道</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="b in branches" :key="b">
|
<tr v-for="r in buildRefs" :key="`${r.type}:${r.name}`">
|
||||||
<td><strong>{{ b }}</strong></td>
|
<td><strong>{{ r.name }}</strong></td>
|
||||||
|
<td>{{ r.type === 'tag' ? 'Tag' : '分支' }}</td>
|
||||||
|
<td>
|
||||||
|
<select :value="branchKind(r.name)" style="width: auto; padding: 4px 8px;" @change="setBranchTrack(r.name, $event.target.value)">
|
||||||
|
<option value="release">上架(App_Store 打包构建号自增)</option>
|
||||||
|
<option value="feature">自测(构建号不自增)</option>
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
<td class="action-btns">
|
<td class="action-btns">
|
||||||
<button class="action-btn delete" @click="deleteBranch(b)">删除</button>
|
<button class="action-btn delete" @click="deleteBranch(r)">删除</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-if="!branches.length">
|
<tr v-if="!buildRefs.length">
|
||||||
<td colspan="2" style="text-align: center; color: #999;">暂无分支配置</td>
|
<td colspan="4" style="text-align: center; color: #999;">暂无分支配置</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -231,7 +285,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>远程路径</label>
|
<label>远程路径</label>
|
||||||
<input v-model="uploadConfig.webdav.base_path" type="text" placeholder="/ios-builds">
|
<input v-model="uploadConfig.webdav.base_path" type="text" placeholder="/iOS">
|
||||||
|
<div style="font-size: 12px; color: #999; margin-top: 4px;">文件直接上传到此目录,不会自动追加 ios-builds/iOS;填 / 表示下载根目录</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>公开访问地址</label>
|
<label>公开访问地址</label>
|
||||||
@@ -258,6 +313,16 @@
|
|||||||
<label>加签密钥(可选)</label>
|
<label>加签密钥(可选)</label>
|
||||||
<input v-model="uploadConfig.dingtalk.secret" type="password" placeholder="留空则不加签">
|
<input v-model="uploadConfig.dingtalk.secret" type="password" placeholder="留空则不加签">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Ad_Hoc @ 开发人员手机号(可选)</label>
|
||||||
|
<textarea v-model="dingtalkAtMobiles" rows="3" placeholder="每行一个手机号,或用逗号分隔;留空则不 @ 人"></textarea>
|
||||||
|
<div style="font-size: 12px; color: #999; margin-top: 4px;">须是钉钉账号绑定的手机号,Ad_Hoc 打包完成的通知会 @ 这些人。</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>App_Store @ 开发人员手机号(可选)</label>
|
||||||
|
<textarea v-model="dingtalkAtMobilesAppStore" rows="3" placeholder="每行一个手机号,或用逗号分隔;留空则不 @ 人"></textarea>
|
||||||
|
<div style="font-size: 12px; color: #999; margin-top: 4px;">App_Store 打包完成的通知会 @ 这些人。</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -269,13 +334,31 @@
|
|||||||
<div v-if="tab === 'build'">
|
<div v-if="tab === 'build'">
|
||||||
<h2>打包设置</h2>
|
<h2>打包设置</h2>
|
||||||
<div style="max-width: 500px;">
|
<div style="max-width: 500px;">
|
||||||
<h4 class="section-title">应用版本号</h4>
|
<template v-for="t in branchTracks" :key="t.name">
|
||||||
<div class="form-group">
|
<h4 class="section-title">
|
||||||
<label>App_Ver(应用版本)</label>
|
{{ t.kind === 'release' ? '上架版本号' : '自测版本号' }}({{ t.branches.join(' / ') }})
|
||||||
<input type="text" v-model="versions.app_ver" placeholder="2.180.0">
|
</h4>
|
||||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">格式:主版本.次版本.修订号</div>
|
<div class="form-group">
|
||||||
</div>
|
<label>App_Ver(应用版本)</label>
|
||||||
<button class="btn btn-primary" style="width: auto; padding: 10px 32px; margin-bottom: 24px;" @click="saveVersions">保存版本号</button>
|
<input type="text" v-model="versions[t.name].app_ver" placeholder="2.180.0" @input="onAppVerInput(t.name)">
|
||||||
|
<div style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||||
|
格式:主版本.次版本.修订号。该版本号只用于 {{ t.branches.join(' / ') }}(轨道 {{ t.name }}),与其它分支 / Tag 互不影响。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Build_Ver(构建号)</label>
|
||||||
|
<input type="text" v-model="versions[t.name].build_ver" placeholder="2.180.0.0">
|
||||||
|
<div v-if="t.kind === 'release'" style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||||
|
四段数字,前三位须与 App_Ver 一致。修改 App_Ver 会自动切换为该版本号已记录的构建号;
|
||||||
|
每个版本号的构建号独立递增,App_Store 打包时自动 +1。一般无需手动修改。
|
||||||
|
</div>
|
||||||
|
<div v-else style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||||
|
四段数字,前三位须与 App_Ver 一致。自测轨打包时<strong>不会自动递增</strong>,
|
||||||
|
始终使用这里填写的值(默认 .0)。需要区分时请手动修改。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" style="width: auto; padding: 10px 32px; margin-bottom: 24px;" @click="saveVersions(t.name)">保存 {{ t.branches.join(' / ') }} 版本号</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
<template v-if="isAdmin">
|
<template v-if="isAdmin">
|
||||||
<h4 class="section-title">打包参数</h4>
|
<h4 class="section-title">打包参数</h4>
|
||||||
@@ -368,17 +451,23 @@
|
|||||||
<label>环境名称 *</label>
|
<label>环境名称 *</label>
|
||||||
<input v-model="serverForm.name" type="text" placeholder="例如:测试环境" :disabled="!!editingServerName">
|
<input v-model="serverForm.name" type="text" placeholder="例如:测试环境" :disabled="!!editingServerName">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<template v-if="isReadoorProject">
|
||||||
<label>API 地址 *</label>
|
<div class="form-group">
|
||||||
<input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn">
|
<label>API 地址 *</label>
|
||||||
</div>
|
<input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn">
|
||||||
<div class="form-group">
|
</div>
|
||||||
<label>Associated Domains</label>
|
<div class="form-group">
|
||||||
<input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn">
|
<label>Associated Domains</label>
|
||||||
</div>
|
<input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn">
|
||||||
<div class="form-group">
|
</div>
|
||||||
<label>Universal Link</label>
|
<div class="form-group">
|
||||||
<input v-model="serverForm.universalLink" type="text" placeholder="https://dev-data1.readoor.cn">
|
<label>Universal Link</label>
|
||||||
|
<input v-model="serverForm.universalLink" type="text" placeholder="https://dev-data1.readoor.cn">
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div v-for="field in serverFields" :key="field.key" class="form-group">
|
||||||
|
<label>{{ field.label }}{{ field.required ? ' *' : '' }}</label>
|
||||||
|
<input v-model="serverForm[field.key]" type="text">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>App ID 前缀</label>
|
<label>App ID 前缀</label>
|
||||||
@@ -422,7 +511,7 @@
|
|||||||
<input v-model.number="appForm.app_id_prefix_override" type="number" min="1" placeholder="仅特殊 App 使用">
|
<input v-model.number="appForm.app_id_prefix_override" type="number" min="1" placeholder="仅特殊 App 使用">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div v-if="isReadoorProject" class="form-row">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>AppGuid *</label>
|
<label>AppGuid *</label>
|
||||||
<input v-model="appForm.AppGuid" type="text" placeholder="应用唯一标识">
|
<input v-model="appForm.AppGuid" type="text" placeholder="应用唯一标识">
|
||||||
@@ -433,7 +522,15 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-if="appFields.length" class="form-row">
|
||||||
|
<div v-for="field in appFields" :key="field.key" class="form-group">
|
||||||
|
<label>{{ field.label }}{{ field.required ? ' *' : '' }}</label>
|
||||||
|
<input v-model="appForm[field.key]" type="text">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 关联配置 -->
|
<!-- 关联配置 -->
|
||||||
|
<template v-if="isReadoorProject">
|
||||||
<h4 class="section-title">关联配置</h4>
|
<h4 class="section-title">关联配置</h4>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -455,16 +552,23 @@
|
|||||||
<input v-model="appForm.weixinpay" type="text" placeholder="wx...">
|
<input v-model="appForm.weixinpay" type="text" placeholder="wx...">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>企业微信 Schema</label>
|
||||||
|
<input v-model="appForm.wxworkSchema" type="text" placeholder="不填则不写入 Info.plist(与微信登录 AppID 相同)">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>腾讯 AppID</label>
|
<label>腾讯 AppID</label>
|
||||||
<input v-model="appForm.tencent" type="text" placeholder="tencent...">
|
<input v-model="appForm.tencent" type="text" placeholder="tencent...(可只填数字,自动补前缀)" @blur="normalizeTencentAppId">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>阿里云 License Key</label>
|
<label>阿里云 License Key</label>
|
||||||
<input v-model="appForm.AlivcLicenseKey" type="text">
|
<input v-model="appForm.AlivcLicenseKey" type="text">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- 证书配置 -->
|
<!-- 证书配置 -->
|
||||||
<h4 class="section-title">证书配置</h4>
|
<h4 class="section-title">证书配置</h4>
|
||||||
@@ -491,7 +595,7 @@
|
|||||||
<label>Provisioning Profile 名称</label>
|
<label>Provisioning Profile 名称</label>
|
||||||
<input v-model="appForm.certificates[certType].pro" type="text" placeholder="/Users/.../xxx.mobileprovision">
|
<input v-model="appForm.certificates[certType].pro" type="text" placeholder="/Users/.../xxx.mobileprovision">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div v-if="isReadoorProject" class="form-group">
|
||||||
<label>主题目录</label>
|
<label>主题目录</label>
|
||||||
<select v-if="appSkins.length"
|
<select v-if="appSkins.length"
|
||||||
:value="appSkins.some(s => s.name.replace('.zip', '') === appForm.certificates[certType].theme) ? appForm.certificates[certType].theme : ''"
|
:value="appSkins.some(s => s.name.replace('.zip', '') === appForm.certificates[certType].theme) ? appForm.certificates[certType].theme : ''"
|
||||||
@@ -511,6 +615,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 皮肤包管理 -->
|
<!-- 皮肤包管理 -->
|
||||||
|
<template v-if="isReadoorProject">
|
||||||
<h4 class="section-title" style="margin-top: 20px;">皮肤包管理</h4>
|
<h4 class="section-title" style="margin-top: 20px;">皮肤包管理</h4>
|
||||||
<div class="skins-section">
|
<div class="skins-section">
|
||||||
<div v-if="!appForm.upload_key" class="skins-hint">请先保存 APP 后再上传皮肤包</div>
|
<div v-if="!appForm.upload_key" class="skins-hint">请先保存 APP 后再上传皮肤包</div>
|
||||||
@@ -519,16 +624,26 @@
|
|||||||
<div v-for="skin in appSkins" :key="skin.name" class="skin-item">
|
<div v-for="skin in appSkins" :key="skin.name" class="skin-item">
|
||||||
<span class="skin-name">{{ skin.name }}</span>
|
<span class="skin-name">{{ skin.name }}</span>
|
||||||
<span class="skin-size">{{ formatSize(skin.size) }}</span>
|
<span class="skin-size">{{ formatSize(skin.size) }}</span>
|
||||||
|
<label class="skin-update-btn" :class="{ disabled: skinUploading }" title="更新(保持文件名不变)">
|
||||||
|
更新
|
||||||
|
<input type="file" accept=".zip" @change="updateSkin(skin.name, $event)" :disabled="skinUploading" hidden>
|
||||||
|
</label>
|
||||||
<button class="btn-icon btn-danger-icon" @click="deleteSkin(skin.name)" title="删除">×</button>
|
<button class="btn-icon btn-danger-icon" @click="deleteSkin(skin.name)" title="删除">×</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="skins-hint">暂无皮肤包</div>
|
<div v-else class="skins-hint">暂无皮肤包</div>
|
||||||
<label class="btn btn-outline skin-upload-btn" :class="{ disabled: skinUploading }">
|
<label class="btn btn-outline skin-upload-btn"
|
||||||
{{ skinUploading ? '上传中...' : '上传皮肤包 (.zip)' }}
|
:class="{ disabled: skinUploading, dragover: skinDragover }"
|
||||||
|
@dragover.prevent="skinDragover = true"
|
||||||
|
@dragenter.prevent="skinDragover = true"
|
||||||
|
@dragleave.prevent="skinDragover = false"
|
||||||
|
@drop.prevent="onSkinDrop">
|
||||||
|
{{ skinUploading ? '上传中...' : (skinDragover ? '松开鼠标上传' : '上传皮肤包 (.zip,或拖拽到此处)') }}
|
||||||
<input type="file" accept=".zip" @change="uploadSkin" :disabled="skinUploading" hidden>
|
<input type="file" accept=".zip" @change="uploadSkin" :disabled="skinUploading" hidden>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
|
<div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
|
||||||
<button class="action-btn" style="padding: 8px 16px;" @click="showAppModal = false">取消</button>
|
<button class="action-btn" style="padding: 8px 16px;" @click="showAppModal = false">取消</button>
|
||||||
@@ -537,6 +652,118 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 项目编辑弹窗 -->
|
||||||
|
<div v-if="showProjectModal" class="modal-overlay" @click.self="showProjectModal = false">
|
||||||
|
<div class="modal-content modal-large">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>{{ editingProjectId ? '编辑' : '新增' }}项目</h3>
|
||||||
|
<button class="modal-close" @click="showProjectModal = false">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>项目 ID *</label>
|
||||||
|
<input v-model="projectForm.id" type="text" placeholder="例如:dyauction(小写字母开头)" :disabled="!!editingProjectId">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>项目名称 *</label>
|
||||||
|
<input v-model="projectForm.name" type="text" placeholder="例如:多云选">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 class="section-title">源码仓库</h4>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Git 仓库地址</label>
|
||||||
|
<input v-model="projectForm.git.remote_url" type="text" placeholder="https://git.example.com/group/repo.git">
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Git 用户名</label>
|
||||||
|
<input v-model="projectForm.git.username" type="text" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Git 密码 / Token</label>
|
||||||
|
<input v-model="projectForm.git.password" type="password" autocomplete="new-password"
|
||||||
|
:placeholder="projectForm.git.password_set ? '已设置,留空保持不变' : ''">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="checkbox-label" style="margin-bottom: 12px;">
|
||||||
|
<input type="checkbox" v-model="projectForm.git.use_env">
|
||||||
|
未填写的 Git 配置使用 .env 中的 GIT_REMOTE_URL / GIT_USERNAME / GIT_PASSWORD
|
||||||
|
</label>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>共享源码目录</label>
|
||||||
|
<input v-model="projectForm.source_dir" type="text" :placeholder="`留空为 <服务目录>/sources/${projectForm.id || '<项目 ID>'}`">
|
||||||
|
<div class="field-hint">打包时会对该目录执行 git reset --hard 和 git clean,不要指向本地开发用的工作副本。</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 class="section-title">Xcode 工程</h4>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Workspace</label>
|
||||||
|
<input v-model="projectForm.xcode.workspace" type="text" placeholder="X.xcworkspace(使用 CocoaPods 时填写)">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Project</label>
|
||||||
|
<input v-model="projectForm.xcode.project" type="text" placeholder="X.xcodeproj">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>配置替换方式</label>
|
||||||
|
<select v-model="projectForm.patcher">
|
||||||
|
<option value="generic">通用(版本号、签名 + 替换规则)</option>
|
||||||
|
<option value="readoor">Readoor 专用</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>代码混淆</label>
|
||||||
|
<label class="checkbox-label"><input type="checkbox" v-model="projectForm.obfuscation"> 支持代码混淆</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>拷贝条目(每行一个,留空拷贝整个仓库)</label>
|
||||||
|
<textarea v-model="projectForm.copy_items_text" rows="3" class="code-textarea"></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 class="section-title">钉钉 @ 人员(留空使用全局名单)</h4>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Ad_Hoc @ 手机号</label>
|
||||||
|
<textarea v-model="projectForm.at_mobiles_text" rows="3" class="code-textarea" placeholder="每行一个,或用逗号分隔"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>App_Store @ 手机号</label>
|
||||||
|
<textarea v-model="projectForm.at_mobiles_app_store_text" rows="3" class="code-textarea" placeholder="每行一个,或用逗号分隔"></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 class="section-title">自定义字段与替换规则(JSON)</h4>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>App 字段</label>
|
||||||
|
<textarea v-model="projectForm.app_fields_text" rows="3" class="code-textarea"
|
||||||
|
placeholder='[{"key": "APPID", "label": "APPID", "required": true}]'></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>服务器环境字段</label>
|
||||||
|
<textarea v-model="projectForm.server_fields_text" rows="3" class="code-textarea"
|
||||||
|
placeholder='[{"key": "ISDEV", "label": "ISDEV(1=开发,0=正式)", "required": true}]'></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>替换规则</label>
|
||||||
|
<textarea v-model="projectForm.patch_rules_text" rows="6" class="code-textarea"
|
||||||
|
placeholder='[{"type": "define", "file": "App/Macro.h", "name": "ISDEV", "value": "${server.ISDEV}"}]'></textarea>
|
||||||
|
<div class="field-hint">
|
||||||
|
define:替换文件中所有未注释的 <code>#define 名称</code> 行;replace_line:整行替换包含 keyword 的行(字段为 line)。
|
||||||
|
值中可用 <code>${app.字段}</code>、<code>${server.字段}</code>、<code>${VERSION}</code> 等。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
|
||||||
|
<button class="action-btn" style="padding: 8px 16px;" @click="showProjectModal = false">取消</button>
|
||||||
|
<button class="btn btn-primary" style="width: auto; padding: 8px 24px;" @click="saveProject">保存</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Scheme 编辑弹窗 -->
|
<!-- Scheme 编辑弹窗 -->
|
||||||
<div v-if="showSchemeModal" class="modal-overlay" @click.self="showSchemeModal = false">
|
<div v-if="showSchemeModal" class="modal-overlay" @click.self="showSchemeModal = false">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
@@ -574,6 +801,16 @@ const isLoggedIn = inject('isLoggedIn')
|
|||||||
const isAdmin = inject('isAdmin')
|
const isAdmin = inject('isAdmin')
|
||||||
const tab = ref('apps')
|
const tab = ref('apps')
|
||||||
|
|
||||||
|
// 当前项目决定 App / 服务器环境表单显示哪些字段
|
||||||
|
const currentProjectInfo = inject('currentProjectInfo', ref(null))
|
||||||
|
const reloadProjects = inject('reloadProjects', async () => {})
|
||||||
|
const isReadoorProject = computed(() => (currentProjectInfo.value?.patcher ?? 'readoor') === 'readoor')
|
||||||
|
const appFields = computed(() => currentProjectInfo.value?.app_fields || [])
|
||||||
|
const serverFields = computed(() => currentProjectInfo.value?.server_fields || [])
|
||||||
|
const missingRequiredFields = (fields, data) => fields
|
||||||
|
.filter(field => field.required && !String(data[field.key] ?? '').trim())
|
||||||
|
.map(field => field.label || field.key)
|
||||||
|
|
||||||
// 用户管理
|
// 用户管理
|
||||||
const users = ref([])
|
const users = ref([])
|
||||||
const showUserModal = ref(false)
|
const showUserModal = ref(false)
|
||||||
@@ -583,23 +820,96 @@ const passwordTarget = ref(null)
|
|||||||
const newPassword = ref('')
|
const newPassword = ref('')
|
||||||
|
|
||||||
// 带认证的 fetch 封装
|
// 带认证的 fetch 封装
|
||||||
|
const currentProject = inject('currentProject', ref(''))
|
||||||
const authFetch = (url, options = {}) => {
|
const authFetch = (url, options = {}) => {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (token) {
|
if (token) {
|
||||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||||
}
|
}
|
||||||
|
if (currentProject.value) {
|
||||||
|
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||||
|
}
|
||||||
return fetch(url, options)
|
return fetch(url, options)
|
||||||
}
|
}
|
||||||
const apps = ref({})
|
const apps = ref({})
|
||||||
const schemes = ref({})
|
const schemes = ref({})
|
||||||
const servers = ref({})
|
const servers = ref({})
|
||||||
const branches = ref([])
|
const branches = ref([])
|
||||||
|
const tags = ref([])
|
||||||
const newBranch = ref('')
|
const newBranch = ref('')
|
||||||
|
const newRefType = ref('branch') // 新增的是分支还是 Tag
|
||||||
|
// 分支管理表格:分支在前,Tag 在后
|
||||||
|
const buildRefs = computed(() => [
|
||||||
|
...branches.value.map(name => ({ name, type: 'branch' })),
|
||||||
|
...tags.value.map(name => ({ name, type: 'tag' })),
|
||||||
|
])
|
||||||
const buildSettings = ref({})
|
const buildSettings = ref({})
|
||||||
const versions = ref({ app_ver: '', build_ver: '' })
|
// 版本轨道:每个分支一条独立轨道,轨道名即分支名(master/main 沿用历史名 release)。
|
||||||
|
// 轨道类型 kind 决定构建号行为:release=上架、App_Store 打包自增;feature=自测、不自增。
|
||||||
|
const versions = ref({}) // 轨道名 -> { app_ver, build_ver }
|
||||||
|
const buildMap = ref({}) // 轨道名 -> { App_Ver: 已用构建号 }
|
||||||
|
const trackKind = ref({}) // 轨道名 -> release | feature
|
||||||
|
const branchTrack = ref({}) // 分支名 -> 轨道名
|
||||||
|
|
||||||
|
const applyVersions = (data) => {
|
||||||
|
const tracks = data.tracks || {}
|
||||||
|
const nextVersions = {}
|
||||||
|
const nextMap = {}
|
||||||
|
const nextKind = {}
|
||||||
|
for (const [name, item] of Object.entries(tracks)) {
|
||||||
|
nextVersions[name] = { app_ver: item.app_ver || '', build_ver: item.build_ver || '' }
|
||||||
|
nextMap[name] = item.build_map || {}
|
||||||
|
nextKind[name] = item.kind || 'release'
|
||||||
|
}
|
||||||
|
versions.value = nextVersions
|
||||||
|
buildMap.value = nextMap
|
||||||
|
trackKind.value = nextKind
|
||||||
|
branchTrack.value = data.branch_track || {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分支所属轨道的类型(供分支管理里的下拉框显示)
|
||||||
|
const branchKind = (branch) => trackKind.value[branchTrack.value[branch]] || 'feature'
|
||||||
|
|
||||||
|
// 打包设置里按分支分块展示版本号;多个分支共用一条轨道时只显示一块
|
||||||
|
const branchTracks = computed(() => {
|
||||||
|
const seen = new Set()
|
||||||
|
const refs = [...branches.value, ...tags.value]
|
||||||
|
return refs
|
||||||
|
.map(b => branchTrack.value[b])
|
||||||
|
.filter(name => name && versions.value[name] && !seen.has(name) && seen.add(name))
|
||||||
|
.map(name => ({
|
||||||
|
name,
|
||||||
|
kind: trackKind.value[name] || 'release',
|
||||||
|
branches: refs.filter(b => branchTrack.value[b] === name),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
// 修改 App_Ver 时,自动把 Build_Ver 切换为该版本号已记录的构建号(新版本号则为 .0)
|
||||||
|
const onAppVerInput = (track) => {
|
||||||
|
const appVer = (versions.value[track]?.app_ver || '').trim()
|
||||||
|
if (/^\d+\.\d+\.\d+$/.test(appVer)) {
|
||||||
|
const n = Number((buildMap.value[track] || {})[appVer] || 0)
|
||||||
|
versions.value[track].build_ver = `${appVer}.${n}`
|
||||||
|
}
|
||||||
|
}
|
||||||
const uploadConfig = ref({ mode: 'oss', oss: {}, webdav: {}, dingtalk: {} })
|
const uploadConfig = ref({ mode: 'oss', oss: {}, webdav: {}, dingtalk: {} })
|
||||||
const jsonContent = ref('{}')
|
const jsonContent = ref('{}')
|
||||||
|
|
||||||
|
// 钉钉 @ 手机号:配置里存字符串数组,输入框按逗号/换行分隔编辑。
|
||||||
|
// Ad_Hoc 与 App_Store 各一份名单。
|
||||||
|
const dingtalkAtMobilesModel = (key) => computed({
|
||||||
|
get: () => (uploadConfig.value.dingtalk?.[key] || []).join('\n'),
|
||||||
|
set: (val) => {
|
||||||
|
if (!uploadConfig.value.dingtalk) uploadConfig.value.dingtalk = {}
|
||||||
|
uploadConfig.value.dingtalk[key] = val
|
||||||
|
.split(/[\s,,]+/)
|
||||||
|
.map(s => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const dingtalkAtMobiles = dingtalkAtMobilesModel('at_mobiles')
|
||||||
|
const dingtalkAtMobilesAppStore = dingtalkAtMobilesModel('at_mobiles_app_store')
|
||||||
|
|
||||||
const showServerModal = ref(false)
|
const showServerModal = ref(false)
|
||||||
const editingServerName = ref(null)
|
const editingServerName = ref(null)
|
||||||
const serverForm = ref({ name: '', api: '', assDom: '', universalLink: '', app_id_prefix: null })
|
const serverForm = ref({ name: '', api: '', assDom: '', universalLink: '', app_id_prefix: null })
|
||||||
@@ -615,6 +925,7 @@ const editingAppId = ref(null)
|
|||||||
const appForm = ref({})
|
const appForm = ref({})
|
||||||
const appSkins = ref([])
|
const appSkins = ref([])
|
||||||
const skinUploading = ref(false)
|
const skinUploading = ref(false)
|
||||||
|
const skinDragover = ref(false)
|
||||||
|
|
||||||
const showSchemeModal = ref(false)
|
const showSchemeModal = ref(false)
|
||||||
const editingSchemeId = ref(null)
|
const editingSchemeId = ref(null)
|
||||||
@@ -626,35 +937,143 @@ onMounted(async () => {
|
|||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
if (!isAdmin.value) {
|
if (!isAdmin.value) {
|
||||||
const [appsRes, versionsRes] = await Promise.all([
|
// 普通用户只能管理 Apps,版本号等配置均为管理员专属
|
||||||
authFetch('/api/config/apps'),
|
const appsRes = await authFetch('/api/config/apps')
|
||||||
authFetch('/api/config/versions'),
|
|
||||||
])
|
|
||||||
if (appsRes.ok) apps.value = await appsRes.json()
|
if (appsRes.ok) apps.value = await appsRes.json()
|
||||||
if (versionsRes.ok) versions.value = await versionsRes.json()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const [appsRes, schemesRes, serversRes, branchesRes, buildRes, uploadRes, configRes, versionsRes, usersRes] = await Promise.all([
|
const [appsRes, schemesRes, serversRes, branchesRes, tagsRes, buildRes, uploadRes, configRes, versionsRes, usersRes, projectsRes] = await Promise.all([
|
||||||
authFetch('/api/config/apps'),
|
authFetch('/api/config/apps'),
|
||||||
authFetch('/api/config/schemes'),
|
authFetch('/api/config/schemes'),
|
||||||
authFetch('/api/config/servers'),
|
authFetch('/api/config/servers'),
|
||||||
authFetch('/api/config/branches'),
|
authFetch('/api/config/branches'),
|
||||||
|
authFetch('/api/config/tags'),
|
||||||
authFetch('/api/config/build'),
|
authFetch('/api/config/build'),
|
||||||
authFetch('/api/config/upload'),
|
authFetch('/api/config/upload'),
|
||||||
authFetch('/api/config'),
|
authFetch('/api/config'),
|
||||||
authFetch('/api/config/versions'),
|
authFetch('/api/config/versions'),
|
||||||
authFetch('/api/users'),
|
authFetch('/api/users'),
|
||||||
|
authFetch('/api/config/projects'),
|
||||||
])
|
])
|
||||||
apps.value = await appsRes.json()
|
apps.value = await appsRes.json()
|
||||||
schemes.value = await schemesRes.json()
|
schemes.value = await schemesRes.json()
|
||||||
servers.value = await serversRes.json()
|
servers.value = await serversRes.json()
|
||||||
branches.value = await branchesRes.json()
|
branches.value = await branchesRes.json()
|
||||||
|
const tagList = await tagsRes.json()
|
||||||
|
tags.value = Array.isArray(tagList) ? tagList : []
|
||||||
buildSettings.value = await buildRes.json()
|
buildSettings.value = await buildRes.json()
|
||||||
uploadConfig.value = await uploadRes.json()
|
uploadConfig.value = await uploadRes.json()
|
||||||
jsonContent.value = JSON.stringify(await configRes.json(), null, 2)
|
jsonContent.value = JSON.stringify(await configRes.json(), null, 2)
|
||||||
versions.value = await versionsRes.json()
|
applyVersions(await versionsRes.json())
|
||||||
if (usersRes.ok) users.value = await usersRes.json()
|
if (usersRes.ok) users.value = await usersRes.json()
|
||||||
|
if (projectsRes?.ok) projectDefinitions.value = await projectsRes.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 项目管理
|
||||||
|
const projectDefinitions = ref([])
|
||||||
|
const showProjectModal = ref(false)
|
||||||
|
const editingProjectId = ref(null)
|
||||||
|
const projectForm = ref({})
|
||||||
|
const splitMobiles = text => (text || '').split(/[\s,,]+/).map(s => s.trim()).filter(Boolean)
|
||||||
|
const toJsonText = value => (value && value.length ? JSON.stringify(value, null, 2) : '')
|
||||||
|
|
||||||
|
const openProjectModal = (project = null) => {
|
||||||
|
editingProjectId.value = project?.id || null
|
||||||
|
const p = project || {
|
||||||
|
id: '', name: '', source_dir: '', patcher: 'generic', obfuscation: false, copy_items: [],
|
||||||
|
git: { remote_url: '', username: '', use_env: false, password_set: false },
|
||||||
|
xcode: { workspace: '', project: '' }, app_fields: [], server_fields: [], patch_rules: [],
|
||||||
|
dingtalk_at: { at_mobiles: [], at_mobiles_app_store: [] },
|
||||||
|
}
|
||||||
|
projectForm.value = {
|
||||||
|
id: p.id,
|
||||||
|
name: p.name,
|
||||||
|
source_dir: p.source_dir || '',
|
||||||
|
patcher: p.patcher,
|
||||||
|
obfuscation: !!p.obfuscation,
|
||||||
|
git: { ...p.git, password: '' },
|
||||||
|
xcode: { ...p.xcode },
|
||||||
|
copy_items_text: (p.copy_items || []).join('\n'),
|
||||||
|
at_mobiles_text: (p.dingtalk_at?.at_mobiles || []).join('\n'),
|
||||||
|
at_mobiles_app_store_text: (p.dingtalk_at?.at_mobiles_app_store || []).join('\n'),
|
||||||
|
app_fields_text: toJsonText(p.app_fields),
|
||||||
|
server_fields_text: toJsonText(p.server_fields),
|
||||||
|
patch_rules_text: toJsonText(p.patch_rules),
|
||||||
|
}
|
||||||
|
showProjectModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveProject = async () => {
|
||||||
|
const form = projectForm.value
|
||||||
|
if (!form.id || !form.name) {
|
||||||
|
alert('请填写必填字段:项目 ID、项目名称')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const parsed = {}
|
||||||
|
for (const [key, label] of [['app_fields', 'App 字段'], ['server_fields', '服务器环境字段'], ['patch_rules', '替换规则']]) {
|
||||||
|
const text = (form[`${key}_text`] || '').trim()
|
||||||
|
try {
|
||||||
|
parsed[key] = text ? JSON.parse(text) : []
|
||||||
|
} catch {
|
||||||
|
alert(`${label} 不是有效的 JSON`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!Array.isArray(parsed[key])) {
|
||||||
|
alert(`${label} 必须是 JSON 数组`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const { password_set: _passwordSet, ...git } = form.git
|
||||||
|
const body = {
|
||||||
|
id: form.id,
|
||||||
|
name: form.name,
|
||||||
|
git,
|
||||||
|
source_dir: form.source_dir,
|
||||||
|
xcode: form.xcode,
|
||||||
|
patcher: form.patcher,
|
||||||
|
obfuscation: form.obfuscation,
|
||||||
|
copy_items: form.copy_items_text.split('\n').map(item => item.trim()).filter(Boolean),
|
||||||
|
dingtalk_at: {
|
||||||
|
at_mobiles: splitMobiles(form.at_mobiles_text),
|
||||||
|
at_mobiles_app_store: splitMobiles(form.at_mobiles_app_store_text),
|
||||||
|
},
|
||||||
|
...parsed,
|
||||||
|
}
|
||||||
|
const editing = editingProjectId.value
|
||||||
|
try {
|
||||||
|
const res = await authFetch(editing ? `/api/config/projects/${encodeURIComponent(editing)}` : '/api/config/projects', {
|
||||||
|
method: editing ? 'PUT' : 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}))
|
||||||
|
throw new Error(err.detail || '保存失败')
|
||||||
|
}
|
||||||
|
showProjectModal.value = false
|
||||||
|
await loadData()
|
||||||
|
await reloadProjects()
|
||||||
|
alert('保存成功')
|
||||||
|
} catch (e) {
|
||||||
|
alert('保存失败: ' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteProject = async (project) => {
|
||||||
|
if (!confirm(`确定删除项目「${project.name}」?该项目的 Apps、Schemes、服务器环境、分支和版本配置都会删除(打包记录保留)。`)) return
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/config/projects/${encodeURIComponent(project.id)}`, { method: 'DELETE' })
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}))
|
||||||
|
throw new Error(err.detail || '删除失败')
|
||||||
|
}
|
||||||
|
await loadData()
|
||||||
|
await reloadProjects()
|
||||||
|
alert('删除成功')
|
||||||
|
} catch (e) {
|
||||||
|
alert('删除失败: ' + e.message)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 用户管理
|
// 用户管理
|
||||||
@@ -752,8 +1171,13 @@ const openServerModal = (name = null, server = null) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const saveServer = async () => {
|
const saveServer = async () => {
|
||||||
if (!serverForm.value.name || !serverForm.value.api) {
|
const missing = [
|
||||||
alert('请填写必填字段:环境名称、API 地址')
|
...(!serverForm.value.name ? ['环境名称'] : []),
|
||||||
|
...(isReadoorProject.value && !serverForm.value.api ? ['API 地址'] : []),
|
||||||
|
...missingRequiredFields(serverFields.value, serverForm.value),
|
||||||
|
]
|
||||||
|
if (missing.length) {
|
||||||
|
alert(`请填写必填字段:${missing.join('、')}`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -818,6 +1242,7 @@ const openAppModal = (id = null, app = null) => {
|
|||||||
UniversalLink: '',
|
UniversalLink: '',
|
||||||
weixinlogin: '',
|
weixinlogin: '',
|
||||||
weixinpay: '',
|
weixinpay: '',
|
||||||
|
wxworkSchema: '',
|
||||||
tencent: '',
|
tencent: '',
|
||||||
AlivcLicenseKey: '',
|
AlivcLicenseKey: '',
|
||||||
app_id_prefix_override: '',
|
app_id_prefix_override: '',
|
||||||
@@ -862,9 +1287,9 @@ const loadSkins = async () => {
|
|||||||
} catch { appSkins.value = [] }
|
} catch { appSkins.value = [] }
|
||||||
}
|
}
|
||||||
|
|
||||||
const uploadSkin = async (event) => {
|
const uploadSkinFile = async (file) => {
|
||||||
const file = event.target.files[0]
|
|
||||||
if (!file) return
|
if (!file) return
|
||||||
|
if (!file.name.toLowerCase().endsWith('.zip')) { alert('仅支持 .zip 格式'); return }
|
||||||
const uploadKey = appForm.value.upload_key
|
const uploadKey = appForm.value.upload_key
|
||||||
if (!uploadKey) { alert('请先保存 APP 后再上传皮肤包'); return }
|
if (!uploadKey) { alert('请先保存 APP 后再上传皮肤包'); return }
|
||||||
skinUploading.value = true
|
skinUploading.value = true
|
||||||
@@ -880,7 +1305,12 @@ const uploadSkin = async (event) => {
|
|||||||
throw new Error(err.detail || '上传失败')
|
throw new Error(err.detail || '上传失败')
|
||||||
}
|
}
|
||||||
await loadSkins()
|
await loadSkins()
|
||||||
event.target.value = ''
|
// 若某证书的主题目录还是空的,自动选中刚上传的皮肤
|
||||||
|
const skinTheme = file.name.replace(/\.zip$/i, '')
|
||||||
|
const certs = appForm.value.certificates || {}
|
||||||
|
Object.keys(certs).forEach(certType => {
|
||||||
|
if (!certs[certType].theme) certs[certType].theme = skinTheme
|
||||||
|
})
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert('上传失败: ' + e.message)
|
alert('上传失败: ' + e.message)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -888,6 +1318,44 @@ const uploadSkin = async (event) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const uploadSkin = async (event) => {
|
||||||
|
await uploadSkinFile(event.target.files[0])
|
||||||
|
event.target.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSkinDrop = (event) => {
|
||||||
|
skinDragover.value = false
|
||||||
|
if (skinUploading.value) return
|
||||||
|
const file = event.dataTransfer.files[0]
|
||||||
|
uploadSkinFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateSkin = async (skinName, event) => {
|
||||||
|
const file = event.target.files[0]
|
||||||
|
if (!file) return
|
||||||
|
const uploadKey = appForm.value.upload_key
|
||||||
|
if (!uploadKey) { event.target.value = ''; return }
|
||||||
|
skinUploading.value = true
|
||||||
|
try {
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
const res = await authFetch(`/api/config/skins/${uploadKey}/${skinName}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: formData,
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json()
|
||||||
|
throw new Error(err.detail || '更新失败')
|
||||||
|
}
|
||||||
|
await loadSkins()
|
||||||
|
} catch (e) {
|
||||||
|
alert('更新失败: ' + e.message)
|
||||||
|
} finally {
|
||||||
|
event.target.value = ''
|
||||||
|
skinUploading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const deleteSkin = async (skinName) => {
|
const deleteSkin = async (skinName) => {
|
||||||
if (!confirm(`确定删除皮肤包 ${skinName}?`)) return
|
if (!confirm(`确定删除皮肤包 ${skinName}?`)) return
|
||||||
const uploadKey = appForm.value.upload_key
|
const uploadKey = appForm.value.upload_key
|
||||||
@@ -906,12 +1374,25 @@ const formatSize = (bytes) => {
|
|||||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 腾讯 AppID 统一带 tencent 前缀(允许只填数字 ID)
|
||||||
|
const normalizeTencentAppId = () => {
|
||||||
|
const value = (appForm.value.tencent || '').trim()
|
||||||
|
appForm.value.tencent = value && !value.startsWith('tencent') ? `tencent${value}` : value
|
||||||
|
}
|
||||||
|
|
||||||
const saveApp = async () => {
|
const saveApp = async () => {
|
||||||
if (!appForm.value.name || !appForm.value.AppGuid) {
|
const missing = [
|
||||||
alert('请填写必填字段:App 名称、AppGuid')
|
...(!appForm.value.name ? ['App 名称'] : []),
|
||||||
|
...(isReadoorProject.value && !appForm.value.AppGuid ? ['AppGuid'] : []),
|
||||||
|
...missingRequiredFields(appFields.value, appForm.value),
|
||||||
|
]
|
||||||
|
if (missing.length) {
|
||||||
|
alert(`请填写必填字段:${missing.join('、')}`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
normalizeTencentAppId()
|
||||||
|
|
||||||
// 清理空证书
|
// 清理空证书
|
||||||
if (appForm.value.certificates) {
|
if (appForm.value.certificates) {
|
||||||
Object.keys(appForm.value.certificates).forEach(key => {
|
Object.keys(appForm.value.certificates).forEach(key => {
|
||||||
@@ -948,9 +1429,18 @@ const saveApp = async () => {
|
|||||||
const err = await res.json().catch(() => ({ detail: '保存失败' }))
|
const err = await res.json().catch(() => ({ detail: '保存失败' }))
|
||||||
throw new Error(err.detail || '保存失败')
|
throw new Error(err.detail || '保存失败')
|
||||||
}
|
}
|
||||||
showAppModal.value = false
|
|
||||||
await loadData()
|
await loadData()
|
||||||
alert('保存成功')
|
if (!editingAppId.value) {
|
||||||
|
// 新建成功:不关弹窗,转为编辑态并回填 upload_key,让皮肤包上传区立即可用
|
||||||
|
const data = await res.json().catch(() => ({}))
|
||||||
|
editingAppId.value = data.id || editingAppId.value
|
||||||
|
if (data.upload_key) appForm.value.upload_key = data.upload_key
|
||||||
|
await loadSkins()
|
||||||
|
alert('保存成功,现在可以上传皮肤包了')
|
||||||
|
} else {
|
||||||
|
showAppModal.value = false
|
||||||
|
alert('保存成功')
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert('保存失败: ' + e.message)
|
alert('保存失败: ' + e.message)
|
||||||
}
|
}
|
||||||
@@ -1005,12 +1495,12 @@ const deleteScheme = async (id) => {
|
|||||||
await loadData()
|
await loadData()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 分支管理
|
// 分支管理(分支与 Tag 共用一张表)
|
||||||
const addBranch = async () => {
|
const addBranch = async () => {
|
||||||
const name = newBranch.value.trim()
|
const name = newBranch.value.trim()
|
||||||
if (!name) return
|
if (!name) return
|
||||||
try {
|
try {
|
||||||
const res = await authFetch('/api/config/branches', {
|
const res = await authFetch(newRefType.value === 'tag' ? '/api/config/tags' : '/api/config/branches', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ name }),
|
body: JSON.stringify({ name }),
|
||||||
@@ -1026,10 +1516,31 @@ const addBranch = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteBranch = async (name) => {
|
const setBranchTrack = async (name, track) => {
|
||||||
if (!confirm(`确定删除分支「${name}」?`)) return
|
|
||||||
try {
|
try {
|
||||||
const res = await authFetch(`/api/config/branches/${encodeURIComponent(name)}`, { method: 'DELETE' })
|
const res = await authFetch('/api/config/branches/track', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ branch: name, track }),
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json()
|
||||||
|
throw new Error(err.detail || '修改失败')
|
||||||
|
}
|
||||||
|
// 切到上架轨可能新建了轨道,重新拉取版本号
|
||||||
|
applyVersions(await (await authFetch('/api/config/versions')).json())
|
||||||
|
} catch (e) {
|
||||||
|
alert('修改失败: ' + e.message)
|
||||||
|
await loadData()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteBranch = async ({ name, type }) => {
|
||||||
|
const isTag = type === 'tag'
|
||||||
|
if (!confirm(`确定删除${isTag ? ' Tag ' : '分支'}「${name}」?`)) return
|
||||||
|
try {
|
||||||
|
const base = isTag ? '/api/config/tags' : '/api/config/branches'
|
||||||
|
const res = await authFetch(`${base}/${encodeURIComponent(name)}`, { method: 'DELETE' })
|
||||||
if (!res.ok) throw new Error('删除失败')
|
if (!res.ok) throw new Error('删除失败')
|
||||||
await loadData()
|
await loadData()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1047,16 +1558,25 @@ const saveBuildSettings = async () => {
|
|||||||
alert('设置已保存')
|
alert('设置已保存')
|
||||||
}
|
}
|
||||||
|
|
||||||
const saveVersions = async () => {
|
const saveVersions = async (track) => {
|
||||||
try {
|
try {
|
||||||
const res = await authFetch('/api/config/versions', {
|
const res = await authFetch('/api/config/versions', {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ app_ver: versions.value.app_ver }),
|
body: JSON.stringify({
|
||||||
|
track,
|
||||||
|
app_ver: versions.value[track].app_ver,
|
||||||
|
build_ver: versions.value[track].build_ver,
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
versions.value = { app_ver: data.app_ver, build_ver: data.build_ver }
|
// 回写该版本号最新的构建号,保持本地 build_map 与服务端一致
|
||||||
|
buildMap.value[track] = {
|
||||||
|
...(buildMap.value[track] || {}),
|
||||||
|
[data.app_ver]: Number((data.build_ver.split('.')[3]) || 0),
|
||||||
|
}
|
||||||
|
versions.value[track] = { app_ver: data.app_ver, build_ver: data.build_ver }
|
||||||
alert('版本号已保存')
|
alert('版本号已保存')
|
||||||
} else {
|
} else {
|
||||||
const err = await res.json()
|
const err = await res.json()
|
||||||
@@ -1141,6 +1661,9 @@ const formatJson = () => {
|
|||||||
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
|
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
|
||||||
.modal-content { background: white; border-radius: 12px; padding: 24px; width: 500px; max-height: 80vh; overflow-y: auto; }
|
.modal-content { background: white; border-radius: 12px; padding: 24px; width: 500px; max-height: 80vh; overflow-y: auto; }
|
||||||
.modal-large { width: 700px; }
|
.modal-large { width: 700px; }
|
||||||
|
.sidebar-project { font-size: 12px; color: #888; margin: -8px 0 12px; }
|
||||||
|
.code-textarea { width: 100%; font-family: Menlo, Monaco, monospace; font-size: 12px; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px; resize: vertical; box-sizing: border-box; }
|
||||||
|
.field-hint { font-size: 12px; color: #999; margin-top: 4px; line-height: 1.6; }
|
||||||
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
|
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
|
||||||
.modal-header h3 { font-size: 16px; margin: 0; }
|
.modal-header h3 { font-size: 16px; margin: 0; }
|
||||||
.modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
|
.modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
|
||||||
@@ -1160,9 +1683,13 @@ const formatJson = () => {
|
|||||||
.btn-icon { width: 24px; height: 24px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; line-height: 1; display: flex; align-items: center; justify-content: center; }
|
.btn-icon { width: 24px; height: 24px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; line-height: 1; display: flex; align-items: center; justify-content: center; }
|
||||||
.btn-danger-icon { background: #fff1f0; color: #ff4d4f; }
|
.btn-danger-icon { background: #fff1f0; color: #ff4d4f; }
|
||||||
.btn-danger-icon:hover { background: #ff4d4f; color: white; }
|
.btn-danger-icon:hover { background: #ff4d4f; color: white; }
|
||||||
|
.skin-update-btn { font-size: 12px; color: #1890ff; cursor: pointer; padding: 2px 8px; border: 1px solid #91d5ff; border-radius: 4px; background: #e6f7ff; line-height: 1.4; }
|
||||||
|
.skin-update-btn:hover { background: #1890ff; color: white; }
|
||||||
|
.skin-update-btn.disabled { opacity: 0.5; pointer-events: none; }
|
||||||
.btn-outline { background: white; border: 1px solid #1890ff; color: #1890ff; cursor: pointer; padding: 6px 16px; border-radius: 6px; font-size: 13px; display: inline-block; }
|
.btn-outline { background: white; border: 1px solid #1890ff; color: #1890ff; cursor: pointer; padding: 6px 16px; border-radius: 6px; font-size: 13px; display: inline-block; }
|
||||||
.btn-outline:hover { background: #e6f7ff; }
|
.btn-outline:hover { background: #e6f7ff; }
|
||||||
.btn-outline.disabled { opacity: 0.5; cursor: not-allowed; }
|
.btn-outline.disabled { opacity: 0.5; cursor: not-allowed; }
|
||||||
.skin-upload-btn { margin-top: 8px; }
|
.skin-upload-btn { margin-top: 8px; transition: background 0.15s, border-color 0.15s; }
|
||||||
|
.skin-upload-btn.dragover { border-color: #1890ff; border-style: dashed; background: #e6f7ff; color: #1890ff; }
|
||||||
.theme-select { width: 100%; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px; }
|
.theme-select { width: 100%; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
<option value="failed">失败</option>
|
<option value="failed">失败</option>
|
||||||
<option value="cancelled">已取消</option>
|
<option value="cancelled">已取消</option>
|
||||||
</select>
|
</select>
|
||||||
|
<label v-if="isAdmin" class="superseded-toggle"><input v-model="showSuperseded" type="checkbox" @change="loadTasks"> 显示已覆盖</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<table class="config-table">
|
<table class="config-table">
|
||||||
@@ -55,7 +56,7 @@
|
|||||||
<img v-if="task.build_type === 'Ad_Hoc' && task.qr_code_path"
|
<img v-if="task.build_type === 'Ad_Hoc' && task.qr_code_path"
|
||||||
:src="task.qr_code_path" alt="QR" class="qr-thumb"
|
:src="task.qr_code_path" alt="QR" class="qr-thumb"
|
||||||
@click="showQrPreview(task)">
|
@click="showQrPreview(task)">
|
||||||
<a v-if="task.build_type === 'App_Store'" :href="task.oss_url" target="_blank" class="download-link">下载 IPA</a>
|
<button v-if="task.build_type === 'App_Store'" class="download-link" :disabled="!!downloadingIds[task.id]" @click="downloadIpa(task.id)">{{ downloadingIds[task.id] ? '下载中...' : '下载 IPA' }}</button>
|
||||||
</template>
|
</template>
|
||||||
<span v-else class="text-muted">-</span>
|
<span v-else class="text-muted">-</span>
|
||||||
</td>
|
</td>
|
||||||
@@ -109,7 +110,7 @@
|
|||||||
<span :class="['build-type-badge', logTask?.build_type === 'App_Store' ? 'badge-appstore' : 'badge-adhoc']">{{ logTask?.build_type }}</span>
|
<span :class="['build-type-badge', logTask?.build_type === 'App_Store' ? 'badge-appstore' : 'badge-adhoc']">{{ logTask?.build_type }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="meta-item">
|
<div class="meta-item">
|
||||||
<span class="meta-label">分支</span>
|
<span class="meta-label">{{ logTask?.ref_type === 'tag' ? 'Tag' : '分支' }}</span>
|
||||||
<span class="meta-value">{{ logTask?.branch || '-' }}</span>
|
<span class="meta-value">{{ logTask?.branch || '-' }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="meta-item">
|
<div class="meta-item">
|
||||||
@@ -158,17 +159,21 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, nextTick, onUnmounted, inject } from 'vue'
|
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, inject } from 'vue'
|
||||||
|
|
||||||
const getToken = inject('getToken', () => '')
|
const getToken = inject('getToken', () => '')
|
||||||
const isAdmin = inject('isAdmin', ref(false))
|
const isAdmin = inject('isAdmin', ref(false))
|
||||||
const tasks = ref([])
|
const tasks = ref([])
|
||||||
|
|
||||||
|
const currentProject = inject('currentProject', ref(''))
|
||||||
const authFetch = (url, options = {}) => {
|
const authFetch = (url, options = {}) => {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (token) {
|
if (token) {
|
||||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||||
}
|
}
|
||||||
|
if (currentProject.value) {
|
||||||
|
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||||
|
}
|
||||||
return fetch(url, options)
|
return fetch(url, options)
|
||||||
}
|
}
|
||||||
const filterStatus = ref('')
|
const filterStatus = ref('')
|
||||||
@@ -180,6 +185,8 @@ const logLines = ref([])
|
|||||||
const logContainer = ref(null)
|
const logContainer = ref(null)
|
||||||
const showVerboseLogs = ref(false)
|
const showVerboseLogs = ref(false)
|
||||||
const qrPreview = ref(null)
|
const qrPreview = ref(null)
|
||||||
|
const showSuperseded = ref(false)
|
||||||
|
const downloadingIds = reactive({})
|
||||||
let logWs = null
|
let logWs = null
|
||||||
|
|
||||||
const getAppVersion = (task) => {
|
const getAppVersion = (task) => {
|
||||||
@@ -210,11 +217,13 @@ const filteredTasks = computed(() => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
onMounted(async () => {
|
const loadTasks = async () => {
|
||||||
const res = await authFetch('/api/tasks?limit=100')
|
const res = await authFetch(`/api/tasks?limit=100${showSuperseded.value ? '&include_superseded=true' : ''}`)
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
tasks.value = data.map(task => ({ ...task, app_version: getAppVersion(task) }))
|
tasks.value = data.map(task => ({ ...task, app_version: getAppVersion(task) }))
|
||||||
})
|
}
|
||||||
|
|
||||||
|
onMounted(loadTasks)
|
||||||
|
|
||||||
const viewLogs = async (taskId) => {
|
const viewLogs = async (taskId) => {
|
||||||
const task = tasks.value.find(t => t.id === taskId)
|
const task = tasks.value.find(t => t.id === taskId)
|
||||||
@@ -304,12 +313,61 @@ onUnmounted(() => {
|
|||||||
if (logWs) { logWs.close(); logWs = null }
|
if (logWs) { logWs.close(); logWs = null }
|
||||||
})
|
})
|
||||||
|
|
||||||
const downloadDsym = (taskId) => {
|
const triggerBlobDownload = (blob, filename) => {
|
||||||
window.open(`/api/tasks/${taskId}/dsym`)
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = url
|
||||||
|
a.download = filename || ''
|
||||||
|
document.body.appendChild(a)
|
||||||
|
a.click()
|
||||||
|
a.remove()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
const downloadObfMaps = (taskId) => {
|
const filenameFromDisposition = (res, fallback) => {
|
||||||
window.open(`/api/tasks/${taskId}/obfuscation-maps`)
|
const cd = res.headers.get('content-disposition') || ''
|
||||||
|
const match = cd.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i)
|
||||||
|
return match ? decodeURIComponent(match[1]) : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
const downloadDsym = async (taskId) => {
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/tasks/${taskId}/dsym`)
|
||||||
|
if (!res.ok) throw new Error()
|
||||||
|
if ((res.headers.get('content-type') || '').includes('application/json')) {
|
||||||
|
const { url } = await res.json()
|
||||||
|
window.open(url, '_blank')
|
||||||
|
} else {
|
||||||
|
triggerBlobDownload(await res.blob(), filenameFromDisposition(res, 'dsym.zip'))
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
alert('下载失败,请稍后重试')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const downloadIpa = async (taskId) => {
|
||||||
|
if (downloadingIds[taskId]) return
|
||||||
|
downloadingIds[taskId] = true
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/tasks/${taskId}/download-link`)
|
||||||
|
if (!res.ok) throw new Error()
|
||||||
|
const { url } = await res.json()
|
||||||
|
window.open(url, '_blank')
|
||||||
|
} catch {
|
||||||
|
alert('下载失败,请稍后重试')
|
||||||
|
} finally {
|
||||||
|
delete downloadingIds[taskId]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const downloadObfMaps = async (taskId) => {
|
||||||
|
try {
|
||||||
|
const res = await authFetch(`/api/tasks/${taskId}/obfuscation-maps`)
|
||||||
|
if (!res.ok) throw new Error()
|
||||||
|
triggerBlobDownload(await res.blob(), filenameFromDisposition(res, 'obfuscation_maps.zip'))
|
||||||
|
} catch {
|
||||||
|
alert('下载失败,请稍后重试')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteTask = async (taskId) => {
|
const deleteTask = async (taskId) => {
|
||||||
@@ -457,6 +515,7 @@ const errorCategoryLabel = (cat) => {
|
|||||||
.meta-value { font-size: 13px; color: #333; font-weight: 500; }
|
.meta-value { font-size: 13px; color: #333; font-weight: 500; }
|
||||||
|
|
||||||
.version-filter { width: 150px; }
|
.version-filter { width: 150px; }
|
||||||
|
.superseded-toggle { display: flex; align-items: center; gap: 4px; color: #666; font-size: 13px; white-space: nowrap; }
|
||||||
|
|
||||||
/* 日志操作栏 */
|
/* 日志操作栏 */
|
||||||
.log-modal-actions {
|
.log-modal-actions {
|
||||||
@@ -506,10 +565,12 @@ const errorCategoryLabel = (cat) => {
|
|||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
}
|
}
|
||||||
.btn-close-log:hover { border-color: #1890ff; color: #1890ff; }
|
.btn-close-log:hover { border-color: #1890ff; color: #1890ff; }
|
||||||
.download-link { color: #1890ff; text-decoration: none; font-size: 13px; }
|
.download-link { color: #1890ff; text-decoration: none; font-size: 13px; border: none; background: none; cursor: pointer; padding: 0; }
|
||||||
.download-link:hover { text-decoration: underline; }
|
.download-link:hover { text-decoration: underline; }
|
||||||
|
.download-link:disabled { color: #999; cursor: default; }
|
||||||
|
.download-link:disabled:hover { text-decoration: none; }
|
||||||
.text-muted { color: #999; font-size: 13px; }
|
.text-muted { color: #999; font-size: 13px; }
|
||||||
.qr-thumb { width: 40px; height: 40px; cursor: pointer; border-radius: 4px; border: 1px solid #e8e8e8; }
|
.qr-thumb { width: 40px; height: 40px; object-fit: cover; cursor: pointer; border-radius: 4px; border: 1px solid #e8e8e8; }
|
||||||
.qr-thumb:hover { border-color: #1890ff; }
|
.qr-thumb:hover { border-color: #1890ff; }
|
||||||
.btn-danger { color: #ff4d4f; border-color: #ff4d4f; }
|
.btn-danger { color: #ff4d4f; border-color: #ff4d4f; }
|
||||||
.btn-danger:hover { background: #ff4d4f; color: white; }
|
.btn-danger:hover { background: #ff4d4f; color: white; }
|
||||||
@@ -519,7 +580,7 @@ const errorCategoryLabel = (cat) => {
|
|||||||
.qr-preview-modal .modal-header { display: flex; justify-content: center; align-items: center; position: relative; margin-bottom: 16px; }
|
.qr-preview-modal .modal-header { display: flex; justify-content: center; align-items: center; position: relative; margin-bottom: 16px; }
|
||||||
.qr-preview-modal .modal-close { position: absolute; right: 0; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 20px; cursor: pointer; color: #999; }
|
.qr-preview-modal .modal-close { position: absolute; right: 0; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 20px; cursor: pointer; color: #999; }
|
||||||
.qr-preview-modal .modal-close:hover { color: #333; }
|
.qr-preview-modal .modal-close:hover { color: #333; }
|
||||||
.qr-preview-img { width: 260px; height: 260px; border: 1px solid #f0f0f0; border-radius: 8px; margin: 16px 0; }
|
.qr-preview-img { width: 260px; height: 260px; object-fit: contain; border: 1px solid #f0f0f0; border-radius: 8px; margin: 16px 0; }
|
||||||
.qr-preview-info { text-align: left; padding: 12px 16px; background: #fafafa; border-radius: 8px; }
|
.qr-preview-info { text-align: left; padding: 12px 16px; background: #fafafa; border-radius: 8px; }
|
||||||
.qr-preview-info p { margin: 6px 0; font-size: 13px; color: #555; }
|
.qr-preview-info p { margin: 6px 0; font-size: 13px; color: #555; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<template>
|
||||||
|
<div v-if="isAdmin" class="container">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="header-row"><h2>操作日志</h2><div><select v-model.number="days" @change="load"><option :value="7">近 7 天</option><option :value="30">近 30 天</option><option :value="90">近 90 天</option></select><button @click="exportCsv">导出 CSV</button></div></div>
|
||||||
|
<div class="cards"><div><strong>{{ summary.total || 0 }}</strong><span>操作总数</span></div><div><strong>{{ summary.action_counts?.build_created || 0 }}</strong><span>发起打包</span></div><div><strong>{{ summary.action_counts?.ipa_download_requested || 0 }}</strong><span>发起 IPA 下载</span></div></div>
|
||||||
|
<div class="columns"><section><h3>活跃用户</h3><p v-for="item in summary.top_users || []" :key="item.name">{{ item.name }} <b>{{ item.count }}</b></p></section><section><h3>App 操作量</h3><p v-for="item in summary.top_apps || []" :key="item.name">{{ item.name }} <b>{{ item.count }}</b></p></section></div>
|
||||||
|
<table><thead><tr><th>时间</th><th>用户</th><th>操作</th><th>App</th><th>资源</th><th>版本</th></tr></thead><tbody><tr v-for="log in logs" :key="log.id"><td>{{ formatTime(log.created_at) }}</td><td>{{ log.username }}</td><td>{{ actionText(log.action) }}</td><td>{{ log.app_name || '-' }}</td><td>{{ log.resource_type || '-' }}</td><td>{{ log.action === 'ipa_download_requested' ? (log.version || '-') : '-' }}</td></tr><tr v-if="!logs.length"><td colspan="6">暂无操作记录</td></tr></tbody></table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup>
|
||||||
|
import { inject, ref, onMounted } from 'vue'
|
||||||
|
const isAdmin = inject('isAdmin', ref(false)); const getToken = inject('getToken', () => '')
|
||||||
|
const days = ref(30); const summary = ref({}); const logs = ref([])
|
||||||
|
const authFetch = (url) => fetch(url, { headers: { Authorization: `Bearer ${getToken()}` } })
|
||||||
|
const load = async () => { const [summaryRes, logsRes] = await Promise.all([authFetch(`/api/operations/summary?days=${days.value}`), authFetch(`/api/operations?days=${days.value}`)]); if (summaryRes.ok) summary.value = await summaryRes.json(); if (logsRes.ok) logs.value = await logsRes.json() }
|
||||||
|
const exportCsv = async () => { const res = await authFetch(`/api/operations/export?days=${days.value}`); if (!res.ok) return; const blob = await res.blob(); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'operation-logs.csv'; link.click(); URL.revokeObjectURL(url) }
|
||||||
|
const formatTime = value => value ? new Date(value.endsWith('Z') ? value : `${value}Z`).toLocaleString('zh-CN', { hour12: false }) : '-'
|
||||||
|
const actionText = action => ({ build_created: '发起打包', build_cancelled: '取消打包', task_deleted: '删除记录', ipa_download_requested: '发起 IPA 下载', dsym_downloaded: '下载 dSYM', obfuscation_maps_downloaded: '下载混淆映射' }[action] || action)
|
||||||
|
onMounted(load)
|
||||||
|
</script>
|
||||||
|
<style scoped>
|
||||||
|
.container{max-width:1200px;margin:0 auto;padding:24px}.panel{background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px #00000014}.header-row{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}.header-row h2{margin:0}.header-row select,.header-row button{padding:8px 12px;margin-left:8px;border:1px solid #d9d9d9;border-radius:6px;background:#fff}.header-row button{color:#1890ff;cursor:pointer}.cards,.columns{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:20px}.cards div,.columns section{padding:16px;border-radius:8px;background:#fafafa}.cards strong{display:block;font-size:24px;color:#1890ff}.cards span{font-size:13px;color:#666}.columns{grid-template-columns:1fr 1fr}.columns h3{margin:0 0 10px;font-size:14px}.columns p{display:flex;justify-content:space-between;margin:8px 0;color:#555}table{width:100%;border-collapse:collapse}th,td{padding:11px;border-bottom:1px solid #eee;text-align:left;font-size:13px}th{color:#666;background:#fafafa}@media(max-width:700px){.cards{grid-template-columns:1fr}.columns{grid-template-columns:1fr}.header-row{align-items:flex-start;gap:12px;flex-direction:column}}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# 打包产物 WebDAV 部署说明
|
||||||
|
|
||||||
|
文件服务器上的下载目录为 `/home/appmgr/app-downloads`,已创建 `Android` 和 `iOS` 子目录。Nginx DAV 模块已编译启用;`httpd-tools` 尚未安装。当前 SSH 用户 `appmgr` 不在 sudoers 中,安装软件和创建密码文件需使用 root 或有 sudo 权限的账号。
|
||||||
|
|
||||||
|
## 安装并创建 WebDAV 账号
|
||||||
|
|
||||||
|
在文件服务器执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dnf install -y httpd-tools
|
||||||
|
htpasswd -c /etc/nginx/app-downloads.htpasswd build-uploader
|
||||||
|
```
|
||||||
|
|
||||||
|
`htpasswd` 会交互式询问密码。`build-uploader` 是 WebDAV 账号,不是 Linux 登录账号。`-c` 仅在首次创建密码文件时使用;后续添加账号时去掉 `-c`,以免覆盖已有账号。
|
||||||
|
|
||||||
|
## Nginx 配置
|
||||||
|
|
||||||
|
将 `nginx-webdav.conf.example` 保存为 `/etc/nginx/conf.d/app-downloads.conf`。示例按现有文件服务器内网地址 `172.1.110.13` 和 iOS 打包服务器来源 `172.1.110.180` 编写。把 Android 打包服务器访问时的来源 IP 也加入 `allow`。外层 Nginx 的下载域名应反代到 `http://172.1.110.13:8081`,并保留原始 URI;防火墙应只允许外层 Nginx 访问 8081。
|
||||||
|
|
||||||
|
检查并重载:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
nginx -t
|
||||||
|
systemctl reload nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
内网 WebDAV 使用 HTTP,Basic Auth 凭据会在内网链路上传输。8080 应通过防火墙限制为打包服务器来源地址。请确认 `172.1.110.13` 和构建服务器地址确实只在受控网络内路由;172 私有网段是 `172.16.0.0/12`。
|
||||||
|
|
||||||
|
## 打包服务后台配置
|
||||||
|
|
||||||
|
在 iOS 打包服务「上传配置」页选择 WebDAV:
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| --- | --- |
|
||||||
|
| 服务器地址 | `http://172.1.110.13:8080` |
|
||||||
|
| 用户名 | `build-uploader` |
|
||||||
|
| 密码 | 创建账号时输入的密码 |
|
||||||
|
| 远程路径 | `/iOS` |
|
||||||
|
| 公开访问地址 | `https://你的外网下载域名` |
|
||||||
|
|
||||||
|
当前 WebDAV 实现将文件直接放在配置的远程目录中,只使用产物文件名,不再附加 `ios-builds/iOS`。因此 `/iOS` 对应文件系统 `/home/appmgr/app-downloads/iOS`,公开链接为 `https://你的外网下载域名/iOS/文件名`。外层 Nginx 必须保留该 URI 并代理到 8081。
|
||||||
|
|
||||||
|
Android 打包服务应将 APK 上传到 `/Android`,公开链接形如 `https://你的外网下载域名/Android/文件名.apk`。Android 的上传和删除配置由对应的 Android 打包服务负责;当前 iOS 项目发布 IPA、plist、安装页和二维码。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
分别从打包服务器发起一次测试上传,使用外网 HTTPS 域名打开生成的链接,再从对应前台删除测试构建并确认文件已删除。Ad Hoc iOS 安装还需要有效的 HTTPS 下载域名、manifest、签名和设备 UDID。
|
||||||
|
|
||||||
|
参考:[Nginx DAV 模块文档](https://nginx.org/en/docs/http/ngx_http_dav_module.html)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# 保存为 /etc/nginx/conf.d/app-downloads.conf。
|
||||||
|
# 文件服务器内网地址:172.1.110.13
|
||||||
|
# 请将 Android 打包服务器来源 IP 也加入 WebDAV allow 列表。
|
||||||
|
|
||||||
|
# 内网 WebDAV:构建服务器通过 PUT 上传、DELETE 删除。
|
||||||
|
server {
|
||||||
|
listen 172.1.110.13:8080;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /home/appmgr/app-downloads;
|
||||||
|
client_max_body_size 5g;
|
||||||
|
client_body_timeout 300s;
|
||||||
|
|
||||||
|
auth_basic "Build Artifacts";
|
||||||
|
auth_basic_user_file /etc/nginx/app-downloads.htpasswd;
|
||||||
|
|
||||||
|
# iOS 打包服务器;将 Android 打包服务器来源 IP 也加入 allow 列表。
|
||||||
|
allow 172.1.110.180;
|
||||||
|
deny all;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
dav_methods PUT DELETE MKCOL;
|
||||||
|
create_full_put_path on;
|
||||||
|
dav_access user:rw group:r;
|
||||||
|
autoindex off;
|
||||||
|
|
||||||
|
# 兼容当前 iOS 打包服务 MKCOL 请求尾部斜杠。
|
||||||
|
if ($request_method = MKCOL) {
|
||||||
|
rewrite ^(.*[^/])$ $1/ break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 内层静态文件服务:由外层 Nginx 反向代理;不要对公网开放 8081。
|
||||||
|
server {
|
||||||
|
listen 172.1.110.13:8081;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /home/appmgr/app-downloads;
|
||||||
|
autoindex off;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
dav_methods off;
|
||||||
|
limit_except GET HEAD {
|
||||||
|
deny all;
|
||||||
|
}
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
}
|
||||||
+196
-1
@@ -48,6 +48,31 @@ def test_create_app_rejects_unknown_environment_id_rule(client, tmp_config):
|
|||||||
assert "ID 规则" in resp.json()["detail"]
|
assert "ID 规则" in resp.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_app_prefixes_tencent_app_id(client, tmp_config):
|
||||||
|
resp = client.post("/api/config/apps", json={
|
||||||
|
"name": "腾讯App", "server": "测试环境", "AppGuid": "guid", "tencent": "123456",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
app_id = resp.json()["id"]
|
||||||
|
assert client.get("/api/config/apps").json()[app_id]["tencent"] == "tencent123456"
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_app_keeps_existing_tencent_prefix(client, tmp_config):
|
||||||
|
resp = client.post("/api/config/apps", json={
|
||||||
|
"name": "腾讯App2", "server": "测试环境", "AppGuid": "guid", "tencent": "tencent123456",
|
||||||
|
})
|
||||||
|
app_id = resp.json()["id"]
|
||||||
|
assert client.get("/api/config/apps").json()[app_id]["tencent"] == "tencent123456"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_app_prefixes_tencent_app_id(client, tmp_config):
|
||||||
|
resp = client.put("/api/config/apps/1", json={
|
||||||
|
"name": "改名App", "AppGuid": "test-guid", "tencent": " 987654 ",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert client.get("/api/config/apps").json()["1"]["tencent"] == "tencent987654"
|
||||||
|
|
||||||
|
|
||||||
def test_update_app(client, tmp_config):
|
def test_update_app(client, tmp_config):
|
||||||
resp = client.put("/api/config/apps/1", json={"name": "改名App", "AppGuid": "test-guid"})
|
resp = client.put("/api/config/apps/1", json={"name": "改名App", "AppGuid": "test-guid"})
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
@@ -172,7 +197,8 @@ def test_update_build_settings(client, tmp_config):
|
|||||||
|
|
||||||
# ---- Versions ----
|
# ---- Versions ----
|
||||||
|
|
||||||
def test_update_versions_resets_build_number(client, tmp_config):
|
def test_update_versions_keeps_per_version_build_number(client, tmp_config):
|
||||||
|
# 首次设置某版本号,构建号从 .0 起(尚未打包)
|
||||||
resp = client.put("/api/config/versions", json={"app_ver": "2.196.0"})
|
resp = client.put("/api/config/versions", json={"app_ver": "2.196.0"})
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert resp.json()["app_ver"] == "2.196.0"
|
assert resp.json()["app_ver"] == "2.196.0"
|
||||||
@@ -180,7 +206,176 @@ def test_update_versions_resets_build_number(client, tmp_config):
|
|||||||
assert client.get("/api/config/versions").json()["build_ver"] == "2.196.0.0"
|
assert client.get("/api/config/versions").json()["build_ver"] == "2.196.0.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_versions_does_not_reset_used_build_number(client, tmp_config):
|
||||||
|
# 模拟 2.195.0 已打到 .5、并切到 2.196.0 后,再回退到 2.195.0
|
||||||
|
import json
|
||||||
|
with open(tmp_config, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
cfg["versions"] = {"app_ver": "2.196.0", "build_map": {"2.195.0": 5, "2.196.0": 3}}
|
||||||
|
with open(tmp_config, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f)
|
||||||
|
|
||||||
|
resp = client.put("/api/config/versions", json={"app_ver": "2.195.0"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
# 回退到旧版本号时,构建号保留其自身已用到的最大值,不被重置
|
||||||
|
assert resp.json()["build_ver"] == "2.195.0.5"
|
||||||
|
assert client.get("/api/config/versions").json()["build_ver"] == "2.195.0.5"
|
||||||
|
|
||||||
|
|
||||||
def test_update_versions_rejects_invalid_app_version(client, tmp_config):
|
def test_update_versions_rejects_invalid_app_version(client, tmp_config):
|
||||||
resp = client.put("/api/config/versions", json={"app_ver": "2.196"})
|
resp = client.put("/api/config/versions", json={"app_ver": "2.196"})
|
||||||
assert resp.status_code == 400
|
assert resp.status_code == 400
|
||||||
assert "App_Ver" in resp.json()["detail"]
|
assert "App_Ver" in resp.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_versions_tracks_are_independent(client, tmp_config):
|
||||||
|
# 每个分支一条轨道(main/master 为 release,其余即分支名),App_Ver 各自独立
|
||||||
|
assert client.post("/api/config/branches", json={"name": "feature/login"}).status_code == 200
|
||||||
|
assert client.put("/api/config/versions", json={"track": "release", "app_ver": "2.196.0"}).status_code == 200
|
||||||
|
assert client.put("/api/config/versions", json={"track": "dev", "app_ver": "2.198.0"}).status_code == 200
|
||||||
|
assert client.put("/api/config/versions", json={"track": "feature/login", "app_ver": "2.100.0"}).status_code == 200
|
||||||
|
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["branch_track"] == {"main": "release", "dev": "dev", "feature/login": "feature/login"}
|
||||||
|
assert data["tracks"]["release"]["app_ver"] == "2.196.0"
|
||||||
|
assert data["tracks"]["dev"]["app_ver"] == "2.198.0"
|
||||||
|
assert data["tracks"]["feature/login"]["app_ver"] == "2.100.0"
|
||||||
|
assert data["tracks"]["feature/login"]["build_ver"] == "2.100.0.0"
|
||||||
|
assert data["tracks"]["release"]["kind"] == "release"
|
||||||
|
assert data["tracks"]["feature/login"]["kind"] == "feature"
|
||||||
|
# 顶层字段镜像主上架轨(第一个上架分支),兼容旧客户端
|
||||||
|
assert data["primary_track"] == "release"
|
||||||
|
assert data["app_ver"] == "2.196.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_versions_rejects_unknown_track(client, tmp_config):
|
||||||
|
resp = client.put("/api/config/versions", json={"track": "beta", "app_ver": "2.196.0"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_versions_split_per_branch(client, tmp_config):
|
||||||
|
"""最旧的单轨配置:拆成每个分支一条轨,各自沿用原来的已用构建号"""
|
||||||
|
import json
|
||||||
|
with open(tmp_config, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
cfg["versions"] = {"app_ver": "2.195.0", "build_ver": "2.195.0.7"}
|
||||||
|
with open(tmp_config, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f)
|
||||||
|
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
# main 留在 release 轨,dev 拆出自己的轨,两者都带着原来的已用构建号
|
||||||
|
assert data["branch_track"] == {"main": "release", "dev": "dev"}
|
||||||
|
for track in ("release", "dev"):
|
||||||
|
assert data["tracks"][track] == {
|
||||||
|
"kind": "release",
|
||||||
|
"app_ver": "2.195.0",
|
||||||
|
"build_ver": "2.195.0.7",
|
||||||
|
"build_map": {"2.195.0": 7},
|
||||||
|
}
|
||||||
|
# 拆分后各轨独立:改 release 不影响 dev
|
||||||
|
assert client.put("/api/config/versions", json={"track": "release", "app_ver": "2.196.0"}).status_code == 200
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["tracks"]["release"]["app_ver"] == "2.196.0"
|
||||||
|
assert data["tracks"]["dev"]["app_ver"] == "2.195.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_shared_tracks_split_per_branch(client, tmp_config):
|
||||||
|
"""旧的共用轨:master 留在 release 轨,其余分支(含自测分支)各拆出自己的轨"""
|
||||||
|
import json
|
||||||
|
with open(tmp_config, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
cfg["branches"] = ["main", "dev", "feature/login", "feature/pay"]
|
||||||
|
cfg["versions"] = {"tracks": {
|
||||||
|
"release": {"app_ver": "2.195.0", "build_map": {"2.195.0": 4}},
|
||||||
|
"feature": {"app_ver": "2.100.0", "build_map": {}},
|
||||||
|
}}
|
||||||
|
cfg["branch_track"] = {
|
||||||
|
"main": "release", "dev": "release",
|
||||||
|
"feature/login": "feature", "feature/pay": "feature",
|
||||||
|
}
|
||||||
|
with open(tmp_config, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f)
|
||||||
|
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["branch_track"] == {
|
||||||
|
"main": "release", "dev": "dev",
|
||||||
|
"feature/login": "feature/login", "feature/pay": "feature/pay",
|
||||||
|
}
|
||||||
|
for track in ("release", "dev"):
|
||||||
|
assert data["tracks"][track]["kind"] == "release"
|
||||||
|
assert data["tracks"][track]["build_ver"] == "2.195.0.4"
|
||||||
|
for track in ("feature/login", "feature/pay"):
|
||||||
|
assert data["tracks"][track]["kind"] == "feature"
|
||||||
|
assert data["tracks"][track]["app_ver"] == "2.100.0"
|
||||||
|
|
||||||
|
# 自测分支的版本号各自独立
|
||||||
|
assert client.put("/api/config/versions", json={"track": "feature/login", "app_ver": "2.101.0"}).status_code == 200
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["tracks"]["feature/login"]["app_ver"] == "2.101.0"
|
||||||
|
assert data["tracks"]["feature/pay"]["app_ver"] == "2.100.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_branch_track_defaults_and_override(client, tmp_config):
|
||||||
|
assert client.post("/api/config/branches", json={"name": "develop"}).status_code == 200
|
||||||
|
assert client.post("/api/config/branches", json={"name": "feature/login"}).status_code == 200
|
||||||
|
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
# 每个分支一条自己的轨道,类型按分支名推断
|
||||||
|
assert data["branch_track"]["develop"] == "develop"
|
||||||
|
assert data["branch_track"]["feature/login"] == "feature/login"
|
||||||
|
assert data["tracks"]["develop"]["kind"] == "release"
|
||||||
|
assert data["tracks"]["feature/login"]["kind"] == "feature"
|
||||||
|
|
||||||
|
# 手动改类型:轨道名不变,只改构建号是否自增
|
||||||
|
resp = client.put("/api/config/branches/track", json={"branch": "feature/login", "track": "release"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["track"] == "feature/login"
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["tracks"]["feature/login"]["kind"] == "release"
|
||||||
|
|
||||||
|
assert client.put("/api/config/branches/track", json={"branch": "feature/login", "track": "feature"}).status_code == 200
|
||||||
|
assert client.get("/api/config/versions").json()["tracks"]["feature/login"]["kind"] == "feature"
|
||||||
|
|
||||||
|
assert client.put("/api/config/branches/track", json={"branch": "nope", "track": "release"}).status_code == 404
|
||||||
|
assert client.put("/api/config/branches/track", json={"branch": "develop", "track": "beta"}).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_branch_with_slash_in_name(client, tmp_config):
|
||||||
|
assert client.post("/api/config/branches", json={"name": "feature/login"}).status_code == 200
|
||||||
|
resp = client.delete("/api/config/branches/feature%2Flogin")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert "feature/login" not in client.get("/api/config/branches").json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tags_crud_and_default_release_track(client, tmp_config):
|
||||||
|
"""Tag 与分支分开存放,默认建一条同名上架轨,可切换类型、可删除"""
|
||||||
|
assert client.get("/api/config/tags").json() == []
|
||||||
|
resp = client.post("/api/config/tags", json={"name": "v3.2.0"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["track"] == "v3.2.0"
|
||||||
|
assert client.get("/api/config/tags").json() == ["v3.2.0"]
|
||||||
|
assert client.get("/api/tags").json() == ["v3.2.0"]
|
||||||
|
assert "v3.2.0" not in client.get("/api/config/branches").json()
|
||||||
|
|
||||||
|
data = client.get("/api/config/versions").json()
|
||||||
|
assert data["branch_track"]["v3.2.0"] == "v3.2.0"
|
||||||
|
assert data["tracks"]["v3.2.0"]["kind"] == "release"
|
||||||
|
# 主上架轨仍按分支判断,Tag 不会抢占
|
||||||
|
assert data["primary_track"] == "release"
|
||||||
|
|
||||||
|
assert client.put("/api/config/branches/track", json={"branch": "v3.2.0", "track": "feature"}).status_code == 200
|
||||||
|
assert client.get("/api/config/versions").json()["tracks"]["v3.2.0"]["kind"] == "feature"
|
||||||
|
|
||||||
|
assert client.delete("/api/config/tags/v3.2.0").status_code == 200
|
||||||
|
assert client.get("/api/config/tags").json() == []
|
||||||
|
assert "v3.2.0" not in client.get("/api/config/versions").json()["branch_track"]
|
||||||
|
assert client.delete("/api/config/tags/v3.2.0").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_and_branch_names_must_not_collide(client, tmp_config):
|
||||||
|
assert client.post("/api/config/tags", json={"name": ""}).status_code == 400
|
||||||
|
assert client.post("/api/config/tags", json={"name": "main"}).status_code == 400
|
||||||
|
assert client.post("/api/config/tags", json={"name": "release/v1"}).status_code == 200
|
||||||
|
assert client.post("/api/config/tags", json={"name": "release/v1"}).status_code == 400
|
||||||
|
assert client.post("/api/config/branches", json={"name": "release/v1"}).status_code == 400
|
||||||
|
assert client.delete("/api/config/tags/release%2Fv1").status_code == 200
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""操作审计日志接口测试。"""
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
|
|
||||||
|
@patch("backend.services.build_queue.build_queue")
|
||||||
|
def test_build_creation_is_recorded_and_visible_to_admin(mock_queue, client, tmp_config):
|
||||||
|
mock_queue.submit = AsyncMock()
|
||||||
|
response = client.post("/api/tasks", json={"app_id": "1", "scheme_id": "1", "build_type": "Ad_Hoc"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
summary = client.get("/api/operations/summary")
|
||||||
|
assert summary.status_code == 200
|
||||||
|
assert summary.json()["action_counts"]["build_created"] == 1
|
||||||
|
|
||||||
|
logs = client.get("/api/operations").json()
|
||||||
|
assert logs[0]["username"] == "admin"
|
||||||
|
assert logs[0]["action"] == "build_created"
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_link_is_recorded(client, tmp_config):
|
||||||
|
from backend.database import SessionLocal
|
||||||
|
from backend.models import Task
|
||||||
|
db = SessionLocal()
|
||||||
|
db.add(Task(id="download-task", app_id="1", app_name="测试App", build_type="App_Store", scheme_id="1", scheme_name="readoor31", status="completed", oss_url="https://files.example.com/app.ipa"))
|
||||||
|
db.commit()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
with patch("backend.services.distribution.get_published_download_url", return_value="https://signed.example.com/app.ipa?signature=1"):
|
||||||
|
response = client.get("/api/tasks/download-task/download-link")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "signature=1" in response.json()["url"]
|
||||||
|
assert client.get("/api/operations").json()[0]["action"] == "ipa_download_requested"
|
||||||
|
|
||||||
|
|
||||||
|
def test_regular_user_cannot_view_operation_logs(client):
|
||||||
|
from backend.database import SessionLocal
|
||||||
|
from backend.models import User
|
||||||
|
from backend.security import hash_password
|
||||||
|
db = SessionLocal()
|
||||||
|
db.add(User(id="regular-user", username="reader", password_hash=hash_password("reader-password"), is_admin=False))
|
||||||
|
db.commit()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
login = client.post("/api/auth/login", json={"username": "reader", "password": "reader-password"})
|
||||||
|
client.headers.update({"Authorization": f"Bearer {login.json()['token']}"})
|
||||||
|
assert client.get("/api/operations").status_code == 403
|
||||||
|
assert client.get("/api/operations/summary").status_code == 403
|
||||||
@@ -38,6 +38,23 @@ def test_create_task_default_branch(mock_queue, client, tmp_config):
|
|||||||
})
|
})
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert resp.json()["branch"] == "main"
|
assert resp.json()["branch"] == "main"
|
||||||
|
assert resp.json()["ref_type"] == "branch"
|
||||||
|
|
||||||
|
|
||||||
|
@patch("backend.services.build_queue.build_queue")
|
||||||
|
def test_create_task_from_tag(mock_queue, client, tmp_config):
|
||||||
|
"""选择已配置的 Tag 打包时,任务记录为 tag 类型"""
|
||||||
|
mock_queue.submit = AsyncMock()
|
||||||
|
assert client.post("/api/config/tags", json={"name": "v3.2.0"}).status_code == 200
|
||||||
|
resp = client.post("/api/tasks", json={
|
||||||
|
"app_id": "1",
|
||||||
|
"build_type": "Ad_Hoc",
|
||||||
|
"scheme_id": "1",
|
||||||
|
"branch": "v3.2.0",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["branch"] == "v3.2.0"
|
||||||
|
assert resp.json()["ref_type"] == "tag"
|
||||||
|
|
||||||
|
|
||||||
@patch("backend.services.build_queue.build_queue")
|
@patch("backend.services.build_queue.build_queue")
|
||||||
@@ -214,3 +231,19 @@ def test_delete_task_keeps_shared_remote_artifact(client, tmp_config):
|
|||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert "仍被其他记录引用" in resp.json()["message"]
|
assert "仍被其他记录引用" in resp.json()["message"]
|
||||||
delete.assert_not_called()
|
delete.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_hides_superseded_tasks_except_for_admin(client, tmp_config):
|
||||||
|
from datetime import datetime
|
||||||
|
from backend.database import SessionLocal
|
||||||
|
from backend.models import Task
|
||||||
|
db = SessionLocal()
|
||||||
|
db.add_all([
|
||||||
|
Task(id="visible", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed"),
|
||||||
|
Task(id="covered", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed", superseded_at=datetime.utcnow()),
|
||||||
|
])
|
||||||
|
db.commit()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
assert [task["id"] for task in client.get("/api/tasks").json()] == ["visible"]
|
||||||
|
assert {task["id"] for task in client.get("/api/tasks?include_superseded=true").json()} == {"visible", "covered"}
|
||||||
|
|||||||
+247
-10
@@ -20,6 +20,7 @@ from backend.services.build_service import (
|
|||||||
run_pod_install,
|
run_pod_install,
|
||||||
_patch_afnetworking_private_headers,
|
_patch_afnetworking_private_headers,
|
||||||
_cleanup_old_builds,
|
_cleanup_old_builds,
|
||||||
|
_mark_superseded_tasks,
|
||||||
_resolve_provisioning_profile,
|
_resolve_provisioning_profile,
|
||||||
)
|
)
|
||||||
from backend.services.log_streamer import LogStreamer
|
from backend.services.log_streamer import LogStreamer
|
||||||
@@ -54,6 +55,17 @@ def tmp_dirs(tmp_path):
|
|||||||
return source_dir, build_dir
|
return source_dir, build_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_project_source(source_dir, remote_url="git@github.com:test/repo.git"):
|
||||||
|
"""让任务所属项目使用指定的远程仓库和共享源码目录"""
|
||||||
|
from backend.projects import ProjectSource
|
||||||
|
source = ProjectSource(remote_url, remote_url, source_dir)
|
||||||
|
return patch.multiple(
|
||||||
|
"backend.services.build_service",
|
||||||
|
load_task_project=MagicMock(return_value={}),
|
||||||
|
get_project_source=MagicMock(return_value=source),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _make_mock_process(returncode=0, output=b"ok\n"):
|
def _make_mock_process(returncode=0, output=b"ok\n"):
|
||||||
"""创建 mock 进程,支持 async for stdout"""
|
"""创建 mock 进程,支持 async for stdout"""
|
||||||
proc = AsyncMock()
|
proc = AsyncMock()
|
||||||
@@ -86,7 +98,7 @@ async def test_update_source_clone_no_remote(tmp_path, log_streamer):
|
|||||||
source_dir = tmp_path / "branches" / "main"
|
source_dir = tmp_path / "branches" / "main"
|
||||||
|
|
||||||
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
|
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
|
||||||
with pytest.raises(Exception, match="GIT_REMOTE_URL"):
|
with pytest.raises(Exception, match="未配置 Git 仓库地址"):
|
||||||
await update_source("t1", source_dir, "main")
|
await update_source("t1", source_dir, "main")
|
||||||
|
|
||||||
|
|
||||||
@@ -111,6 +123,25 @@ async def test_update_source_existing(tmp_path, log_streamer):
|
|||||||
assert call_count == 4 # fetch, checkout, reset, clean
|
assert call_count == 4 # fetch, checkout, reset, clean
|
||||||
|
|
||||||
|
|
||||||
|
async def test_update_source_tag_checks_out_detached(tmp_path, log_streamer):
|
||||||
|
"""Tag 打包:拉取 Tag 后以游离 HEAD 检出 refs/tags/<tag>,不依赖同名远程分支"""
|
||||||
|
source_dir = tmp_path / "workspace"
|
||||||
|
source_dir.mkdir()
|
||||||
|
(source_dir / ".git").mkdir()
|
||||||
|
|
||||||
|
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
|
||||||
|
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
|
||||||
|
await update_source("t1", source_dir, "v3.2.0", "tag")
|
||||||
|
|
||||||
|
git_args = [call.args[3:] for call in mock_exec.call_args_list]
|
||||||
|
assert git_args == [
|
||||||
|
("fetch", "origin", "--tags", "--force"),
|
||||||
|
("checkout", "--detach", "refs/tags/v3.2.0"),
|
||||||
|
("reset", "--hard", "refs/tags/v3.2.0"),
|
||||||
|
("clean", "-ffdx"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
async def test_update_source_fetch_failure(tmp_path, log_streamer):
|
async def test_update_source_fetch_failure(tmp_path, log_streamer):
|
||||||
"""fetch 失败时抛异常"""
|
"""fetch 失败时抛异常"""
|
||||||
source_dir = tmp_path / "branches" / "dev"
|
source_dir = tmp_path / "branches" / "dev"
|
||||||
@@ -132,15 +163,28 @@ async def test_prepare_source_snapshot_serializes_shared_source(tmp_dirs, log_st
|
|||||||
source_dir, build_dir_parent = tmp_dirs
|
source_dir, build_dir_parent = tmp_dirs
|
||||||
task = MagicMock(branch="main")
|
task = MagicMock(branch="main")
|
||||||
|
|
||||||
with patch("backend.services.build_service.get_git_remote_url", return_value="git@github.com:test/repo.git"), \
|
with _patch_project_source(source_dir), \
|
||||||
patch("backend.services.build_service.get_shared_source_dir", return_value=source_dir), \
|
|
||||||
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
|
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
|
||||||
patch("backend.services.build_service.update_source", new_callable=AsyncMock), \
|
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
|
||||||
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
|
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
|
||||||
build_dir, commit = await prepare_source_snapshot("t1", task)
|
build_dir, commit = await prepare_source_snapshot("t1", task)
|
||||||
|
|
||||||
assert build_dir.exists()
|
assert build_dir.exists()
|
||||||
assert commit == "abc123"
|
assert commit == "abc123"
|
||||||
|
assert mock_update.call_args.args[2:] == ("main", "branch")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_prepare_source_snapshot_passes_tag_ref_type(tmp_dirs, log_streamer):
|
||||||
|
source_dir, build_dir_parent = tmp_dirs
|
||||||
|
task = MagicMock(id="tag-task", branch="v3.2.0", ref_type="tag")
|
||||||
|
|
||||||
|
with _patch_project_source(source_dir), \
|
||||||
|
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
|
||||||
|
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
|
||||||
|
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
|
||||||
|
await prepare_source_snapshot("t1", task)
|
||||||
|
|
||||||
|
assert mock_update.call_args.args[2:] == ("v3.2.0", "tag")
|
||||||
|
|
||||||
|
|
||||||
# ---- copy_source_code ----
|
# ---- copy_source_code ----
|
||||||
@@ -231,6 +275,7 @@ async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
|
|||||||
source_dir.mkdir(parents=True)
|
source_dir.mkdir(parents=True)
|
||||||
source_file = source_dir / "AFHTTPSessionManager.m"
|
source_file = source_dir / "AFHTTPSessionManager.m"
|
||||||
source_file.write_text("#import <netinet6/in6.h>\n")
|
source_file.write_text("#import <netinet6/in6.h>\n")
|
||||||
|
(tmp_path / "Podfile").write_text("pod 'AFNetworking'")
|
||||||
|
|
||||||
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()):
|
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()):
|
||||||
await run_pod_install("t1", tmp_path)
|
await run_pod_install("t1", tmp_path)
|
||||||
@@ -238,6 +283,18 @@ async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
|
|||||||
assert "netinet6/in6.h" not in source_file.read_text()
|
assert "netinet6/in6.h" not in source_file.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_run_pod_install_uses_xcode_subdirectory(tmp_path, log_streamer):
|
||||||
|
"""工程在仓库子目录时,在 Podfile 所在的子目录执行 pod install。"""
|
||||||
|
sub = tmp_path / "Demo"
|
||||||
|
sub.mkdir()
|
||||||
|
(sub / "Podfile").write_text("pod 'SnapKit'")
|
||||||
|
|
||||||
|
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
|
||||||
|
await run_pod_install("t1", tmp_path, {"workspace": "Demo/App.xcworkspace", "project": ""})
|
||||||
|
|
||||||
|
assert mock_exec.call_args.kwargs["cwd"] == str(sub)
|
||||||
|
|
||||||
|
|
||||||
async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_streamer):
|
async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_streamer):
|
||||||
"""Scheme 中的 shell 特殊字符只能作为 xcodebuild 参数,不能被执行。"""
|
"""Scheme 中的 shell 特殊字符只能作为 xcodebuild 参数,不能被执行。"""
|
||||||
build_dir = tmp_path / "build"
|
build_dir = tmp_path / "build"
|
||||||
@@ -305,7 +362,41 @@ async def test_generate_config(tmp_path, log_streamer):
|
|||||||
assert saved["APPID"] == "guid-123"
|
assert saved["APPID"] == "guid-123"
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_provisioning_profile_extracts_name_and_team(tmp_path):
|
@pytest.mark.parametrize("app_fields, appid, expected_id, expected_label", [
|
||||||
|
([{"key": "APPID", "label": "APPID"}], "1587365345", "1587365345", "APPID"),
|
||||||
|
([{"key": "APPID", "label": "APPID"}], "", "dy_app", "App 标识"),
|
||||||
|
([], "", "dy_app", "App 标识"),
|
||||||
|
])
|
||||||
|
async def test_generate_config_generic_project_identifier(
|
||||||
|
tmp_path, log_streamer, app_fields, appid, expected_id, expected_label,
|
||||||
|
):
|
||||||
|
"""通用项目没有 AppGuid,以第一个 App 字段作为产物文件名和通知中的 App 标识"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock()
|
||||||
|
task.project_id = "dyauction"
|
||||||
|
task.app_id = "1"
|
||||||
|
task.scheme_id = "1"
|
||||||
|
task.build_type = "Ad_Hoc"
|
||||||
|
task.obfuscation = False
|
||||||
|
|
||||||
|
mock_config = {
|
||||||
|
"patcher": "generic",
|
||||||
|
"app_fields": app_fields,
|
||||||
|
"apps": {"1": {"name": "朵云轩", "server": "正式环境", "APPID": appid, "upload_key": "dy_app",
|
||||||
|
"certificates": {}}},
|
||||||
|
"schemes": {"1": {"name": "DyAuction", "ossFloder": "dy"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
assert result["APPID"] == expected_id
|
||||||
|
assert result["APPID_LABEL"] == expected_label
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
profile_path = tmp_path / "profile.mobileprovision"
|
profile_path = tmp_path / "profile.mobileprovision"
|
||||||
profile_path.write_bytes(b"signed profile")
|
profile_path.write_bytes(b"signed profile")
|
||||||
decoded = plistlib.dumps({"Name": "a4YX061_adHoc", "TeamIdentifier": ["MG4Z7FU83W"]})
|
decoded = plistlib.dumps({"Name": "a4YX061_adHoc", "TeamIdentifier": ["MG4Z7FU83W"]})
|
||||||
@@ -314,6 +405,23 @@ def test_resolve_provisioning_profile_extracts_name_and_team(tmp_path):
|
|||||||
assert _resolve_provisioning_profile(str(profile_path)) == ("a4YX061_adHoc", "MG4Z7FU83W")
|
assert _resolve_provisioning_profile(str(profile_path)) == ("a4YX061_adHoc", "MG4Z7FU83W")
|
||||||
|
|
||||||
|
|
||||||
|
def _versions_config(tracks: dict) -> dict:
|
||||||
|
"""构造带版本轨道的配置;tracks 为 轨道名 -> {kind, app_ver, build_map}。"""
|
||||||
|
return {
|
||||||
|
"apps": {"1": {"name": "App", "certificates": {}}},
|
||||||
|
"schemes": {"1": {"name": "sch", "ossFloder": "f"}},
|
||||||
|
"versions": {"tracks": tracks},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _release(app_ver: str, build_map: dict = None) -> dict:
|
||||||
|
return {"kind": "release", "app_ver": app_ver, "build_map": build_map or {}}
|
||||||
|
|
||||||
|
|
||||||
|
def _feature(app_ver: str, build_map: dict = None) -> dict:
|
||||||
|
return {"kind": "feature", "app_ver": app_ver, "build_map": build_map or {}}
|
||||||
|
|
||||||
|
|
||||||
async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
||||||
"""从服务配置读取版本号,不依赖分支源码脚本"""
|
"""从服务配置读取版本号,不依赖分支源码脚本"""
|
||||||
build_dir = tmp_path / "build"
|
build_dir = tmp_path / "build"
|
||||||
@@ -324,12 +432,9 @@ async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
|||||||
task.scheme_id = "1"
|
task.scheme_id = "1"
|
||||||
task.build_type = "Ad_Hoc"
|
task.build_type = "Ad_Hoc"
|
||||||
task.obfuscation = False
|
task.obfuscation = False
|
||||||
|
task.branch = "master"
|
||||||
|
|
||||||
mock_config = {
|
mock_config = _versions_config({"release": _release("3.0.1"), "feature": _feature("9.9.9")})
|
||||||
"apps": {"1": {"name": "App", "certificates": {}}},
|
|
||||||
"schemes": {"1": {"name": "sch", "ossFloder": "f"}},
|
|
||||||
"versions": {"app_ver": "3.0.1", "build_ver": "3.0.1.0"},
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch("backend.routers.config.load_config", return_value=mock_config):
|
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||||
result = await generate_config("t1", task, build_dir)
|
result = await generate_config("t1", task, build_dir)
|
||||||
@@ -338,6 +443,122 @@ async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
|||||||
assert result["BUILD_VERSION"] == "3.0.1.0"
|
assert result["BUILD_VERSION"] == "3.0.1.0"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_config_appstore_increments_per_version(tmp_path, log_streamer):
|
||||||
|
"""App_Store 打包时,按版本号在其自身已用构建号上 +1(回退旧版本号亦从自身最大值继续)"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||||
|
obfuscation=False, branch="master")
|
||||||
|
|
||||||
|
# 2.195.0 已打到 .5,切到 2.196.0 后又回退到 2.195.0
|
||||||
|
mock_config = _versions_config({
|
||||||
|
"release": _release("2.195.0", {"2.195.0": 5, "2.196.0": 3}),
|
||||||
|
"feature": _feature("2.195.0"),
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||||
|
patch("backend.routers.config.save_config") as save_mock:
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
# 从 2.195.0 自身的 5 继续到 6,不受 2.196.0 影响,也不撞已传的 .5
|
||||||
|
release_map = mock_config["versions"]["tracks"]["release"]["build_map"]
|
||||||
|
assert result["BUILD_VERSION"] == "2.195.0.6"
|
||||||
|
assert release_map["2.195.0"] == 6
|
||||||
|
assert release_map["2.196.0"] == 3
|
||||||
|
save_mock.assert_called()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_config_release_branches_are_independent(tmp_path, log_streamer):
|
||||||
|
"""master 与 develop 各用自己的轨道,版本号与构建号互不影响"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||||
|
obfuscation=False, branch="develop")
|
||||||
|
|
||||||
|
mock_config = _versions_config({
|
||||||
|
"release": _release("2.195.0", {"2.195.0": 5}), # master
|
||||||
|
"develop": _release("2.196.0", {"2.196.0": 1}),
|
||||||
|
"feature": _feature("2.100.0"),
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||||
|
patch("backend.routers.config.save_config"):
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
assert result["VERSION"] == "2.196.0"
|
||||||
|
assert result["BUILD_VERSION"] == "2.196.0.2"
|
||||||
|
# master 的 release 轨完全不受影响
|
||||||
|
assert mock_config["versions"]["tracks"]["release"]["build_map"] == {"2.195.0": 5}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_config_build_no_skips_other_release_track(tmp_path, log_streamer):
|
||||||
|
"""两个上架分支临时用同一 App_Ver 时,构建号跨轨道取最大值 +1,避免 App Store 重号"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||||
|
obfuscation=False, branch="develop")
|
||||||
|
|
||||||
|
mock_config = _versions_config({
|
||||||
|
"release": _release("2.196.0", {"2.196.0": 7}), # master
|
||||||
|
"develop": _release("2.196.0", {"2.196.0": 2}),
|
||||||
|
"feature": _feature("2.100.0"),
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||||
|
patch("backend.routers.config.save_config"):
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
assert result["BUILD_VERSION"] == "2.196.0.8"
|
||||||
|
assert mock_config["versions"]["tracks"]["develop"]["build_map"]["2.196.0"] == 8
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_config_feature_branch_never_increments(tmp_path, log_streamer):
|
||||||
|
"""自测分支用自己那条轨道的版本号,且构建号永不自增(即使是 App_Store 打包)"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||||
|
obfuscation=False, branch="feature/login")
|
||||||
|
|
||||||
|
mock_config = _versions_config({
|
||||||
|
"release": _release("2.195.0", {"2.195.0": 5}),
|
||||||
|
"feature/login": _feature("2.100.0"),
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||||
|
patch("backend.routers.config.save_config") as save_mock:
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
assert result["VERSION"] == "2.100.0"
|
||||||
|
assert result["BUILD_VERSION"] == "2.100.0.0"
|
||||||
|
assert mock_config["versions"]["tracks"]["feature/login"]["build_map"] == {}
|
||||||
|
save_mock.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generate_config_branch_track_override(tmp_path, log_streamer):
|
||||||
|
"""branch_track 中的显式配置优先于按分支名推断"""
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
build_dir.mkdir()
|
||||||
|
|
||||||
|
task = MagicMock(app_id="1", scheme_id="1", build_type="Ad_Hoc",
|
||||||
|
obfuscation=False, branch="release/2.196")
|
||||||
|
|
||||||
|
mock_config = _versions_config({
|
||||||
|
"release": _release("2.196.0"),
|
||||||
|
"feature/login": _feature("2.100.0"),
|
||||||
|
})
|
||||||
|
# release/2.196 按名字本应是上架轨,显式指到 feature/login 那条轨道
|
||||||
|
mock_config["branch_track"] = {"release/2.196": "feature/login"}
|
||||||
|
|
||||||
|
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||||
|
result = await generate_config("t1", task, build_dir)
|
||||||
|
|
||||||
|
assert result["VERSION"] == "2.100.0"
|
||||||
|
|
||||||
|
|
||||||
async def test_generate_config_uses_server_theme_not_source_autopacking(tmp_path, log_streamer):
|
async def test_generate_config_uses_server_theme_not_source_autopacking(tmp_path, log_streamer):
|
||||||
"""Web 打包不读取分支源码中的 AutoPacking 目录。"""
|
"""Web 打包不读取分支源码中的 AutoPacking 目录。"""
|
||||||
build_dir = tmp_path / "build"
|
build_dir = tmp_path / "build"
|
||||||
@@ -418,3 +639,19 @@ def test_cleanup_keeps_recent(tmp_path):
|
|||||||
|
|
||||||
assert recent_dir.exists()
|
assert recent_dir.exists()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mark_superseded_tasks_for_same_oss_url():
|
||||||
|
from backend.database import SessionLocal, init_db
|
||||||
|
from backend.models import Task
|
||||||
|
init_db()
|
||||||
|
db = SessionLocal()
|
||||||
|
old = Task(id="old", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed", oss_url="https://files.example.com/app.html")
|
||||||
|
latest = Task(id="latest", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed", oss_url="https://files.example.com/app.html")
|
||||||
|
db.add_all([old, latest])
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
_mark_superseded_tasks(db, latest)
|
||||||
|
assert db.get(Task, "old").superseded_at is not None
|
||||||
|
assert db.get(Task, "latest").superseded_at is None
|
||||||
|
db.close()
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ from unittest.mock import patch
|
|||||||
|
|
||||||
from backend.services.distribution import (
|
from backend.services.distribution import (
|
||||||
_artifact_stem,
|
_artifact_stem,
|
||||||
|
_upload_webdav,
|
||||||
delete_published_artifacts,
|
delete_published_artifacts,
|
||||||
_write_distribution_files,
|
_write_distribution_files,
|
||||||
_write_download_page,
|
_write_download_page,
|
||||||
_write_manifest,
|
_write_manifest,
|
||||||
publish_ipa,
|
publish_ipa,
|
||||||
|
get_published_download_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -85,6 +87,11 @@ def test_adhoc_distribution_uploads_qrcode(tmp_path):
|
|||||||
".ipa", ".plist", ".html", ".png",
|
".ipa", ".plist", ".html", ".png",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# 桌面端钉钉会把图片裁成横向比例,二维码需放在 3:2 的横向画布上
|
||||||
|
from PIL import Image
|
||||||
|
with Image.open(tmp_path / "build" / "distribution" / "100_2_0_0_dev_adhoc.png") as image:
|
||||||
|
assert image.width == round(image.height * 1.5)
|
||||||
|
|
||||||
|
|
||||||
def test_delete_adhoc_artifacts_deletes_all_remote_files():
|
def test_delete_adhoc_artifacts_deletes_all_remote_files():
|
||||||
config = {"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main", "BUILD_TYPE": "Ad_Hoc", "OSS_FLODER": "readoor"}
|
config = {"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main", "BUILD_TYPE": "Ad_Hoc", "OSS_FLODER": "readoor"}
|
||||||
@@ -119,3 +126,102 @@ def test_delete_uses_saved_url_for_legacy_artifact_name():
|
|||||||
"readoor/iOS/100_2_0_0_0.html",
|
"readoor/iOS/100_2_0_0_0.html",
|
||||||
"readoor/iOS/100_2_0_0_0.png",
|
"readoor/iOS/100_2_0_0_0.png",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_webdav_upload_uses_configured_directory_without_oss_path(tmp_path, monkeypatch):
|
||||||
|
ipa = tmp_path / "build.ipa"
|
||||||
|
ipa.write_bytes(b"ipa")
|
||||||
|
calls = {"mkcol": [], "put": []}
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
status_code = 201
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, **_kwargs): pass
|
||||||
|
def __enter__(self): return self
|
||||||
|
def __exit__(self, *_args): pass
|
||||||
|
def request(self, method, url):
|
||||||
|
calls["mkcol"].append((method, url))
|
||||||
|
return FakeResponse()
|
||||||
|
def put(self, url, content):
|
||||||
|
calls["put"].append((url, content))
|
||||||
|
return FakeResponse()
|
||||||
|
|
||||||
|
monkeypatch.setattr("backend.services.distribution.httpx.Client", FakeClient)
|
||||||
|
result = _upload_webdav(
|
||||||
|
{
|
||||||
|
"webdav": {
|
||||||
|
"server_url": "http://dav.example.com",
|
||||||
|
"username": "u",
|
||||||
|
"password": "p",
|
||||||
|
"base_path": "/iOS/",
|
||||||
|
"public_url": "https://download.example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[(ipa, "ios-builds/iOS/legacy-path.ipa")],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert calls["mkcol"] == [("MKCOL", "http://dav.example.com/iOS/")]
|
||||||
|
assert calls["put"] == [("http://dav.example.com/iOS/build.ipa", b"ipa")]
|
||||||
|
assert result[".ipa"] == "https://download.example.com/iOS/build.ipa"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_webdav_artifacts_uses_path_from_published_url():
|
||||||
|
config = {
|
||||||
|
"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main",
|
||||||
|
"BUILD_TYPE": "Ad_Hoc", "OSS_FLODER": "legacy-oss-folder",
|
||||||
|
}
|
||||||
|
upload = {
|
||||||
|
"mode": "webdav",
|
||||||
|
"webdav": {
|
||||||
|
"base_path": "/Android",
|
||||||
|
"public_url": "https://download.example.com",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
with patch("backend.services.distribution._delete_webdav") as delete:
|
||||||
|
delete_published_artifacts(
|
||||||
|
config, upload,
|
||||||
|
"https://download.example.com/Android/build.html",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert delete.call_args.args[1] == [
|
||||||
|
"Android/build.ipa",
|
||||||
|
"Android/build.plist",
|
||||||
|
"Android/build.html",
|
||||||
|
"Android/build.png",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_webdav_dsym_uses_published_url():
|
||||||
|
config = {"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main"}
|
||||||
|
upload = {
|
||||||
|
"mode": "webdav",
|
||||||
|
"webdav": {
|
||||||
|
"base_path": "/iOS",
|
||||||
|
"public_url": "https://download.example.com",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
with patch("backend.services.distribution._delete_webdav") as delete:
|
||||||
|
from backend.services.distribution import delete_published_dsym
|
||||||
|
delete_published_dsym(config, upload, "https://download.example.com/iOS/build.dSYM.zip")
|
||||||
|
|
||||||
|
assert delete.call_args.args[1] == ["iOS/build.dSYM.zip"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_oss_download_url_is_short_lived_and_uses_actual_object_key(monkeypatch):
|
||||||
|
class FakeBucket:
|
||||||
|
def __init__(self, *_args, **_kwargs): pass
|
||||||
|
def sign_url(self, method, key, expires, **kwargs):
|
||||||
|
assert (method, key, expires, kwargs) == ("GET", "readoor/iOS/100_2_0_0_0.ipa", 600, {"slash_safe": True})
|
||||||
|
return "https://signed.example.com/app.ipa?signature=1"
|
||||||
|
class FakeOss:
|
||||||
|
Auth = staticmethod(lambda *_args: object())
|
||||||
|
Bucket = FakeBucket
|
||||||
|
monkeypatch.setitem(__import__("sys").modules, "oss2", FakeOss)
|
||||||
|
|
||||||
|
url = get_published_download_url(
|
||||||
|
{"BUILD_TYPE": "App_Store"},
|
||||||
|
{"mode": "oss", "oss": {"access_key_id": "id", "access_key_secret": "secret", "endpoint": "oss.example.com", "bucket_name": "bucket", "base_url": "https://files.example.com"}},
|
||||||
|
"https://files.example.com/readoor/iOS/100_2_0_0_0.ipa",
|
||||||
|
)
|
||||||
|
assert "signature=1" in url
|
||||||
|
|||||||
@@ -66,6 +66,20 @@ def test_download_dsym_nonexistent_task(client, tmp_config):
|
|||||||
assert resp.status_code == 404
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_dsym_remote_fallback(client, tmp_config):
|
||||||
|
"""本地文件已被清理,但保存了远端地址时应返回远端下载链接(而非直接重定向,
|
||||||
|
因为该接口需要认证信息,浏览器无法直接跳转到 302 目标)"""
|
||||||
|
task_id = _create_task_with_files(
|
||||||
|
client, tmp_config,
|
||||||
|
dsym_path="/tmp/nonexistent.dSYM",
|
||||||
|
dsym_url="https://oss.example.com/ios-builds/iOS/app_1_0_0_main_adhoc.dSYM.zip",
|
||||||
|
)
|
||||||
|
with patch("backend.services.distribution.get_published_dsym_url", return_value="https://signed.example.com/app.dSYM.zip?signature=1"):
|
||||||
|
resp = client.get(f"/api/tasks/{task_id}/dsym")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["url"] == "https://signed.example.com/app.dSYM.zip?signature=1"
|
||||||
|
|
||||||
|
|
||||||
# ---- 混淆映射表下载 ----
|
# ---- 混淆映射表下载 ----
|
||||||
|
|
||||||
def test_download_obfuscation_maps_not_exist(client, tmp_config):
|
def test_download_obfuscation_maps_not_exist(client, tmp_config):
|
||||||
|
|||||||
@@ -35,6 +35,90 @@ def test_dingtalk_payload_matches_autopacking_content():
|
|||||||
assert "" in text
|
assert "" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_dingtalk_payload_uses_project_identifier_label():
|
||||||
|
payload = build_dingtalk_payload(
|
||||||
|
{**_build_config(), "APPID": "1587365345", "APPID_LABEL": "APPID"},
|
||||||
|
"https://download.example.com/app.html",
|
||||||
|
)
|
||||||
|
|
||||||
|
text = payload["markdown"]["text"]
|
||||||
|
assert "**APPID:** 1587365345" in text
|
||||||
|
assert "App Guid" not in text
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
payload = build_dingtalk_payload(
|
||||||
|
_build_config(),
|
||||||
|
"https://download.example.com/app.html",
|
||||||
|
at_mobiles=["13800000000", " 13900000001 ", "13800000000", ""],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 去重去空后写入 at.atMobiles,并在正文追加 @手机号(钉钉 markdown 必需)
|
||||||
|
assert payload["at"]["atMobiles"] == ["13800000000", "13900000001"]
|
||||||
|
assert "@13800000000" in payload["markdown"]["text"]
|
||||||
|
assert "@13900000001" in payload["markdown"]["text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dingtalk_payload_without_at_mobiles_has_empty_at():
|
||||||
|
payload = build_dingtalk_payload(_build_config(), "https://download.example.com/app.html")
|
||||||
|
assert payload["at"]["atMobiles"] == []
|
||||||
|
assert "@" not in payload["markdown"]["text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dingtalk_notification_forwards_at_mobiles():
|
||||||
|
response = MagicMock(status_code=200)
|
||||||
|
response.json.return_value = {"errcode": 0}
|
||||||
|
with patch("backend.services.notification.httpx.post", return_value=response) as post:
|
||||||
|
send_dingtalk_notification(
|
||||||
|
{
|
||||||
|
"enabled": True,
|
||||||
|
"webhook_url": "https://example.com/robot",
|
||||||
|
"at_mobiles": ["13800000000", "13900000001"],
|
||||||
|
},
|
||||||
|
_build_config(),
|
||||||
|
"https://download.example.com/app.html",
|
||||||
|
)
|
||||||
|
|
||||||
|
sent = post.call_args.kwargs["json"]
|
||||||
|
assert sent["at"]["atMobiles"] == ["13800000000", "13900000001"]
|
||||||
|
assert "@13800000000" in sent["markdown"]["text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dingtalk_payload_app_store_heading_and_no_qr():
|
||||||
|
config = {**_build_config(), "BUILD_TYPE": "App_Store"}
|
||||||
|
# App_Store 流程不传二维码地址(publish_ipa 返回空串)
|
||||||
|
payload = build_dingtalk_payload(
|
||||||
|
config, "https://oss.example.com/readoor/iOS/app_2_197_1.ipa"
|
||||||
|
)
|
||||||
|
text = payload["markdown"]["text"]
|
||||||
|
# 标题保留「打包」二字,避免命中钉钉自定义关键词拦截
|
||||||
|
assert "## 【iOS】App_Store 打包信息" in text
|
||||||
|
assert "**iOS 下载链接:** https://oss.example.com/readoor/iOS/app_2_197_1.ipa" in text
|
||||||
|
assert "![image]" not in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_dingtalk_notification_app_store_uses_own_at_list():
|
||||||
|
response = MagicMock(status_code=200)
|
||||||
|
response.json.return_value = {"errcode": 0}
|
||||||
|
dingtalk_config = {
|
||||||
|
"enabled": True,
|
||||||
|
"webhook_url": "https://example.com/robot",
|
||||||
|
"at_mobiles": ["13800000000"],
|
||||||
|
"at_mobiles_app_store": ["13911111111", "13922222222"],
|
||||||
|
}
|
||||||
|
with patch("backend.services.notification.httpx.post", return_value=response) as post:
|
||||||
|
send_dingtalk_notification(
|
||||||
|
dingtalk_config,
|
||||||
|
{**_build_config(), "BUILD_TYPE": "App_Store"},
|
||||||
|
"https://oss.example.com/app.ipa",
|
||||||
|
)
|
||||||
|
|
||||||
|
sent = post.call_args.kwargs["json"]
|
||||||
|
assert sent["at"]["atMobiles"] == ["13911111111", "13922222222"]
|
||||||
|
assert "## 【iOS】App_Store 打包信息" in sent["markdown"]["text"]
|
||||||
|
assert "@13800000000" not in sent["markdown"]["text"]
|
||||||
|
|
||||||
|
|
||||||
def test_dingtalk_notification_skips_when_disabled():
|
def test_dingtalk_notification_skips_when_disabled():
|
||||||
with patch("backend.services.notification.httpx.post") as post:
|
with patch("backend.services.notification.httpx.post") as post:
|
||||||
assert send_dingtalk_notification({}, _build_config(), "https://download.example.com/app") is False
|
assert send_dingtalk_notification({}, _build_config(), "https://download.example.com/app") is False
|
||||||
@@ -58,3 +142,21 @@ def test_dingtalk_notification_sends_markdown():
|
|||||||
def test_dingtalk_notification_requires_webhook_when_enabled():
|
def test_dingtalk_notification_requires_webhook_when_enabled():
|
||||||
with pytest.raises(NotificationError, match="Webhook"):
|
with pytest.raises(NotificationError, match="Webhook"):
|
||||||
send_dingtalk_notification({"enabled": True}, _build_config(), "https://download.example.com/app")
|
send_dingtalk_notification({"enabled": True}, _build_config(), "https://download.example.com/app")
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_at_mobiles_override_global_per_build_type():
|
||||||
|
from backend.services.notification import merge_project_at_mobiles
|
||||||
|
|
||||||
|
global_config = {"enabled": True, "at_mobiles": ["111"], "at_mobiles_app_store": ["222"]}
|
||||||
|
merged = merge_project_at_mobiles(global_config, {"at_mobiles": ["333", "333", " "], "at_mobiles_app_store": []})
|
||||||
|
|
||||||
|
assert merged["at_mobiles"] == ["333"]
|
||||||
|
assert merged["at_mobiles_app_store"] == ["222"] # 项目未配置,沿用全局
|
||||||
|
assert global_config["at_mobiles"] == ["111"] # 不修改全局配置
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_at_mobiles_missing_keeps_global():
|
||||||
|
from backend.services.notification import merge_project_at_mobiles
|
||||||
|
|
||||||
|
global_config = {"at_mobiles": ["111"]}
|
||||||
|
assert merge_project_at_mobiles(global_config, None) == global_config
|
||||||
|
|||||||
@@ -33,7 +33,9 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
|||||||
"<string>applinks:old</string>\n", encoding="utf-8"
|
"<string>applinks:old</string>\n", encoding="utf-8"
|
||||||
)
|
)
|
||||||
with (build_dir / "readoor" / "3.0" / "readoor31.plist").open("wb") as f:
|
with (build_dir / "readoor" / "3.0" / "readoor31.plist").open("wb") as f:
|
||||||
plistlib.dump({"CFBundleURLTypes": []}, f)
|
plistlib.dump({"CFBundleURLTypes": [
|
||||||
|
{"CFBundleURLName": "wxwork", "CFBundleURLSchemes": ["1"]},
|
||||||
|
]}, f)
|
||||||
|
|
||||||
theme = tmp_path / "theme" / "AppIcon.appiconset"
|
theme = tmp_path / "theme" / "AppIcon.appiconset"
|
||||||
theme.mkdir(parents=True)
|
theme.mkdir(parents=True)
|
||||||
@@ -42,6 +44,7 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
|||||||
config = {
|
config = {
|
||||||
"VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.1", "APPID": "guid",
|
"VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.1", "APPID": "guid",
|
||||||
"API": "https://api.example.com", "weixinpay": "wx-pay", "APPID_NAME": "Test",
|
"API": "https://api.example.com", "weixinpay": "wx-pay", "APPID_NAME": "Test",
|
||||||
|
"wxworkSchema": "wx1234567890abcdef",
|
||||||
"BUNDLE_ID": "com.example.test", "TEAM_ID": "TEAM", "PROVISIONING_NAME": "profile",
|
"BUNDLE_ID": "com.example.test", "TEAM_ID": "TEAM", "PROVISIONING_NAME": "profile",
|
||||||
"ASSOCIATED_DOMAINS": "applinks:example.com", "THEME": str(theme.parent), "BUILD_TYPE": "Ad_Hoc",
|
"ASSOCIATED_DOMAINS": "applinks:example.com", "THEME": str(theme.parent), "BUILD_TYPE": "Ad_Hoc",
|
||||||
"CERTIFICATE": "Apple Distribution",
|
"CERTIFICATE": "Apple Distribution",
|
||||||
@@ -58,3 +61,53 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
|||||||
assert "iPhone Developer" not in project_content
|
assert "iPhone Developer" not in project_content
|
||||||
assert (build_dir / "exportOptions.plist").exists()
|
assert (build_dir / "exportOptions.plist").exists()
|
||||||
assert (logo / "icon-1024.png").read_bytes() == b"icon"
|
assert (logo / "icon-1024.png").read_bytes() == b"icon"
|
||||||
|
with (build_dir / "readoor" / "3.0" / "readoor31.plist").open("rb") as f:
|
||||||
|
url_types = plistlib.load(f)["CFBundleURLTypes"]
|
||||||
|
wxwork = next(i for i in url_types if i["CFBundleURLName"] == "wxwork")
|
||||||
|
assert wxwork["CFBundleURLSchemes"] == ["wx1234567890abcdef"]
|
||||||
|
|
||||||
|
|
||||||
|
def _make_minimal_project(build_dir):
|
||||||
|
"""构造 apply_project_config 所需的最小工程骨架,返回关键文件路径。"""
|
||||||
|
project = build_dir / "readoor.xcodeproj"
|
||||||
|
swift = build_dir / "readoor" / "3.0" / "AppConfig"
|
||||||
|
entitlements_dir = build_dir / "readoor" / "3.0"
|
||||||
|
for path in [project, swift, entitlements_dir]:
|
||||||
|
path.mkdir(parents=True, exist_ok=True)
|
||||||
|
(project / "project.pbxproj").write_text(
|
||||||
|
"MARKETING_VERSION = 1.0;\nCURRENT_PROJECT_VERSION = 1;\n"
|
||||||
|
'CODE_SIGN_IDENTITY = "iPhone Developer";\n'
|
||||||
|
'"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
(swift / "RDAppConfiguration.swift").write_text(
|
||||||
|
'let RD_APP_GUID: String = "old"\nlet RD_API_DOMAIN: String = "old"\n'
|
||||||
|
'let RD_WECHAT_PAY_ID: String = "old"\nlet RD_SOURCE_VERSION: String = "old"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
(entitlements_dir / "readoor31.entitlements").write_text(
|
||||||
|
"<string>applinks:old</string>\n", encoding="utf-8"
|
||||||
|
)
|
||||||
|
return entitlements_dir / "readoor31.plist"
|
||||||
|
|
||||||
|
|
||||||
|
def test_wxwork_schema_removed_when_not_configured(tmp_path):
|
||||||
|
build_dir = tmp_path / "build"
|
||||||
|
plist_path = _make_minimal_project(build_dir)
|
||||||
|
with plist_path.open("wb") as f:
|
||||||
|
plistlib.dump({"CFBundleURLTypes": [
|
||||||
|
{"CFBundleURLName": "wxwork", "CFBundleURLSchemes": ["1"]},
|
||||||
|
]}, f)
|
||||||
|
|
||||||
|
config = {
|
||||||
|
"VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.1", "APPID": "guid",
|
||||||
|
"API": "https://api.example.com", "APPID_NAME": "Test",
|
||||||
|
"ASSOCIATED_DOMAINS": "applinks:example.com", "BUILD_TYPE": "Ad_Hoc",
|
||||||
|
"CERTIFICATE": "Apple Distribution",
|
||||||
|
}
|
||||||
|
|
||||||
|
apply_project_config(build_dir, config)
|
||||||
|
|
||||||
|
with plist_path.open("rb") as f:
|
||||||
|
url_types = plistlib.load(f)["CFBundleURLTypes"]
|
||||||
|
assert all(i.get("CFBundleURLName") != "wxwork" for i in url_types)
|
||||||
|
|||||||
@@ -0,0 +1,347 @@
|
|||||||
|
"""多项目配置测试"""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from backend.projects import get_project_source
|
||||||
|
from backend.services.project_patcher import ProjectPatchError, apply_project_config
|
||||||
|
|
||||||
|
DY_PROJECT = {
|
||||||
|
"id": "dyauction",
|
||||||
|
"name": "多云选",
|
||||||
|
"git": {"remote_url": "https://git.example.com/dy.git", "username": "bot", "password": "secret"},
|
||||||
|
"xcode": {"workspace": "", "project": "DyAuction.xcodeproj"},
|
||||||
|
"patcher": "generic",
|
||||||
|
"patch_rules": [
|
||||||
|
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "ISDEV", "value": "${server.ISDEV}"},
|
||||||
|
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "APPID", "value": '@"${app.APPID}"'},
|
||||||
|
],
|
||||||
|
"app_fields": [{"key": "APPID", "label": "APPID", "required": True}],
|
||||||
|
"server_fields": [{"key": "ISDEV", "label": "ISDEV", "required": True}],
|
||||||
|
}
|
||||||
|
|
||||||
|
DY = {"X-Project": "dyauction"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def dy_project(client, tmp_config):
|
||||||
|
resp = client.post("/api/config/projects", json=DY_PROJECT)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
return "dyauction"
|
||||||
|
|
||||||
|
|
||||||
|
def _root(tmp_config: Path) -> dict:
|
||||||
|
return json.loads(tmp_config.read_text())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 迁移与隔离 ----
|
||||||
|
|
||||||
|
def test_legacy_config_migrates_to_readoor_project(client, tmp_config):
|
||||||
|
assert client.get("/api/config/apps").status_code == 200
|
||||||
|
|
||||||
|
root = _root(tmp_config)
|
||||||
|
assert list(root["projects"]) == ["readoor"]
|
||||||
|
readoor = root["projects"]["readoor"]
|
||||||
|
assert readoor["patcher"] == "readoor"
|
||||||
|
assert readoor["git"]["use_env"] is True
|
||||||
|
assert readoor["apps"]["1"]["name"] == "测试App"
|
||||||
|
assert "apps" not in root
|
||||||
|
assert "upload" not in readoor
|
||||||
|
|
||||||
|
|
||||||
|
def test_projects_list_hides_git_password(client, dy_project):
|
||||||
|
public = client.get("/api/projects").json()
|
||||||
|
assert [p["id"] for p in public] == ["readoor", "dyauction"]
|
||||||
|
assert "git" not in public[1]
|
||||||
|
assert public[1]["app_fields"][0]["key"] == "APPID"
|
||||||
|
|
||||||
|
admin = client.get("/api/config/projects").json()
|
||||||
|
dy = next(p for p in admin if p["id"] == "dyauction")
|
||||||
|
assert dy["git"]["password_set"] is True
|
||||||
|
assert "password" not in dy["git"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_data_is_isolated(client, dy_project):
|
||||||
|
assert client.get("/api/apps", headers=DY).json() == {}
|
||||||
|
assert "1" in client.get("/api/apps").json()
|
||||||
|
|
||||||
|
resp = client.post("/api/config/servers", headers=DY, json={"name": "测试环境", "ISDEV": "1", "api": "x"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
servers = client.get("/api/config/servers", headers=DY).json()
|
||||||
|
# 通用项目只保留自定义字段
|
||||||
|
assert servers["测试环境"] == {"ISDEV": "1", "app_id_prefix": 1}
|
||||||
|
# Readoor 项目的同名环境不受影响
|
||||||
|
assert client.get("/api/config/servers").json()["测试环境"]["api"] == "https://test.api.com"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_project_rejected(client, tmp_config):
|
||||||
|
resp = client.get("/api/apps", headers={"X-Project": "nope"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_required_custom_fields(client, dy_project):
|
||||||
|
resp = client.post("/api/config/servers", headers=DY, json={"name": "正式环境"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
client.post("/api/config/servers", headers=DY, json={"name": "正式环境", "ISDEV": "0"})
|
||||||
|
|
||||||
|
resp = client.post("/api/config/apps", headers=DY, json={"name": "多云选", "server": "正式环境"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
resp = client.post("/api/config/apps", headers=DY,
|
||||||
|
json={"name": "多云选", "server": "正式环境", "APPID": "1587365345"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["id"] == "100"
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_config_is_shared(client, dy_project):
|
||||||
|
client.put("/api/config/upload", headers=DY, json={"mode": "webdav"})
|
||||||
|
assert client.get("/api/config/upload").json()["mode"] == "webdav"
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_config_put_keeps_current_project(client, dy_project):
|
||||||
|
config = client.get("/api/config", headers=DY).json()
|
||||||
|
config["branches"] = ["develop"]
|
||||||
|
config["_project"] = "readoor"
|
||||||
|
assert client.put("/api/config", headers=DY, json=config).status_code == 200
|
||||||
|
assert client.get("/api/branches", headers=DY).json() == ["develop"]
|
||||||
|
assert client.get("/api/branches").json() == ["main", "dev"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 项目管理 ----
|
||||||
|
|
||||||
|
def test_update_project_keeps_password_when_empty(client, dy_project, tmp_config):
|
||||||
|
resp = client.put("/api/config/projects/dyauction",
|
||||||
|
json={"name": "多云选拍卖", "git": {"remote_url": "https://git.example.com/dy2.git", "username": "bot"}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
dy = _root(tmp_config)["projects"]["dyauction"]
|
||||||
|
assert dy["name"] == "多云选拍卖"
|
||||||
|
assert dy["git"]["password"] == "secret"
|
||||||
|
assert dy["git"]["remote_url"].endswith("dy2.git")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", [
|
||||||
|
{"id": "Bad ID"},
|
||||||
|
{"id": "readoor"},
|
||||||
|
{"id": "x1", "xcode": {"workspace": "X.xcworkspace"}}, # 通用替换需要 project
|
||||||
|
{"id": "x2", "xcode": {"project": "X.xcodeproj"}, "app_fields": [{"key": "server"}]},
|
||||||
|
{"id": "x3", "xcode": {"project": "X.xcodeproj"}, "patch_rules": [{"type": "define", "file": "../a.h", "name": "A"}]},
|
||||||
|
{"id": "x4", "xcode": {"project": "X.xcodeproj"}, "patch_rules": [{"type": "sed"}]},
|
||||||
|
])
|
||||||
|
def test_create_project_validation(client, tmp_config, payload):
|
||||||
|
assert client.post("/api/config/projects", json=payload).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_project_keeps_last(client, dy_project):
|
||||||
|
assert client.delete("/api/config/projects/dyauction").status_code == 200
|
||||||
|
assert client.delete("/api/config/projects/readoor").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_management_requires_admin(client, tmp_config):
|
||||||
|
client.post("/api/users", json={"username": "builder", "password": "builder-password-123", "is_admin": False})
|
||||||
|
token = client.post("/api/auth/login",
|
||||||
|
json={"username": "builder", "password": "builder-password-123"}).json()["token"]
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
assert client.get("/api/config/projects", headers=headers).status_code == 403
|
||||||
|
assert client.post("/api/config/projects", json=DY_PROJECT, headers=headers).status_code == 403
|
||||||
|
assert client.get("/api/projects", headers=headers).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 任务 ----
|
||||||
|
|
||||||
|
def _create_dy_app(client):
|
||||||
|
client.post("/api/config/servers", headers=DY, json={"name": "正式环境", "ISDEV": "0"})
|
||||||
|
client.post("/api/config/schemes", headers=DY, json={"name": "DyAuction", "ossFloder": "dy"})
|
||||||
|
resp = client.post("/api/config/apps", headers=DY, json={
|
||||||
|
"name": "多云选", "server": "正式环境", "APPID": "1587365345",
|
||||||
|
"certificates": {"Ad_Hoc": {"name": "cn.touchv.auction", "cer": "c", "pro": "p"}},
|
||||||
|
})
|
||||||
|
return resp.json()["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_task_belongs_to_project(client, dy_project):
|
||||||
|
app_id = _create_dy_app(client)
|
||||||
|
with patch("backend.services.build_queue.build_queue.submit", new_callable=AsyncMock):
|
||||||
|
resp = client.post("/api/tasks", headers=DY, json={
|
||||||
|
"app_id": app_id, "build_type": "Ad_Hoc", "scheme_id": "1", "branch": "main",
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json()["project_id"] == "dyauction"
|
||||||
|
|
||||||
|
assert len(client.get("/api/tasks", headers=DY).json()) == 1
|
||||||
|
assert client.get("/api/tasks").json() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_task_rejects_obfuscation_when_unsupported(client, dy_project):
|
||||||
|
app_id = _create_dy_app(client)
|
||||||
|
resp = client.post("/api/tasks", headers=DY, json={
|
||||||
|
"app_id": app_id, "build_type": "Ad_Hoc", "scheme_id": "1", "branch": "main", "obfuscation": True,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_generic_project_does_not_restrict_schemes(client, dy_project):
|
||||||
|
_create_dy_app(client)
|
||||||
|
apps = client.get("/api/apps", headers=DY).json()
|
||||||
|
assert all(app["allowed_scheme_names"] == [] for app in apps.values())
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 源码目录 ----
|
||||||
|
|
||||||
|
def test_project_source_uses_own_git_settings():
|
||||||
|
source = get_project_source("dyauction", DY_PROJECT)
|
||||||
|
assert source.remote_url == "https://git.example.com/dy.git"
|
||||||
|
assert source.remote_url_with_credentials == "https://bot:secret@git.example.com/dy.git"
|
||||||
|
assert source.shared_dir.parts[-2:] == ("sources", "dyauction")
|
||||||
|
assert source.manual_base is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_project_source_falls_back_to_env():
|
||||||
|
with patch("backend.projects.GIT_REMOTE_URL", "https://env.example.com/r.git"), \
|
||||||
|
patch("backend.projects.GIT_USERNAME", "env"), patch("backend.projects.GIT_PASSWORD", ""):
|
||||||
|
source = get_project_source("readoor", {})
|
||||||
|
assert source.remote_url_with_credentials == "https://env@env.example.com/r.git"
|
||||||
|
assert source.manual_base is not None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_build_uses_xcodeproj_when_no_workspace(tmp_path):
|
||||||
|
from backend.services.build_service import build_project
|
||||||
|
from backend.services.log_streamer import LogStreamer
|
||||||
|
|
||||||
|
proc = AsyncMock(returncode=0)
|
||||||
|
proc.wait = AsyncMock(return_value=0)
|
||||||
|
|
||||||
|
async def _stdout():
|
||||||
|
yield b"ok\n"
|
||||||
|
|
||||||
|
def _make(*args, **kwargs):
|
||||||
|
proc.stdout = _stdout()
|
||||||
|
return proc
|
||||||
|
|
||||||
|
with patch("backend.services.build_service.log_streamer", LogStreamer()), \
|
||||||
|
patch("asyncio.create_subprocess_exec", side_effect=_make) as mock_exec:
|
||||||
|
with pytest.raises(Exception, match="未找到 IPA 文件"):
|
||||||
|
await build_project("t1", MagicMock(), {"SCHEME": "DyAuction"}, tmp_path,
|
||||||
|
{"workspace": "", "project": "DyAuction.xcodeproj"})
|
||||||
|
archive_args = mock_exec.call_args_list[1].args
|
||||||
|
assert ("-project", "DyAuction.xcodeproj") == archive_args[2:4]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 通用配置替换 ----
|
||||||
|
|
||||||
|
PBXPROJ = """
|
||||||
|
A1 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||||
|
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||||
|
CURRENT_PROJECT_VERSION = 1.2.25;
|
||||||
|
DEVELOPMENT_TEAM = AAA;
|
||||||
|
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = BBB;
|
||||||
|
MARKETING_VERSION = 1.2.25;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.auction;
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = duoyunxuan;
|
||||||
|
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = TouchLinked_adHoc;
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
A2 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.DyAuctionTests;
|
||||||
|
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DyAuction.app/DyAuction";
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
"""
|
||||||
|
|
||||||
|
MACRO = """#define APPCHEME @"cntouchauction"
|
||||||
|
|
||||||
|
#define ISDEV 1
|
||||||
|
|
||||||
|
#if ISDEV
|
||||||
|
//#define APPID @"1587429852"
|
||||||
|
#define APPID @"1587026338"
|
||||||
|
#else
|
||||||
|
#define APPID @"1587365345"
|
||||||
|
#endif
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def dy_build_dir(tmp_path):
|
||||||
|
(tmp_path / "DyAuction.xcodeproj").mkdir()
|
||||||
|
(tmp_path / "DyAuction.xcodeproj" / "project.pbxproj").write_text(PBXPROJ)
|
||||||
|
(tmp_path / "DyAuction" / "Public").mkdir(parents=True)
|
||||||
|
(tmp_path / "DyAuction" / "Public" / "DyConstantsMacro.h").write_text(MACRO)
|
||||||
|
return tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
def _dy_config(**overrides):
|
||||||
|
config = {
|
||||||
|
"VERSION": "1.2.26", "BUILD_VERSION": "1.2.26.1", "BUILD_TYPE": "Ad_Hoc",
|
||||||
|
"BUNDLE_ID": "cn.touchv.auction2", "TEAM_ID": "MG4Z7FU83W", "PROVISIONING_NAME": "Dy AdHoc",
|
||||||
|
"CERTIFICATE": "Apple Distribution", "APP_VARS": {"APPID": "1587000000"}, "SERVER_VARS": {"ISDEV": "0"},
|
||||||
|
}
|
||||||
|
config.update(overrides)
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def test_generic_patcher_replaces_macros_and_settings(dy_build_dir):
|
||||||
|
messages = apply_project_config(dy_build_dir, _dy_config(), DY_PROJECT)
|
||||||
|
|
||||||
|
macro = (dy_build_dir / "DyAuction" / "Public" / "DyConstantsMacro.h").read_text()
|
||||||
|
assert "#define ISDEV 0\n" in macro
|
||||||
|
assert macro.count('#define APPID @"1587000000"') == 2
|
||||||
|
assert '//#define APPID @"1587429852"' in macro
|
||||||
|
|
||||||
|
pbx = (dy_build_dir / "DyAuction.xcodeproj" / "project.pbxproj").read_text()
|
||||||
|
assert "MARKETING_VERSION = 1.2.26;" in pbx
|
||||||
|
assert "CURRENT_PROJECT_VERSION = 1.2.26.1;" in pbx
|
||||||
|
assert "PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.auction2;" in pbx
|
||||||
|
assert "PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.DyAuctionTests;" in pbx
|
||||||
|
assert '"DEVELOPMENT_TEAM[sdk=iphoneos*]" = MG4Z7FU83W;' in pbx
|
||||||
|
assert '"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Dy AdHoc";' in pbx
|
||||||
|
assert '"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";' in pbx
|
||||||
|
assert (dy_build_dir / "exportOptions.plist").exists()
|
||||||
|
assert any("ISDEV 0" in line for line in messages)
|
||||||
|
|
||||||
|
|
||||||
|
def test_generic_patcher_requires_template_values(dy_build_dir):
|
||||||
|
with pytest.raises(ProjectPatchError, match="app.APPID"):
|
||||||
|
apply_project_config(dy_build_dir, _dy_config(APP_VARS={"APPID": ""}), DY_PROJECT)
|
||||||
|
|
||||||
|
|
||||||
|
def test_generic_patcher_reports_missing_define(dy_build_dir):
|
||||||
|
project = {**DY_PROJECT, "patch_rules": [
|
||||||
|
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "NOPE", "value": "1"},
|
||||||
|
]}
|
||||||
|
with pytest.raises(ProjectPatchError, match="NOPE"):
|
||||||
|
apply_project_config(dy_build_dir, _dy_config(), project)
|
||||||
|
|
||||||
|
|
||||||
|
def test_generic_patcher_replace_line_rule(dy_build_dir):
|
||||||
|
project = {**DY_PROJECT, "patch_rules": [
|
||||||
|
{"type": "replace_line", "file": "DyAuction/Public/DyConstantsMacro.h",
|
||||||
|
"keyword": "APPCHEME", "line": '#define APPCHEME @"${BUNDLE_ID}"'},
|
||||||
|
]}
|
||||||
|
apply_project_config(dy_build_dir, _dy_config(), project)
|
||||||
|
macro = (dy_build_dir / "DyAuction" / "Public" / "DyConstantsMacro.h").read_text()
|
||||||
|
assert '#define APPCHEME @"cn.touchv.auction2"' in macro
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_dingtalk_at_saved_and_returned(client, dy_project, tmp_config):
|
||||||
|
resp = client.put("/api/config/projects/dyauction",
|
||||||
|
json={"dingtalk_at": {"at_mobiles": "13800000001,13800000002\n13800000001"}})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
dy = _root(tmp_config)["projects"]["dyauction"]
|
||||||
|
assert dy["dingtalk_at"] == {"at_mobiles": ["13800000001", "13800000002"], "at_mobiles_app_store": []}
|
||||||
|
|
||||||
|
listed = {p["id"]: p for p in client.get("/api/config/projects").json()}
|
||||||
|
assert listed["dyauction"]["dingtalk_at"]["at_mobiles"] == ["13800000001", "13800000002"]
|
||||||
|
assert listed["readoor"]["dingtalk_at"] == {"at_mobiles": [], "at_mobiles_app_store": []}
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_dingtalk_at_must_be_object(client, dy_project):
|
||||||
|
resp = client.put("/api/config/projects/dyauction", json={"dingtalk_at": ["138"]})
|
||||||
|
assert resp.status_code == 400
|
||||||
@@ -37,8 +37,8 @@ def test_production_rejects_default_security_settings(monkeypatch):
|
|||||||
config.validate_production_security()
|
config.validate_production_security()
|
||||||
|
|
||||||
|
|
||||||
def test_config_routes_limit_regular_users_to_apps_and_versions(client, tmp_config):
|
def test_config_routes_limit_regular_users_to_apps(client, tmp_config):
|
||||||
"""普通账号可管理 Apps 与版本号,不能读取或修改管理员配置。"""
|
"""普通账号只能管理 Apps,版本号等其余配置均为管理员专属。"""
|
||||||
response = client.post("/api/users", json={
|
response = client.post("/api/users", json={
|
||||||
"username": "builder",
|
"username": "builder",
|
||||||
"password": "builder-password-123",
|
"password": "builder-password-123",
|
||||||
@@ -57,10 +57,13 @@ def test_config_routes_limit_regular_users_to_apps_and_versions(client, tmp_conf
|
|||||||
assert client.post("/api/config/apps", json={
|
assert client.post("/api/config/apps", json={
|
||||||
"name": "普通用户 App", "server": "测试环境",
|
"name": "普通用户 App", "server": "测试环境",
|
||||||
}, headers=headers).status_code == 200
|
}, headers=headers).status_code == 200
|
||||||
assert client.get("/api/config/versions", headers=headers).status_code == 200
|
assert client.get("/api/config/versions", headers=headers).status_code == 403
|
||||||
versions = client.put("/api/config/versions", json={"app_ver": "2.196.0"}, headers=headers)
|
assert client.put(
|
||||||
assert versions.status_code == 200
|
"/api/config/versions", json={"app_ver": "2.196.0"}, headers=headers
|
||||||
assert versions.json()["build_ver"] == "2.196.0.0"
|
).status_code == 403
|
||||||
|
assert client.put(
|
||||||
|
"/api/config/branches/track", json={"branch": "master", "track": "feature"}, headers=headers
|
||||||
|
).status_code == 403
|
||||||
assert client.get("/api/config", headers=headers).status_code == 403
|
assert client.get("/api/config", headers=headers).status_code == 403
|
||||||
assert client.get("/api/config/servers", headers=headers).status_code == 403
|
assert client.get("/api/config/servers", headers=headers).status_code == 403
|
||||||
assert client.put("/api/config/build", json={"max_concurrent_builds": 1}, headers=headers).status_code == 403
|
assert client.put("/api/config/build", json={"max_concurrent_builds": 1}, headers=headers).status_code == 403
|
||||||
|
|||||||
Reference in New Issue
Block a user