feat: resolve account platforms prioritizing structural snapshot values and correction on existing accounts

This commit is contained in:
SmartUp Developer
2026-07-02 22:58:15 +08:00
parent 1cb13e878e
commit fd2755d539
4 changed files with 359 additions and 13 deletions
+70 -13
View File
@@ -462,6 +462,17 @@ def import_groups_from_upstream(
)
SUPPORTED_PLATFORMS = {"openai", "anthropic", "gemini", "antigravity"}
def _resolve_platform(text: str, group_snapshot: dict | None, fallback: str = "openai") -> str:
if group_snapshot and isinstance(group_snapshot, dict):
platform = group_snapshot.get("platform")
if platform and str(platform).lower() in SUPPORTED_PLATFORMS:
return str(platform).lower()
return _detect_platform(text, fallback)
def _detect_platform(text: str, fallback: str = "openai") -> str:
"""根据 Key 名或分组名关键词判断平台类型。"""
lower = text.lower()
@@ -496,6 +507,12 @@ def sync_imported_upstream_keys(
.all()
)
items: list[ImportAccountItem] = []
# 预载最新快照映射,用于结构化 platform 解析
upstream_ids = {row.upstream_id for row in rows}
latest_snapshots = {}
for uid in upstream_ids:
latest_snapshots[uid] = latest_rate_map(db, uid)
with _client(website) as c:
remote_accounts = None
try:
@@ -513,7 +530,9 @@ def sync_imported_upstream_keys(
remote_ids = None
for row in rows:
platform = _detect_platform(f"{row.group_name} {row.group_id} {row.key_name}", "openai")
snap_groups = latest_snapshots.get(row.upstream_id) or {}
group_snap = snap_groups.get(row.group_id) if isinstance(snap_groups, dict) else None
platform = _resolve_platform(f"{row.group_name} {row.group_id} {row.key_name}", group_snap, "openai")
if not row.imported_account_id:
continue
old_account_id = row.imported_account_id
@@ -645,12 +664,17 @@ def import_upstream_keys_as_accounts(
)
for kid in missing_ids
]
# 预载上游以方便获取名称 base_url
# 预载上游以方便获取名称 and base_url
from app.models.upstream import Upstream as _Up
upstream_ids = {row.upstream_id for row in rows}
upstreams_db = db.query(_Up).filter(_Up.id.in_(upstream_ids)).all()
upstreams_map = {u.id: u for u in upstreams_db}
# 预载最新快照映射,用于结构化 platform 解析
latest_snapshots: dict[int, dict[str, Any]] = {}
for uid in upstream_ids:
latest_snapshots[uid] = latest_rate_map(db, uid)
# 按倍率自动分配优先级
rate_priority_map: dict[tuple[str, int, str], int] = {}
if body.auto_priority_by_rate:
@@ -706,8 +730,11 @@ def import_upstream_keys_as_accounts(
continue
# 先确定平台(失败项也需要记录)
if body.platform_mode == "auto":
platform = _detect_platform(
snap_groups = latest_snapshots.get(row.upstream_id) or {}
group_snap = snap_groups.get(row.group_id) if isinstance(snap_groups, dict) else None
platform = _resolve_platform(
f"{row.group_name} {row.group_id} {row.key_name}",
group_snap,
body.default_platform,
)
else:
@@ -1644,6 +1671,18 @@ def organize_website_groups(
if acc_id:
remote_account_map[str(acc_id)] = acc
# 预载所有相关的上游快照映射
all_upstream_ids = set()
for b in bindings:
for src in binding_sources(b):
_uid = src.get("upstream_id")
if _uid:
all_upstream_ids.add(int(_uid))
latest_snapshots: dict[int, dict[str, Any]] = {}
for _uid in all_upstream_ids:
latest_snapshots[_uid] = latest_rate_map(db, _uid)
# 对每个绑定关系遍历其对应的上游 Key 进行整理
for b in bindings:
target_group_id = b.target_group_id
@@ -1659,14 +1698,10 @@ def organize_website_groups(
_u = db.query(Upstream).filter(Upstream.id == uid).first()
upstream_name = _u.name if _u else f"#{uid}"
snapshot_groups = latest_snapshots.get(int(uid)) or {}
# 来源名称优先取 src.group_name,再 fallback 快照,再 fallback ID
source_group_name = src.get("group_name") or ""
if not source_group_name:
snapshot_groups = {}
try:
snapshot_groups = latest_rate_map(db, uid)
except Exception:
pass
if gid in snapshot_groups:
g_data = snapshot_groups[gid]
if isinstance(g_data, dict):
@@ -1725,8 +1760,10 @@ def organize_website_groups(
continue
# 检测平台类型
platform = _detect_platform(
group_snap = snapshot_groups.get(row.group_id) if isinstance(snapshot_groups, dict) else None
platform = _resolve_platform(
f"{row.group_name} {row.group_id} {row.key_name}",
group_snap,
"openai",
)
@@ -1771,11 +1808,31 @@ def organize_website_groups(
old_set = {str(g) for g in current_group_ids}
new_set = {str(g) for g in new_group_ids}
remote_platform = remote_acc.get("platform")
if remote_platform is not None:
platform_mismatch = (str(remote_platform).lower() != str(platform).lower())
else:
platform_mismatch = (str(platform).lower() != "openai")
update_payload = {}
if old_set != new_set:
c.update_account(old_account_id, {"group_ids": new_group_ids})
# 顺便更新下 remote_account_map 中的数据,防止同个账号后续在其他绑定中重复处理
remote_acc["group_ids"] = new_group_ids
msg = "已存在,已迁移到目标分组"
update_payload["group_ids"] = new_group_ids
if platform_mismatch:
update_payload["platform"] = platform
if update_payload:
c.update_account(old_account_id, update_payload)
if "group_ids" in update_payload:
remote_acc["group_ids"] = new_group_ids
if "platform" in update_payload:
remote_acc["platform"] = platform
msg_parts = []
if old_set != new_set:
msg_parts.append("已迁移到目标分组")
if platform_mismatch:
msg_parts.append(f"平台从 {remote_platform} 修正为 {platform}")
msg = "已存在," + "".join(msg_parts)
else:
msg = "已存在且已对齐,已跳过"