diff --git a/autojs6/home_yibao/README.md b/autojs6/home_yibao/README.md index 9cc118b..d1dbaf2 100644 --- a/autojs6/home_yibao/README.md +++ b/autojs6/home_yibao/README.md @@ -164,11 +164,31 @@ yibaoPackage: "com.tencent.android.qqdownloader" **执行追踪**:主任务各阶段有“阶段切换”日志;额外任务 8 步每步进入时都会输出“步骤标记: 额外任务 n/8 …”日志(`setStep`)。失败时当前步骤会随异常日志(`step=`)与失败现场截图文件名一起带出——logcat 缓冲溢出丢行或脚本中断后,也能判断执行到了哪一步。 +## `ad_view_3.js` 手机本地命令截图兜底 + +只对 `ad_view_3.js` 生效,不需要电脑服务或 ADB。默认保留 `captureScreen()` 的三次重试;连续失败后,通过独立进程执行 Root 命令,先运行 `id` 确认 UID 0,再运行 `/system/bin/screencap -p <临时PNG>`。 + +```javascript +shellCaptureFallback: { + enabled: true, + executable: "/system/xbin/mus", + commandTimeoutMs: 5000 +} +``` + +- `executable` 必须是当前手机实际已授权的 Root 程序绝对路径,可按环境改成 `su` 的实际路径;不会自动尝试其他提权通道,也不调用 Shizuku。 +- 身份检查和每次截图分别限制为默认 5 秒。首次切换最多包含一次身份检查和一次截图;此前原投影三次重试仍可能耗时约 30 秒。 +- 成功后,本次运行的全屏 OCR、局部 OCR 和失败现场截图都使用命令后端,不再逐帧尝试失效投影。每张图使用独立的应用缓存文件,校验成功码、非空文件、解码及尺寸后交给原有 OCR,随后删除 PNG,避免读到旧图。 +- Root 身份不足、命令超时、PNG 无效或尺寸不符时立即熔断。之后截图直接报错,OCR 不会把这个错误当作普通漏帧;主流程停止,不再回桌面重跑,也不会为了失败现场截图再次等待原投影。 +- 命令不使用同步 `shell()`、`waitFor()` 或阻塞管道读取,超时后尝试销毁直接子进程;不能保证终止 Root 程序派生的所有进程,因此不会自动重新探测。 +- **本机已有 mus 从 AutoJS app 域调用阻塞的历史。兜底代码不等于已经获得可用 Root 权限,是否可用仍须在手机中运行验证。** 日志应出现“本地命令截图 Root 身份验证通过”和“切换到本地命令截图”;若提示身份校验失败或超时,应先处理手机端授权/执行通道。 +- 此功能只在运行中截屏失败时切换,启动时仍申请原截图权限;不重新申请投影,也不能保证避免云手机推流进程自身崩溃。设 `enabled: false` 可恢复原截图行为;修改配置后需停止旧运行并重新启动。 + ## 已知问题(本云手机 ROM) - **不要在脚本里调用 AutoJS6 内置的 `currentPackage()` / `currentActivity()`**:它们内部自起子进程读 stdout,在本云手机上输出管道不关闭,`readLine()` 会永久阻塞脚本线程(症状:日志停在“返回 Android 桌面”后无任何输出)。前台应用检测改用无障碍服务的活动窗口缓存 `auto.rootInActiveWindow.getPackageName()`(纯 Java API,不走 shell,毫秒级返回;实测应用宝/桌面包名均准确)。 - **AutoJS6 Rhino 引擎:循环体内声明的 `const` 从第二次迭代起赋值静默失效**(`let`/`var` 正常)。例如 `for (...) { const v = "v" + k; }` 中 `v` 恒为首次的值,不报错、难察觉。这曾导致所有 OCR 匹配逻辑只比较第一条文本(长期“识别率低”的真正原因)。**本脚本已全部改用 `var`,后续新增代码禁止在循环体内用 `const`。** -- **画面完全静止时 `captureScreen()` 会抛出 "Failed to capture screen image"**:云手机视频流不产生新帧时,AutoJS6 的 ImageReader 等满内部超时(约 10 秒)后抛错。脚本内置 `captureCurrentScreen()` 重试(3 次),失败间隙用一次 1px 拖动(`forceScreenRefresh()`)强制刷新画面;OCR 循环单帧采样失败会跳过该帧而不是中止流程。 +- **画面完全静止时 `captureScreen()` 会抛出 "Failed to capture screen image"**:云手机视频流不产生新帧时,AutoJS6 的 ImageReader 等满内部超时(约 10 秒)后抛错。脚本内置 `captureCurrentScreen()` 重试(3 次),失败间隙用一次 1px 拖动(`forceScreenRefresh()`)强制刷新画面。普通 OCR 单帧采样失败会跳过;`ad_view_3.js` 的命令截图兜底若已熔断,则会停止流程,详见上节。 - `dumpsys window` 的 `mCurrentFocus`/`mFocusedApp` 均为 null,解析会失败;脚本已回退到 `dumpsys activity activities` 的 `mResumedActivity`。且探针实测:`mus` 从 AutoJS app 进程调用会永久挂死(仅 adb shell 域可用,app 域被阻塞而非报错),裸 `dumpsys` 是 Permission Denial——因此 `foregroundDumpEnabled` 默认 false,dumpsys 路径仅作无障碍不可用设备的回退。 排查方法:`adb shell "mus -c 'kill -3 '"` 触发线程转储,再用 `mus -c 'cat /data/anr/trace_01'` 拉取分析卡住的线程栈;AutoJS6 进程的 `System.err` 堆栈(如 `Failed to capture screen image`)可在 logcat 中按 pid 过滤获取。 diff --git a/autojs6/home_yibao/ad_view_1.js b/autojs6/home_yibao/ad_view_1.js index dcf426d..a810236 100644 --- a/autojs6/home_yibao/ad_view_1.js +++ b/autojs6/home_yibao/ad_view_1.js @@ -46,7 +46,7 @@ var CONFIG = { "了解详情", "了解详倩", "了解详请", "了解詳情", "了解详", "查看详情", "查看详倩", "详情", "详倩", "立即体验", "立即下载", "立即下載", "下载应用", "点击下载", - "下载游戏" + "下载游戏", "立即领取", "立即安装", "立即抢购", "立即打开应用" ], adConfirmTexts: ["可获得奖励", "可得奖励", "看15秒", "广告", "跳转详情", "第三方应用"], @@ -574,6 +574,9 @@ function normalizeText(value) { .replace(/详[倩请請晴睛靖情]/g, "详情") .replace(/詳[倩请請晴睛靖情]/g, "详情") .replace(/祥[倩请請晴睛靖情]/g, "详情") + // 两字目标不再任意单字容错,仅兼容明确的 OCR 别名和繁体写法。 + .replace(/账钱/g, "赚钱") + .replace(/下載/g, "下载") .replace(/倩/g, "情") .replace(/請/g, "请") .toLowerCase(); @@ -996,9 +999,9 @@ function isCjkText(text) { return true; } -// 与桌面版 ocr_task.py 的 text_matches 同源的容错规则: -// 1) 精确子串;2) 目标缺头/缺尾一个字的截断子串;3) 等长滑窗汉明距离 <=1 的单字误读。 -// 云手机视频流小字常出现“赚钱→账钱”“放弃福利→放弃福”这类识别偏差。 +// 基于桌面版 ocr_task.py 的 text_matches,短目标采用更严格的匹配规则: +// 1) 归一化后的精确子串;2) 至少三字目标允许缺头/缺尾;3) 至少三字目标允许单字误读。 +// 两字目标只兼容 normalizeText 中的明确别名,避免“友情”以单字差异误命中“详情”。 function textMatchesLoose(normalizedItem, normalizedTarget) { if (!normalizedTarget) { return false; @@ -1014,7 +1017,7 @@ function textMatchesLoose(normalizedItem, normalizedTarget) { return true; } } - if (normalizedTarget.length >= 2 && normalizedItem.length >= normalizedTarget.length) { + if (normalizedTarget.length >= 3 && normalizedItem.length >= normalizedTarget.length) { // 全中文目标不与含数字/字母的窗口做单字容错:“11.6.01 开发者”归一化 // 成“11601开发者”后,滑窗“1开”曾以汉明距离 1 误命中“打开”。 var targetIsCjk = isCjkText(normalizedTarget); diff --git a/autojs6/home_yibao/ad_view_2.js b/autojs6/home_yibao/ad_view_2.js index a7e3097..ef542c6 100644 --- a/autojs6/home_yibao/ad_view_2.js +++ b/autojs6/home_yibao/ad_view_2.js @@ -46,7 +46,7 @@ var CONFIG = { "了解详情", "了解详倩", "了解详请", "了解詳情", "了解详", "查看详情", "查看详倩", "详情", "详倩", "立即体验", "立即下载", "立即下載", "下载应用", "点击下载", - "下载游戏", "去微信观看全集", "立即领取" + "下载游戏", "去微信观看全集", "立即领取", "立即安装", "立即抢购", "立即打开应用" ], adConfirmTexts: ["可获得奖励", "可得奖励", "看15秒", "广告", "跳转详情", "第三方应用", "进入详情页或第三方应用"], @@ -561,6 +561,11 @@ function normalizeText(value) { .replace(/详[倩请請晴睛靖情]/g, "详情") .replace(/詳[倩请請晴睛靖情]/g, "详情") .replace(/祥[倩请請晴睛靖情]/g, "详情") + // 两字目标不再任意单字容错,仅兼容明确的 OCR 别名和繁体写法。 + .replace(/賺/g, "赚") + .replace(/錢/g, "钱") + .replace(/账钱/g, "赚钱") + .replace(/下載/g, "下载") .replace(/倩/g, "情") .replace(/請/g, "请") .toLowerCase(); @@ -983,9 +988,9 @@ function isCjkText(text) { return true; } -// 与桌面版 ocr_task.py 的 text_matches 同源的容错规则: -// 1) 精确子串;2) 目标缺头/缺尾一个字的截断子串;3) 等长滑窗汉明距离 <=1 的单字误读。 -// 云手机视频流小字常出现“赚钱→账钱”“放弃福利→放弃福”这类识别偏差。 +// 基于桌面版 ocr_task.py 的 text_matches,短目标采用更严格的匹配规则: +// 1) 归一化后的精确子串;2) 至少三字目标允许缺头/缺尾;3) 至少三字目标允许单字误读。 +// 两字目标只兼容 normalizeText 中的明确别名,避免“友情”以单字差异误命中“详情”。 function textMatchesLoose(normalizedItem, normalizedTarget) { if (!normalizedTarget) { return false; @@ -1001,7 +1006,7 @@ function textMatchesLoose(normalizedItem, normalizedTarget) { return true; } } - if (normalizedTarget.length >= 2 && normalizedItem.length >= normalizedTarget.length) { + if (normalizedTarget.length >= 3 && normalizedItem.length >= normalizedTarget.length) { // 全中文目标不与含数字/字母的窗口做单字容错:“11.6.01 开发者”归一化 // 成“11601开发者”后,滑窗“1开”曾以汉明距离 1 误命中“打开”。 var targetIsCjk = isCjkText(normalizedTarget); @@ -1090,7 +1095,7 @@ function createMatchConfirmer() { // 点击后验证:目标从屏幕消失,或同词移动到新位置,都视为点击已生效; // 目标仍在原位则判定未生效并重试点击。 -function clickWithVerify(match, targets, offsetYRatio) { +function clickWithVerify(match, targets, offsetYRatio, matchFinder) { let current = match; for (let attempt = 1; attempt <= CONFIG.reliability.clickVerifyRetries; attempt += 1) { var offset = offsetYRatio !== undefined ? offsetYRatio : 0; @@ -1098,7 +1103,9 @@ function clickWithVerify(match, targets, offsetYRatio) { sleep(CONFIG.reliability.verifyDelayMs); var stillItems = recognizeScreenSafe(); // 采样失败时无法验证点击是否生效,视为已生效,交给后续阶段兜底。 - var stillMatches = stillItems === null ? [] : findMatches(stillItems, targets); + // 主任务的同名按钮必须重新绑定标题,重试时不能跳到其他任务行。 + var stillMatches = stillItems === null ? [] : + (matchFinder ? matchFinder(stillItems) : findMatches(stillItems, targets)); if (stillMatches.length === 0) { log("点击验证通过: target=" + current.target + " 已从屏幕消失 attempt=" + attempt); return true; @@ -1346,42 +1353,57 @@ function findBesideAnchor(items, target, anchor) { return best; } -function findWatchTaskAnchors(items, preferredText) { - // “兑好礼/兑豪礼”经常被 OCR 识别成不同文字,甚至被拆成另一个框。 - // 锚点只依赖更稳定的核心词,不要求整句完全识别。 - var keywords = [ - preferredText, - "去快影看视频赚积分", - "看视频赚积分", - "视频赚积分", - "赚积分", - "看视频" - ]; +function findWatchTaskAnchors(items) { + // 只接受主任务标题和明确别名;“兑好礼/兑豪礼”可独立拆框。 + // 不用“赚积分/看视频”等泛化词,避免跨到下方惊喜任务或领积分任务。 + var titlePattern = /^(?:去快影)?看视频赚积分(?:兑[好豪]礼)?$/; var anchors = []; - var matchedTexts = []; for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) { var item = items[itemIndex]; - var rawText = String(item.text || ""); - var normalizedItem = normalizeText(rawText); - let matchedKeyword = ""; - for (let keywordIndex = 0; keywordIndex < keywords.length; keywordIndex += 1) { - var normalizedKeyword = normalizeText(keywords[keywordIndex]); - if (normalizedKeyword && normalizedItem.indexOf(normalizedKeyword) >= 0) { - matchedKeyword = keywords[keywordIndex]; - break; - } - } - if (matchedKeyword) { + if (titlePattern.test(normalizeText(item.text))) { anchors.push({ item: item, target: "看视频任务标题" }); - matchedTexts.push(rawText + "~" + matchedKeyword); } } - if (matchedTexts.length > 0) { - log("看视频任务标题候选=" + matchedTexts.join(" | ")); + anchors.sort(function (left, right) { + return left.item.centerY - right.item.centerY; + }); + if (anchors.length > 0) { + log("主任务标题锚点=" + anchors.map(function (match) { + return String(match.item.text); + }).join(" | ")); } return anchors; } +function findWatchButtonBesideAnchor(items, anchor) { + var best = null; + var bestDistance = Number.MAX_VALUE; + for (let index = 0; index < items.length; index += 1) { + var button = items[index]; + if (["去观看", "去观", "观看"].indexOf(normalizeText(button.text)) < 0) { + continue; + } + var distance = Math.abs(button.centerY - anchor.centerY); + var rowHeight = Math.max(button.bounds.bottom - button.bounds.top, + anchor.bounds.bottom - anchor.bounds.top); + if (button.centerX > anchor.bounds.right && distance <= rowHeight * 1.5 && + distance < bestDistance) { + best = { item: button, target: "去观看" }; + bestDistance = distance; + } + } + return best; +} + +function findWatchTaskButtons(items) { + var anchors = findWatchTaskAnchors(items); + if (anchors.length === 0) { + return []; + } + var button = findWatchButtonBesideAnchor(items, anchors[0].item); + return button ? [button] : []; +} + function recognizeWatchButtonRegion(anchor) { if (typeof images === "undefined" || !images || typeof images.clip !== "function" || typeof images.resize !== "function") { @@ -1447,34 +1469,27 @@ function recognizeWatchButtonRegion(anchor) { } function clickWatchButtonByAnchor(items, anchorText) { - var anchorMatches = findWatchTaskAnchors(items, anchorText); + var anchorMatches = findWatchTaskAnchors(items); if (anchorMatches.length === 0) { - log("未找到看视频任务标题锚点,允许关键词=" + - [anchorText, "去快影看视频赚积分", "看视频赚积分", "视频赚积分", "赚积分", "看视频"].join(" / ")); + log("未找到主任务标题锚点,不点击其他任务的去观看: " + anchorText); return false; } - // 按钮文字较小、颜色较浅时 OCR 可能识别不到;如果识别到了, - // 仍优先使用它的实际框,避免固定坐标受窗口比例影响。 - var buttonMatch = findBesideAnchor( - items, - ["去观看", "去观", "观看"], - [anchorText, "去快影看视频赚积分", "看视频赚积分", "视频赚积分", "赚积分", "看视频"] - ); + // 全屏识别、局部识别和重试均绑定同一个主任务标题区域。 + var anchor = anchorMatches[0].item; + var buttonMatch = findWatchButtonBesideAnchor(items, anchor); if (buttonMatch) { - clickWithVerify(buttonMatch, ["去观看", "去观", "观看"], 0); - log("按标题锚点右侧 OCR 框点击“去观看”"); + clickWithVerify(buttonMatch, ["去观看", "去观", "观看"], 0, findWatchTaskButtons); + log("按主任务标题右侧 OCR 框点击“去观看”"); return true; } - // 截图中的布局是:标题在左,棕色“去观看”按钮在同一行右侧。 - // 使用标题框的 Y 中心,X 使用云手机屏幕右侧按钮中心,不使用电脑窗口坐标。 - var anchor = anchorMatches[0].item; + // 按钮漏识别时只在该标题右侧局部放大,不重新全页搜索同名按钮。 var localItems = recognizeWatchButtonRegion(anchor); - var localButton = findMatches(localItems, ["去观看", "去观", "观看"]); - if (localButton.length > 0) { - clickWithVerify(localButton[0], ["去观看", "去观", "观看"], 0); - log("去观看局部放大 OCR 命中"); + var localButton = findWatchButtonBesideAnchor(localItems, anchor); + if (localButton) { + clickWithVerify(localButton, ["去观看", "去观", "观看"], 0, findWatchTaskButtons); + log("主任务去观看局部放大 OCR 命中"); return true; } @@ -1536,23 +1551,23 @@ function scrollPageUp(scan) { function scrollForOcrTarget(target, anchor, maxScans) { var confirmer = createMatchConfirmer(); + var watchButtonFinder = target === "去观看" && anchor ? findWatchTaskButtons : null; for (let scan = 1; scan <= maxScans; scan += 1) { var items = recognizeScreenSafe(); if (items === null) { sleep(CONFIG.reliability.frameIntervalMs); continue; } - var anchored = anchor ? findBesideAnchor(items, target, anchor) : null; - // 带锚点的目标(“去观看”)只允许锚点路径点击:直接文本匹配会经单字 - // 容错误点其他任务行的“去完成”等按钮(“去观”与“去完”距离为 1)。 - // 按钮框 OCR 未命中时交给 clickWatchButtonByAnchor 的局部放大/布局兜底。 + var anchored = watchButtonFinder ? watchButtonFinder(items)[0] : + (anchor ? findBesideAnchor(items, target, anchor) : null); + // 主任务去观看只允许精确主标题路径;局部 OCR/布局兜底也不得跨任务行。 var direct = anchor ? [] : findMatches(items, target); var candidate = anchored || (direct.length > 0 ? direct[0] : null); if (candidate) { // 命中后先做相邻帧确认再点击;确认期间不滚动,避免目标移出屏幕。 var confirmed = confirmer.feed([candidate]); if (confirmed) { - clickWithVerify(confirmed, [target], 0); + clickWithVerify(confirmed, [target], 0, watchButtonFinder); log("第 " + scan + " 次扫描点击“" + target + "”(已多帧确认)"); return true; } diff --git a/autojs6/home_yibao/ad_view_3.js b/autojs6/home_yibao/ad_view_3.js index f4c3d2a..b89cee0 100644 --- a/autojs6/home_yibao/ad_view_3.js +++ b/autojs6/home_yibao/ad_view_3.js @@ -21,6 +21,14 @@ var CONFIG = { scrollMaxScans: 30, ocrReadyWaitMs: 4000, + // 投影连续三次失败后,用手机本地 Root 命令截图;不依赖 ADB。 + // mus 在部分云手机 app 域会阻塞,权限探测和每次截图都必须有硬超时。 + shellCaptureFallback: { + enabled: true, + executable: "/system/xbin/mus", // 可改为实际已授权的 su 绝对路径,不自动尝试其他提权方式。 + commandTimeoutMs: 5000 + }, + // dumpsys 前台检测已默认停用:探针实测 mus 从 AutoJS app 进程调用会永久挂死 // (timeout code=124 零输出,仅 adb shell 域可用),裸 dumpsys 又是 Permission // Denial。前台应用改用无障碍活动窗口(见 foregroundPreferAutoJs)。 @@ -48,7 +56,7 @@ var CONFIG = { "了解详情", "了解详倩", "了解详请", "了解詳情", "了解详", "查看详情", "查看详倩", "详情", "详倩", "立即体验", "立即下载", "立即下載", "下载应用", "点击下载", - "下载游戏", "去微信观看全集", "立即领取" + "下载游戏", "去微信观看全集", "立即领取", "立即安装", "立即抢购", "立即打开应用" ], adConfirmTexts: ["可获得奖励", "可得奖励", "看15秒", "广告", "跳转详情", "第三方应用", "进入详情页或第三方应用"], @@ -115,7 +123,7 @@ var CONFIG = { // actionTexts 保留全部按钮类型用于识别列表,不要通过删这里的类型来禁用任务。 actionTexts: ["去观看", "去浏览", "去下载", "领积分"], // 仅执行这里列出的列表任务。恢复全部: ["去观看", "去浏览", "去下载", "领积分"]。 - enabledTaskTexts: ["去下载", "去浏览", "领积分"], + enabledTaskTexts: ["去下载", "去浏览", "领积分", "去观看"], claimedText: "已领取", browseWaitMs: 20000, browseEntryTimeoutMs: 60000, @@ -508,6 +516,9 @@ function observeAfterAction(actionName, beforeForeground) { return afterForeground; } +// 后端状态跨主流程重试保留:切换成功后不再等待失效投影,失败后不反复启动 Root 命令。 +var captureBackendState = { mode: "projection", rootVerified: false, fatalError: null }; + function requestCapturePermission() { if (typeof requestScreenCapture === "function") { return requestScreenCapture(false); @@ -542,7 +553,131 @@ function forceScreenRefresh() { } } +function captureCommandNow() { + return Number(android.os.SystemClock.elapsedRealtime()); +} + +function createCaptureTempFile(suffix) { + return java.io.File.createTempFile("autojs_capture_", suffix, context.getCacheDir()); +} + +function startCaptureShellProcess(command, outputPath) { + var executable = String(CONFIG.shellCaptureFallback.executable || ""); + if (executable.charAt(0) !== "/" || /[\r\n\x00]/.test(executable)) { + throw new Error("本地命令截图需要有效的 Root 程序绝对路径"); + } + // 与卸载脚本相同:独立进程,输出重定向到文件,不使用 shell()/waitFor()/readLine()。 + var script = "exec " + shellQuote(executable) + " -c " + shellQuote(command) + + " > " + shellQuote(outputPath) + " 2>&1"; + var args = java.lang.reflect.Array.newInstance(java.lang.String, 3); + args[0] = "/system/bin/sh"; + args[1] = "-c"; + args[2] = script; + return new java.lang.ProcessBuilder(args).start(); +} + +function runCaptureShellCommand(command) { + var timeoutMs = Number(CONFIG.shellCaptureFallback.commandTimeoutMs); + if (!isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 30000) { + throw new Error("本地命令截图超时必须为 0~30000ms 内的有限正数"); + } + var outputFile = createCaptureTempFile(".log"); + var outputPath = String(outputFile.getAbsolutePath()); + var process = null; + try { + var started = captureCommandNow(); + process = startCaptureShellProcess(command, outputPath); + while (true) { + var code = null; + try { code = Number(process.exitValue()); } catch (running) {} + var elapsed = captureCommandNow() - started; + if (code !== null || elapsed >= timeoutMs) { + var output = ""; + try { output = String(files.read(outputPath)).slice(-2000); } + catch (readError) { output = "无法读取命令输出: " + String(readError); } + if (code !== null) { + return { code: code, output: output }; + } + var timeout = new Error("本地命令截图超时(" + timeoutMs + "ms),Root=" + + CONFIG.shellCaptureFallback.executable + ",命令=" + command + ",输出=" + output); + timeout.captureCommandTimedOut = true; + throw timeout; + } + sleep(100); + } + } finally { + if (process !== null) { + try { process.destroy(); } catch (ignoreDestroy) {} + } + try { outputFile.delete(); } catch (ignoreDelete) {} + } +} + +function captureScreenWithShell() { + if (!captureBackendState.rootVerified) { + log("本地命令截图:检查 Root 身份,程序=" + CONFIG.shellCaptureFallback.executable); + var identity = runCaptureShellCommand("id"); + if (identity.code !== 0 || !/(^|\s)uid=0\b/.test(identity.output)) { + throw new Error("本地命令截图 Root 身份校验失败,code=" + identity.code + + ",输出=" + identity.output); + } + captureBackendState.rootVerified = true; + log("本地命令截图 Root 身份验证通过: " + identity.output.trim()); + } + + // 每帧使用系统生成的独立文件,绝不把上次截图误当成本次成功结果。 + var pngFile = createCaptureTempFile(".png"); + var pngPath = String(pngFile.getAbsolutePath()); + var image = null; + var accepted = false; + try { + var result = runCaptureShellCommand("/system/bin/screencap -p " + shellQuote(pngPath)); + if (result.code !== 0) { + throw new Error("screencap 失败,code=" + result.code + ",输出=" + result.output); + } + if (!pngFile.isFile() || Number(pngFile.length()) <= 0) { + throw new Error("screencap 输出文件不存在或为空"); + } + image = images.read(pngPath); + if (!image) throw new Error("screencap PNG 无法读取或解码"); + var width = Number(image.getWidth()); + var height = Number(image.getHeight()); + if (width !== Number(device.width) || height !== Number(device.height)) { + throw new Error("screencap 图片尺寸不符: " + width + "x" + height + + ",预期=" + device.width + "x" + device.height + ",停止使用错误坐标"); + } + accepted = true; + return image; + } finally { + if (!accepted && image && image.recycle) { + try { image.recycle(); } catch (ignoreRecycle) {} + } + try { pngFile.delete(); } catch (ignoreDelete) {} + } +} + +function captureWithShellFallback() { + try { + var image = captureScreenWithShell(); + if (!image) throw new Error("本地命令截图返回空图片"); + if (captureBackendState.mode !== "shell") { + captureBackendState.mode = "shell"; + log("切换到本地命令截图,本次运行不再使用 MediaProjection"); + } + return image; + } catch (error) { + var fatal = new Error("本地命令截图兜底不可用,停止本次运行: " + + String(error && error.message || error)); + fatal.captureBackendFatal = true; + captureBackendState.fatalError = fatal; + log(fatal.message + ";已熔断,不再重试 Root 命令或失效投影"); + throw fatal; + } +} + function captureCurrentScreen() { + if (captureBackendState.fatalError) throw captureBackendState.fatalError; + if (captureBackendState.mode === "shell") return captureWithShellFallback(); var attempts = 3; for (let attempt = 1; attempt <= attempts; attempt += 1) { try { @@ -552,12 +687,17 @@ function captureCurrentScreen() { } log("captureScreen() 返回空图片(第 " + attempt + "/" + attempts + " 次)"); } catch (error) { - log("captureScreen 失败(第 " + attempt + "/" + attempts + " 次): " + errorText(error)); + log("captureScreen 失败(第 " + attempt + "/" + attempts + " 次),原因=" + + String(error && error.message || error) + ",堆栈=" + errorText(error)); } if (attempt < attempts) { forceScreenRefresh(); } } + if (CONFIG.shellCaptureFallback && CONFIG.shellCaptureFallback.enabled) { + log("投影截图连续失败,开始验证手机本地命令截图兜底"); + return captureWithShellFallback(); + } throw new Error("captureScreen 连续 " + attempts + " 次失败(画面可能已静止或锁屏)"); } @@ -599,6 +739,9 @@ function normalizeText(value) { .replace(/详[倩请請晴睛靖情]/g, "详情") .replace(/詳[倩请請晴睛靖情]/g, "详情") .replace(/祥[倩请請晴睛靖情]/g, "详情") + // 两字目标不再任意单字容错,仅兼容明确的 OCR 别名和繁体写法。 + .replace(/账钱/g, "赚钱") + .replace(/下載/g, "下载") .replace(/倩/g, "情") .replace(/請/g, "请") .toLowerCase(); @@ -897,6 +1040,7 @@ function recognizeScreenSafe() { try { return recognizeScreen(); } catch (error) { + if (error && error.captureBackendFatal) throw error; log("OCR 采样失败,跳过本帧: " + errorText(error)); return null; } @@ -1021,9 +1165,9 @@ function isCjkText(text) { return true; } -// 与桌面版 ocr_task.py 的 text_matches 同源的容错规则: -// 1) 精确子串;2) 目标缺头/缺尾一个字的截断子串;3) 等长滑窗汉明距离 <=1 的单字误读。 -// 云手机视频流小字常出现“赚钱→账钱”“放弃福利→放弃福”这类识别偏差。 +// 基于桌面版 ocr_task.py 的 text_matches,短目标采用更严格的匹配规则: +// 1) 归一化后的精确子串;2) 至少三字目标允许缺头/缺尾;3) 至少三字目标允许单字误读。 +// 两字目标只兼容 normalizeText 中的明确别名,避免“友情”以单字差异误命中“详情”。 function textMatchesLoose(normalizedItem, normalizedTarget) { if (!normalizedTarget) { return false; @@ -1039,7 +1183,7 @@ function textMatchesLoose(normalizedItem, normalizedTarget) { return true; } } - if (normalizedTarget.length >= 2 && normalizedItem.length >= normalizedTarget.length) { + if (normalizedTarget.length >= 3 && normalizedItem.length >= normalizedTarget.length) { // 全中文目标不与含数字/字母的窗口做单字容错:“11.6.01 开发者”归一化 // 成“11601开发者”后,滑窗“1开”曾以汉明距离 1 误命中“打开”。 var targetIsCjk = isCjkText(normalizedTarget); @@ -2110,7 +2254,7 @@ function waitDownloadComplete(timeoutMs) { function runExtraDownloadTask(resumeFrom) { // 主任务奖励后出现“继续做任务得额外奖励”时的附加流程:下载并打开浏览 - // 第三方应用。全程容错,失败只记录日志不抛出,不影响已完成的主任务结果。 + // 第三方应用。普通任务异常只记日志;截图后端熔断必须终止,不能继续盲操作。 // resumeFrom:缺省=从奖励页入口开始;“detail”=从残留详情页继续; // “installer”=从残留安装器继续(上次运行中断恢复)。 var extra = CONFIG.extraTask; @@ -2234,6 +2378,7 @@ function runExtraDownloadTask(resumeFrom) { log("额外任务流程完成"); return true; } catch (error) { + if (error && error.captureBackendFatal) throw error; log("额外任务异常(步骤=" + (currentStep || "未知") + ",不影响已完成的主任务): " + errorText(error)); return false; } @@ -2960,6 +3105,7 @@ try { try { log("主流程尝试 " + attempt + "/" + CONFIG.flowMaxAttempts); runHomeYibao(); + if (captureBackendState.fatalError) throw captureBackendState.fatalError; flowSuccess = true; } catch (error) { log("主流程失败(尝试 " + attempt + "/" + CONFIG.flowMaxAttempts + @@ -2967,6 +3113,10 @@ try { toast("失败阶段: " + currentPhase + (currentStep ? "(" + currentStep + ")" : "")); // 异常路径同样保存失败现场(saveFailureCapture 内部自带 try/catch)。 saveFailureCapture(currentPhase + (currentStep ? "_" + currentStep : "")); + if ((error && error.captureBackendFatal) || captureBackendState.fatalError) { + log("截图后端已熔断,终止主流程,不返回桌面重复尝试"); + break; + } if (attempt < CONFIG.flowMaxAttempts) { log("返回桌面后重试整个流程"); try {