2223 lines
93 KiB
JavaScript
2223 lines
93 KiB
JavaScript
"auto";
|
||
|
||
/*
|
||
* 蜂云手机 / 应用宝任务脚本(AutoJS 6,OCR 版)
|
||
*
|
||
* 云手机画面是 Canvas/视频流,无障碍树中没有应用和按钮节点。
|
||
* 本脚本只使用截图 OCR 和屏幕坐标,不使用 text()/desc() 无障碍选择器。
|
||
*/
|
||
|
||
auto.waitFor();
|
||
|
||
var CONFIG = {
|
||
// 优先使用 Google ML Kit;如果当前 AutoJS6 未暴露 gmlkit.ocr,再回退到旧 OCR 插件。
|
||
ocrEngine: "gmlkit",
|
||
yibaoPackage: "com.tencent.android.qqdownloader",
|
||
appLaunchWaitMs: 10000,
|
||
scanIntervalMs: 3000,
|
||
clickTimeoutMs: 20000,
|
||
scrollMaxScans: 30,
|
||
ocrReadyWaitMs: 4000,
|
||
|
||
// dumpsys 前台检测已默认停用:探针实测 mus 从 AutoJS app 进程调用会永久挂死
|
||
// (timeout code=124 零输出,仅 adb shell 域可用),裸 dumpsys 又是 Permission
|
||
// Denial。前台应用改用无障碍活动窗口(见 foregroundPreferAutoJs)。
|
||
// 保留此开关与 dumpsys 代码路径,供无障碍不可用的设备回退。
|
||
foregroundDumpEnabled: false,
|
||
// 阶段切换时不做前台检测,避免脚本刚启动/申请截图权限前卡在 shell()。
|
||
foregroundLogOnPhase: false,
|
||
// 前台应用第一来源:无障碍服务的活动窗口缓存 auto.rootInActiveWindow。
|
||
// root.getPackageName() 是纯 Java API,不走 shell、无阻塞风险;实测应用宝前台
|
||
// 返回 com.tencent.android.qqdownloader,home() 后返回 com.android.launcher3,
|
||
// 毫秒级返回。注意与 currentPackage()(内部走 shell,在本云手机永久阻塞)不是一条路径。
|
||
foregroundPreferAutoJs: true,
|
||
// AutoJS 进程直接执行 dumpsys 在部分 Android 版本会 Permission Denial;优先用 mus -c 提权执行。
|
||
foregroundUseMusRoot: true,
|
||
foregroundShellRoot: false,
|
||
// 防止 AutoJS shell/mus/dumpsys 在个别 ROM 上卡住导致脚本看起来“运行不起来”。
|
||
foregroundCommandTimeoutSec: 3,
|
||
foregroundAfterActionDelayMs: 700,
|
||
foregroundStableMs: 1000,
|
||
foregroundStableTimeoutMs: 6000,
|
||
|
||
// 广告按钮通常位于云手机画面底部;全屏 OCR 未命中时只识别该区域。
|
||
adButtonCrop: { x: 0, y: 0.70, width: 1, height: 0.30, scale: 2 },
|
||
adActionTargets: [
|
||
"了解详情", "了解详倩", "了解详请", "了解詳情", "了解详",
|
||
"查看详情", "查看详倩", "详情", "详倩",
|
||
"立即体验", "立即下载", "立即下載", "下载应用", "点击下载",
|
||
"下载游戏", "去微信观看全集", "立即领取"
|
||
],
|
||
adConfirmTexts: ["可获得奖励", "可得奖励", "看15秒", "广告", "跳转详情", "第三方应用", "进入详情页或第三方应用"],
|
||
|
||
// 相对 Android 云手机屏幕的比例,不是电脑窗口坐标。
|
||
adClose: { x: 0.158, y: 0.065 },
|
||
rewardClose: { x: 0.935, y: 0.083 },
|
||
// 广告页右上角“圆圈 X”:按截图 720x1280 标定,中心约 (663,142)。
|
||
adCircleClose: { x: 0.9222, y: 0.1109 },
|
||
adPageClose: { x: 0.933, y: 0.108 },
|
||
|
||
// 可靠性优先:用多帧确认、容错匹配和点击验证换取识别率/成功率,牺牲速度。
|
||
reliability: {
|
||
// 目标需要连续 N 帧 OCR 命中(同一目标且位置基本不变)才允许点击。
|
||
confirmFrames: 2,
|
||
// 确认帧之间的间隔,给视频流刷新和页面动画留时间。
|
||
frameIntervalMs: 800,
|
||
// 点击后目标仍在原位时,最多重试点击的次数。
|
||
clickVerifyRetries: 3,
|
||
// 点击后等待页面反应的时间,再做目标消失验证。
|
||
verifyDelayMs: 1500
|
||
},
|
||
// 整个流程失败后返回桌面重试的次数(含首次共 flowMaxAttempts 次尝试)。
|
||
flowMaxAttempts: 2,
|
||
// 失败时保存现场截图的目录,便于事后标定与诊断。
|
||
failureCaptureDir: "/sdcard/Download/",
|
||
|
||
// 额外任务(“下载并打开浏览,多得 40 积分”):主任务奖励发放后若出现
|
||
// “继续做任务得额外奖励”横幅则自动执行;未出现则当次任务完成。
|
||
extraTask: {
|
||
// 触发横幅的判定文本(按顺序容错匹配)。
|
||
entryTexts: ["继续做任务得额外奖励", "做任务得额外奖励", "得额外奖励"],
|
||
// 主任务 6/6 等额外任务入口:实测无入口的奖励页保持静止,10 秒轮询
|
||
// 只会重复读到同一帧;缩短等待,仍为入口加载保留几秒缓冲。
|
||
entryWaitMs: 6000,
|
||
// 未出现额外任务入口后,检查残留奖励/广告页的时间。
|
||
residualWaitMs: 3000,
|
||
// 应用详情页的判定文本(应用名称/权限详情/隐私协议 等,兼容“名称→各称”误读)。
|
||
detailTexts: ["应用名称", "权限详情", "隐私协议", "功能介绍", "备案信息"],
|
||
// 下载等待超时(第三方应用约 180MB,云手机下载速度不定)。
|
||
downloadTimeoutMs: 300000,
|
||
// 安装完成、跳回应用宝详情页的等待超时。
|
||
installTimeoutMs: 90000,
|
||
// 第 5 步:打开第三方应用后的浏览时长。
|
||
openWaitMs: 8000,
|
||
// 第 7 步:再次打开第三方应用后的浏览时长。
|
||
reopenWaitMs: 15000,
|
||
// 详情页左上角“く×”按钮:Rect(36,78-126,108) 中心 (81,93),屏幕 720x1280。
|
||
detailClose: { x: 0.1125, y: 0.073 },
|
||
// “立即打开应用”按钮与“立即下载”同位:Rect(297,1118-422,1153) 中心
|
||
// (360,1136),OCR 未命中时的标定兜底。
|
||
openAppButton: { x: 0.5, y: 0.8875 },
|
||
// 系统安装器“下一步”按钮:Rect(475,1177-565,1209) 中心 (520,1193)。
|
||
// 安装器底部小按钮 OCR 不稳(常只识别到标题“个软件安装”),用
|
||
// 标定坐标直接点击,配合前台包名确认安装器在场。
|
||
installNextButton: { x: 0.7222, y: 0.9320 },
|
||
// 安装器包名(系统 PackageInstaller),用于前台确认。
|
||
installerPackage: "com.android.packageinstaller"
|
||
},
|
||
|
||
// 额外任务 #2:整套流程结束后,页面可能提示“恭喜您 / 再看一条再领”。
|
||
// 出现该提示说明应用宝会自动重新进入一条广告任务;等待 reenterWaitMs
|
||
// 后从“主任务 4/6:等待并点击广告按钮”继续执行后续关闭/领奖逻辑。
|
||
extraTask2: {
|
||
checkDelayMs: 1500,
|
||
checkIntervalMs: 1000,
|
||
checkWindowMs: 7000,
|
||
titleTexts: ["恭喜您"],
|
||
// “恭喜您”容易与普通奖励页“恭喜已获得”容错误命中;真正触发 #2
|
||
// 以“再看一条/再领”按钮为准。
|
||
triggerTexts: ["再看一条再领", "再看一条", "再领"],
|
||
reenterWaitMs: 10000,
|
||
maxRounds: 1
|
||
}
|
||
};
|
||
|
||
function log(message) {
|
||
// 所有日志都带上当前阶段/步骤,便于从 logcat 中定位中断点。
|
||
// currentPhase/currentStep 在函数首次调用前已初始化;这里仍用 try 兜底,
|
||
// 避免极早期异常日志因变量尚未初始化而丢失。
|
||
var prefix = "[home_yibao]";
|
||
try {
|
||
if (currentPhase) {
|
||
prefix += "[阶段=" + currentPhase + "]";
|
||
}
|
||
if (currentStep) {
|
||
prefix += "[步骤=" + currentStep + "]";
|
||
}
|
||
} catch (ignore) {
|
||
// Ignore prefix enrichment errors.
|
||
}
|
||
console.log(prefix + " " + message);
|
||
}
|
||
|
||
let currentPhase = "初始化";
|
||
|
||
function setPhase(phase) {
|
||
currentPhase = phase;
|
||
log("阶段切换: " + phase);
|
||
if (CONFIG.foregroundLogOnPhase) {
|
||
logForegroundApp("阶段=" + phase);
|
||
}
|
||
}
|
||
|
||
// 当前执行到的步骤标记(如“额外任务 3/8 安装器点击下一步”)。分步骤流程
|
||
// 进入每一步时用 setStep 更新;失败日志与失败现场截图文件名都会带上,
|
||
// logcat 丢行/脚本中断后也能判断执行到了哪一步。
|
||
let currentStep = "";
|
||
|
||
function setStep(step) {
|
||
currentStep = step;
|
||
log("步骤标记: " + step);
|
||
}
|
||
|
||
function errorText(error) {
|
||
if (!error) {
|
||
return "未知错误";
|
||
}
|
||
return String(error.stack || error.message || error);
|
||
}
|
||
|
||
// 失败时把当前画面保存到 /sdcard/Download/,便于事后标定与诊断。
|
||
function saveFailureCapture(tag) {
|
||
try {
|
||
var image = captureCurrentScreen();
|
||
var safeTag = String(tag || currentPhase).replace(/[^0-9a-zA-Z\u4e00-\u9fff_-]/g, "_");
|
||
var path = CONFIG.failureCaptureDir + "home_yibao_" + safeTag + "_" + Date.now() + ".png";
|
||
if (typeof files !== "undefined" && files && typeof files.ensureDir === "function") {
|
||
files.ensureDir(path);
|
||
}
|
||
images.save(image, path);
|
||
log("失败现场已截图: " + path);
|
||
if (image.recycle) {
|
||
image.recycle();
|
||
}
|
||
} catch (error) {
|
||
log("失败现场截图失败: " + errorText(error));
|
||
}
|
||
}
|
||
|
||
function failWithCapture(message) {
|
||
saveFailureCapture(currentPhase + (currentStep ? "_" + currentStep : ""));
|
||
throw new Error(message);
|
||
}
|
||
|
||
function shellQuote(value) {
|
||
return "'" + String(value).replace(/'/g, "'\"'\"'") + "'";
|
||
}
|
||
|
||
function buildForegroundDumpCommand(command) {
|
||
var timeoutPrefix = CONFIG.foregroundCommandTimeoutSec > 0
|
||
? "timeout " + CONFIG.foregroundCommandTimeoutSec + " "
|
||
: "";
|
||
if (CONFIG.foregroundUseMusRoot) {
|
||
// 尽量不用管道和复杂引号。AutoJS shell() 在部分环境里执行
|
||
// mus -c sh -c 'cmd | grep ...' 会拿不到 stdout,导致 foreground=unknown。
|
||
// 这里直接让 mus 执行 dumpsys 原命令,JS 里再解析完整输出。
|
||
return timeoutPrefix + "mus -c " + command;
|
||
}
|
||
return timeoutPrefix + command;
|
||
}
|
||
|
||
function runShellCore(finalCommand) {
|
||
if (typeof shell === "function") {
|
||
var result = shell(finalCommand, CONFIG.foregroundShellRoot);
|
||
if (result === null || result === undefined) {
|
||
return { code: -1, output: "", error: "shell() 返回空" };
|
||
}
|
||
return {
|
||
code: Number(result.code !== undefined ? result.code : 0),
|
||
output: String(result.result || result.output || result.stdout || ""),
|
||
error: String(result.error || result.stderr || "")
|
||
};
|
||
}
|
||
if (typeof $shell !== "undefined" && $shell && typeof $shell.exec === "function") {
|
||
var shellResult = $shell.exec(finalCommand);
|
||
return {
|
||
code: Number(shellResult.code !== undefined ? shellResult.code : 0),
|
||
output: String(shellResult.result || shellResult.output || shellResult.stdout || ""),
|
||
error: String(shellResult.error || shellResult.stderr || "")
|
||
};
|
||
}
|
||
return { code: -1, output: "", error: "当前 AutoJS 没有 shell()/$shell.exec() 接口" };
|
||
}
|
||
|
||
let shellTimeoutCount = 0;
|
||
|
||
function execShellCommand(command) {
|
||
var finalCommand = buildForegroundDumpCommand(command);
|
||
// shell()/mus 在个别 ROM 上可能永久阻塞:`timeout` 前缀依赖 toybox 且只能杀直接子进程。
|
||
// 所以在 JS 层用工作线程 + join 超时做硬看门狗,超时直接放弃这次前台检测,
|
||
// 保证脚本不会卡死在“返回 Android 桌面”这类诊断日志上。
|
||
var holder = { done: false, result: null };
|
||
let worker = null;
|
||
try {
|
||
worker = threads.start(function () {
|
||
try {
|
||
holder.result = runShellCore(finalCommand);
|
||
} catch (error) {
|
||
holder.result = { code: -1, output: "", error: errorText(error) };
|
||
} finally {
|
||
holder.done = true;
|
||
}
|
||
});
|
||
} catch (error) {
|
||
return { code: -1, output: "", error: "threads.start 失败: " + errorText(error) };
|
||
}
|
||
var watchdogMs = (CONFIG.foregroundCommandTimeoutSec + 2) * 1000;
|
||
try {
|
||
worker.join(watchdogMs);
|
||
} catch (error) {
|
||
// join 不可用时退化为轮询等待结果标记,同样受看门狗时限约束。
|
||
var pollDeadline = Date.now() + watchdogMs;
|
||
while (!holder.done && Date.now() < pollDeadline) {
|
||
sleep(100);
|
||
}
|
||
}
|
||
if (holder.done && holder.result) {
|
||
shellTimeoutCount = 0;
|
||
return holder.result;
|
||
}
|
||
shellTimeoutCount += 1;
|
||
log("shell 命令看门狗超时(" + watchdogMs + "ms, 连续第 " + shellTimeoutCount + " 次): " + command);
|
||
if (shellTimeoutCount >= 2 && CONFIG.foregroundDumpEnabled) {
|
||
CONFIG.foregroundDumpEnabled = false;
|
||
log("shell 连续超时,本次运行内停用 dumpsys 前台检测(不影响 OCR 主流程)");
|
||
}
|
||
return { code: -1, output: "", error: "shell 命令看门狗超时" };
|
||
}
|
||
|
||
function parseComponentFromDump(text) {
|
||
var raw = String(text || "");
|
||
var patterns = [
|
||
/topResumedActivity=ActivityRecord\{[^\n]*\s([a-zA-Z0-9_.$]+)\/([^\s}\n]+)/,
|
||
/mResumedActivity:\s*ActivityRecord\{[^\n]*\s([a-zA-Z0-9_.$]+)\/([^\s}\n]+)/,
|
||
/mFocusedApp=ActivityRecord\{[^\n]*\s([a-zA-Z0-9_.$]+)\/([^\s}\n]+)/,
|
||
/mCurrentFocus=Window\{[^\n]*\s([a-zA-Z0-9_.$]+)\/([^\s}\n]+)/,
|
||
/mFocusedWindow=Window\{[^\n]*\s([a-zA-Z0-9_.$]+)\/([^\s}\n]+)/,
|
||
/ACTIVITY\s+([a-zA-Z0-9_.$]+)\/([^\s]+)/
|
||
];
|
||
for (let index = 0; index < patterns.length; index += 1) {
|
||
var match = raw.match(patterns[index]);
|
||
if (match) {
|
||
return {
|
||
packageName: match[1],
|
||
activity: match[2],
|
||
component: match[1] + "/" + match[2]
|
||
};
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function getForegroundApp(silent) {
|
||
var autoJsFirst = CONFIG.foregroundPreferAutoJs ? getForegroundAppByAutoJs() : null;
|
||
if (autoJsFirst) {
|
||
return autoJsFirst;
|
||
}
|
||
if (!CONFIG.foregroundDumpEnabled) {
|
||
return null;
|
||
}
|
||
var commands = [
|
||
// 不在 shell 层 grep,避免 AutoJS + mus + 管道/引号导致 stdout 丢失。
|
||
// dumpsys 输出可能稍大,所以外层 buildForegroundDumpCommand() 会套 timeout。
|
||
// 本云手机 dumpsys window 的 mCurrentFocus/mFocusedApp 均为 null,
|
||
// 所以补上 dumpsys activity activities 作为第二来源(mResumedActivity 正常)。
|
||
{ name: "window", command: "dumpsys window" },
|
||
{ name: "activity", command: "dumpsys activity activities" }
|
||
];
|
||
var diagnostics = [];
|
||
for (let index = 0; index < commands.length; index += 1) {
|
||
var item = commands[index];
|
||
var result = execShellCommand(item.command);
|
||
var output = result.output || "";
|
||
var parsed = parseComponentFromDump(output);
|
||
diagnostics.push(item.name + " code=" + result.code +
|
||
" out=" + output.replace(/\s+/g, " ").substring(0, 180) +
|
||
(result.error ? " err=" + result.error.substring(0, 120) : ""));
|
||
if (parsed) {
|
||
parsed.source = item.name;
|
||
if (item.name === "window") {
|
||
parsed.focusPackage = parsed.packageName;
|
||
parsed.focusActivity = parsed.activity;
|
||
} else if (item.name === "activity") {
|
||
parsed.topPackage = parsed.packageName;
|
||
parsed.topActivity = parsed.activity;
|
||
} else if (item.name === "activityTop") {
|
||
parsed.fallbackTopPackage = parsed.packageName;
|
||
parsed.fallbackTopActivity = parsed.activity;
|
||
}
|
||
return parsed;
|
||
}
|
||
}
|
||
var autoJsForeground = getForegroundAppByAutoJs();
|
||
if (autoJsForeground) {
|
||
if (!silent) {
|
||
log("dumpsys 前台应用解析失败,回退 AutoJS: " + describeForegroundApp(autoJsForeground) +
|
||
" diagnostics=" + diagnostics.join(" || "));
|
||
}
|
||
return autoJsForeground;
|
||
}
|
||
if (!silent) {
|
||
log("前台应用解析失败: " + diagnostics.join(" || "));
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function getForegroundAppByAutoJs() {
|
||
// 注意与 currentPackage()/currentActivity() 的区别:那两个 API 内部自起子进程读
|
||
// stdout,在本云手机上输出管道不关闭会永久阻塞(kill -3 线程转储已确认)。
|
||
// 这里用的是无障碍服务自身的活动窗口缓存(纯 Java API,不走 shell):
|
||
// auto.rootInActiveWindow 即当前活动窗口的节点根,其包名就是前台应用包名。
|
||
try {
|
||
if (typeof auto === "undefined" || !auto || !auto.service) {
|
||
return null;
|
||
}
|
||
var root = auto.rootInActiveWindow;
|
||
if (!root) {
|
||
return null;
|
||
}
|
||
var pkg = String(root.getPackageName() || "");
|
||
if (!pkg) {
|
||
return null;
|
||
}
|
||
var info = {
|
||
packageName: pkg,
|
||
activity: null,
|
||
component: pkg,
|
||
source: "accessibility"
|
||
};
|
||
// 活动窗口的 title(如“应用宝”“桌面”)是包名之外唯一的可读信息,
|
||
// 取不到也不影响包名判断。
|
||
try {
|
||
var windows = auto.service.getWindows();
|
||
for (let i = 0; windows && i < windows.size(); i += 1) {
|
||
var w = windows.get(i);
|
||
if (w && w.isActive && w.isActive()) {
|
||
var title = String(w.getTitle() || "");
|
||
if (title) {
|
||
info.title = title;
|
||
info.component = pkg + "/" + title;
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
} catch (titleError) {
|
||
// title 只是附加诊断信息,取不到就跳过。
|
||
}
|
||
return info;
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function describeForegroundApp(foreground) {
|
||
if (!foreground) {
|
||
return "unknown";
|
||
}
|
||
var main = foreground.component || (foreground.packageName + "/" + foreground.activity);
|
||
var details = [];
|
||
if (foreground.focusPackage) {
|
||
details.push("focus=" + foreground.focusPackage + "/" + foreground.focusActivity);
|
||
}
|
||
if (foreground.topPackage) {
|
||
details.push("top=" + foreground.topPackage + "/" + foreground.topActivity);
|
||
}
|
||
if (foreground.fallbackTopPackage && foreground.fallbackTopPackage !== foreground.topPackage) {
|
||
details.push("topFallback=" + foreground.fallbackTopPackage + "/" + foreground.fallbackTopActivity);
|
||
}
|
||
return details.length > 0 ? main + " [" + details.join(", ") + "]" : main;
|
||
}
|
||
|
||
function logForegroundApp(prefix) {
|
||
var foreground = getForegroundApp();
|
||
log((prefix || "前台应用") + " foreground=" + describeForegroundApp(foreground));
|
||
return foreground;
|
||
}
|
||
|
||
function waitForegroundStable(timeoutMs, stableMs) {
|
||
if (!CONFIG.foregroundPreferAutoJs && !CONFIG.foregroundDumpEnabled) {
|
||
return null;
|
||
}
|
||
var deadline = Date.now() + (timeoutMs || CONFIG.foregroundStableTimeoutMs);
|
||
var requiredStableMs = stableMs || CONFIG.foregroundStableMs;
|
||
let lastComponent = null;
|
||
let lastForeground = null;
|
||
let stableSince = 0;
|
||
while (Date.now() < deadline) {
|
||
var foreground = getForegroundApp(true);
|
||
var component = describeForegroundApp(foreground);
|
||
if (component === lastComponent) {
|
||
if (stableSince && Date.now() - stableSince >= requiredStableMs) {
|
||
log("前台应用已稳定: " + component);
|
||
return foreground;
|
||
}
|
||
} else {
|
||
lastComponent = component;
|
||
lastForeground = foreground;
|
||
stableSince = Date.now();
|
||
log("前台应用变化/采样: " + component);
|
||
}
|
||
sleep(250);
|
||
}
|
||
log("等待前台应用稳定超时,最后=" + lastComponent);
|
||
return lastForeground;
|
||
}
|
||
|
||
function observeAfterAction(actionName, beforeForeground) {
|
||
sleep(CONFIG.foregroundAfterActionDelayMs);
|
||
var afterForeground = waitForegroundStable(
|
||
CONFIG.foregroundStableTimeoutMs,
|
||
CONFIG.foregroundStableMs
|
||
);
|
||
var beforePackage = beforeForeground && beforeForeground.packageName;
|
||
var afterPackage = afterForeground && afterForeground.packageName;
|
||
if (beforePackage && afterPackage && beforePackage !== afterPackage) {
|
||
log(actionName + " 后发生应用切换: " +
|
||
describeForegroundApp(beforeForeground) + " -> " + describeForegroundApp(afterForeground));
|
||
} else {
|
||
log(actionName + " 后前台应用: " + describeForegroundApp(afterForeground));
|
||
}
|
||
return afterForeground;
|
||
}
|
||
|
||
function requestCapturePermission() {
|
||
if (typeof requestScreenCapture === "function") {
|
||
return requestScreenCapture(false);
|
||
}
|
||
if (typeof images !== "undefined" && images && typeof images.requestScreenCapture === "function") {
|
||
return images.requestScreenCapture(false);
|
||
}
|
||
throw new Error("当前 AutoJS 没有 requestScreenCapture() 或 images.requestScreenCapture() 接口");
|
||
}
|
||
|
||
function captureScreenOnce() {
|
||
if (typeof captureScreen === "function") {
|
||
return captureScreen();
|
||
}
|
||
if (typeof images !== "undefined" && images && typeof images.captureScreen === "function") {
|
||
return images.captureScreen();
|
||
}
|
||
throw new Error("当前 AutoJS 没有 captureScreen() 或 images.captureScreen() 接口");
|
||
}
|
||
|
||
// 画面完全静止时,云手机视频流不再产生新帧,captureScreen() 会在内部
|
||
// 超时(约 10 秒)后抛出 "Failed to capture screen image"。
|
||
// 重试之间用一次 1px 拖动强制画面刷新,让 ImageReader 拿到新帧。
|
||
function forceScreenRefresh() {
|
||
try {
|
||
var centerX = Math.round(device.width / 2);
|
||
var centerY = Math.round(device.height / 2);
|
||
swipe(centerX, centerY, centerX + 1, centerY, 100);
|
||
sleep(300);
|
||
} catch (error) {
|
||
sleep(800);
|
||
}
|
||
}
|
||
|
||
function captureCurrentScreen() {
|
||
var attempts = 3;
|
||
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
||
try {
|
||
var image = captureScreenOnce();
|
||
if (image) {
|
||
return image;
|
||
}
|
||
log("captureScreen() 返回空图片(第 " + attempt + "/" + attempts + " 次)");
|
||
} catch (error) {
|
||
log("captureScreen 失败(第 " + attempt + "/" + attempts + " 次): " + errorText(error));
|
||
}
|
||
if (attempt < attempts) {
|
||
forceScreenRefresh();
|
||
}
|
||
}
|
||
throw new Error("captureScreen 连续 " + attempts + " 次失败(画面可能已静止或锁屏)");
|
||
}
|
||
|
||
function describeOcrApis() {
|
||
var available = [];
|
||
if (typeof ocr !== "undefined") {
|
||
if (typeof ocr === "function") available.push("ocr(image)");
|
||
if (ocr && typeof ocr.recognize === "function") available.push("ocr.recognize");
|
||
if (ocr && typeof ocr.recognizeText === "function") available.push("ocr.recognizeText");
|
||
if (ocr && typeof ocr.detect === "function") available.push("ocr.detect");
|
||
}
|
||
if (typeof mlkit !== "undefined" && mlkit && typeof mlkit.ocr === "function") available.push("mlkit.ocr");
|
||
if (typeof gmlkit !== "undefined" && gmlkit && typeof gmlkit.ocr === "function") available.push("gmlkit.ocr");
|
||
if (typeof paddle !== "undefined" && paddle && typeof paddle.ocr === "function") available.push("paddle.ocr");
|
||
if (typeof $ocr !== "undefined" && $ocr) {
|
||
if (typeof $ocr.recognize === "function") available.push("$ocr.recognize");
|
||
if (typeof $ocr.detect === "function") available.push("$ocr.detect");
|
||
}
|
||
return available.length ? available.join(", ") : "无";
|
||
}
|
||
|
||
function sleepScan() {
|
||
sleep(CONFIG.scanIntervalMs);
|
||
}
|
||
|
||
function normalizeTexts(texts) {
|
||
if (typeof texts === "string") {
|
||
return [texts];
|
||
}
|
||
return texts || [];
|
||
}
|
||
|
||
function normalizeText(value) {
|
||
// OCR 结果可能带有不可见字符、中文标点或全半角符号;
|
||
// 点击匹配只关心中文、英文和数字本身。
|
||
return String(value || "")
|
||
.replace(/[^0-9a-zA-Z\u3400-\u4dbf\u4e00-\u9fff]/g, "")
|
||
// ML Kit 常把“详情”误识别为“详倩/详请/详晴/詳情”等。
|
||
.replace(/详[倩请請晴睛靖情]/g, "详情")
|
||
.replace(/詳[倩请請晴睛靖情]/g, "详情")
|
||
.replace(/祥[倩请請晴睛靖情]/g, "详情")
|
||
.replace(/倩/g, "情")
|
||
.replace(/請/g, "请")
|
||
.toLowerCase();
|
||
}
|
||
|
||
function getField(object, names) {
|
||
if (!object || typeof object !== "object") {
|
||
return null;
|
||
}
|
||
for (let index = 0; index < names.length; index += 1) {
|
||
if (object[names[index]] !== undefined && object[names[index]] !== null) {
|
||
return object[names[index]];
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function parseBounds(raw) {
|
||
if (!raw) {
|
||
return null;
|
||
}
|
||
if (Array.isArray(raw)) {
|
||
if (raw.length >= 4 && typeof raw[0] === "number") {
|
||
return { left: raw[0], top: raw[1], right: raw[2], bottom: raw[3] };
|
||
}
|
||
var points = raw.map(function (point) {
|
||
if (Array.isArray(point) && point.length >= 2) {
|
||
return { x: Number(point[0]), y: Number(point[1]) };
|
||
}
|
||
return { x: Number(point.x), y: Number(point.y) };
|
||
}).filter(function (point) {
|
||
return isFinite(point.x) && isFinite(point.y);
|
||
});
|
||
if (points.length > 0) {
|
||
return {
|
||
left: Math.min.apply(null, points.map(function (point) { return point.x; })),
|
||
top: Math.min.apply(null, points.map(function (point) { return point.y; })),
|
||
right: Math.max.apply(null, points.map(function (point) { return point.x; })),
|
||
bottom: Math.max.apply(null, points.map(function (point) { return point.y; }))
|
||
};
|
||
}
|
||
}
|
||
if (typeof raw === "object") {
|
||
var left = Number(getField(raw, ["left", "x"]));
|
||
var top = Number(getField(raw, ["top", "y"]));
|
||
var rightValue = getField(raw, ["right"]);
|
||
var bottomValue = getField(raw, ["bottom"]);
|
||
var width = Number(getField(raw, ["width", "w"]));
|
||
var height = Number(getField(raw, ["height", "h"]));
|
||
var right = rightValue !== null ? Number(rightValue) : left + width;
|
||
var bottom = bottomValue !== null ? Number(bottomValue) : top + height;
|
||
if ([left, top, right, bottom].every(isFinite)) {
|
||
return { left: left, top: top, right: right, bottom: bottom };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function toJsArray(value) {
|
||
if (!value) {
|
||
return [];
|
||
}
|
||
if (Array.isArray(value)) {
|
||
return value;
|
||
}
|
||
if (typeof util !== "undefined" && util.java && typeof util.java.toJsArray === "function") {
|
||
return util.java.toJsArray(value);
|
||
}
|
||
if (typeof value.size === "function" && typeof value.get === "function") {
|
||
var result = [];
|
||
for (let index = 0; index < value.size(); index += 1) {
|
||
result.push(value.get(index));
|
||
}
|
||
return result;
|
||
}
|
||
return value.length !== undefined ? Array.prototype.slice.call(value) : [];
|
||
}
|
||
|
||
function javaClassName(value) {
|
||
try {
|
||
if (value && typeof value.getClass === "function") {
|
||
return String(value.getClass().getName());
|
||
}
|
||
} catch (error) {
|
||
// Ignore diagnostic-only reflection errors.
|
||
}
|
||
return value === null ? "null" : typeof value;
|
||
}
|
||
|
||
function objectKeys(value) {
|
||
if (!value || typeof value !== "object") {
|
||
return [];
|
||
}
|
||
try {
|
||
return Object.keys(value);
|
||
} catch (error) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function describeRawOcrResult(raw) {
|
||
var keys = objectKeys(raw);
|
||
let preview = "";
|
||
try {
|
||
if (typeof raw === "string") {
|
||
preview = raw.substring(0, 160);
|
||
} else if (keys.length > 0) {
|
||
preview = keys.slice(0, 20).map(function (key) {
|
||
let value;
|
||
try {
|
||
value = raw[key];
|
||
} catch (error) {
|
||
value = "<读取失败>";
|
||
}
|
||
return key + "=" + String(value).substring(0, 120);
|
||
}).join(", ");
|
||
}
|
||
} catch (error) {
|
||
preview = "<预览失败: " + errorText(error) + ">";
|
||
}
|
||
log("OCR 原始结果 type=" + javaClassName(raw) +
|
||
" jsType=" + typeof raw +
|
||
" keys=[" + keys.join(",") + "] preview=" + preview);
|
||
}
|
||
|
||
function listOcrItems(raw) {
|
||
if (!raw) {
|
||
return [];
|
||
}
|
||
if (Array.isArray(raw)) {
|
||
return raw;
|
||
}
|
||
if (raw.results) {
|
||
var results = toJsArray(raw.results);
|
||
if (results.length > 0) {
|
||
return results;
|
||
}
|
||
}
|
||
// AutoJS gmlkit.ocr() 返回 GoogleMLKitOcrResult;第 2 层是文字行。
|
||
if (typeof raw.toArray === "function") {
|
||
try {
|
||
return toJsArray(raw.toArray(2));
|
||
} catch (error) {
|
||
return toJsArray(raw.toArray());
|
||
}
|
||
}
|
||
if (raw.result) {
|
||
var result = toJsArray(raw.result);
|
||
if (result.length > 0) {
|
||
return result;
|
||
}
|
||
}
|
||
if (raw.textBlocks) {
|
||
var textBlocks = toJsArray(raw.textBlocks);
|
||
if (textBlocks.length > 0) {
|
||
return textBlocks;
|
||
}
|
||
}
|
||
if (raw.text && raw.bounds) {
|
||
return [raw];
|
||
}
|
||
if (raw.data) {
|
||
var data = toJsArray(raw.data);
|
||
if (data.length > 0) {
|
||
return data;
|
||
}
|
||
}
|
||
return [];
|
||
}
|
||
|
||
function normalizeOcrItem(item) {
|
||
let textValue = null;
|
||
let boundsValue = null;
|
||
let score = 0;
|
||
if (Array.isArray(item)) {
|
||
if (typeof item[0] === "string") {
|
||
textValue = item[0];
|
||
boundsValue = item[1];
|
||
score = Number(item[2]) || 0;
|
||
} else {
|
||
boundsValue = item[0];
|
||
textValue = item[1];
|
||
score = Number(item[2]) || 0;
|
||
}
|
||
} else if (item && typeof item === "object") {
|
||
textValue = getField(item, ["text", "label", "words", "str", "value"]);
|
||
boundsValue = getField(item, ["bounds", "boundingBox", "rect", "box", "points"]);
|
||
score = Number(getField(item, ["confidence", "score", "probability"])) || 0;
|
||
}
|
||
if (textValue && typeof textValue !== "string") {
|
||
textValue = String(textValue);
|
||
}
|
||
var bounds = parseBounds(boundsValue);
|
||
if (!textValue || !bounds) {
|
||
return null;
|
||
}
|
||
return {
|
||
text: String(textValue),
|
||
normalized: normalizeText(textValue),
|
||
score: score,
|
||
bounds: bounds,
|
||
centerX: (bounds.left + bounds.right) / 2,
|
||
centerY: (bounds.top + bounds.bottom) / 2
|
||
};
|
||
}
|
||
|
||
function recognizeWithAvailableEngine(image) {
|
||
// AutoJS6 不同发行版的 OCR 插件名称略有差异,按常见接口依次兼容。
|
||
// 当前设备安装的 ML Kit 中文插件通过 AutoJS6 共享接口暴露为 ocr.detect,
|
||
// 并不会创建名为 gmlkit 的全局对象。
|
||
if (CONFIG.ocrEngine === "gmlkit") {
|
||
if (typeof gmlkit !== "undefined" && gmlkit && typeof gmlkit.ocr === "function") {
|
||
try {
|
||
log("OCR 引擎=Google ML Kit (gmlkit.ocr, zh)");
|
||
return gmlkit.ocr(image, "zh");
|
||
} catch (error) {
|
||
log("Google ML Kit 调用失败,回退兼容 OCR: " + errorText(error));
|
||
}
|
||
}
|
||
}
|
||
|
||
// recognizeText() 在部分版本中只有文本结果,不能用于坐标点击。
|
||
if (typeof ocr !== "undefined" && ocr && typeof ocr.detect === "function") {
|
||
log("OCR 引擎=Google ML Kit 中文插件(AutoJS6 共享接口 ocr.detect)");
|
||
return ocr.detect(image);
|
||
}
|
||
log("OCR 引擎=Google ML Kit 插件不可用,回退兼容 OCR;可用接口=" + describeOcrApis());
|
||
if (typeof paddle !== "undefined" && paddle && typeof paddle.ocr === "function") {
|
||
log("OCR 引擎=PaddleOCR");
|
||
return paddle.ocr(image);
|
||
}
|
||
if (typeof ocr !== "undefined" && ocr && typeof ocr.recognize === "function") {
|
||
return ocr.recognize(image);
|
||
}
|
||
if (typeof ocr !== "undefined" && ocr && typeof ocr.recognizeText === "function") {
|
||
return ocr.recognizeText(image);
|
||
}
|
||
if (typeof mlkit !== "undefined" && mlkit && typeof mlkit.ocr === "function") {
|
||
return mlkit.ocr(image);
|
||
}
|
||
if (typeof $ocr !== "undefined" && $ocr && typeof $ocr.recognize === "function") {
|
||
return $ocr.recognize(image);
|
||
}
|
||
if (typeof $ocr !== "undefined" && $ocr && typeof $ocr.detect === "function") {
|
||
return $ocr.detect(image);
|
||
}
|
||
if (typeof ocr === "function") {
|
||
return ocr(image);
|
||
}
|
||
throw new Error("未找到 AutoJS OCR 接口,请安装/启用 OCR 插件(ocr 或 mlkit)");
|
||
}
|
||
|
||
function recognizeScreen() {
|
||
var image = captureCurrentScreen();
|
||
if (!image) {
|
||
throw new Error("captureScreen() 返回空图片");
|
||
}
|
||
log("OCR 开始,接口=" + describeOcrApis());
|
||
let raw;
|
||
try {
|
||
raw = recognizeWithAvailableEngine(image);
|
||
if (raw && typeof raw.then === "function") {
|
||
throw new Error("当前 OCR 接口返回 Promise;请使用 AutoJS6 的同步 OCR 接口或对应 OCR 插件");
|
||
}
|
||
} finally {
|
||
if (image.recycle) {
|
||
image.recycle();
|
||
}
|
||
}
|
||
describeRawOcrResult(raw);
|
||
var rawItems = listOcrItems(raw);
|
||
log("OCR 原始条目 count=" + rawItems.length +
|
||
(rawItems.length > 0 ?
|
||
" firstType=" + javaClassName(rawItems[0]) +
|
||
" firstKeys=[" + objectKeys(rawItems[0]).join(",") + "]" : ""));
|
||
if (rawItems.length > 0) {
|
||
var first = rawItems[0];
|
||
try {
|
||
log("OCR 首条 text=" + String(getField(first, ["text", "label", "words", "str", "value"])) +
|
||
" bounds=" + String(getField(first, ["bounds", "boundingBox", "rect", "box", "points"])) +
|
||
" confidence=" + String(getField(first, ["confidence", "score", "probability"])));
|
||
} catch (error) {
|
||
log("OCR 首条诊断失败: " + errorText(error));
|
||
}
|
||
}
|
||
var matches = rawItems.map(normalizeOcrItem).filter(function (item) {
|
||
return item !== null;
|
||
});
|
||
log("OCR 识别到 " + matches.length + " 个文字框");
|
||
return matches;
|
||
}
|
||
|
||
// OCR 采样失败(如静止画面截图超时)时返回 null,由调用方跳过该帧,
|
||
// 避免单帧异常中断整个流程。
|
||
function recognizeScreenSafe() {
|
||
try {
|
||
return recognizeScreen();
|
||
} catch (error) {
|
||
log("OCR 采样失败,跳过本帧: " + errorText(error));
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function recognizeAdButtonRegion(targets) {
|
||
if (typeof images === "undefined" || !images ||
|
||
typeof images.clip !== "function" || typeof images.resize !== "function") {
|
||
log("OCR 局部增强跳过: images.clip/images.resize 不可用");
|
||
return [];
|
||
}
|
||
|
||
var screen = captureCurrentScreen();
|
||
if (!screen) {
|
||
log("OCR 局部增强跳过: captureScreen 返回空图片");
|
||
return [];
|
||
}
|
||
|
||
var screenWidth = screen.getWidth();
|
||
var screenHeight = screen.getHeight();
|
||
var cropConfig = CONFIG.adButtonCrop;
|
||
var cropX = Math.max(0, Math.round(screenWidth * cropConfig.x));
|
||
var cropY = Math.max(0, Math.round(screenHeight * cropConfig.y));
|
||
var cropWidth = Math.min(screenWidth - cropX,
|
||
Math.round(screenWidth * cropConfig.width));
|
||
var cropHeight = Math.min(screenHeight - cropY,
|
||
Math.round(screenHeight * cropConfig.height));
|
||
let crop = null;
|
||
let enlarged = null;
|
||
try {
|
||
crop = images.clip(screen, cropX, cropY, cropWidth, cropHeight);
|
||
enlarged = images.resize(crop, [
|
||
Math.round(cropWidth * cropConfig.scale),
|
||
Math.round(cropHeight * cropConfig.scale)
|
||
]);
|
||
log("OCR 局部增强区域=" + cropX + "," + cropY + "," + cropWidth + "x" + cropHeight +
|
||
" scale=" + cropConfig.scale + " targets=" + normalizeTexts(targets).join(" / "));
|
||
|
||
var raw = recognizeWithAvailableEngine(enlarged);
|
||
var rawItems = listOcrItems(raw);
|
||
var localItems = rawItems.map(normalizeOcrItem).filter(function (item) {
|
||
return item !== null;
|
||
});
|
||
var mappedItems = localItems.map(function (item) {
|
||
var bounds = item.bounds;
|
||
var mappedBounds = {
|
||
left: cropX + bounds.left / cropConfig.scale,
|
||
top: cropY + bounds.top / cropConfig.scale,
|
||
right: cropX + bounds.right / cropConfig.scale,
|
||
bottom: cropY + bounds.bottom / cropConfig.scale
|
||
};
|
||
return {
|
||
text: item.text,
|
||
normalized: item.normalized,
|
||
score: item.score,
|
||
bounds: mappedBounds,
|
||
centerX: (mappedBounds.left + mappedBounds.right) / 2,
|
||
centerY: (mappedBounds.top + mappedBounds.bottom) / 2
|
||
};
|
||
});
|
||
log("OCR 局部增强识别到 " + mappedItems.length + " 个文字框");
|
||
var matches = findMatches(mappedItems, targets);
|
||
if (matches.length > 0) {
|
||
log("OCR 局部增强命中 text=" + matches[0].item.text +
|
||
" target=" + matches[0].target +
|
||
" point=(" + Math.round(matches[0].item.centerX) + "," +
|
||
Math.round(matches[0].item.centerY) + ")");
|
||
} else {
|
||
log("OCR 局部增强未命中,texts=" + mappedItems.map(function (item) {
|
||
return item.text;
|
||
}).join(" | "));
|
||
}
|
||
return mappedItems;
|
||
} catch (error) {
|
||
log("OCR 局部增强失败: " + errorText(error));
|
||
return [];
|
||
} finally {
|
||
if (enlarged && enlarged.recycle) enlarged.recycle();
|
||
if (crop && crop.recycle) crop.recycle();
|
||
if (screen.recycle) screen.recycle();
|
||
}
|
||
}
|
||
|
||
function countMismatch(left, right) {
|
||
let mismatches = 0;
|
||
for (let index = 0; index < left.length; index += 1) {
|
||
if (left.charAt(index) !== right.charAt(index)) {
|
||
mismatches += 1;
|
||
if (mismatches > 1) {
|
||
return mismatches;
|
||
}
|
||
}
|
||
}
|
||
return mismatches;
|
||
}
|
||
|
||
// 只保留独立短文本的匹配(按钮/标签),过滤包含目标词的长句(页面标题、
|
||
// 说明文字)。详情页头部“应用名称…11.6.01 开发者…”这类长文本曾以滑窗容错
|
||
// 误命中“打开”,把 25% 的下载进度判成“下载完成”。
|
||
function filterShortTextMatches(matches, maxLength) {
|
||
return (matches || []).filter(function (match) {
|
||
return String(match.item.text || "").length <= maxLength;
|
||
});
|
||
}
|
||
|
||
function isCjkChar(character) {
|
||
// 与 normalizeText 保留的汉字区间一致(含扩展 A 区)。
|
||
var code = character.charCodeAt(0);
|
||
return (code >= 0x3400 && code <= 0x4dbf) || (code >= 0x4e00 && code <= 0x9fff);
|
||
}
|
||
|
||
function isCjkText(text) {
|
||
var value = String(text || "");
|
||
if (!value) {
|
||
return false;
|
||
}
|
||
for (let index = 0; index < value.length; index += 1) {
|
||
if (!isCjkChar(value.charAt(index))) {
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// 与桌面版 ocr_task.py 的 text_matches 同源的容错规则:
|
||
// 1) 精确子串;2) 目标缺头/缺尾一个字的截断子串;3) 等长滑窗汉明距离 <=1 的单字误读。
|
||
// 云手机视频流小字常出现“赚钱→账钱”“放弃福利→放弃福”这类识别偏差。
|
||
function textMatchesLoose(normalizedItem, normalizedTarget) {
|
||
if (!normalizedTarget) {
|
||
return false;
|
||
}
|
||
if (normalizedItem.indexOf(normalizedTarget) >= 0) {
|
||
return true;
|
||
}
|
||
if (normalizedTarget.length >= 3) {
|
||
if (normalizedItem.indexOf(normalizedTarget.substring(0, normalizedTarget.length - 1)) >= 0) {
|
||
return true;
|
||
}
|
||
if (normalizedItem.indexOf(normalizedTarget.substring(1)) >= 0) {
|
||
return true;
|
||
}
|
||
}
|
||
if (normalizedTarget.length >= 2 && normalizedItem.length >= normalizedTarget.length) {
|
||
// 全中文目标不与含数字/字母的窗口做单字容错:“11.6.01 开发者”归一化
|
||
// 成“11601开发者”后,滑窗“1开”曾以汉明距离 1 误命中“打开”。
|
||
var targetIsCjk = isCjkText(normalizedTarget);
|
||
for (let start = 0; start + normalizedTarget.length <= normalizedItem.length; start += 1) {
|
||
var windowText = normalizedItem.substring(start, start + normalizedTarget.length);
|
||
if (targetIsCjk && !isCjkText(windowText)) {
|
||
continue;
|
||
}
|
||
if (countMismatch(windowText, normalizedTarget) <= 1) {
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function findMatches(items, targets) {
|
||
var wanted = normalizeTexts(targets);
|
||
var matches = [];
|
||
for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) {
|
||
for (let targetIndex = 0; targetIndex < wanted.length; targetIndex += 1) {
|
||
var rawTarget = String(wanted[targetIndex] || "");
|
||
var target = normalizeText(rawTarget);
|
||
var rawItem = String(items[itemIndex].text || "");
|
||
var normalizedItem = items[itemIndex].normalized || normalizeText(rawItem);
|
||
// 先做原始文本包含匹配,再做归一化容错匹配,兼容 Java String、
|
||
// OCR 单字误读(账钱/详倩)和按钮边缘截断(放弃福)。
|
||
let matched = false;
|
||
if (rawTarget && rawItem.indexOf(rawTarget) >= 0) {
|
||
matched = true;
|
||
} else if (target && textMatchesLoose(normalizedItem, target)) {
|
||
log("OCR 容错命中 target=" + rawTarget + " text=" + rawItem);
|
||
matched = true;
|
||
}
|
||
if (matched) {
|
||
matches.push({ item: items[itemIndex], target: wanted[targetIndex] });
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return matches;
|
||
}
|
||
|
||
// OCR 文本可能是“点击后,看15秒可获得奖励”这类完整句子,
|
||
// 所以确认提示只判断是否包含目标词,不做全文精确相等判断。
|
||
function findContainsMatches(items, targets) {
|
||
return findMatches(items, targets);
|
||
}
|
||
|
||
// 多帧确认器:同一目标(target 相同、坐标抖动在桶容差内)连续 confirmFrames 帧命中
|
||
// 才算稳定目标,过滤视频流偶发误检和加载动画期间的模糊帧。
|
||
function createMatchConfirmer() {
|
||
return {
|
||
streak: 0,
|
||
key: null,
|
||
last: null,
|
||
feed: function (matches) {
|
||
if (!matches || matches.length === 0) {
|
||
this.streak = 0;
|
||
this.key = null;
|
||
this.last = null;
|
||
return null;
|
||
}
|
||
var match = matches[0];
|
||
// 坐标按 24px 桶化,避免整行轻微抖动打断连击计数。
|
||
var key = String(match.target) + "@" +
|
||
Math.round(match.item.centerX / 24) + "," +
|
||
Math.round(match.item.centerY / 24);
|
||
if (key === this.key) {
|
||
this.streak += 1;
|
||
} else {
|
||
this.key = key;
|
||
this.streak = 1;
|
||
}
|
||
this.last = match;
|
||
if (this.streak >= CONFIG.reliability.confirmFrames) {
|
||
log("多帧确认通过 target=" + match.target + " streak=" + this.streak +
|
||
" point=(" + Math.round(match.item.centerX) + "," +
|
||
Math.round(match.item.centerY) + ")");
|
||
return match;
|
||
}
|
||
return null;
|
||
}
|
||
};
|
||
}
|
||
|
||
// 点击后验证:目标从屏幕消失,或同词移动到新位置,都视为点击已生效;
|
||
// 目标仍在原位则判定未生效并重试点击。
|
||
function clickWithVerify(match, targets, offsetYRatio) {
|
||
let current = match;
|
||
for (let attempt = 1; attempt <= CONFIG.reliability.clickVerifyRetries; attempt += 1) {
|
||
var offset = offsetYRatio !== undefined ? offsetYRatio : 0;
|
||
clickOcrMatch(current, offset);
|
||
sleep(CONFIG.reliability.verifyDelayMs);
|
||
var stillItems = recognizeScreenSafe();
|
||
// 采样失败时无法验证点击是否生效,视为已生效,交给后续阶段兜底。
|
||
var stillMatches = stillItems === null ? [] : findMatches(stillItems, targets);
|
||
if (stillMatches.length === 0) {
|
||
log("点击验证通过: target=" + current.target + " 已从屏幕消失 attempt=" + attempt);
|
||
return true;
|
||
}
|
||
var movedAway = stillMatches.every(function (candidate) {
|
||
return candidate.target !== current.target ||
|
||
Math.abs(candidate.item.centerX - current.item.centerX) >= 24 ||
|
||
Math.abs(candidate.item.centerY - current.item.centerY) >= 24;
|
||
});
|
||
if (movedAway) {
|
||
log("点击验证通过: target=" + current.target + " 位置已变化 attempt=" + attempt +
|
||
" newText=" + stillMatches[0].item.text);
|
||
return true;
|
||
}
|
||
log("点击验证失败: target=" + current.target + " 仍在原位,重试 attempt=" + attempt +
|
||
"/" + CONFIG.reliability.clickVerifyRetries);
|
||
current = stillMatches[0];
|
||
}
|
||
log("点击重试 " + CONFIG.reliability.clickVerifyRetries + " 次后目标仍在,交给后续阶段兜底");
|
||
return true;
|
||
}
|
||
|
||
function clickOcrMatch(match, offsetYRatio) {
|
||
var offset = offsetYRatio || 0;
|
||
let x = Math.round(match.item.centerX);
|
||
let y = Math.round(match.item.centerY + device.height * offset);
|
||
x = Math.max(1, Math.min(device.width - 1, x));
|
||
y = Math.max(1, Math.min(device.height - 1, y));
|
||
log("OCR 点击 text=" + match.item.text + " target=" + match.target +
|
||
" score=" + match.item.score + " box=" + JSON.stringify(match.item.bounds) +
|
||
" point=(" + x + "," + y + ")");
|
||
var beforeForeground = logForegroundApp("点击前");
|
||
click(x, y);
|
||
observeAfterAction("点击 " + match.target, beforeForeground);
|
||
return true;
|
||
}
|
||
|
||
function clickOcr(targets, timeoutMs, offsetYRatio, preferShortText) {
|
||
var deadline = Date.now() + timeoutMs;
|
||
var confirmer = createMatchConfirmer();
|
||
while (Date.now() < deadline) {
|
||
var items = recognizeScreenSafe();
|
||
if (items === null) {
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
continue;
|
||
}
|
||
var matches = findMatches(items, targets);
|
||
// 按钮类目标(打开/下一步/立即打开应用)优先点独立短文本:同屏常有
|
||
// 含目标词的长句(标题、说明文字),按文本长度升序后再喂给确认器。
|
||
if (preferShortText && matches.length > 1) {
|
||
matches.sort(function (left, right) {
|
||
return String(left.item.text || "").length - String(right.item.text || "").length;
|
||
});
|
||
}
|
||
var confirmed = confirmer.feed(matches);
|
||
if (confirmed) {
|
||
return clickWithVerify(confirmed, targets, offsetYRatio);
|
||
}
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
log("OCR 未找到: " + normalizeTexts(targets).join(" / "));
|
||
return false;
|
||
}
|
||
|
||
function waitOcr(targets, timeoutMs) {
|
||
var deadline = Date.now() + timeoutMs;
|
||
var confirmer = createMatchConfirmer();
|
||
while (Date.now() < deadline) {
|
||
var items = recognizeScreenSafe();
|
||
if (items === null) {
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
continue;
|
||
}
|
||
var confirmed = confirmer.feed(findMatches(items, targets));
|
||
if (confirmed) {
|
||
return confirmed;
|
||
}
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function clickRatio(point) {
|
||
var x = Math.round(device.width * point.x);
|
||
var y = Math.round(device.height * point.y);
|
||
log("比例坐标点击: (" + x + "," + y + ") ratio=(" + point.x + "," + point.y + ")");
|
||
var beforeForeground = logForegroundApp("比例点击前");
|
||
click(x, y);
|
||
observeAfterAction("比例点击", beforeForeground);
|
||
}
|
||
|
||
function launchYibao() {
|
||
log("返回 Android 桌面");
|
||
var beforeHome = logForegroundApp("home 前");
|
||
log("home() 开始执行");
|
||
home();
|
||
log("home() 已返回");
|
||
observeAfterAction("home", beforeHome);
|
||
sleep(1200);
|
||
var beforeLaunch = logForegroundApp("按包名启动前");
|
||
log("按包名启动应用宝: " + CONFIG.yibaoPackage);
|
||
var launched = app.launchPackage(CONFIG.yibaoPackage);
|
||
if (launched === false) {
|
||
throw new Error("按包名启动应用宝失败: " + CONFIG.yibaoPackage);
|
||
}
|
||
observeAfterAction("启动 " + CONFIG.yibaoPackage, beforeLaunch);
|
||
sleep(CONFIG.appLaunchWaitMs);
|
||
var foreground = waitForegroundStable(CONFIG.foregroundStableTimeoutMs, CONFIG.foregroundStableMs);
|
||
if (foreground && foreground.packageName !== CONFIG.yibaoPackage) {
|
||
throw new Error("应用宝未进入前台,当前=" + describeForegroundApp(foreground));
|
||
}
|
||
log("应用宝启动流程完成,当前=" + describeForegroundApp(foreground));
|
||
}
|
||
|
||
function isYibaoTaskCenter(items) {
|
||
// 不只依赖单个 OCR 框:同一段标题有时会被 OCR 拆成多个框,或者
|
||
// Java OcrResult 的 text 属性在 JS 中表现为 Java String。拼接整页文本后
|
||
// 再归一化,可以同时兼容拆框、全半角符号和“兼钱任务中心”等误字。
|
||
var markers = [
|
||
["任务中心"],
|
||
["积分兑好礼"],
|
||
["每日福利签到"],
|
||
["看视频赚积分", "看视频赚积分兑豪礼"],
|
||
["限时应用专区"],
|
||
["我的积分"],
|
||
["可兑现金", "可兌现金"]
|
||
];
|
||
var corpus = normalizeText(items.map(function (item) {
|
||
return String(item.text || "");
|
||
}).join(""));
|
||
var seen = [];
|
||
for (let index = 0; index < markers.length; index += 1) {
|
||
var aliases = markers[index];
|
||
var matched = aliases.some(function (marker) {
|
||
return corpus.indexOf(normalizeText(marker)) >= 0;
|
||
});
|
||
if (matched) {
|
||
seen.push(aliases[0]);
|
||
}
|
||
}
|
||
log("任务中心页面检测 markers=" + seen.join(" / ") +
|
||
" count=" + seen.length + " corpus=" + corpus.substring(0, 120));
|
||
return seen.length >= 2;
|
||
}
|
||
|
||
function enterYibaoTaskCenter() {
|
||
var deadline = Date.now() + CONFIG.clickTimeoutMs;
|
||
var entryConfirmer = createMatchConfirmer();
|
||
let clickedEntry = false;
|
||
let scan = 0;
|
||
|
||
while (Date.now() < deadline) {
|
||
scan += 1;
|
||
var items = recognizeScreenSafe();
|
||
if (items === null) {
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
continue;
|
||
}
|
||
|
||
// 如果脚本重启时已经停在广告页,不要继续按“点击赚钱”阶段失败。
|
||
// 直接把状态视为已越过任务中心,交给后续“等待广告按钮”阶段点击详情/下载。
|
||
var adMatches = findMatches(items, CONFIG.adActionTargets);
|
||
var adConfirmMatches = findContainsMatches(items, CONFIG.adConfirmTexts);
|
||
if (adMatches.length > 0 && adConfirmMatches.length > 0) {
|
||
log("检测到已在广告页,跳过赚钱入口和去观看查找: action=" + adMatches[0].item.text +
|
||
" confirm=" + adConfirmMatches[0].item.text + " scan=" + scan);
|
||
return "ad_page";
|
||
}
|
||
|
||
// 上次运行中断残留的奖励页:主任务奖励已发放(出现“继续做任务得额外
|
||
// 奖励”横幅),从桌面重新点开应用宝会原样恢复该页。直接跳到额外任务
|
||
// 分支把未完成的“下载并打开浏览”做完,而不是按“未进入任务中心”失败。
|
||
if (adConfirmMatches.length > 0 &&
|
||
findMatches(items, CONFIG.extraTask.entryTexts).length > 0) {
|
||
log("检测到残留的额外任务奖励页,跳过主流程直接执行额外任务 scan=" + scan);
|
||
return "reward_page";
|
||
}
|
||
|
||
// 上次运行中断残留的应用详情页(应用名称/权限详情/隐私协议等同时出现
|
||
// 多项):额外任务已进行到下载/安装阶段,从详情页继续。要求至少命中
|
||
// 两个详情页标签,避免单标签误判。
|
||
var detailHits = 0;
|
||
for (let detailIndex = 0; detailIndex < CONFIG.extraTask.detailTexts.length; detailIndex += 1) {
|
||
if (findMatches(items, [CONFIG.extraTask.detailTexts[detailIndex]]).length > 0) {
|
||
detailHits += 1;
|
||
}
|
||
}
|
||
if (detailHits >= 2) {
|
||
log("检测到残留的应用详情页(额外任务中断恢复),从详情页继续 scan=" + scan);
|
||
return "detail_page";
|
||
}
|
||
|
||
// 上次运行中断残留的安装器(同屏“下一步”+“取消”):从安装步骤继续。
|
||
if (filterShortTextMatches(findMatches(items, ["下一步"]), 6).length > 0 &&
|
||
filterShortTextMatches(findMatches(items, ["取消"]), 6).length > 0) {
|
||
log("检测到残留的安装器(额外任务中断恢复),从安装步骤继续 scan=" + scan);
|
||
return "installer_page";
|
||
}
|
||
|
||
// 页面加载可能发生在等待过程中的任意一帧,不能只在进入函数时检查一次。
|
||
if (isYibaoTaskCenter(items)) {
|
||
log("已确认位于赚钱任务中心,scan=" + scan +
|
||
(clickedEntry ? "(点击入口后加载完成)" : "(无需再次点击赚钱)"));
|
||
return true;
|
||
}
|
||
|
||
if (!clickedEntry) {
|
||
// 不把 OCR 误字“兼钱”作为可点击候选,避免误点“兼钱任务中心”标题。
|
||
var confirmedEntry = entryConfirmer.feed(findMatches(items, "赚钱"));
|
||
if (confirmedEntry) {
|
||
clickOcrMatch(confirmedEntry, 0);
|
||
clickedEntry = true;
|
||
log("已点击赚钱入口(多帧确认),继续等待任务中心加载");
|
||
}
|
||
} else {
|
||
entryConfirmer.feed([]);
|
||
}
|
||
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
|
||
log("进入赚钱任务中心超时 clickedEntry=" + clickedEntry + " scans=" + scan);
|
||
return false;
|
||
}
|
||
|
||
function findBesideAnchor(items, target, anchor) {
|
||
var targets = findMatches(items, target);
|
||
var anchors = findMatches(items, anchor);
|
||
let best = null;
|
||
let bestDistance = Number.MAX_VALUE;
|
||
for (let anchorIndex = 0; anchorIndex < anchors.length; anchorIndex += 1) {
|
||
for (let targetIndex = 0; targetIndex < targets.length; targetIndex += 1) {
|
||
var targetItem = targets[targetIndex].item;
|
||
var anchorItem = anchors[anchorIndex].item;
|
||
var verticalDistance = Math.abs(targetItem.centerY - anchorItem.centerY);
|
||
var targetHeight = targetItem.bounds.bottom - targetItem.bounds.top;
|
||
var anchorHeight = anchorItem.bounds.bottom - anchorItem.bounds.top;
|
||
var sameRow = verticalDistance <= Math.max(targetHeight, anchorHeight) * 1.5;
|
||
if (sameRow && targetItem.centerX > anchorItem.centerX && verticalDistance < bestDistance) {
|
||
best = targets[targetIndex];
|
||
bestDistance = verticalDistance;
|
||
}
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
|
||
function findWatchTaskAnchors(items, preferredText) {
|
||
// “兑好礼/兑豪礼”经常被 OCR 识别成不同文字,甚至被拆成另一个框。
|
||
// 锚点只依赖更稳定的核心词,不要求整句完全识别。
|
||
var keywords = [
|
||
preferredText,
|
||
"去快影看视频赚积分",
|
||
"看视频赚积分",
|
||
"视频赚积分",
|
||
"赚积分",
|
||
"看视频"
|
||
];
|
||
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) {
|
||
anchors.push({ item: item, target: "看视频任务标题" });
|
||
matchedTexts.push(rawText + "~" + matchedKeyword);
|
||
}
|
||
}
|
||
if (matchedTexts.length > 0) {
|
||
log("看视频任务标题候选=" + matchedTexts.join(" | "));
|
||
}
|
||
return anchors;
|
||
}
|
||
|
||
function recognizeWatchButtonRegion(anchor) {
|
||
if (typeof images === "undefined" || !images ||
|
||
typeof images.clip !== "function" || typeof images.resize !== "function") {
|
||
log("去观看局部 OCR 跳过: images.clip/images.resize 不可用");
|
||
return [];
|
||
}
|
||
|
||
var screen = captureCurrentScreen();
|
||
if (!screen) {
|
||
log("去观看局部 OCR 跳过: captureScreen 返回空图片");
|
||
return [];
|
||
}
|
||
|
||
var width = screen.getWidth();
|
||
var height = screen.getHeight();
|
||
var scale = 3;
|
||
// 按标题框定位右侧按钮,只截右侧 32% 区域,避免其他任务文字干扰。
|
||
var cropX = Math.max(0, Math.round(width * 0.68));
|
||
var marginY = Math.max(40, Math.round((anchor.bounds.bottom - anchor.bounds.top) * 2.5));
|
||
var cropY = Math.max(0, Math.round(anchor.bounds.top - marginY));
|
||
var cropBottom = Math.min(height, Math.round(anchor.bounds.bottom + marginY));
|
||
var cropWidth = width - cropX;
|
||
var cropHeight = Math.max(1, cropBottom - cropY);
|
||
let crop = null;
|
||
let enlarged = null;
|
||
try {
|
||
crop = images.clip(screen, cropX, cropY, cropWidth, cropHeight);
|
||
enlarged = images.resize(crop, [cropWidth * scale, cropHeight * scale]);
|
||
log("去观看局部 OCR 区域=" + cropX + "," + cropY + "," +
|
||
cropWidth + "x" + cropHeight + " scale=" + scale);
|
||
var raw = recognizeWithAvailableEngine(enlarged);
|
||
var localItems = listOcrItems(raw).map(normalizeOcrItem).filter(function (item) {
|
||
return item !== null;
|
||
});
|
||
var mappedItems = localItems.map(function (item) {
|
||
var mappedBounds = {
|
||
left: cropX + item.bounds.left / scale,
|
||
top: cropY + item.bounds.top / scale,
|
||
right: cropX + item.bounds.right / scale,
|
||
bottom: cropY + item.bounds.bottom / scale
|
||
};
|
||
return {
|
||
text: item.text,
|
||
normalized: item.normalized,
|
||
score: item.score,
|
||
bounds: mappedBounds,
|
||
centerX: (mappedBounds.left + mappedBounds.right) / 2,
|
||
centerY: (mappedBounds.top + mappedBounds.bottom) / 2
|
||
};
|
||
});
|
||
log("去观看局部 OCR 文本=" + mappedItems.map(function (item) {
|
||
return item.text;
|
||
}).join(" | "));
|
||
return mappedItems;
|
||
} catch (error) {
|
||
log("去观看局部 OCR 失败: " + errorText(error));
|
||
return [];
|
||
} finally {
|
||
if (enlarged && enlarged.recycle) enlarged.recycle();
|
||
if (crop && crop.recycle) crop.recycle();
|
||
if (screen.recycle) screen.recycle();
|
||
}
|
||
}
|
||
|
||
function clickWatchButtonByAnchor(items, anchorText) {
|
||
var anchorMatches = findWatchTaskAnchors(items, anchorText);
|
||
if (anchorMatches.length === 0) {
|
||
log("未找到看视频任务标题锚点,允许关键词=" +
|
||
[anchorText, "去快影看视频赚积分", "看视频赚积分", "视频赚积分", "赚积分", "看视频"].join(" / "));
|
||
return false;
|
||
}
|
||
|
||
// 按钮文字较小、颜色较浅时 OCR 可能识别不到;如果识别到了,
|
||
// 仍优先使用它的实际框,避免固定坐标受窗口比例影响。
|
||
var buttonMatch = findBesideAnchor(
|
||
items,
|
||
["去观看", "去观", "观看"],
|
||
[anchorText, "去快影看视频赚积分", "看视频赚积分", "视频赚积分", "赚积分", "看视频"]
|
||
);
|
||
if (buttonMatch) {
|
||
clickWithVerify(buttonMatch, ["去观看", "去观", "观看"], 0);
|
||
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 命中");
|
||
return true;
|
||
}
|
||
|
||
var anchorHeight = Math.max(1, anchor.bounds.bottom - anchor.bounds.top);
|
||
var x = Math.round(device.width * 0.86);
|
||
var y = Math.round(anchor.centerY + anchorHeight * 0.18);
|
||
var safeX = Math.max(1, Math.min(device.width - 1, x));
|
||
var safeY = Math.max(1, Math.min(device.height - 1, y));
|
||
log("标题锚点 OCR 已命中但按钮文字未命中,采用右侧布局点击" +
|
||
" anchorText='" + anchor.text + "'" +
|
||
" anchorBox=" + JSON.stringify(anchor.bounds) +
|
||
" point=(" + safeX + "," + safeY + ")" +
|
||
" screen=" + device.width + "x" + device.height);
|
||
var beforeForeground = logForegroundApp("布局点击前");
|
||
click(safeX, safeY);
|
||
observeAfterAction("布局点击去观看", beforeForeground);
|
||
return true;
|
||
}
|
||
|
||
function scrollPageUp(scan) {
|
||
var startX = Math.round(device.width * 0.5);
|
||
var startY = Math.round(device.height * 0.82);
|
||
var endX = Math.round(device.width * 0.5);
|
||
var endY = Math.round(device.height * 0.26);
|
||
var durationMs = 700;
|
||
let result = false;
|
||
|
||
log("滚动开始 scan=" + scan + " from=(" + startX + "," + startY +
|
||
") to=(" + endX + "," + endY + ") duration=" + durationMs);
|
||
var beforeForeground = logForegroundApp("滚动前");
|
||
try {
|
||
if (typeof gesture === "function") {
|
||
result = gesture(
|
||
durationMs,
|
||
[startX, startY],
|
||
[startX - 4, Math.round((startY + endY) / 2)],
|
||
[endX, endY]
|
||
);
|
||
log("滚动 gesture result=" + result);
|
||
if (result !== false) {
|
||
observeAfterAction("滚动 gesture", beforeForeground);
|
||
return true;
|
||
}
|
||
}
|
||
} catch (error) {
|
||
log("滚动 gesture 失败: " + errorText(error));
|
||
}
|
||
|
||
try {
|
||
result = swipe(startX, startY, endX, endY, durationMs);
|
||
log("滚动 swipe 回退 result=" + result);
|
||
observeAfterAction("滚动 swipe", beforeForeground);
|
||
return result !== false;
|
||
} catch (error) {
|
||
log("滚动 swipe 回退失败: " + errorText(error));
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function scrollForOcrTarget(target, anchor, maxScans) {
|
||
var confirmer = createMatchConfirmer();
|
||
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 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);
|
||
log("第 " + scan + " 次扫描点击“" + target + "”(已多帧确认)");
|
||
return true;
|
||
}
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
continue;
|
||
}
|
||
confirmer.feed([]);
|
||
if (target === "去观看" && anchor && clickWatchButtonByAnchor(items, anchor)) {
|
||
log("第 " + scan + " 次扫描通过标题锚点点击“去观看”");
|
||
return true;
|
||
}
|
||
if (!scrollPageUp(scan)) {
|
||
log("第 " + scan + " 次滚动未被系统接受,继续下一次 OCR 检查");
|
||
}
|
||
sleepScan();
|
||
}
|
||
log("OCR 扫描 " + maxScans + " 次仍未找到: " + target);
|
||
return false;
|
||
}
|
||
|
||
function waitAndClickOcr(targets, confirmTexts, waitMs) {
|
||
var deadline = Date.now() + waitMs;
|
||
var confirmer = createMatchConfirmer();
|
||
while (Date.now() < deadline) {
|
||
var items = recognizeScreenSafe();
|
||
if (items === null) {
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
continue;
|
||
}
|
||
var confirmMatches = findContainsMatches(items, confirmTexts);
|
||
if (confirmMatches.length > 0) {
|
||
log("OCR 已包含确认文本: target=" + normalizeTexts(confirmTexts).join(" / ") +
|
||
" actual=" + confirmMatches[0].item.text);
|
||
}
|
||
var matches = findMatches(items, targets);
|
||
// 与原 JSON await_click 语义一致:目标先出现即可点击,confirm 只作为状态日志。
|
||
if (matches.length > 0) {
|
||
var confirmed = confirmer.feed(matches);
|
||
if (confirmed) {
|
||
return clickWithVerify(confirmed, targets, 0);
|
||
}
|
||
} else {
|
||
confirmer.feed([]);
|
||
var buttonCandidates = items.filter(function (item) {
|
||
return item.normalized.indexOf("下载") >= 0 ||
|
||
item.normalized.indexOf("详情") >= 0 ||
|
||
item.normalized.indexOf("体验") >= 0;
|
||
}).map(function (item) {
|
||
return item.text + "=>" + item.normalized;
|
||
});
|
||
if (buttonCandidates.length > 0) {
|
||
log("OCR 按钮候选未命中 target=" + normalizeTexts(targets).join(" / ") +
|
||
" candidates=" + buttonCandidates.join(" | "));
|
||
}
|
||
|
||
// 只有确认已进入奖励广告,或全屏 OCR 已发现按钮候选时,
|
||
// 才启动局部放大 OCR,避免每轮都额外消耗一次截图和识别。
|
||
if (confirmMatches.length > 0 || buttonCandidates.length > 0) {
|
||
var localItems = [];
|
||
try {
|
||
localItems = recognizeAdButtonRegion(targets);
|
||
} catch (localError) {
|
||
log("OCR 局部增强失败,跳过: " + errorText(localError));
|
||
}
|
||
var localMatches = findMatches(localItems, targets);
|
||
if (localMatches.length > 0) {
|
||
return clickWithVerify(localMatches[0], targets, 0);
|
||
}
|
||
}
|
||
}
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function backToYibao(timeoutMs) {
|
||
// 用无障碍前台检测确认回到应用宝:返回键优先(第三方应用由应用宝拉起,
|
||
// back() 会退回应用宝),连续两次无效时按包名拉起兜底。
|
||
var deadline = Date.now() + (timeoutMs || 15000);
|
||
var backTried = 0;
|
||
while (Date.now() < deadline) {
|
||
var foreground = getForegroundApp();
|
||
if (foreground && foreground.packageName === CONFIG.yibaoPackage) {
|
||
log("已回到应用宝: " + describeForegroundApp(foreground));
|
||
return true;
|
||
}
|
||
if (backTried < 2) {
|
||
backTried += 1;
|
||
log("当前前台=" + describeForegroundApp(foreground) + ",按返回键回应用宝");
|
||
back();
|
||
} else {
|
||
log("返回键未回到应用宝,按包名拉起");
|
||
try {
|
||
app.launchPackage(CONFIG.yibaoPackage);
|
||
} catch (error) {
|
||
log("按包名拉起应用宝失败: " + errorText(error));
|
||
}
|
||
backTried = 0;
|
||
}
|
||
sleep(1500);
|
||
}
|
||
log("回到应用宝超时,最后前台=" + describeForegroundApp(getForegroundApp()));
|
||
return false;
|
||
}
|
||
|
||
function isThirdPartyForeground(foreground) {
|
||
// 应用宝任务流程中,非应用宝/安装器/脚本/桌面的前台应用都视为被广告或
|
||
// “立即打开应用”拉起的第三方应用。主任务广告按钮有时点“立即下载”会
|
||
// 直接跳出应用宝,这时后续处理应复用额外任务第 7 步:浏览后返回应用宝。
|
||
return foreground &&
|
||
foreground.packageName &&
|
||
foreground.packageName !== CONFIG.yibaoPackage &&
|
||
foreground.packageName !== CONFIG.extraTask.installerPackage &&
|
||
foreground.packageName !== "org.autojs.autojs6" &&
|
||
foreground.packageName !== "com.android.launcher3";
|
||
}
|
||
|
||
function waitThirdPartyForeground(timeoutMs) {
|
||
var deadline = Date.now() + (timeoutMs || 5000);
|
||
while (Date.now() < deadline) {
|
||
var foreground = getForegroundApp();
|
||
if (isThirdPartyForeground(foreground)) {
|
||
log("检测到第三方应用前台: " + describeForegroundApp(foreground));
|
||
return foreground;
|
||
}
|
||
sleep(500);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function clickByAccessibilityDesc(descText, reason) {
|
||
// 主流程其他按钮仍坚持 OCR/坐标;这里只给广告关闭按钮做无障碍兜底,
|
||
// 因为右上角 X 无文字,且已确认它的 desc="点击退出关闭视频"。
|
||
if (typeof desc !== "function") {
|
||
log("无障碍 desc() 不可用,跳过 desc 点击: " + descText);
|
||
return false;
|
||
}
|
||
try {
|
||
var node = desc(descText).findOne(1200);
|
||
if (!node) {
|
||
log("无障碍未找到 desc=" + descText + " reason=" + reason);
|
||
return false;
|
||
}
|
||
var bounds = node.bounds();
|
||
var x = bounds.centerX();
|
||
var y = bounds.centerY();
|
||
log("无障碍点击 desc=" + descText + " point=(" + x + "," + y + ") reason=" + reason);
|
||
var clicked = false;
|
||
try {
|
||
if (typeof node.click === "function") {
|
||
clicked = node.click();
|
||
log("无障碍 node.click result=" + clicked);
|
||
}
|
||
} catch (nodeClickError) {
|
||
log("无障碍 node.click 异常,改用坐标点击: " + errorText(nodeClickError));
|
||
}
|
||
if (!clicked) {
|
||
click(x, y);
|
||
}
|
||
sleep(1200);
|
||
return true;
|
||
} catch (error) {
|
||
log("无障碍 desc 点击失败 desc=" + descText + " error=" + errorText(error));
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function closeYibaoTaskPage(reason) {
|
||
// 这里不是 OCR 识别 X:右上角 X 通常没有稳定文字。优先使用你通过
|
||
// 无障碍确认到的 desc="点击退出关闭视频",失败后兜底点击坐标
|
||
// 720x1280 屏幕上的 (664,142)。
|
||
if (clickByAccessibilityDesc("点击退出关闭视频", reason)) {
|
||
log("已通过无障碍 desc 点击右上角圆圈 X");
|
||
return true;
|
||
}
|
||
|
||
var points = [
|
||
// 截图中右上角圆圈 X 的中心约为 720x1280 屏上的 (663,142),
|
||
// 优先点击该标定点;不是 OCR 识别。
|
||
{ name: "adCircleClose", point: CONFIG.adCircleClose },
|
||
{ name: "adPageClose", point: CONFIG.adPageClose },
|
||
{ name: "rewardClose", point: CONFIG.rewardClose },
|
||
{ name: "detailClose", point: CONFIG.extraTask.detailClose }
|
||
];
|
||
for (let i = 0; i < points.length; i += 1) {
|
||
var foreground = getForegroundApp();
|
||
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) {
|
||
log("关闭页前当前不在应用宝,停止点 X: " + describeForegroundApp(foreground));
|
||
return false;
|
||
}
|
||
log("尝试关闭应用宝任务页: " + points[i].name + " reason=" + reason);
|
||
clickRatio(points[i].point);
|
||
sleep(1200);
|
||
|
||
var items = recognizeScreenSafe();
|
||
if (items === null) {
|
||
log("关闭后 OCR 采样失败,无法验证,继续尝试下一个 X 坐标");
|
||
continue;
|
||
}
|
||
var stillReward = findMatches(items, CONFIG.extraTask.entryTexts).length > 0 ||
|
||
findMatches(items, ["打开浏览", "立即打开应用", "立即打开", "打开应用"]).length > 0 ||
|
||
findContainsMatches(items, CONFIG.adConfirmTexts).length > 0;
|
||
if (!stillReward) {
|
||
log("关闭应用宝任务页验证通过: " + points[i].name);
|
||
return true;
|
||
}
|
||
log("关闭应用宝任务页后仍检测到任务/广告页文本,继续尝试下一个 X 坐标");
|
||
}
|
||
log("多个 X 坐标均未确认关闭,保留当前页面给后续流程/下次恢复处理");
|
||
return false;
|
||
}
|
||
|
||
function handleThirdPartyAsExtraStep7(reason) {
|
||
setStep("额外任务 7/8:第三方应用浏览 15 秒后回应用宝");
|
||
log("已进入第三方应用,按额外任务第 7 步处理: " + reason);
|
||
sleep(CONFIG.extraTask.reopenWaitMs);
|
||
if (!backToYibao(15000)) {
|
||
log("第三方跳转处理:未能回到应用宝,跳过点 X");
|
||
return false;
|
||
}
|
||
sleep(1200);
|
||
setStep("额外任务 8/8:点击右上角 X 结束当次任务");
|
||
closeYibaoTaskPage(reason);
|
||
log("第三方跳转处理完成");
|
||
return true;
|
||
}
|
||
|
||
function waitDownloadComplete(timeoutMs) {
|
||
// 等待“已下载n%”进度走完:以安装器出现(下一步/安装)或详情页按钮
|
||
// 变为独立短文本“打开”作为完成信号,期间记录进度变化。完成信号只认
|
||
// 独立短文本,避免长句里的目标词把下载中误判成已完成。
|
||
var deadline = Date.now() + timeoutMs;
|
||
var lastProgress = "";
|
||
while (Date.now() < deadline) {
|
||
var items = recognizeScreenSafe();
|
||
if (items !== null) {
|
||
if (filterShortTextMatches(findMatches(items, ["下一步", "安装"]), 6).length > 0) {
|
||
log("下载完成,安装器已出现");
|
||
return true;
|
||
}
|
||
// 前台已是第三方应用(应用已装、详情页按钮直接是“打开”被点开等):
|
||
// 下载安装必然完成,不再空等进度。
|
||
var downloadForeground = getForegroundApp();
|
||
if (isThirdPartyForeground(downloadForeground)) {
|
||
log("前台已是第三方应用(" + downloadForeground.packageName + "),视为下载安装完成");
|
||
return true;
|
||
}
|
||
for (let i = 0; i < items.length; i += 1) {
|
||
var text = String(items[i].text || "");
|
||
if (text.indexOf("已下载") >= 0) {
|
||
if (text !== lastProgress) {
|
||
lastProgress = text;
|
||
log("下载进度: " + text);
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
// 部分安装流程静默完成:详情页按钮变为独立短文本“打开”且不再有“立即下载”。
|
||
if (filterShortTextMatches(findMatches(items, ["打开"]), 6).length > 0 &&
|
||
findMatches(items, ["立即下载"]).length === 0) {
|
||
log("详情页按钮已变为“打开”,视为下载安装完成");
|
||
return true;
|
||
}
|
||
}
|
||
sleep(2000);
|
||
}
|
||
log("下载等待超时(" + timeoutMs + "ms),继续后续步骤");
|
||
return false;
|
||
}
|
||
|
||
function runExtraDownloadTask(resumeFrom) {
|
||
// 主任务奖励后出现“继续做任务得额外奖励”时的附加流程:下载并打开浏览
|
||
// 第三方应用。全程容错,失败只记录日志不抛出,不影响已完成的主任务结果。
|
||
// resumeFrom:缺省=从奖励页入口开始;“detail”=从残留详情页继续;
|
||
// “installer”=从残留安装器继续(上次运行中断恢复)。
|
||
var extra = CONFIG.extraTask;
|
||
try {
|
||
setPhase("额外任务:下载并打开浏览");
|
||
currentStep = "";
|
||
|
||
setStep("额外任务 1/8:点击“立即下载”入口");
|
||
if (resumeFrom === "detail") {
|
||
log("额外任务:从残留详情页恢复,跳过入口点击");
|
||
} else if (resumeFrom === "installer") {
|
||
log("额外任务:从残留安装器恢复,跳过入口点击和下载等待");
|
||
} else {
|
||
// 1. 点击额外任务的“立即下载”入口。APK 曾下载过(如上次运行中断)
|
||
// 时按钮文案会是“立即安装”,一并作为点击目标。
|
||
if (!clickOcr(["立即下载", "立即下載", "点击下载", "下载应用", "立即安装"], 20000)) {
|
||
log("额外任务:未找到“立即下载”入口,跳过额外任务");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
setStep("额外任务 2/8:详情页点击下载/安装并等待完成");
|
||
// 2. 跳转后等详情页或安装器:正常路径进应用详情页(应用名称/权限详情/
|
||
// 隐私协议)再点“立即下载/安装”等“已下载n%”完成;APK 已缓存(如
|
||
// 上次运行中断后重试)时点击入口会直达安装器,跳过详情页和下载等待。
|
||
var detailSeen = resumeFrom === "detail";
|
||
var installerSeen = resumeFrom === "installer";
|
||
if (!detailSeen && !installerSeen) {
|
||
var jumpDeadline = Date.now() + 15000;
|
||
while (Date.now() < jumpDeadline && !detailSeen && !installerSeen) {
|
||
var jumpItems = recognizeScreenSafe();
|
||
if (jumpItems !== null) {
|
||
detailSeen = findMatches(jumpItems, extra.detailTexts).length > 0;
|
||
// 安装器特征:同屏出现“下一步”和“取消”两个独立短按钮。
|
||
installerSeen = filterShortTextMatches(findMatches(jumpItems, ["下一步"]), 6).length > 0 &&
|
||
filterShortTextMatches(findMatches(jumpItems, ["取消"]), 6).length > 0;
|
||
}
|
||
if (!detailSeen && !installerSeen) {
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
}
|
||
}
|
||
if (detailSeen) {
|
||
// 按钮文案随状态变化:未下载“立即下载”/下载中“已下载n%”/
|
||
// APK 已缓存“安装”或“立即安装”/已安装“打开”。短文本优先,
|
||
// 避免点到说明文字里含“安装/打开”的长句。
|
||
if (!clickOcr(["立即下载", "立即下載", "立即安装", "安装", "打开"], 20000, 0, true)) {
|
||
log("额外任务:详情页未找到下载/安装按钮,仍继续等待下载/安装");
|
||
}
|
||
waitDownloadComplete(extra.downloadTimeoutMs);
|
||
} else if (installerSeen) {
|
||
log("额外任务:直达安装器(APK 已缓存),跳过下载等待");
|
||
} else {
|
||
log("额外任务:未检测到详情页/安装器,仍尝试等待下载/安装");
|
||
waitDownloadComplete(extra.downloadTimeoutMs);
|
||
}
|
||
|
||
setStep("额外任务 3/8:安装器点击“下一步”并等待安装完成");
|
||
// 3. 安装器点击“下一步”,等待安装完成跳回应用宝(详情页或奖励页)。
|
||
// 系统安装器布局固定但底部小按钮 OCR 不稳(常只识别到标题
|
||
// “个软件安装”),确认安装器在前台后用标定坐标直接点“下一步”。
|
||
var installForeground = getForegroundApp();
|
||
if (installForeground && installForeground.packageName === extra.installerPackage) {
|
||
log("额外任务:安装器在前台,标定坐标点击“下一步”");
|
||
clickRatio(extra.installNextButton);
|
||
} else if (!clickOcr(["下一步"], 10000, 0, true)) {
|
||
log("额外任务:未出现安装器“下一步”,继续等待回到应用宝");
|
||
}
|
||
var backDeadline = Date.now() + extra.installTimeoutMs;
|
||
var backSeen = false;
|
||
while (Date.now() < backDeadline && !backSeen) {
|
||
var backItems = recognizeScreenSafe();
|
||
if (backItems !== null) {
|
||
backSeen = findMatches(backItems, extra.detailTexts).length > 0 ||
|
||
findMatches(backItems, CONFIG.extraTask.entryTexts).length > 0;
|
||
}
|
||
if (!backSeen) {
|
||
// 前台已是第三方应用(安装后自动打开等):无需等待回页。
|
||
var backForeground = getForegroundApp();
|
||
if (isThirdPartyForeground(backForeground)) {
|
||
log("额外任务:前台已是第三方应用(" + backForeground.packageName + "),跳过回页等待");
|
||
backSeen = true;
|
||
}
|
||
}
|
||
if (!backSeen) {
|
||
sleep(1500);
|
||
}
|
||
}
|
||
if (backSeen) {
|
||
log("额外任务:安装后已回到应用宝页面");
|
||
}
|
||
|
||
setStep("额外任务 4/8:点击“打开”跳转第三方应用");
|
||
// 4. 详情页点击独立的“打开”按钮,跳转到第三方应用。短文本优先,
|
||
// 避免点到头部“应用名称…版本…开发者”拼接出的长文本。点不到时
|
||
// 若前台已是第三方应用(按钮被直接点开/安装后自动打开),视为完成。
|
||
if (!clickOcr(["打开"], 20000, 0, true)) {
|
||
var openForeground = getForegroundApp();
|
||
if (isThirdPartyForeground(openForeground)) {
|
||
log("额外任务:前台已是第三方应用(" + openForeground.packageName + "),视为已打开");
|
||
} else {
|
||
log("额外任务:详情页未找到“打开”按钮,跳过后续步骤");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
setStep("额外任务 5/8:浏览 8 秒后回应用宝并关闭详情页");
|
||
// 5. 等待 8 秒后回到应用宝;回到的是详情页时点左上角 X 关闭
|
||
// (直达安装器的路径安装后直接回奖励页,无需关闭详情页)。
|
||
sleep(extra.openWaitMs);
|
||
if (!backToYibao(15000)) {
|
||
log("额外任务:未能回到应用宝,跳过后续步骤");
|
||
return false;
|
||
}
|
||
sleep(800);
|
||
var afterOpenItems = recognizeScreenSafe();
|
||
if (afterOpenItems !== null &&
|
||
findMatches(afterOpenItems, extra.detailTexts).length > 0) {
|
||
clickRatio(extra.detailClose);
|
||
} else {
|
||
log("额外任务:当前不在详情页,跳过详情页左上角 X");
|
||
}
|
||
|
||
setStep("额外任务 6/8:等待“打开浏览 5 秒多得 40 积分”弹窗");
|
||
// 6. 等待“打开浏览 5 秒,多得 40 积分”奖励弹窗出现。
|
||
// 弹窗按钮与“立即下载”同位,OCR 未命中时用标定坐标兜底。
|
||
var dialogSeen = waitOcr(["打开浏览", "立即打开应用", "立即打开", "打开应用"], 30000) !== null;
|
||
|
||
setStep("额外任务 7/8:点击“立即打开应用”浏览 10 秒后回应用宝");
|
||
// 7. 点击“立即打开应用”,等待 10 秒后回到应用宝。
|
||
if (!clickOcr(["立即打开应用", "立即打开", "打开应用"], 20000, 0, true) && dialogSeen) {
|
||
log("额外任务:“立即打开应用”未命中 OCR,使用标定坐标兜底");
|
||
clickRatio(extra.openAppButton);
|
||
}
|
||
sleep(extra.reopenWaitMs);
|
||
backToYibao(15000);
|
||
|
||
setStep("额外任务 8/8:点击右上角 X 结束当次任务");
|
||
// 8. 回到应用宝后点击右上角 X,结束当次任务。
|
||
sleep(800);
|
||
closeYibaoTaskPage("额外任务正常收尾");
|
||
log("额外任务流程完成");
|
||
return true;
|
||
} catch (error) {
|
||
log("额外任务异常(步骤=" + (currentStep || "未知") + ",不影响已完成的主任务): " + errorText(error));
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function findExtraTask2Trigger(items) {
|
||
if (!items) {
|
||
return null;
|
||
}
|
||
var triggerMatches = findMatches(items, CONFIG.extraTask2.triggerTexts);
|
||
if (triggerMatches.length > 0) {
|
||
return triggerMatches[0];
|
||
}
|
||
var titleMatches = findMatches(items, CONFIG.extraTask2.titleTexts || []);
|
||
if (titleMatches.length > 0) {
|
||
log("额外任务#2:看到标题候选“" + titleMatches[0].item.text +
|
||
"”,但未看到“再看一条/再领”按钮,暂不触发");
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function waitExtraTask2TriggerWindow(extra2) {
|
||
var deadline = Date.now() + extra2.checkWindowMs;
|
||
var scan = 0;
|
||
while (Date.now() < deadline) {
|
||
scan += 1;
|
||
var items = recognizeScreenSafe();
|
||
if (items !== null) {
|
||
var match = findExtraTask2Trigger(items);
|
||
if (match) {
|
||
return { match: match, scan: scan };
|
||
}
|
||
} else {
|
||
log("额外任务#2:第 " + scan + " 次 OCR 采样失败,继续轮询");
|
||
}
|
||
sleep(extra2.checkIntervalMs);
|
||
}
|
||
return { match: null, scan: scan };
|
||
}
|
||
|
||
function waitForAdActionOrThirdParty(timeoutMs) {
|
||
var deadline = Date.now() + timeoutMs;
|
||
while (Date.now() < deadline) {
|
||
var foreground = getForegroundApp();
|
||
if (isThirdPartyForeground(foreground)) {
|
||
return { state: "third_party", foreground: foreground };
|
||
}
|
||
|
||
var items = recognizeScreenSafe();
|
||
if (items !== null) {
|
||
var confirmMatches = findContainsMatches(items, CONFIG.adConfirmTexts);
|
||
var actionMatches = findMatches(items, CONFIG.adActionTargets);
|
||
if (actionMatches.length > 0) {
|
||
return { state: "ad_action", action: actionMatches[0], confirmed: confirmMatches.length > 0 };
|
||
}
|
||
var extra2Match = findExtraTask2Trigger(items);
|
||
if (extra2Match) {
|
||
log("额外任务#2:仍停留在触发弹窗,尝试点击“" + extra2Match.target + "”进入下一条广告");
|
||
clickOcrMatch(extra2Match, 0);
|
||
}
|
||
}
|
||
sleep(CONFIG.reliability.frameIntervalMs);
|
||
}
|
||
return { state: "timeout" };
|
||
}
|
||
|
||
function checkAndRunExtraTask2(round) {
|
||
var extra2 = CONFIG.extraTask2;
|
||
var currentRound = round || 0;
|
||
if (!extra2 || currentRound >= extra2.maxRounds) {
|
||
return false;
|
||
}
|
||
|
||
setStep("额外任务#2:结束后轮询检查触发提示");
|
||
log("整体任务结束," + extra2.checkDelayMs + "ms 后开始检查额外任务#2提示," +
|
||
"每 " + extra2.checkIntervalMs + "ms 检查一次,持续 " + extra2.checkWindowMs + "ms");
|
||
sleep(extra2.checkDelayMs);
|
||
|
||
var result = waitExtraTask2TriggerWindow(extra2);
|
||
if (!result.match) {
|
||
log("额外任务#2:" + result.scan + " 次检查均未检测到触发提示(" +
|
||
extra2.triggerTexts.join("/") + ")");
|
||
return false;
|
||
}
|
||
|
||
log("额外任务#2:第 " + result.scan + " 次检查检测到触发提示 text=" +
|
||
result.match.item.text + " target=" + result.match.target +
|
||
",等待自动重新进入主任务 4/6");
|
||
sleep(extra2.reenterWaitMs);
|
||
|
||
var enterState = waitForAdActionOrThirdParty(15000);
|
||
if (enterState.state === "third_party") {
|
||
handleThirdPartyAsExtraStep7("额外任务#2 自动进入后直达 " + enterState.foreground.packageName);
|
||
checkAndRunExtraTask2(currentRound + 1);
|
||
return true;
|
||
}
|
||
if (enterState.state !== "ad_action") {
|
||
log("额外任务#2:等待重新进入主任务 4/6 超时,state=" + enterState.state);
|
||
saveFailureCapture("额外任务#2_未进入主任务4_6");
|
||
return false;
|
||
}
|
||
|
||
runMainTaskTail(currentRound + 1);
|
||
return true;
|
||
}
|
||
|
||
function runMainTaskTail(extra2Round) {
|
||
setStep("主任务 4/6:等待并点击广告按钮");
|
||
setPhase("OCR 等待广告按钮");
|
||
if (!waitAndClickOcr(
|
||
CONFIG.adActionTargets,
|
||
CONFIG.adConfirmTexts,
|
||
30000
|
||
)) {
|
||
return failWithCapture("OCR 未找到“了解详情/查看详情/立即体验/立即下载/下载应用”");
|
||
}
|
||
|
||
var directThirdParty = waitThirdPartyForeground(5000);
|
||
if (directThirdParty) {
|
||
handleThirdPartyAsExtraStep7("主任务 4/6 点击广告按钮后直达 " + directThirdParty.packageName);
|
||
log("home_yibao OCR 流程完成(主任务直达第三方应用)");
|
||
checkAndRunExtraTask2(extra2Round || 0);
|
||
return;
|
||
}
|
||
|
||
setStep("主任务 5/6:关闭广告并等待奖励");
|
||
setPhase("关闭广告并等待奖励");
|
||
log("等待广告观看 20 秒后点击左侧 X 关闭广告");
|
||
sleep(20000);
|
||
// 主任务 5/6 关闭的是广告页左侧 X;右上角圆圈 X 是主任务 6/6
|
||
// 奖励/残留页的关闭位,不能在这里使用。
|
||
clickRatio(CONFIG.adClose);
|
||
sleep(1200);
|
||
|
||
if (waitOcr("恭喜已获得", 12000)) {
|
||
clickRatio(CONFIG.rewardClose);
|
||
sleep(800);
|
||
} else {
|
||
log("点击左侧 X 后未检测到“恭喜已获得”,继续进入 6/6 检查收尾");
|
||
}
|
||
|
||
// “放弃福利”仅在部分奖励弹窗出现;实测没有此按钮时,15 秒内
|
||
// OCR 每帧都是同一张奖励页,等待不会带来新信息。保留短暂动画缓冲。
|
||
if (!clickOcr("放弃福利", 2500)) {
|
||
log("奖励页未出现“放弃福利”,跳过可选按钮");
|
||
}
|
||
|
||
setStep("主任务 6/6:检查额外任务入口并收尾");
|
||
// 额外任务分支:出现“继续做任务得额外奖励”横幅时执行“下载并打开浏览”
|
||
// 任务;未出现但仍看到“看15秒/恭喜已获得”等残留奖励/广告页时,Android
|
||
// 返回键在该页无响应,改回点击右上角带圆圈的 X 关闭。
|
||
// 注意:奖励页完全静止时 captureScreen 每次要阻塞约 10 秒才超时重试,
|
||
// 等待窗口必须足够长(实测 8 秒窗口内可能一帧都采样不到)。
|
||
if (waitOcr(CONFIG.extraTask.entryTexts, CONFIG.extraTask.entryWaitMs)) {
|
||
runExtraDownloadTask();
|
||
} else if (clickByAccessibilityDesc("点击退出关闭视频", "主任务6/6 未出现额外任务入口,直接关闭右上角 X")) {
|
||
log("主任务 6/6 通过无障碍 desc 关闭右上角圆圈 X");
|
||
} else if (waitOcr(["看15秒", "恭喜已获得"], CONFIG.extraTask.residualWaitMs)) {
|
||
log("主任务 6/6 检测到奖励/广告页残留,点击右上角圆圈 X 关闭");
|
||
closeYibaoTaskPage("主任务6/6奖励/广告页残留");
|
||
}
|
||
log("home_yibao OCR 流程完成");
|
||
checkAndRunExtraTask2(extra2Round || 0);
|
||
}
|
||
|
||
function runHomeYibao() {
|
||
// 每次主流程尝试开始时清空步骤标记,避免上次尝试的额外任务步骤残留
|
||
// 到本次失败的日志/截图里;随后主任务每个关键动作都会设置步骤标记。
|
||
currentStep = "";
|
||
setStep("主任务 1/6:按包名启动应用宝");
|
||
setPhase("按包名启动应用宝");
|
||
launchYibao();
|
||
|
||
setStep("主任务 2/6:点击赚钱进入任务中心");
|
||
setPhase("OCR 点击赚钱");
|
||
var taskCenterState = enterYibaoTaskCenter();
|
||
if (taskCenterState === "reward_page") {
|
||
// 残留的奖励页:主任务奖励已发放,直接补完“下载并打开浏览”额外任务。
|
||
runExtraDownloadTask();
|
||
log("home_yibao OCR 流程完成(从残留奖励页恢复)");
|
||
checkAndRunExtraTask2(0);
|
||
return;
|
||
}
|
||
if (taskCenterState === "detail_page" || taskCenterState === "installer_page") {
|
||
// 残留的详情页/安装器:额外任务已进行到下载/安装阶段,从中断处继续。
|
||
runExtraDownloadTask(taskCenterState === "detail_page" ? "detail" : "installer");
|
||
log("home_yibao OCR 流程完成(从残留" +
|
||
(taskCenterState === "detail_page" ? "详情页" : "安装器") + "恢复)");
|
||
checkAndRunExtraTask2(0);
|
||
return;
|
||
}
|
||
if (!taskCenterState) {
|
||
return failWithCapture("OCR 未找到“赚钱”");
|
||
}
|
||
sleep(500);
|
||
|
||
if (taskCenterState !== "ad_page") {
|
||
setStep("主任务 3/6:查找并点击“去观看”");
|
||
setPhase("OCR 查找去观看");
|
||
if (!scrollForOcrTarget("去观看", "看视频赚积分 兑好礼", CONFIG.scrollMaxScans)) {
|
||
return failWithCapture("OCR 未找到“去观看”");
|
||
}
|
||
sleep(500);
|
||
} else {
|
||
log("当前已在广告页,跳过 OCR 查找去观看");
|
||
}
|
||
|
||
runMainTaskTail(0);
|
||
}
|
||
|
||
try {
|
||
// 截图权限只申请一次;失败重试整个流程时不再重复申请,避免重复请求异常。
|
||
setStep("准备 0/6:申请截图权限");
|
||
setPhase("申请截图权限");
|
||
if (!requestCapturePermission()) {
|
||
throw new Error("未获得截图权限,请允许 AutoJS6 录屏/截图权限");
|
||
}
|
||
sleep(CONFIG.ocrReadyWaitMs);
|
||
|
||
let flowSuccess = false;
|
||
for (let attempt = 1; attempt <= CONFIG.flowMaxAttempts && !flowSuccess; attempt += 1) {
|
||
try {
|
||
log("主流程尝试 " + attempt + "/" + CONFIG.flowMaxAttempts);
|
||
runHomeYibao();
|
||
flowSuccess = true;
|
||
} catch (error) {
|
||
log("主流程失败(尝试 " + attempt + "/" + CONFIG.flowMaxAttempts +
|
||
") phase=" + currentPhase + " step=" + (currentStep || "-") + " error=" + errorText(error));
|
||
toast("失败阶段: " + currentPhase + (currentStep ? "(" + currentStep + ")" : ""));
|
||
// 异常路径同样保存失败现场(saveFailureCapture 内部自带 try/catch)。
|
||
saveFailureCapture(currentPhase + (currentStep ? "_" + currentStep : ""));
|
||
if (attempt < CONFIG.flowMaxAttempts) {
|
||
log("返回桌面后重试整个流程");
|
||
try {
|
||
home();
|
||
} catch (homeError) {
|
||
log("返回桌面失败: " + errorText(homeError));
|
||
}
|
||
sleep(3000);
|
||
}
|
||
}
|
||
}
|
||
if (flowSuccess) {
|
||
toast("home_yibao 流程成功");
|
||
}
|
||
} catch (error) {
|
||
var detail = errorText(error);
|
||
log("脚本失败 phase=" + currentPhase + " step=" + (currentStep || "-") + " error=" + detail);
|
||
toast("失败阶段: " + currentPhase + (currentStep ? "(" + currentStep + ")" : ""));
|
||
}
|