From c91b01524dc6baa2a3ee068415d2cf03766152af Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Mon, 19 Oct 2026 11:05:55 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=AE=BE=E5=A4=87=E7=AB=AF):=20=E7=B4=A0?= =?UTF-8?q?=E6=9D=90=E9=A1=B5=E8=BD=AE=E8=AF=A2=E5=BD=93=E5=89=8D=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=20+=20=E5=88=87=E5=8F=B7/=E8=AF=BB=E5=90=8D=E5=90=8E?= =?UTF-8?q?=E5=B9=BF=E6=92=AD=E4=B8=8B=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 GET /api/device/agent/account(adb dumpsys account,1.5s 缓存) - push_account_name() 广播给设备端 AccountReceiver,不抢焦点 - switch_account 切号成功 / read_account_name 读名成功后自动推送 - probe_one_dumpsys 支持 timeout(HTTP 轮询用 5s) - 测试与 DEVICE_AGENT/API 文档同步 --- core/account_probe.py | 43 +++++++++++++++++++- doc/API.md | 1 + doc/DEVICE_AGENT.md | 57 ++++++++++++++++++++++++++- scripts/tests/test_dumpsys_account.py | 20 ++++++++++ scripts/tests/test_name_scope.py | 3 ++ scripts/tests/test_switch_account.py | 3 ++ tasks/generic/task.py | 30 ++++++++++++++ web/device_agent_api.py | 54 ++++++++++++++++++++++++- 8 files changed, 205 insertions(+), 6 deletions(-) diff --git a/core/account_probe.py b/core/account_probe.py index c95a742..b346410 100644 --- a/core/account_probe.py +++ b/core/account_probe.py @@ -14,7 +14,11 @@ 另有**快速通道** `probe_one_dumpsys()` / `probe_online_dumpsys()`:直接用 adb `dumpsys account` 读当前账号,不打开抖音、不点「我」。代价是 MIUI 会把昵称中间 打码成 `***`,历史记录里只有 AccountId/时间戳;需要完整昵称时仍用 u2 的 `probe_one()`。 + +读到的名字用 `push_account_name()` 通过广播推给设备端 Agent(素材页/身份页显示), +不抢焦点、不会打断正在操作抖音的任务。 """ +import base64 import re import time from concurrent.futures import ThreadPoolExecutor @@ -129,18 +133,19 @@ def parse_dumpsys_account(text): "uid": uid, "last_switch": last_switch} -def probe_one_dumpsys(serial): +def probe_one_dumpsys(serial, timeout=15): """用 adb `dumpsys account` 读一台设备的当前抖音账号(快,不用打开抖音)。 返回 `{serial, name, masked, last_switch, error}`: · name 可能是 MIUI 打码后的(如 `锋哥苏***实录`) · last_switch = 这个 uid 最近一次 action_account_add/remove 的时间 · 读不到时 error 是人话原因(不抛异常) + · `timeout` 给 HTTP 轮询用短一点(默认 15s 适合人工/任务) """ if not serial: return {"serial": serial, "name": "", "masked": False, "last_switch": "", "error": "缺少 serial"} - out = adb_helper._adb("-s", serial, "shell", "dumpsys account", timeout=15) + out = adb_helper._adb("-s", serial, "shell", "dumpsys account", timeout=timeout) if not out: return {"serial": serial, "name": "", "masked": False, "last_switch": "", "error": "dumpsys account 无输出(设备离线/超时)"} @@ -174,6 +179,40 @@ def probe_online_dumpsys(serials=None, workers=8): return out +def push_account_name(serial, name=None): + """把当前抖音账号推给设备端 Agent(素材页/身份页显示)。 + + `name` 为空时先走 `probe_one_dumpsys()`(要 1~3 秒,且刚切号时可能还是旧值); + **已知名字时直接传**,只发一次广播(百毫秒级,素材页立即更新)。 + 用**广播**而不是 Activity:不抢焦点,不会打断正在操作抖音的任务。 + + 返回 `(ok, msg)`;不抛异常。设备端收到后写 SharedPreferences, + 素材页 2 秒内自动显示,`PingActivity` 的 `status.json` 里也能看到。 + """ + if not serial: + return False, "缺少 serial" + if name is None: + name = probe_one_dumpsys(serial).get("name", "") + name = (name or "").strip() + if not name: + return False, "没有可下发的账号名(dumpsys 没读到)" + + b64 = base64.b64encode(name.encode("utf-8")).decode("ascii") + out = adb_helper._adb( + "-s", serial, "shell", "am", "broadcast", + "-n", "com.example.deviceagent/.AccountReceiver", + "-a", "com.example.deviceagent.SET_ACCOUNT", + "--es", "name_b64", b64, + timeout=15, + ) + ok = "broadcast completed" in (out or "").lower() + if ok: + _log.info(f"[{serial}] 已下发当前账号: {name}") + return True, f"已下发 {name}" + _log.warning(f"[{serial}] 下发账号名失败: {(out or '')[:120]}") + return False, f"下发失败: {(out or '')[:120]}" + + def busy_serials(): """正在跑任务/正在连接的设备(探测要跳过它们:抢屏会打断任务)。""" from core import device_worker diff --git a/doc/API.md b/doc/API.md index f3e814d..d8169f9 100644 --- a/doc/API.md +++ b/doc/API.md @@ -322,6 +322,7 @@ | 方法 | 路径 | 功能 | |------|------|------| | GET | `/api/device/agent/bootstrap` | 设备拉自己的身份 + 可安装应用清单 | +| GET | `/api/device/agent/account` | 设备素材页轮询当前抖音账号(平台走 adb `dumpsys account`,1.5s 缓存;昵称可能被 MIUI 打码) | | GET | `/api/device/agent/apk/` | 下载 APK 文件 | | POST | `/api/device/agent/report` | 上报下载/安装结果 | diff --git a/doc/DEVICE_AGENT.md b/doc/DEVICE_AGENT.md index 506c5ba..dd473d8 100644 --- a/doc/DEVICE_AGENT.md +++ b/doc/DEVICE_AGENT.md @@ -164,6 +164,34 @@ --- +### 3.6 `GET /api/device/agent/account` + +素材页轮询:让平台现场读「这台设备现在登的是哪个抖音号」。平台走 adb +`dumpsys account`(免 root、不打开抖音),返回的 `name` 可能被 MIUI 打码成 +`锋哥苏***实录`。 + +**请求头**同 §3.1。**响应** + +```json +{ + "ok": true, + "agent_api_version": 1, + "server_time": "2026-10-19 10:30:00", + "device": {"fingerprint": "...", "serial": "...", "name": "A08", "known": true}, + "account": {"name": "锋哥苏***实录", "masked": true, + "last_switch": "2026-10-19 10:13:59"} +} +``` + +- 读不到(没登录/没注册/设备离线)→ `200 {"ok":false,"error":"人话原因"}`; + 设备端保留上次显示的值即可 +- 平台侧有约 1.5 秒缓存,素材页每 2 秒轮询不会每次都跑 `dumpsys` +- 完整未打码昵称仍用 u2 读「我」页(§5.5);这个接口只保证“快”和“免 root” +- 设备端「切换账号 / 读取本机账号名字」成功后仍会通过广播主动推一次(§5.5), + 比轮询更快 + +--- + ## 4. 平台侧配置(管理端) 「工具 → 应用管理 → 📱 设备端应用商店」: @@ -285,6 +313,28 @@ adb -s shell am start -n /.MaterialActivity --es close 1 同一份 dump 里的 `Accounts History` 是切号时间。 - `core.account_probe.probe_one(serial)`:u2 打开抖音点「我」,读完整昵称(慢一些)。 +读到的值用 `core.account_probe.push_account_name(serial, name=None)` 推给设备端: +**已知名字时直接传**(只发广播,百毫秒级);`name` 为空时才 `dumpsys` 读(1~3 秒, +刚切号时可能还是旧值)。也可以手动发: + +```bash +adb -s shell am broadcast \ + -n /.AccountReceiver \ + -a com.example.deviceagent.SET_ACCOUNT \ + --es name_b64 "" +``` + +设备端收到后写 SharedPreferences,**正在显示的素材页/身份页立即刷新**(不等轮询); +`PingActivity` 的 `status.json` 里可回读 `account_name`。 + +任务步骤已经接好:`switch_account` 切号成功(回读校验通过)后、`read_account_name` +读到名字后,都会用**已知名字**自动推送(`GenericStepsWorker._push_account_name`), +所以平台切完号素材页马上变,不会再等下一次探测。 + +另外素材页自己也会**主动拉**(§3.6):打开/回到页面立即拉一次,可见期间每 2 秒 +拉一次(平台侧 1.5 秒缓存)。所以即使没有广播(例如在抖音里手动切号), +账号也会在几秒内更新;广播推送仍然更快、且是完整昵称。 + > Agent 端**读不到**抖音账号:Android 8+ 的账号可见性规则 + 抖音 authenticator > 不放行(`GET_ACCOUNTS` + `READ_CONTACTS` 都授了也只放行小米账号), > `dumpsys account` 又需要 shell 的 `DUMP` 权限。所以当前账号只能由平台读、再下发。 @@ -328,8 +378,11 @@ logcat 记 `MATERIAL_SHARE abort`。 设备端收到"没有这个 extra"时照旧只显示身份信息即可。) - 素材页 extras(`folder`/`share`/`filter`/`close`/`account_name`)是**新增的可选能力**, 只在设备端 v1.6+ 生效;v1.7 起增加「写入中保护」(未传完不可点,`share` 会被拒绝); - v1.9 起 `account_name` 由平台下发并显示(Agent 自己读不到抖音账号)。旧版 Agent - 不认识这些 extra,平台触发前可用 `PingActivity` 的 `status.json` + v1.9 起 `account_name` 由平台下发并显示;v2.0 增加**广播下发** + (`AccountReceiver`,不抢焦点);v2.1 广播到达后**立即刷新**(不再等 2 秒轮询); + v2.2 素材页**主动轮询** §3.6 `GET /api/device/agent/account`(打开即拉、可见时每 2 秒)。 + Agent 自己读不到抖音账号,但可以主动问平台。 + 旧版 Agent 不认识这些 extra,平台触发前可用 `PingActivity` 的 `status.json` 看 `material_dir`/`can_read_media`/`account_name`/`douyin_installed`。 **`agent_api_version` 不变(仍为 1)**。 - `agent_api_version`(当前 **1**)在每次 `bootstrap` 响应里返回 diff --git a/scripts/tests/test_dumpsys_account.py b/scripts/tests/test_dumpsys_account.py index a6352ac..3d6ab1a 100644 --- a/scripts/tests/test_dumpsys_account.py +++ b/scripts/tests/test_dumpsys_account.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- """`dumpsys account` 解析用例(纯字符串,不连设备、不连库)。""" +import base64 import io import os import sys @@ -8,6 +9,7 @@ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='repla sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) os.chdir(sys.path[0]) +from core import account_probe as ap # noqa: E402 from core.account_probe import parse_dumpsys_account # noqa: E402 fails = [] @@ -42,6 +44,24 @@ r = parse_dumpsys_account("Accounts: 1\n Account {name=abc, type=com.xiaomi}") check('name 为空', r['name'], '') check('masked=False', r['masked'], False) +print('=== 3. push_account_name 走广播(假 adb,不连设备)===') +_calls = [] +_orig_adb = ap.adb_helper._adb +ap.adb_helper._adb = lambda *a, **kw: ( + _calls.append(a), "Broadcast completed: result=0" +)[1] +try: + ok, msg = ap.push_account_name("A:5555", "锋哥苏***实录") +finally: + ap.adb_helper._adb = _orig_adb +check('返回 ok', ok, True) +check('消息', msg, '已下发 锋哥苏***实录') +check('显式广播组件', _calls[0][5:7], + ("-n", "com.example.deviceagent/.AccountReceiver")) +check('使用 name_b64', _calls[0][10], "name_b64") +check('base64 是标准编码', base64.b64decode(_calls[0][11]).decode("utf-8"), + "锋哥苏***实录") + print() if fails: print('❌ 失败 %d 项:%s' % (len(fails), ' / '.join(fails))) diff --git a/scripts/tests/test_name_scope.py b/scripts/tests/test_name_scope.py index fa6962b..ec35b6d 100644 --- a/scripts/tests/test_name_scope.py +++ b/scripts/tests/test_name_scope.py @@ -25,6 +25,9 @@ from core import video_plan as vp # noqa: E40 from tasks.generic import task as gt # noqa: E402 from tasks.generic import publish_flow as flow # noqa: E402 +# 假设备用例:读名/切号后不要尝试 adb 广播(不连真机) +gt.GenericStepsWorker.account_push_enabled = False + fails = [] diff --git a/scripts/tests/test_switch_account.py b/scripts/tests/test_switch_account.py index 1066af9..a7a51d4 100644 --- a/scripts/tests/test_switch_account.py +++ b/scripts/tests/test_switch_account.py @@ -19,6 +19,9 @@ os.chdir(_ROOT) from tasks.generic import task as gt # noqa: E402 +# 假设备用例:切号成功后不要尝试 adb 广播(不连真机) +gt.GenericStepsWorker.account_push_enabled = False + fails = [] diff --git a/tasks/generic/task.py b/tasks/generic/task.py index 4a17951..23527bd 100644 --- a/tasks/generic/task.py +++ b/tasks/generic/task.py @@ -291,6 +291,10 @@ class GenericStepsWorker(BaseWorker): 只实现 run_task,按步骤类型分发到 _exec_ 方法。 """ + # 切号/读名成功后,是否把当前账号广播推给设备端 Agent(素材页/身份页显示)。 + # 测试里用假设备、不能发 adb,把类属性置 False 即可(见 scripts/tests)。 + account_push_enabled = True + def __init__(self, serial, params=None, ctx=None): super().__init__(serial, params, ctx=ctx) p = {**DEFAULT_PARAMS, **(self.params or {})} @@ -1150,6 +1154,27 @@ class GenericStepsWorker(BaseWorker): pass return False + def _push_account_name(self, name): + """把当前账号推给设备端 Agent(广播,不抢焦点);失败只记日志。 + + 切号/读名成功时调用,设备端素材页/身份页会**立即**显示当前账号。 + 这里传了已知的 name,只发一次广播(不要再走 dumpsys,慢)。 + """ + name = (name or "").strip() + if not name: + return + if not getattr(self, "account_push_enabled", True): + return + try: + from core.account_probe import push_account_name + ok, msg = push_account_name(self.serial, name) + if ok: + _log.info(f"[{self.serial}] 已下发当前账号:{msg}") + else: + _log.warning(f"[{self.serial}] 下发当前账号失败:{msg}") + except Exception as e: + _log.warning(f"[{self.serial}] 下发当前账号异常:{e}") + def _exec_read_account_name(self, d, params, depth=0): """读取本机当前登录的账号名字(抖音「我」页面上的昵称控件)。 @@ -1201,6 +1226,8 @@ class GenericStepsWorker(BaseWorker): self._vars["account_name"] = name _log.info(f"[{self.serial}] 本机账号名字 = 『{name}』(元素原文 {raw!r})") self.set_action(f"本机账号:{name}") + # 让设备端素材页/身份页**立即**显示当前账号(广播,不抢焦点) + self._push_account_name(name) return True def _exec_read_text(self, d, params, depth=0): @@ -1539,6 +1566,7 @@ class GenericStepsWorker(BaseWorker): if got and got == target: _log.info(f"[{self.serial}] 切换账号:当前就是『{target}』,不用切(一个号都没点)") self.set_action(f"已经是『{target}』,不用切") + self._push_account_name(target) return True switch_val = self._vars_sub((params.get("switch_selector_value") or "").strip()) if not switch_val: @@ -1650,6 +1678,8 @@ class GenericStepsWorker(BaseWorker): f"等了 {wait_after:.0f}s)") self.set_action(f"已切到『{target}』") self._vars["account_name"] = target + # 切号成功立刻下发,素材页不用等下一次探测 + self._push_account_name(target) return True time.sleep(0.8) hint = self._page_has_text(d, self._LOGIN_HINTS) if not last_got else "" diff --git a/web/device_agent_api.py b/web/device_agent_api.py index f1c71d2..59cc4e2 100644 --- a/web/device_agent_api.py +++ b/web/device_agent_api.py @@ -1,7 +1,7 @@ """设备端 Agent 专用接口(设备主动来取,**不走登录会话**,靠设备令牌鉴权)。 -用途:设备上装的聚合 Agent(剪贴板注入 / 身份显示 / 应用商店)用这组接口 -自报身份、拉可安装的应用清单、下载 APK、回报安装结果。 +用途:设备上装的聚合 Agent(剪贴板注入 / 身份显示 / 素材页 / 应用商店)用这组接口 +自报身份、拉可安装的应用清单、下载 APK、回报安装结果、读当前抖音账号。 为什么另开一组接口而不是复用管理端 API: * 设备登录不了后台会话,也不该拿 admin 的凭据; @@ -41,6 +41,10 @@ _K_CREATED = "agent_device_token_at" # 令牌生成/重置时间 _API_VERSION = 1 # 本组接口的版本(契约里写死给 agent 对照) _MAX_LOG = 500 # 记录表最多保留条数(超了删最旧) +# 设备端素材页每 ~2 秒轮询当前账号;缓存 1.5 秒,避免每个请求都跑一次 dumpsys +_ACCOUNT_CACHE = {} # key(serial/fp) -> (ts, result) +_ACCOUNT_CACHE_TTL = 1.5 + # ================== 公共:开关与令牌 ================== def store_enabled(): @@ -142,6 +146,52 @@ def api_dev_agent_bootstrap(): }) +def _account_cached(serial, fp, timeout=5): + """读当前账号(带短缓存):素材页轮询时避免每次都跑 dumpsys。""" + key = serial or fp + now = time.time() + hit = _ACCOUNT_CACHE.get(key) + if hit and now - hit[0] < _ACCOUNT_CACHE_TTL: + return hit[1] + if serial: + from core.account_probe import probe_one_dumpsys + r = probe_one_dumpsys(serial, timeout=timeout) + else: + r = {"serial": serial, "name": "", "masked": False, "last_switch": "", + "error": "无法识别设备(缺 serial)"} + if not r.get("error"): + _ACCOUNT_CACHE[key] = (now, r) + return r + + +@bp.route("/api/device/agent/account") +def api_dev_agent_account(): + """设备端素材页轮询:当前登录的抖音账号(平台走 adb dumpsys account,免 root)。 + + 请求头同 §3.1。返回的 `account.name` 可能是 MIUI 打码后的 + (如 `锋哥苏***实录`);读不到时 `ok=false` + `error`(HTTP 仍 200, + 设备端保留上次的值即可)。 + """ + deny = _deny() + if deny: + return deny + fp, serial, name, known = _identify() + r = _account_cached(serial, fp) + resp = { + "ok": not r.get("error"), + "agent_api_version": _API_VERSION, + "server_time": time.strftime("%Y-%m-%d %H:%M:%S"), + "device": {"fingerprint": fp, "serial": serial, + "name": name, "known": known}, + } + if r.get("error"): + resp["error"] = r["error"] + else: + resp["account"] = {"name": r["name"], "masked": r.get("masked", False), + "last_switch": r.get("last_switch", "")} + return jsonify(resp) + + @bp.route("/api/device/agent/apk/") def api_dev_agent_apk(apk_id): """下载 APK 文件(设备自己拉,比 adb push 快且可并行)。"""