hmz 8de61173e0 修复应用宝一条龙任务恢复、常亮及公共浏览安装流程
完善惊喜任务逐项执行和存储授权,兼容微信浏览入口及应用推荐下载落点。增加重复运行保护、投影恢复和任务完成复核,并保留原有安装适配。

验证:59项离线回归通过,生成文件一致性、语法及差异空白检查通过。
2026-11-18 16:05:57 +08:00

489 lines
24 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 公共广告识别、退出验证及收尾;业务差异由当前流程策略控制。
function readAdActionNode(node, state, depth) {
if (!node || depth > 40 || ++state.count > 2500) {
throw new Error("广告节点树不完整或超过读取上限");
}
var rect = new android.graphics.Rect();
node.getBoundsInScreen(rect);
var snapshot = {
className: String(node.getClassName() || ""),
visible: Boolean(node.isVisibleToUser()),
desc: String(node.getContentDescription() || ""),
bounds: [rect.left, rect.top, rect.right, rect.bottom],
children: []
};
for (var i = 0; i < node.getChildCount(); i += 1) {
snapshot.children.push(readAdActionNode(node.getChild(i), state, depth + 1));
}
return snapshot;
}
function findAdActionButtonsInTree(tree, width, height) {
var groupClass = "android.view.ViewGroup";
var viewClass = "android.view.View";
var matches = [];
var hasAdClose = false;
function contains(outer, inner) {
return inner[0] >= outer[0] && inner[1] >= outer[1] &&
inner[2] <= outer[2] && inner[3] <= outer[3] &&
inner[2] > inner[0] && inner[3] > inner[1];
}
function visit(node) {
if (!node || !node.visible) return;
if (node.desc === "点击退出关闭视频") hasAdClose = true;
var rows = node.children;
var shape = rows.length === 4 ? [3, 2, 1, 1] :
(rows.length === 3 ? [2, 1, 1] : null);
if (node.className === groupClass && shape &&
rows.every(function (row, index) {
return row.visible && row.className === groupClass &&
row.children.length === shape[index];
})) {
var buttonIndex = rows.length - 2;
var button = rows[buttonIndex];
var leaf = button.children[0];
var footerRow = rows[buttonIndex + 1];
var footer = footerRow.children[0];
var bounds = button.bounds;
var buttonWidth = bounds[2] - bounds[0];
var buttonHeight = bounds[3] - bounds[1];
var aspect = buttonWidth / Math.max(1, buttonHeight);
var ordered = rows.every(function (row, index) {
return contains(node.bounds, row.bounds) &&
(index === 0 || rows[index - 1].bounds[3] <= row.bounds[1]);
});
if (ordered && leaf.visible && leaf.className === viewClass &&
footer.visible && footer.className === viewClass &&
contains(bounds, leaf.bounds) && contains(footerRow.bounds, footer.bounds) &&
contains([0, 0, width, height], node.bounds) &&
buttonWidth >= width * 0.6 && aspect >= 3.5 && aspect <= 12 &&
(bounds[1] + bounds[3]) / 2 >= height * 0.5) {
matches.push({ bounds: bounds.slice(),
centerX: (bounds[0] + bounds[2]) / 2,
centerY: (bounds[1] + bounds[3]) / 2 });
}
}
node.children.forEach(visit);
}
visit(tree);
// 用广告关闭按钮的无障碍描述确认广告上下文,避免普通列表结构误命中。
return hasAdClose ? matches : [];
}
function inspectAdActionHierarchy() {
try {
if (typeof auto === "undefined" || !auto || !auto.service) {
return { status: "无障碍服务不可用", matches: [] };
}
var root = auto.rootInActiveWindow;
if (!root) return { status: "无活动窗口", matches: [] };
if (handleYibaoAppJumpPrompt(root)) {
root = auto.rootInActiveWindow;
if (!root) return { status: "无活动窗口", matches: [] };
}
var packageName = String(root.getPackageName() || "");
if (packageName !== CONFIG.yibaoPackage) {
return { status: "其他应用", packageName: packageName, matches: [] };
}
var tree = readAdActionNode(root, { count: 0 }, 0);
return { status: "ok", matches: findAdActionButtonsInTree(tree, device.width, device.height) };
} catch (error) {
return { status: "节点读取失败: " + errorText(error), matches: [] };
}
}
function sameAdActionBounds(left, right) {
return left && right && left.bounds.every(function (value, index) {
var tolerance = index % 2 === 0 ? device.width * 0.01 : device.height * 0.005;
return Math.abs(value - right.bounds[index]) <= Math.max(2, tolerance);
});
}
function waitAndClickAdAction(waitMs) {
var items = recognizeScreenSafe();
if (handleAdView1BrowseOffer(items)) return "browse_handled";
if (findYibaoCardAdClose(items)) return {type:"card_ad",items:items};
var deadline = Date.now() + waitMs;
var nextOcrAt = 0;
var repeatConfirmer = createMatchConfirmer();
var repeatClicks = 0;
var previous = null;
var streak = 0;
var lastStatus = "";
while (Date.now() < deadline) {
if (Date.now() >= nextOcrAt) {
if (nextOcrAt !== 0) items = recognizeScreenSafe();
nextOcrAt = Date.now() + 3000;
if (handleAdView1BrowseOffer(items)) return "browse_handled";
if (findYibaoCardAdClose(items)) return {type:"card_ad",items:items};
var prompt = findAdView1RepeatVideoPrompt(items);
if (prompt) {
var confirmed = repeatConfirmer.feed([prompt]);
if (confirmed) {
if (++repeatClicks > 2) return failAdView1BrowseOffer("再看1条视频提示未切页,未点击背景广告");
log("前台是安装奖励弹窗,优先点击再看1条视频进入广告");
clickOcrMatch(confirmed, 0);
repeatConfirmer.feed([]);
sleep(1200);
}
nextOcrAt = Date.now();
sleep(CONFIG.reliability.frameIntervalMs);
continue;
}
repeatConfirmer.feed([]);
if (isAdView1CompletedAd(items) && findAdView1CloseNode("点击退出关闭视频")) {
log("已识别广告奖励完成,跳过CTA等待,直接关闭收尾");
return "ad_reward";
}
}
var state = inspectAdActionHierarchy();
var status = state.status + " 候选=" + state.matches.length;
if (status !== lastStatus) {
log("广告按钮结构扫描:" + status);
lastStatus = status;
}
if (state.status !== "ok" || state.matches.length !== 1) {
previous = null;
streak = 0;
sleep(CONFIG.reliability.frameIntervalMs);
continue;
}
var candidate = state.matches[0];
streak = sameAdActionBounds(previous, candidate) ? streak + 1 : 1;
previous = candidate;
if (streak >= Math.max(2, CONFIG.reliability.confirmFrames)) {
// 点击前重新读取,防止两帧确认后界面已经切换或出现第二个候选。
var fresh = inspectAdActionHierarchy();
if (fresh.status !== "ok" || fresh.matches.length !== 1 ||
!sameAdActionBounds(candidate, fresh.matches[0])) {
previous = null;
streak = 0;
continue;
}
candidate = fresh.matches[0];
var x = Math.round(candidate.centerX);
var y = Math.round(candidate.centerY);
log("无障碍结构点击广告按钮 bounds=" + JSON.stringify(candidate.bounds) +
" point=(" + x + "," + y + "),本阶段仅点击一次");
var accepted = click(x, y);
if (accepted !== false && verifyAdActionTransition(8000)) return true;
if (handleAdView1BrowseOffer()) return "browse_handled";
// 验证阶段不重新点,也不重跑整条任务,避免点到下一页的下载按钮。
var clickError = new Error("广告按钮结构点击后未确认页面切换,停止任务");
clickError.taskInterrupted = true;
throw clickError;
}
sleep(CONFIG.reliability.frameIntervalMs);
}
log("等待广告按钮结构超时:" + lastStatus);
return false;
}
function findYibaoCardAdClose(items, images) {
var corpus = (items || []).map(function (item) { return normalizeText(item.text); }).join("");
if (!/点击卡片查看详情/.test(corpus) || !(items || []).some(function (item) {
return normalizeText(item.text) === "广告";
})) return null;
images = images || readMealRewardImages();
var cards = (images || []).filter(function (b) {
return b.left >= 0 && b.right <= device.width && b.top > device.height * .15 &&
b.bottom < device.height * .9 && b.right - b.left >= device.width * .85 &&
b.bottom - b.top >= device.height * .25;
});
var matches = (images || []).filter(function (b) {
var width = b.right - b.left, height = b.bottom - b.top;
return width >= device.width * .035 && width <= device.width * .10 && height >= width * .7 && height <= width * 1.3 &&
cards.some(function (card) {
return Math.abs(b.right - card.right) <= device.width * .025 &&
Math.abs(b.top - card.top) <= device.height * .025 && b.left >= card.left && b.bottom <= card.bottom;
});
});
return matches.length === 1 ? matches[0] : null;
}
function waitAndCloseYibaoCardAd(items) {
var initial = findYibaoCardAdClose(items);
if (!initial) return false;
setStep("静态卡片广告:前台观看30秒后关闭右上角叉叉");
log("检测到点击卡片查看详情广告,等待观看,不点击中央推广卡片");
var started = Date.now();
while (Date.now() - started < 30000) {
var foreground = getForegroundApp();
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) return false;
sleep(Math.max(1, Math.min(1000, 30000 - (Date.now() - started))));
}
var absentFrames = 0, clicks = 0;
for (var frame = 0; frame < 8; frame += 1) {
var current = getForegroundApp();
if (!current || current.packageName !== CONFIG.yibaoPackage) return false;
var close = findYibaoCardAdClose(items, readMealRewardImages());
if (!close) {
if (++absentFrames >= 2) {
log("静态卡片广告关闭验证通过,返回任务列表复查下一条视频");
return true;
}
} else {
absentFrames = 0;
// 重读原生控件并校验位置,不能用旧截图去点击新页面。
if (Math.abs(close.left - initial.left) > device.width * .02 ||
Math.abs(close.top - initial.top) > device.height * .02) return false;
if (++clicks > 3) return false;
log("关闭静态卡片广告右上角叉叉 bounds=" + JSON.stringify(close));
if (press(Math.round((close.left + close.right) / 2), Math.round((close.top + close.bottom) / 2), 100) === false) return false;
}
sleep(700);
}
return false;
}
function findAdView1CloseNode(descText) {
if (typeof desc !== "function") return null;
var node = desc(descText).findOne(300);
if (!node || (typeof node.visibleToUser === "function" && !node.visibleToUser())) return null;
var bounds = node.bounds();
return bounds.width() > 0 && bounds.height() > 0 &&
bounds.centerX() > 0 && bounds.centerX() < device.width &&
bounds.centerY() > 0 && bounds.centerY() < device.height ? node : null;
}
function isAdView1CompletedAd(items) {
return !isAdView1BrowseOffer(items) && (items || []).some(function (item) {
return /恭喜已获得奖励|恭喜(?:已)?获得\d+积分/.test(normalizeText(item.text));
});
}
function closeCompletedAdLanding(items) {
for (var attempt = 1; attempt <= 3; attempt += 1) {
var foreground = getForegroundApp();
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) return false;
if (isAdView1ExtraDownloadOffer(items)) {
log("奖励页已出现下载并打开浏览任务,停止关页并接续额外下载流程");
return finishYibaoOptionalDownload();
}
if (findVisibleCloseNode("点击退出关闭视频")) {
if (clickByAccessibilityDesc("点击退出关闭视频", "关闭已领奖励广告页", items)) return true;
// 关闭动作可能弹出额外任务;用新页面接续,不继续点弹窗背后的叉。
items = recognizeScreenSafe();
if (isAdView1ExtraDownloadOffer(items)) return finishYibaoOptionalDownload();
return false;
}
var match = findCompletedAdCloseMatch(items);
if (!match) return false;
clickOcrMatch(match, 0);
sleep(1200);
items = recognizeScreenSafe();
if (!items || !items.length) return false;
if (isAdView1ExtraDownloadOffer(items)) {
log("关闭奖励落地页后出现下载任务,接续下载并打开浏览");
return finishYibaoOptionalDownload();
}
if (!isCompletedAdLanding(items)) {
sleep(500);
var confirm = recognizeScreenSafe();
if (confirm && confirm.length && !isCompletedAdLanding(confirm)) return true;
}
}
return false;
}
function clickByAccessibilityDesc(descText, reason, initialItems) {
try {
for (var attempt = 1; attempt <= 3; attempt += 1) {
var foreground = getForegroundApp();
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) return false;
var node = findAdView1CloseNode(descText);
if (!node) return false;
// 调用方刚读取的当前页可直接用于弹窗检查,静止奖励页重复截图可能超时。
// 后续重试仍重新识别,不能复用点击之前的旧页面。
var beforeItems = attempt === 1 && initialItems ? initialItems : recognizeScreenSafe();
if (isAdView1BrowseOffer(beforeItems) && !yibaoWechatBrowseBusy) {
log("关闭前发现浏览挽留弹窗,先处理前台提示,停止点击背景叉");
handleAdView1BrowseOffer(beforeItems, false);
foreground = getForegroundApp();
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) return false;
node = findAdView1CloseNode(descText);
if (!node) {
sleep(500);
foreground = getForegroundApp();
if (foreground && foreground.packageName === CONFIG.yibaoPackage && !findAdView1CloseNode(descText)) {
log("关闭验证通过:浏览返回后退出控件已消失,reason=" + reason);
return true;
}
return false;
}
}
var bounds = node.bounds();
log("短按真实关闭按钮 attempt=" + attempt + " point=(" + bounds.centerX() + "," +
bounds.centerY() + ") reason=" + reason);
if (typeof press === "function") press(bounds.centerX(), bounds.centerY(), 100);
else click(bounds.centerX(), bounds.centerY());
sleep(1200);
foreground = getForegroundApp();
if (!foreground || foreground.packageName !== CONFIG.yibaoPackage) return false;
if (!findAdView1CloseNode(descText)) {
sleep(500);
foreground = getForegroundApp();
if (foreground && foreground.packageName === CONFIG.yibaoPackage && !findAdView1CloseNode(descText)) {
log("关闭验证通过:退出控件连续两次消失,reason=" + reason);
return true;
}
} else {
var items = recognizeScreenSafe();
// 关闭时如弹出浏览提示,先完成浏览再重试关页;关闭由本循环负责,避免递归。
if (isAdView1BrowseOffer(items) && !yibaoWechatBrowseBusy) handleAdView1BrowseOffer(items, false);
}
}
log("关闭控件仍在,不能报告关闭成功:" + reason);
} catch (error) {
if (error && error.taskInterrupted) throw error;
log("关闭验证失败:" + errorText(error));
}
return false;
}
function closeYibaoTaskPage(reason) {
// 这里不是 OCR 识别 X:右上角 X 通常没有稳定文字。优先使用你通过
// 无障碍确认到的 desc="点击退出关闭视频",失败后兜底点击坐标
// 720x1280 屏幕上的 (664,142)。
var knownClose = findAdView1CloseNode("点击退出关闭视频");
if (clickByAccessibilityDesc("点击退出关闭视频", reason)) {
log("已通过无障碍 desc 点击右上角圆圈 X");
return true;
}
if (knownClose) return false; // 已知按钮仍在时不继续乱点其他固定坐标。
var currentItems = recognizeScreenSafe();
if (currentItems && isYibaoTaskCenter(currentItems) && !findAdView1RepeatVideoPrompt(currentItems)) 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 采样失败,无法验证,不继续盲点其他坐标");
return false;
}
var stillReward = findMatches(items, CONFIG.extraTask.entryTexts).length > 0 ||
findMatches(items, ["打开浏览", "立即打开应用", "立即打开", "打开应用"]).length > 0 ||
findContainsMatches(items, CONFIG.adConfirmTexts).length > 0;
if (!stillReward && (isYibaoTaskCenter(items) || findAdView1RepeatVideoPrompt(items))) {
log("关闭应用宝任务页验证通过: " + points[i].name);
return true;
}
log("关闭应用宝任务页后仍检测到任务/广告页文本,继续尝试下一个 X 坐标");
}
log("多个 X 坐标均未确认关闭,保留当前页面给后续流程/下次恢复处理");
return false;
}
function runMainTaskTail(extra2Round) {
setStep("主任务 4/6:等待并点击广告按钮");
setPhase("无障碍结构等待广告按钮");
var actionResult = waitAndClickAdAction(30000);
if (!actionResult) {
return failWithCapture("未找到唯一、稳定的广告按钮结构");
}
if (actionResult && actionResult.type === "card_ad") {
if (!waitAndCloseYibaoCardAd(actionResult.items)) return failWithCapture("静态卡片广告未确认观看或关闭完成");
if (activeYibaoFlow.id !== "2") checkAndRunExtraTask2(extra2Round || 0);
return true;
}
var browseHandled = actionResult === "browse_handled" || actionResult === "ad_reward";
var directThirdParty = browseHandled ? null : waitThirdPartyForeground(5000);
if (directThirdParty) {
var directBrowseMs = Math.max(20000, CONFIG.adView1.rewardBrowseWaitMs || 0);
log("广告直达第三方应用,先在目标应用前台浏览 " + (directBrowseMs / 1000) + " 秒,再返回领奖");
if (!browseThirdPartyThenReturn(directBrowseMs)) {
return failWithCapture("广告直达第三方应用后浏览未达标或未返回应用宝");
}
if (activeYibaoFlow.id === "0_1") {
back();
return "back_and_end";
}
log("已从第三方应用返回应用宝,跳过主任务 5/6,直接进入 6/6");
}
if (!directThirdParty && !browseHandled) {
setStep("主任务 5/6:关闭广告并等待奖励");
setPhase("关闭广告并等待奖励");
// 首次广告按钮也可能拉起安装器。先返回应用宝广告页,再观看和关闭。
if (!backToYibao(20000)) {
return failWithCapture("主任务 5/6:未回到应用宝广告页,不能点击左上角 X");
}
log("等待广告观看 20 秒后点击左侧 X 关闭广告");
sleep(20000);
// 主任务 5/6 关闭的是广告页左侧 X;右上角圆圈 X 是主任务 6/6
// 奖励/残留页的关闭位,不能在这里使用。
if (!backToYibao(20000)) {
return failWithCapture("主任务 5/6:观看等待后未回到应用宝,不能点击左上角 X");
}
var landingItems = recognizeScreenSafe();
if (landingItems && isAdView1ExtraDownloadOffer(landingItems)) {
log("已领奖励页仍有下载并打开浏览额外任务,先执行原有下载流程,不关闭入口");
if (!finishYibaoOptionalDownload()) return failWithCapture("额外下载失败后未能安全退出页面");
} else if (landingItems && isCompletedAdLanding(landingItems)) {
if (!closeCompletedAdLanding(landingItems)) return failWithCapture("奖励落地页未关闭");
} else if (findAdView1CloseNode("点击退出关闭视频")) {
if (!clickByAccessibilityDesc("点击退出关闭视频", "主任务5/6广告结束关闭", landingItems)) {
return failAdView1BrowseOffer("广告结束后未确认关闭,未继续下一轮");
}
} else {
clickRatio(CONFIG.adClose);
}
sleep(1200);
handleAdView1BrowseOffer();
var bonusState = activeYibaoFlow.id === "2" ? runAdActionBonusBranch() : "none";
if (bonusState === "failed") return failWithCapture("广告额外任务未完成");
if (bonusState === "none" && waitOcr("恭喜已获得", 12000)) {
clickRatio(CONFIG.rewardClose);
sleep(800);
} else {
log("点击左侧 X 后未检测到“恭喜已获得”,继续进入 6/6 检查收尾");
}
// “放弃福利”只在部分奖励弹窗出现;未出现时不要在静止画面等满 15 秒。
if (!clickOcr("放弃福利", 2500)) {
log("奖励页未出现“放弃福利”,跳过可选按钮");
}
}
setStep("主任务 6/6:检查额外任务入口并收尾");
handleAdView1BrowseOffer();
// 额外任务分支:出现“继续做任务得额外奖励”横幅时执行“下载并打开浏览”
// 任务;未出现但仍看到“看15秒/恭喜已获得”等残留奖励/广告页时,Android
// 返回键在该页无响应,改回点击右上角带圆圈的 X 关闭。
// 注意:奖励页完全静止时 captureScreen 每次要阻塞约 10 秒才超时重试,
// 等待窗口必须足够长(实测 8 秒窗口内可能一帧都采样不到)。
var tailItems = recognizeScreenSafe();
if (isAdView1ExtraDownloadOffer(tailItems) || waitOcr(CONFIG.extraTask.entryTexts, CONFIG.extraTask.entryWaitMs)) {
if (!finishYibaoOptionalDownload()) return failWithCapture("额外下载失败后未能安全退出页面");
} 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奖励/广告页残留");
}
if (findAdView1CloseNode("点击退出关闭视频") && !closeYibaoTaskPage("主任务6/6最终关闭复核")) {
return failAdView1BrowseOffer("广告退出控件仍在,未将本轮视为完成");
}
log("home_yibao OCR 流程完成");
if (activeYibaoFlow.id !== "2") checkAndRunExtraTask2(extra2Round || 0);
}