feat: 支持多项目打包

- config.json 改为按项目存储(projects.<id>),上传配置全局共用;旧单项目配置自动迁移为 readoor
- 新增项目管理(管理员):Git 仓库/凭据、源码目录、Xcode 工程、拷贝条目、配置替换方式、自定义字段、替换规则
- 通用配置替换:pbxproj 版本号与签名,patch_rules 支持 define / replace_line 及 ${app.X}、${server.X} 模板
- 请求通过 X-Project 头选择项目;打包任务记录 project_id,历史按项目过滤
- 前端顶部切换项目,App/服务器环境表单按项目显示字段

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-22 14:59:30 +09:00
co-authored by Claude Opus 5.5
parent 2bd5c7057f
commit 8f2f23682f
19 changed files with 1535 additions and 137 deletions
+291 -30
View File
@@ -1,5 +1,6 @@
"""配置管理 API"""
import asyncio
import copy
import json
import os
import re
@@ -23,6 +24,17 @@ from ..config import (
SKINS_DIR,
)
from ..deps import get_current_user, require_admin
from ..projects import (
DEFINITION_KEYS,
LEGACY_PROJECT_DEFINITION,
LEGACY_PROJECT_ID,
PATCHER_READOOR,
PATCHERS,
current_project_id,
default_definition,
get_definition,
is_valid_project_id,
)
def _require_config_permission(request: Request, user: dict = Depends(get_current_user)) -> dict:
@@ -533,27 +545,86 @@ def _migrate_old_themes(config: dict) -> bool:
return True
def load_config() -> dict:
"""读取 config.json"""
def _default_project_data(project_id: str) -> dict:
"""新项目的初始数据;旧项目沿用原单项目时的默认服务器环境。"""
legacy = project_id == LEGACY_PROJECT_ID
return {
"apps": {}, "schemes": {},
"servers": dict(DEFAULT_SERVERS) if legacy else {},
"next_app_id_prefix": 5 if legacy else 1,
"branches": ["main"],
}
def _migrate_root(raw: dict) -> tuple:
"""把升级前的单项目配置(顶层即项目数据)包装为 projects.readoor,返回 (root, 是否变更)。"""
if isinstance(raw.get("projects"), dict) and raw["projects"]:
return raw, False
project = {key: value for key, value in raw.items() if key not in ("projects", "upload")}
if not project:
project = _default_project_data(LEGACY_PROJECT_ID)
project = {**copy.deepcopy(LEGACY_PROJECT_DEFINITION), **project}
root = {"projects": {LEGACY_PROJECT_ID: project}}
if "upload" in raw:
root["upload"] = raw["upload"]
return root, True
def _read_root() -> dict:
"""读取 config.json 根对象(含所有项目),必要时迁移旧结构。"""
if not CONFIG_JSON_PATH.exists():
# 首次部署:优先从项目根目录下的 config.json 导入
if BOOTSTRAP_CONFIG_PATH.exists():
CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(BOOTSTRAP_CONFIG_PATH, CONFIG_JSON_PATH)
else:
return {
"apps": {}, "schemes": {}, "servers": DEFAULT_SERVERS,
"next_app_id_prefix": 5, "branches": ["main"], "upload": DEFAULT_UPLOAD,
}
root, _ = _migrate_root({})
root["upload"] = DEFAULT_UPLOAD
return root
with open(CONFIG_JSON_PATH, "r", encoding="utf-8") as f:
config = json.load(f)
root, migrated = _migrate_root(json.load(f))
if "upload" not in root:
root["upload"] = DEFAULT_UPLOAD
if migrated:
_write_root(root)
return root
def _write_root(root: dict):
"""保存 config.json(自动备份)"""
if CONFIG_JSON_PATH.exists():
backup_path = CONFIG_JSON_PATH.with_suffix(".json.bak")
shutil.copy2(CONFIG_JSON_PATH, backup_path)
CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(root, f, indent=2, ensure_ascii=False)
def resolve_project_id(root: dict, project_id: str = None) -> str:
"""确定要操作的项目:显式指定 > 请求头 X-Project > 第一个项目。"""
projects = root["projects"]
project_id = project_id or current_project_id.get()
if not project_id:
return next(iter(projects))
if project_id not in projects:
raise HTTPException(status_code=400, detail=f"项目不存在: {project_id}")
return project_id
def load_config(project_id: str = None) -> dict:
"""读取某个项目的配置视图。
返回值与单项目时的 config.json 结构相同(apps/schemes/servers/... + upload),
并带 "_project" 标记,save_config() 据此写回对应项目。
"""
root = _read_root()
project_id = resolve_project_id(root, project_id)
config = {**root["projects"][project_id], "upload": root["upload"], "_project": project_id}
# 确保必要字段存在
if "servers" not in config:
config["servers"] = DEFAULT_SERVERS
config["servers"] = _default_project_data(project_id)["servers"]
if "branches" not in config:
config["branches"] = ["main"]
if "upload" not in config:
config["upload"] = DEFAULT_UPLOAD
versions_changed = _ensure_versions(config)
# 自动补齐旧配置的环境前缀、特殊 App 覆盖和 upload_key。
prefixes_changed = _ensure_server_id_prefixes(config)
@@ -568,12 +639,25 @@ def load_config() -> dict:
def save_config(config: dict):
"""保存 config.json(自动备份)"""
if CONFIG_JSON_PATH.exists():
backup_path = CONFIG_JSON_PATH.with_suffix(".json.bak")
shutil.copy2(CONFIG_JSON_PATH, backup_path)
with open(CONFIG_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
"""保存 load_config() 返回的项目配置视图(其中的 upload 为所有项目共用)。"""
root = _read_root()
project_id = config.get("_project") or resolve_project_id(root)
root["projects"][project_id] = {
key: value for key, value in config.items() if key not in ("upload", "_project")
}
if "upload" in config:
root["upload"] = config["upload"]
_write_root(root)
def load_upload_config() -> dict:
"""读取所有项目共用的上传配置"""
return _read_root()["upload"]
def load_projects() -> dict:
"""读取所有项目(项目 ID → 项目配置,不含共用的 upload)。"""
return _read_root()["projects"]
def get_build_config_value(db: Session, key: str, default=None) -> str:
@@ -584,14 +668,15 @@ def get_build_config_value(db: Session, key: str, default=None) -> str:
@router.get("")
async def get_full_config():
"""获取完整 config.json"""
"""获取当前项目的完整配置"""
return load_config()
@router.put("")
async def update_full_config(config: dict):
"""更新整个 config.json"""
"""更新当前项目的完整配置(upload 为所有项目共用)"""
async with _config_lock:
config["_project"] = load_config()["_project"]
save_config(config)
return {"message": "配置已更新"}
@@ -603,6 +688,25 @@ async def get_apps():
return config.get("apps", {})
def _validate_custom_fields(config: dict, fields_key: str, data: dict):
"""校验项目自定义字段(app_fields / server_fields)中的必填项。"""
definition = get_definition(config["_project"], config)
for field in definition[fields_key]:
if field.get("required") and not str(data.get(field["key"], "")).strip():
raise HTTPException(status_code=400, detail=f"{field.get('label') or field['key']} 不能为空")
def _server_entry(config: dict, server_data: dict, app_id_prefix) -> dict:
"""按项目保留服务器环境字段:Readoor 工程使用 api/assDom/universalLink,另加项目自定义字段。"""
definition = get_definition(config["_project"], config)
keys = [field["key"] for field in definition["server_fields"]]
if definition["patcher"] == PATCHER_READOOR:
keys = ["api", "assDom", "universalLink"] + keys
entry = {key: str(server_data.get(key, "")).strip() for key in keys}
entry["app_id_prefix"] = app_id_prefix
return entry
@router.post("/apps")
async def create_app(app: dict):
"""新增 app"""
@@ -611,6 +715,8 @@ async def create_app(app: dict):
config = load_config()
apps = config.get("apps", {})
_validate_custom_fields(config, "app_fields", app)
# 按服务环境自动生成三位 ID(例如测试环境 1xx、正式环境 2xx)。
_apply_special_app_prefix_override(app)
_normalize_tencent_app_id(app)
@@ -636,6 +742,7 @@ async def update_app(app_id: str, app: dict):
if app_id not in apps:
raise HTTPException(status_code=404, detail="App 不存在")
_validate_custom_fields(config, "app_fields", app)
_normalize_tencent_app_id(app)
apps[app_id] = app
config["apps"] = apps
@@ -1111,13 +1218,9 @@ async def create_server(server_data: dict):
if name in servers:
raise HTTPException(status_code=400, detail="环境名称已存在")
_validate_custom_fields(config, "server_fields", server_data)
prefix = config.get("next_app_id_prefix", 1)
servers[name] = {
"api": server_data.get("api", ""),
"assDom": server_data.get("assDom", ""),
"universalLink": server_data.get("universalLink", ""),
"app_id_prefix": prefix,
}
servers[name] = _server_entry(config, server_data, prefix)
config["servers"] = servers
config["next_app_id_prefix"] = prefix + 1
save_config(config)
@@ -1143,12 +1246,8 @@ async def update_server(server_name: str, server_data: dict):
else:
new_name = server_name
servers[new_name] = {
"api": server_data.get("api", ""),
"assDom": server_data.get("assDom", ""),
"universalLink": server_data.get("universalLink", ""),
"app_id_prefix": servers[new_name].get("app_id_prefix"),
}
_validate_custom_fields(config, "server_fields", server_data)
servers[new_name] = _server_entry(config, server_data, servers[new_name].get("app_id_prefix"))
config["servers"] = servers
save_config(config)
return {"message": "服务器环境已更新"}
@@ -1174,3 +1273,165 @@ async def delete_server(server_name: str):
config["servers"] = servers
save_config(config)
return {"message": "服务器环境已删除"}
# ---- 项目管理 ----
# App / 服务器环境中已有固定含义的字段,项目自定义字段不能占用
_RESERVED_FIELD_KEYS = {
"app_fields": {"name", "server", "certificates", "upload_key", "skins"},
"server_fields": {"name", "app_id_prefix"},
}
_FIELD_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_RULE_TYPES = {"define": ("file", "name", "value"), "replace_line": ("file", "keyword", "line")}
def _mask_definition(project_id: str, project: dict) -> dict:
"""项目定义(不返回 Git 密码,只标记是否已设置)"""
definition = get_definition(project_id, project)
git = dict(definition["git"])
git["password_set"] = bool(git.pop("password", ""))
return {"id": project_id, **definition, "git": git}
def _clean_fields(fields, fields_key: str) -> list:
if not isinstance(fields, list):
raise HTTPException(status_code=400, detail=f"{fields_key} 必须是数组")
cleaned, seen = [], set()
for field in fields:
key = str((field or {}).get("key", "")).strip()
if not _FIELD_KEY_PATTERN.fullmatch(key):
raise HTTPException(status_code=400, detail=f"字段名无效: {key or '(空)'}(字母、数字、下划线)")
if key in _RESERVED_FIELD_KEYS[fields_key] or key in seen:
raise HTTPException(status_code=400, detail=f"字段名重复或为保留字段: {key}")
seen.add(key)
cleaned.append({
"key": key,
"label": str(field.get("label", "")).strip() or key,
"required": bool(field.get("required")),
})
return cleaned
def _clean_patch_rules(rules) -> list:
if not isinstance(rules, list):
raise HTTPException(status_code=400, detail="patch_rules 必须是数组")
cleaned = []
for index, rule in enumerate(rules, start=1):
rule_type = (rule or {}).get("type")
if rule_type not in _RULE_TYPES:
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则类型无效(define / replace_line)")
item = {"type": rule_type}
for key in _RULE_TYPES[rule_type]:
value = str(rule.get(key, ""))
if key != "value" and key != "line" and not value.strip():
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则缺少 {key}")
item[key] = value.strip() if key in ("file", "name", "keyword") else value
file = item["file"]
if file.startswith("/") or ".." in Path(file).parts:
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则文件需为仓库内相对路径")
cleaned.append(item)
return cleaned
def _apply_definition(project: dict, data: dict, existing_git: dict = None):
"""把请求中的项目定义字段校验后写入 project(只更新请求中出现的字段)。"""
if "name" in data:
name = str(data["name"]).strip()
if not name:
raise HTTPException(status_code=400, detail="项目名称不能为空")
project["name"] = name
if "git" in data:
git = data["git"] or {}
password = str(git.get("password", ""))
if not password and existing_git:
password = existing_git.get("password", "")
project["git"] = {
"remote_url": str(git.get("remote_url", "")).strip(),
"username": str(git.get("username", "")).strip(),
"password": password,
"use_env": bool(git.get("use_env")),
}
if "source_dir" in data:
project["source_dir"] = str(data["source_dir"] or "").strip()
if "xcode" in data:
xcode = data["xcode"] or {}
project["xcode"] = {
"workspace": str(xcode.get("workspace", "")).strip(),
"project": str(xcode.get("project", "")).strip(),
}
if "copy_items" in data:
items = data["copy_items"]
if not isinstance(items, list):
raise HTTPException(status_code=400, detail="copy_items 必须是数组")
project["copy_items"] = [str(item).strip() for item in items if str(item).strip()]
if "patcher" in data:
if data["patcher"] not in PATCHERS:
raise HTTPException(status_code=400, detail=f"配置替换方式无效: {data['patcher']}")
project["patcher"] = data["patcher"]
if "patch_rules" in data:
project["patch_rules"] = _clean_patch_rules(data["patch_rules"])
for fields_key in ("app_fields", "server_fields"):
if fields_key in data:
project[fields_key] = _clean_fields(data[fields_key], fields_key)
if "obfuscation" in data:
project["obfuscation"] = bool(data["obfuscation"])
xcode = project.get("xcode") or {}
if not xcode.get("workspace") and not xcode.get("project"):
raise HTTPException(status_code=400, detail="Xcode workspace 和 project 至少填写一个")
if project.get("patcher") != PATCHER_READOOR and not xcode.get("project"):
raise HTTPException(status_code=400, detail="通用配置替换需要填写 Xcode project(.xcodeproj)")
@router.get("/projects")
async def get_project_definitions():
"""获取所有项目定义"""
return [_mask_definition(project_id, project) for project_id, project in load_projects().items()]
@router.post("/projects")
async def create_project(data: dict):
"""新增项目"""
project_id = str(data.get("id", "")).strip()
if not is_valid_project_id(project_id):
raise HTTPException(status_code=400, detail="项目 ID 需以小写字母开头,仅含小写字母、数字、-、_,最长 32 位")
async with _config_lock:
root = _read_root()
if project_id in root["projects"]:
raise HTTPException(status_code=400, detail="项目 ID 已存在")
project = {**copy.deepcopy(default_definition(project_id)), **_default_project_data(project_id)}
_apply_definition(project, data)
root["projects"][project_id] = project
_write_root(root)
return {"id": project_id, "message": "项目已创建"}
@router.put("/projects/{project_id}")
async def update_project(project_id: str, data: dict):
"""更新项目定义(Git 密码留空则保留原密码)"""
async with _config_lock:
root = _read_root()
if project_id not in root["projects"]:
raise HTTPException(status_code=404, detail="项目不存在")
project = root["projects"][project_id]
current = get_definition(project_id, project)
for key in DEFINITION_KEYS:
project.setdefault(key, copy.deepcopy(current[key]))
_apply_definition(project, {key: data[key] for key in DEFINITION_KEYS if key in data}, current["git"])
_write_root(root)
return {"message": "项目已更新"}
@router.delete("/projects/{project_id}")
async def delete_project(project_id: str):
"""删除项目(至少保留一个项目)"""
async with _config_lock:
root = _read_root()
if project_id not in root["projects"]:
raise HTTPException(status_code=404, detail="项目不存在")
if len(root["projects"]) == 1:
raise HTTPException(status_code=400, detail="至少需要保留一个项目")
del root["projects"][project_id]
_write_root(root)
return {"message": "项目已删除"}