feat: 支持按项目配置钉钉通知 @ 名单

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-11-03 09:59:05 +09:00
co-authored by Claude Opus 5.5
parent a4cd855b0c
commit 10c39b5116
7 changed files with 90 additions and 6 deletions
+6 -1
View File
@@ -15,6 +15,8 @@ config.json 结构:
"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
@@ -48,7 +50,7 @@ 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",
"patch_rules", "app_fields", "server_fields", "obfuscation", "dingtalk_at",
)
# 原单项目(阅门户)的定义,迁移旧配置时写入。
@@ -63,6 +65,7 @@ LEGACY_PROJECT_DEFINITION = {
"app_fields": [],
"server_fields": [],
"obfuscation": True,
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
}
# 当前请求操作的项目,由 main.py 的中间件按请求头 X-Project 设置;
@@ -93,6 +96,7 @@ def default_definition(project_id: str) -> dict:
"app_fields": [],
"server_fields": [],
"obfuscation": False,
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
}
@@ -102,6 +106,7 @@ def get_definition(project_id: str, project: dict) -> dict:
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
+6
View File
@@ -24,6 +24,7 @@ from ..config import (
SKINS_DIR,
)
from ..deps import get_current_user, require_admin
from ..services.notification import AT_MOBILES_KEYS, normalize_mobiles
from ..projects import (
DEFINITION_KEYS,
LEGACY_PROJECT_DEFINITION,
@@ -1376,6 +1377,11 @@ def _apply_definition(project: dict, data: dict, existing_git: dict = None):
project[fields_key] = _clean_fields(data[fields_key], fields_key)
if "obfuscation" in data:
project["obfuscation"] = bool(data["obfuscation"])
if "dingtalk_at" in data:
dingtalk_at = data["dingtalk_at"] or {}
if not isinstance(dingtalk_at, dict):
raise HTTPException(status_code=400, detail="dingtalk_at 必须是对象")
project["dingtalk_at"] = {key: normalize_mobiles(dingtalk_at.get(key)) for key in AT_MOBILES_KEYS}
xcode = project.get("xcode") or {}
if not xcode.get("workspace") and not xcode.get("project"):
+7 -3
View File
@@ -23,7 +23,7 @@ from ..config import (
from ..projects import LEGACY_PROJECT_ID, PATCHER_READOOR, get_definition, get_project_source
from .log_streamer import log_streamer
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
@@ -553,9 +553,13 @@ async def run_build_task(task_id: str):
await log_streamer.emit(task_id, f"下载链接: {task.oss_url}")
# Ad Hoc 发安装页二维码通知,App Store 发 IPA 下载地址通知;
# 两者标题与 @ 名单不同,均由 send_dingtalk_notification 按 BUILD_TYPE 区分。
# 两者标题与 @ 名单不同,均由 send_dingtalk_notification 按 BUILD_TYPE 区分;
# 项目配置了 @ 名单时覆盖全局名单。
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
dingtalk_config = config_data.get("_upload_config", {}).get("dingtalk", {})
dingtalk_config = merge_project_at_mobiles(
config_data.get("_upload_config", {}).get("dingtalk", {}),
definition.get("dingtalk_at"),
)
try:
notified = await asyncio.to_thread(
send_dingtalk_notification,
+16 -2
View File
@@ -27,7 +27,7 @@ def _signed_webhook_url(webhook_url: str, secret: str) -> str:
return f"{webhook_url}{separator}timestamp={timestamp}&sign={quote(base64.b64encode(signature))}"
def _normalize_mobiles(at_mobiles) -> list:
def normalize_mobiles(at_mobiles) -> list:
"""把手机号配置统一成去重、去空的字符串列表,兼容列表或逗号/换行分隔的字符串。"""
if not at_mobiles:
return []
@@ -43,6 +43,20 @@ def _normalize_mobiles(at_mobiles) -> list:
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,
@@ -50,7 +64,7 @@ def build_dingtalk_payload(
at_mobiles=None,
) -> dict:
"""生成与 AutoPacking/upload_iap.py 一致的钉钉 Markdown 内容。"""
mobiles = _normalize_mobiles(at_mobiles)
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】打包信息"
+20
View File
@@ -725,6 +725,18 @@
<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>
@@ -963,6 +975,7 @@ 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) => {
@@ -971,6 +984,7 @@ const openProjectModal = (project = null) => {
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,
@@ -981,6 +995,8 @@ const openProjectModal = (project = null) => {
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),
@@ -1018,6 +1034,10 @@ const saveProject = async () => {
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
+18
View File
@@ -142,3 +142,21 @@ def test_dingtalk_notification_sends_markdown():
def test_dingtalk_notification_requires_webhook_when_enabled():
with pytest.raises(NotificationError, match="Webhook"):
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
+17
View File
@@ -328,3 +328,20 @@ def test_generic_patcher_replace_line_rule(dy_build_dir):
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