Files
iOSBuildServer/backend/services/notification.py
T
shenlei 83a1db21e5 feat: 接入 iOSGuard LLVM 混淆工具链与 IPA 加固门禁,按分支策略兼容旧版本打包
- 新增 toolchain_manager:构建前自愈校验 LLVM opt 工具链,按 Xcode 版本与渠道隔离 obj_cache
- readoor31/readoor31OtherPay Archive 透传 IG_DIST_CHANNEL/IG_OBF_MODE/IG_ALL_GUARD_OFF/IG_RELEASE_SEED
- Archive 前核对分发渠道编译条件:上架包缺失 IG_APPSTORE_DISTRIBUTION 即阻断,非上架包带该条件仅告警,未接入 anti_tamper 的分支跳过
- 导出后执行 IPA 加固门禁审计,失败阻断上传;持久化 dSYM、混淆映射、诊断事件码与审计报告
- 混淆是否执行改由分支 AutoPacking/build_policy.json 声明:force_obfuscation=true 强制,否则按任务勾选,兼容旧分支/旧 Tag;恢复打包页混淆勾选框
- 分支未自带混淆脚本时回退服务端脚本并告警;同步更新服务端 L1 混淆脚本
- .gitignore 忽略 iosguard_cache 与 artifacts 运行时目录;README 补充分支打包策略说明
2026-11-24 12:03:54 +09:00

168 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""打包完成后的钉钉通知。"""
import base64
import hashlib
import hmac
import time
from urllib.parse import quote
import httpx
class NotificationError(Exception):
"""通知发送失败。"""
def _signed_webhook_url(webhook_url: str, secret: str) -> str:
"""为启用了加签的钉钉机器人附加 timestamp 与 sign 参数。"""
if not secret:
return webhook_url
timestamp = str(round(time.time() * 1000))
signature = hmac.new(
secret.encode("utf-8"),
f"{timestamp}\n{secret}".encode("utf-8"),
hashlib.sha256,
).digest()
separator = "&" if "?" in webhook_url else "?"
return f"{webhook_url}{separator}timestamp={timestamp}&sign={quote(base64.b64encode(signature))}"
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 内容。"""
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 = (
f"**环境:** {config_data.get('SERVER', '')}\n\n"
f"**版本:** {config_data.get('VERSION', '')}\n\n"
f"**APP名称:** {config_data.get('APPID_NAME', '')}\n\n"
f"**包名:** {config_data.get('BUNDLE_ID', '')}\n\n"
f"**{config_data.get('APPID_LABEL', 'App Guid')}:** {config_data.get('APPID', '')}"
)
text = f"## {heading}\n\n{details}\n\n**iOS 下载链接:** {download_url}\n"
if qr_code_url:
text += f"\n![image]({qr_code_url})"
# 钉钉 markdown 消息必须在正文内出现 @手机号 才会真正 @ 到人,
# 仅靠 at.atMobiles 不生效。
if mobiles:
text += "\n\n" + " ".join(f"@{m}" for m in mobiles)
return {
"msgtype": "markdown",
"markdown": {"title": "iOS应用下载", "text": text},
"at": {"atMobiles": mobiles, "isAtAll": False},
}
def send_dingtalk_notification(
dingtalk_config: dict,
config_data: dict,
download_url: str,
qr_code_url: str = "",
) -> bool:
"""发送钉钉通知;未启用通知时不发起网络请求。"""
if not dingtalk_config.get("enabled"):
return False
webhook_url = dingtalk_config.get("webhook_url", "").strip()
if not webhook_url:
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
# Ad_Hoc 与 App_Store 使用各自的 @ 名单。
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(
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
json=payload,
timeout=15,
)
if response.status_code // 100 != 2:
raise NotificationError(f"钉钉通知发送失败 ({response.status_code})")
try:
result = response.json()
except ValueError as exc:
raise NotificationError("钉钉通知返回内容无效") from exc
if result.get("errcode", 0) != 0:
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
return True
def send_toolchain_dingtalk_alert(
dingtalk_config: dict,
title: str,
lines: list[str],
) -> bool:
"""发送 Xcode/opt 工具链状态通知(标题和正文必须保留「打包」关键词)。"""
if not (dingtalk_config or {}).get("enabled"):
return False
webhook_url = (dingtalk_config.get("webhook_url") or "").strip()
if not webhook_url:
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
safe_title = title if "打包" in title else f"【iOS打包服务】{title}"
mobiles = normalize_mobiles(dingtalk_config.get("at_mobiles", []))
body_lines = [f"## {safe_title}", "", *lines]
if mobiles:
body_lines.extend(["", " ".join(f"@{m}" for m in mobiles)])
payload = {
"msgtype": "markdown",
"markdown": {"title": safe_title, "text": "\n\n".join(body_lines)},
"at": {"atMobiles": mobiles, "isAtAll": False},
}
response = httpx.post(
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
json=payload,
timeout=15,
)
if response.status_code // 100 != 2:
raise NotificationError(f"钉钉通知发送失败 ({response.status_code})")
try:
result = response.json()
except ValueError as exc:
raise NotificationError("钉钉通知返回内容无效") from exc
if result.get("errcode", 0) != 0:
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
return True