app_auto_all/qimao_auto/qimao-daily.auto.js

1458 lines
79 KiB
JavaScript
Raw 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.

"auto";
// 七猫免费小说:福利中心 → 吃饭补贴 → 逛街赚金币 → 逛商城赚金币。
// 无障碍 + 手机内存中的本地OCR,不上传或导出图片。
var CONFIG = {
version:"2026-10-22-qimao-17", packageName:"com.kmxs.reader", rewardThreshold:100,
pollMs:1200, pageTimeoutMs:8000, navigationTimeoutMs:30000, videoTimeoutMs:180000, maxVideos:15,
stepTimeoutMs:240000, taskSearchScrolls:16, recognitionTimeoutMs:15000,
captureRecoveryLimit:2, capturePermissionTimeoutMs:60000, useLocalOcr:true,
mealSessionTimeoutMs:1800000, browseCycleTimeoutMs:240000,
logPath:"/sdcard/Download/qimao-daily-run.log", pageTextPath:"/sdcard/Download/qimao-daily-page.json"
};
var localOcrEnabled=false, commonHandling=false, actionSerial=0;
var captureQueue=null, captureWorker=null, captureRecoveries=0;
var flipSettlementDone=false, flipActionDone=false;
var MEAL_PAGE=/吃饭补贴|饭点.*补贴/;
var STREET_LABEL=/^逛[街衛衔][赚賺嫌]金[币市]/;
var MALL_LABEL=/^逛商城[赚賺嫌]金[币市]/;
function writeRunLog(message) {
var line = new Date().toISOString() + " " + message;
log(line);
files.append(CONFIG.logPath, line + "\n");
}
// 各脚本保持可单独复制运行;共同启动行为由跨脚本回归测试验证。
var nextScreenKeepAliveAt = 0;
function keepScreenAwake() {
if (typeof device === "undefined" || typeof device.keepScreenOn !== "function" || Date.now() < nextScreenKeepAliveAt) return;
device.keepScreenOn(3600000);
nextScreenKeepAliveAt = Date.now() + 60000;
}
function releaseScreenAwake() {
nextScreenKeepAliveAt = 0;
if (typeof device !== "undefined" && typeof device.cancelKeepingAwake === "function") device.cancelKeepingAwake();
}
function waitStartupPackage(packageName, timeoutMs) {
var deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
keepScreenAwake();
if (foregroundPackage() === packageName) return;
sleep(200);
}
throw new Error("等待应用进入前台超时:" + packageName);
}
function clickStartupNode(node) {
for (var depth = 0; node && depth < 4; depth++, node = node.parent()) {
if (!node.enabled()) return false;
if (node.clickable()) return node.click();
}
return false;
}
function prepareCaptureForeground() {
keepScreenAwake();
auto.waitFor();
var hostPackage = String(context.getPackageName());
if (foregroundPackage() !== hostPackage && !app.launchPackage(hostPackage)) throw new Error("无法将 AutoJs6 切到前台申请截屏授权");
waitStartupPackage(hostPackage, 8000);
sleep(400);
}
// 仅处理系统的 AutoJs6 录屏对话框,不处理应用里的“允许”等按钮。
function approveCaptureDialog(state) {
var verified = false;
var deadline = Date.now() + CONFIG.capturePermissionTimeoutMs;
while (state.pending && Date.now() < deadline) {
if (foregroundPackage() === "com.android.systemui") {
var title = textMatches(/.*AutoJs6.*(?:录制|投放|投射|截取|共享|分享|screen|capture).*/i).packageName("com.android.systemui").findOnce();
if (title) verified = true;
if (verified) {
var whole = textMatches(/^(?:整个屏幕|Entire screen|Full screen)$/i).packageName("com.android.systemui").findOnce();
var single = textMatches(/^(?:单个应用|单个应用程序|A single app|Single app)$/i).packageName("com.android.systemui").findOnce();
if (single && !whole) clickStartupNode(single);
else if (whole && !title) clickStartupNode(whole); // 展开的范围菜单
else if (title && !single) {
var allow = textMatches(/^(?:开始|立即开始|允许|Start now|Start|Allow)$/i).packageName("com.android.systemui").findOnce();
if (allow && clickStartupNode(allow)) writeRunLog("CAPTURE APPROVE: 已确认 AutoJs6 系统截屏授权。");
}
}
} else verified = false;
sleep(200);
}
}
function requestLocalCapture() {
prepareCaptureForeground();
var state = {pending: true};
var approver = threads.start(function () { approveCaptureDialog(state); });
try {
return requestScreenCapture(false);
} finally {
state.pending = false;
approver.interrupt();
approver.join(1500);
if (approver.isAlive()) {
var error = new Error("截屏授权辅助线程未退出,不能继续操作页面");
error.unsafeWorker = true;
throw error;
}
}
}
function restartTargetApp() {
keepScreenAwake();
auto.waitFor();
var settingsPackage = "com.android.settings";
var appName = String(app.getAppName(CONFIG.packageName) || "");
if (!appName) throw new Error("未安装目标应用:" + CONFIG.packageName);
writeRunLog("APP RESTART: 打开目标应用详情,关闭后重新启动:" + CONFIG.packageName);
app.openAppSetting(CONFIG.packageName);
waitStartupPackage(settingsPackage, 8000);
var deadline = Date.now() + 8000, stop = null;
while (Date.now() < deadline) {
if (foregroundPackage() === settingsPackage && text(appName).packageName(settingsPackage).exists()) {
stop = textMatches(/^(?:强行停止|强制停止|结束运行|Force stop)$/i).packageName(settingsPackage).findOnce();
if (stop) break;
}
sleep(200);
}
if (!stop) throw new Error("未找到目标应用详情的强行停止按钮,不把返回桌面当成重启");
sleep(500);
stop = textMatches(/^(?:强行停止|强制停止|结束运行|Force stop)$/i).packageName(settingsPackage).findOnce();
if (!stop) throw new Error("应用详情在启动前发生变化");
if (stop.enabled()) {
if (!clickStartupNode(stop)) throw new Error("目标应用强行停止按钮无法点击");
var stopped = false;
deadline = Date.now() + 8000;
while (Date.now() < deadline) {
if (foregroundPackage() !== settingsPackage) throw new Error("关闭应用时离开目标设置页面");
var confirm = id("android:id/button1").packageName(settingsPackage).findOnce();
if (confirm && /^(?:强行停止|强制停止|确定|确认|停止|Force stop|OK)$/i.test(String(confirm.text()))) clickStartupNode(confirm);
stop = textMatches(/^(?:强行停止|强制停止|结束运行|Force stop)$/i).packageName(settingsPackage).findOnce();
if (stop && !stop.enabled()) { stopped = true; break; }
sleep(200);
}
if (!stopped) throw new Error("强行停止后未确认目标应用已关闭");
} else writeRunLog("APP STOPPED: 目标应用当前已停止。");
if (!app.launchPackage(CONFIG.packageName)) throw new Error("无法重新打开目标应用:" + CONFIG.packageName);
waitStartupPackage(CONFIG.packageName, 15000);
sleep(CONFIG.pollMs);
writeRunLog("APP RESTARTED: 已关闭并重新进入目标应用;运行期间保持亮屏。");
}
function stopWith(message) {
throw new Error(message.replace(/已停止/g, "本步骤跳过"));
}
// 任务和识别分别限时;结束旧线程后才允许后续任务使用屏幕。
function boundedCall(name, timeoutMs, action) {
var result;
var failure;
var worker = threads.start(function () {
try { result = action(); } catch (error) { failure = error; }
});
var deadline = Date.now() + timeoutMs;
try {
while (worker.isAlive() && Date.now() < deadline) sleep(100);
if (worker.isAlive()) {
worker.interrupt();
worker.join(1500);
var timeout = new Error(name + "超时(" + timeoutMs + "ms)");
if (worker.isAlive()) timeout.unsafeWorker = true;
throw timeout;
}
if (failure) throw failure;
return result;
} finally {
if (worker.isAlive()) {
worker.interrupt();
worker.join(1500);
if (worker.isAlive()) {
var unsafe = new Error(name + "的线程无法终止,不能让旧任务与下一任务同时点击");
unsafe.unsafeWorker = true;
throw unsafe;
}
}
}
}
function runStep(name, action, timeoutMs) {
writeRunLog("STEP START: " + name);
try {
var value = boundedCall(name, timeoutMs || CONFIG.stepTimeoutMs, action);
writeRunLog("STEP DONE: " + name);
return {ok: true, value: value};
} catch (error) {
if (error.unsafeWorker || error.captureFatal) throw error;
writeRunLog("STEP SKIP: " + name + ";原因=" + error + ";继续下一步骤");
return {ok: !!error.noMatch, skipped: true, retryable: !!error.foregroundTransient};
}
}
function foregroundPackage() {
// currentPackage() 在部分 ROM 内部调用 shell 可能阻塞,直接读取无障碍窗口。
var root = auto.rootInActiveWindow;
return root ? String(root.getPackageName()) : "";
}
function skipStep(message) {
var error = new Error(message);
error.noMatch = true;
throw error;
}
function compact(value) {
var text = String(value || "").replace(/\s+/g, "").replace(/領/g, "领").replace(/貼/g, "贴").replace(/朴贴/g, "补贴")
.replace(/視/g, "视").replace(/頻/g, "频");
return /^(?:close[_-]?button|关闭按钮)$/i.test(text) ? "关闭" : text;
}
function rectOf(bounds) {
if (!bounds) return null;
function numberAt(name) {
return Number(typeof bounds[name] === "function" ? bounds[name]() : bounds[name]);
}
var rect = {left: numberAt("left"), top: numberAt("top"),
right: numberAt("right"), bottom: numberAt("bottom")};
if (!isFinite(rect.left) || !isFinite(rect.top) || !isFinite(rect.right) ||
!isFinite(rect.bottom) || rect.right <= rect.left || rect.bottom <= rect.top) return null;
if (rect.left < 0 || rect.top < 0 || rect.right > device.width || rect.bottom > device.height) return null;
return rect;
}
// 整次运行复用同一截图线程,避免每次识别创建新的投影显示。
function captureCall(name, timeoutMs, action) {
if (!captureWorker || !captureWorker.isAlive()) {
captureQueue = new java.util.concurrent.LinkedBlockingQueue();
captureWorker = threads.start(function () {
while (!java.lang.Thread.currentThread().isInterrupted()) {
var job = captureQueue.take();
try { job.value.set({value: job.action()}); }
catch (error) { job.value.set({error: error}); }
}
});
}
var result = new java.util.concurrent.atomic.AtomicReference();
captureQueue.put({action: action, value: result});
var deadline = Date.now() + timeoutMs;
while (result.get() === null && Date.now() < deadline) sleep(100);
var done = result.get();
if (done === null) {
captureWorker.interrupt();
captureWorker.join(1500);
var timeout = new Error(name + "超时,截图通道不可用");
timeout.unsafeWorker = true;
throw timeout;
}
if (done.error) throw done.error;
return done.value;
}
function initLocalOcr() {
if (!CONFIG.useLocalOcr || typeof $ocr === "undefined" || typeof $ocr.detect !== "function") {
log("未检测到本地 $ocr.detect,仅使用无障碍文字;识别不到时停止,不按旧坐标点击。");
return;
}
captureCall("申请截图", CONFIG.capturePermissionTimeoutMs, function () {
// Android 14+ 不允许复用同一个授权令牌创建第二个显示。
// 本任务为竖屏,固定方向可避免 AUTO 模式在页面切换后重建显示。
if (!requestLocalCapture()) stopWith("未获得本机截屏权限;无需上传图片。");
localOcrEnabled = true;
});
}
function isProjectionFailure(error) {
return /MediaProjection|VirtualDisplay|resultData|projection instance|Failed to capture screen|截图通道不可用/.test(String(error));
}
function readPage(name) {
try {
return captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot);
} catch (error) {
if (error.unsafeWorker || !isProjectionFailure(error)) throw error;
if (captureRecoveries >= CONFIG.captureRecoveryLimit) {
error.captureFatal = true;
writeRunLog("截图通道连续失效,结束本次运行;不能将识别故障当作类目缺失。");
throw error;
}
captureRecoveries++;
writeRunLog("CAPTURE RECOVER: " + captureRecoveries + "/" + CONFIG.captureRecoveryLimit + ";释放失效投影并重新申请本机截屏。");
try {
captureCall("恢复截图授权", CONFIG.capturePermissionTimeoutMs, function () {
images.stopScreenCapture();
if (!requestLocalCapture()) throw new Error("恢复截图授权未获允许");
if (!app.launchPackage(CONFIG.packageName)) throw new Error("截图恢复后无法返回目标应用");
waitStartupPackage(CONFIG.packageName, 10000);
sleep(500);
});
var page = captureCall("恢复后重新识别", CONFIG.recognitionTimeoutMs, readSnapshot);
writeRunLog("CAPTURE RECOVERED: 本机页面识别已恢复。");
return page;
} catch (recoveryError) {
recoveryError.captureFatal = true;
throw recoveryError;
}
}
}
function flipPopupHasAction(items) { return false; }
function isPopupAction(item) {
return isCenteredPopupItem(item) && /^[||]?(?:立即[领颌颁頒]取|领取奖励|开心收下|确认|继续领金币|[领颌]更多金币|看视频领取|立即阅读|领\d+金币吃饭补贴)$/.test(item.text);
}
// 只在手机当前帧采样按钮文字周边背景,不上传像素或图片。
function isDarkButton(frame, item) {
var rect = item.rect;
var values = [];
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 2; y++) {
var px = Math.round(rect.left + (rect.right - rect.left) * (x + 0.5) / 5);
var py = Math.round(y ? rect.bottom - 2 : rect.top + 2);
var color = images.pixel(frame, px, py);
values.push(0.2126 * colors.red(color) + 0.7152 * colors.green(color) + 0.0722 * colors.blue(color));
}
}
values.sort(function (a, b) { return a - b; });
return values[Math.floor(values.length / 2)] < 190;
}
function singleButtonPopupDecision(items) {
if (flipPopupHasAction(items)) return null;
if (first(items, /签到/, isCenteredPopupItem)) return null;
var heading = first(items, /^(?:[.,,。||]*恭喜|[.,,。||]*一共[赢贏]取|今日签到|签到奖励|额外奖励|领取成功|奖励已到账|再看.*(?:视频|秒)|获得奖励)/, isCenteredPopupItem);
var popupFrame = first(items, /^(?:common-info-modalbackground|common-info-modal-background)$/);
if (!heading && popupFrame) heading = first(items, /金币|奖励|签到/, function (item) {
return item.rect.top >= popupFrame.rect.top && item.rect.bottom <= popupFrame.rect.bottom;
});
if (!heading) heading = first(items, /^\d+(?:,\d{3})*(?:金币)?$/, isCenteredPopupItem);
if (!heading) return null;
var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
var center = (item.rect.left + item.rect.right) / 2;
return center >= device.width * 0.2 && center <= device.width * 0.8 &&
item.rect.top >= heading.rect.bottom && item.rect.bottom <= device.height * 0.92;
});
// 广告创意会绘制仿奖励弹窗;无真实弹窗边框或中央关闭时,不能用正文打断广告倒计时。
if ((isAdvertisementPage(items) || countdown(items)) && !popupFrame && !close) return null;
// 必须有前景弹窗证据,避免取背景任务行的立即领取。
if (!close && !rewardReceiptHeading(items) && !findFlipSettlementHeading(items)) return null;
var buttons = matches(items, {test: function () { return true; }}, function (item) {
return isPopupAction(item) && item.rect.top >= heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.5;
});
if (buttons.length !== 1) return null;
if (first(items, /^[||]?(?:坚持退出|退出|取消|暂不使用)$/, isCenteredPopupItem)) return null;
var button = buttons[0];
// 若还存在带金额的操作选项,则不是单按钮弹窗。
if (first(items, /^[||]?(?:领|看视频(?:再得|再领|领))\d+(?:,\d{3})*金币$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom;
})) return null;
var amounts = [];
items.forEach(function (item) {
if (item.rect.top < heading.rect.top || item.rect.bottom > button.rect.top ||
!isCenteredPopupItem(item) || /最高|量高|最多|上限|余额|累计|7天签到必得/.test(item.text)) return;
var re = /(\d+(?:,\d{3})*)金币/g;
var match;
while ((match = re.exec(item.text)) !== null) {
var amount = Number(match[1].replace(/,/g, ""));
if (amounts.indexOf(amount) < 0) amounts.push(amount);
}
if (/^\d+(?:,\d{3})*$/.test(item.text) && first(items, /^金币$/, function (unit) {
return isCenteredPopupItem(unit) && Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08;
})) {
var split = Number(item.text.replace(/,/g, ""));
if (amounts.indexOf(split) < 0) amounts.push(split);
}
});
var take = amounts.length === 1 && amounts[0] >= CONFIG.rewardThreshold && button.darkButton === true;
return {button: take ? button : close, amount: amounts.length === 1 ? amounts[0] : null,
take: take, settlement: !!findFlipSettlementHeading(items)};
}
function findListeningPopupClose(items) {
var heading = first(items, /听读/, isCenteredPopupItem);
if (!heading) return null;
var listening = first(items, /^(?:立即听读|去听读|继续听读)$/, isCenteredPopupItem);
if (!listening) return null;
return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= listening.rect.bottom;
});
}
function findPlaybackPopupDismiss(items) {
if (!first(items, /悬浮窗播放功能|退出直播间后也能继续观看/, isCenteredPopupItem)) return null;
return first(items, /^暂不使用(?:按钮)?$/, isCenteredPopupItem);
}
function liveExitAction(items) {
var dismiss = findPlaybackPopupDismiss(items);
if (dismiss) return {button: dismiss, reason: "不使用直播悬浮窗"};
var confirmation = first(items, /(?:确定|确认|是否|即将).*?(?:退出|离开).*?直播|退出直播间后|离开直播间后/);
var exit = first(items, /^(?:退出直播间|离开直播间|退出直播|确认退出|确定退出|立即退出|退出|离开)$/,
isCenteredPopupItem);
if (exit && (confirmation || first(items, /^(?:继续观看|继续看直播|留在直播间)$/))) {
return {button: exit, reason: "确认退出直播间"};
}
// 用直播间自身控件判定,不能仅因任务列表或广告文案提及“直播”就返回。
var room = first(items, /本场点赞|在线观众/, function (item) {
return item.rect.top < device.height * 0.2;
}) || first(items, /^(?:[·「|]?更多直播[>〉]?|[·]?左滑查看更多直播)$/);
var chat = first(items, /^说点什么$/) && first(items, /^(?:礼物|连线|商品列表|粉丝团)$/);
if (room || chat) return {back: true, reason: "已进入直播页面,立即返回"};
return null;
}
function isAdvertisementPage(items) {
return !!first(items, /^(?:广告(?:[|!!1ご))((].*)?|.*直播间)$/, function (item) {
return item.rect.top < device.height * 0.15;
});
}
function findVideoSurveyDismiss(items) {
if (!first(items, /刚才的视频你觉得如何|评价有助于我们做得更好/)) return null;
return first(items, /^我知道了$/, isCenteredPopupItem);
}
function needsCommonHandling(items) {
if (findQimaoDirectClaim(items)) return true;
if (isMallPage(items)) return false; // 商品文案和红包由商城循环处理。
if (isWelfarePage(items) || isMealPage(items)) {
return !!(findSignInPopupClose(items) || findVideoSurveyDismiss(items) || findQimaoPopupClose(items) || rewardReceiptHeading(items));
}
return !!(isStreetScrollAd(items) || liveExitAction(items) || countdown(items) || isAdvertisementPage(items) || findTopRightClose(items) || findVideoSurveyDismiss(items) || singleButtonPopupDecision(items) || findRewardReceiptClose(items) || findMoreCoinsButton(items) || offerAmount(items));
}
function snapshot() {
var page = readPage("页面识别");
var deadline = Date.now() + CONFIG.stepTimeoutMs;
while (!commonHandling && needsCommonHandling(page)) {
if (Date.now() >= deadline) stopWith("通用页面处理超时,保留当前页面");
writeRunLog("通用规则优先:暂停当前任务,先处理倒计时、关闭或额外奖励。");
handleVideos(/./);
page = readPage("通用处理后重新识别");
// 广告切换或弹窗动画中关闭按钮可能晚一帧出现;重新执行通用规则,不能全局退出。
}
return page;
}
// 小号X常被整屏OCR漏掉;只在手机内存裁剪放大右上区域再识别。
function readCloseRegion(frame, items, region) {
var left = region ? region.left : Math.floor(device.width * 0.55);
var top = region ? region.top : Math.floor(device.height * 0.045);
var width = region ? region.width : device.width - left;
var height = region ? region.height : Math.floor(device.height * 0.22);
var crop = null;
var enlarged = null;
try {
crop = images.clip(frame, left, top, width, height);
enlarged = images.resize(crop, [width * 3, height * 3]);
var results = $ocr.detect(enlarged);
if (!Array.isArray(results)) return;
for (var i = 0; i < results.length; i++) {
var raw = results[i].bounds;
if (!raw) continue;
function at(key) { return Number(typeof raw[key] === "function" ? raw[key]() : raw[key]); }
var rect = rectOf({left: left + at("left") / 3, top: top + at("top") / 3,
right: left + at("right") / 3, bottom: top + at("bottom") / 3});
var value = compact(results[i].text);
if (rect && /^(?:关闭|关闭广告|[xX×✕✖✗✘]|(?:领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕])$/.test(value)) {
items.push({text: /^[xX×✕✖✗✘]$/.test(value) ? "X" : value, rect: rect, node: null});
writeRunLog("局部放大识别关闭:" + value + " @" + Math.round(rect.left) + "," + Math.round(rect.top));
}
}
} finally {
if (enlarged) enlarged.recycle();
if (crop) crop.recycle();
}
}
function readReceiptCloseRegion(frame, items) {
var heading=rewardReceiptHeading(items);
if(!heading || findQimaoDirectClaim(items) || findQimaoPopupClose(items))return;
// 七猫的关闭X在领取层右上方,可能高于标题;仅对已确认的奖励层局部放大。
var upper=Math.max(Math.floor(device.height*0.18),Math.floor(heading.rect.top-device.height*0.18));
readCloseRegion(frame,items,{left:Math.floor(device.width*0.72),top:upper,
width:Math.floor(device.width*0.21),height:Math.floor(heading.rect.bottom+device.height*0.04)-upper});
if(findQimaoPopupClose(items))return;
var action=first(items,/^看(?:小)?视频.*最高(?:可)?(?:再)?领(?:\d+金[币市而])?$/,isCenteredPopupItem);
if(!action)return;
var top=Math.floor(action.rect.bottom),bottom=Math.floor(device.height*0.92);
if(top<bottom)readCloseRegion(frame,items,{left:Math.floor(device.width*0.35),top:top,width:Math.floor(device.width*0.3),height:bottom-top});
}
function readSnapshot() {
keepScreenAwake();
var foreground = foregroundPackage();
var foregroundDeadline = Date.now() + 1500;
while (foreground !== CONFIG.packageName && Date.now() < foregroundDeadline) {
sleep(150);
foreground = foregroundPackage();
}
// 系统浮层可能短暂成为无障碍活动窗口。等待其消失,不能把它当作任务完成。
if (foreground !== CONFIG.packageName && (!foreground || foreground === "com.android.systemui")) {
writeRunLog("FOREGROUND WAIT: 系统界面暂时遮挡七猫,暂停识别与点击。");
foregroundDeadline = Date.now() + 5000;
while ((!foreground || foreground === "com.android.systemui") && Date.now() < foregroundDeadline) {
sleep(200);
foreground = foregroundPackage();
}
if (foreground === CONFIG.packageName) writeRunLog("FOREGROUND RESUMED: 七猫前台恢复,继续当前步骤。");
}
if (foreground !== CONFIG.packageName) {
var foregroundError = new Error("当前不是七猫免费小说页面(" + foreground + "),暂停本步骤");
foregroundError.foregroundTransient = !foreground || foreground === "com.android.systemui";
throw foregroundError;
}
var items = [];
var selectors = [textMatches(/.+/), descMatches(/.+/)];
for (var s = 0; s < selectors.length; s++) {
var nodes = selectors[s].find();
for (var i = 0; i < nodes.size(); i++) {
var node = nodes.get(i);
var rect = rectOf(node.bounds());
var value = compact(s === 0 ? node.text() : node.desc());
if (value && rect && node.visibleToUser()) items.push({text: value, rect: rect, node: node});
}
}
// 直播间动态画面可能拖住截屏/OCR;原生控件已确认直播时直接交给退出规则。
if (localOcrEnabled && !liveExitAction(items)) {
var frame = null;
try {
// captureScreen 返回的原图由 AutoJs 管理,仅回收自己复制的 OCR 图。
frame = images.copy(captureScreen());
// 此适配器要求 detect 返回 [{text, bounds:{left,top,right,bottom}}]。
// 不兼容的 OCR 返回格式会停止,不能把整段文字当作可点击坐标。
var results = $ocr.detect(frame);
if (!Array.isArray(results)) stopWith("本地 OCR 返回格式不兼容,请适配 snapshot();无需上传图片。");
for (var j = 0; j < results.length; j++) {
var box = rectOf(results[j].bounds);
var textValue = compact(results[j].text);
if (textValue && !box) {
writeRunLog("OCR 跳过边界无效的文字:" + textValue);
continue;
}
if (textValue && box) items.push({text: textValue, rect: box, node: null});
}
if (!findTopRightClose(items)) readCloseRegion(frame, items);
if(isStreetScrollAd(items)&&!findStreetClose(items))readCloseRegion(frame,items,{left:0,top:Math.floor(device.height*0.045),width:Math.floor(device.width*0.24),height:Math.floor(device.height*0.10)});
readReceiptCloseRegion(frame, items);
items.forEach(function (item) {
if (isPopupAction(item)) item.darkButton = isDarkButton(frame, item);
});
} finally {
if (frame && typeof frame.recycle === "function") frame.recycle();
}
}
// 同一按钮可能同时被无障碍和 OCR 识别,合并后优先使用无障碍节点。
var unique = [];
for (var n = 0; n < items.length; n++) {
var duplicate = false;
for (var k = 0; k < unique.length; k++) {
if (items[n].text === unique[k].text &&
Math.abs(items[n].rect.left - unique[k].rect.left) < 35 &&
Math.abs(items[n].rect.top - unique[k].rect.top) < 35) duplicate = true;
}
if (!duplicate) unique.push(items[n]);
}
files.write(CONFIG.pageTextPath, JSON.stringify(unique.map(function (item) { return {text: item.text, rect: item.rect, darkButton: item.darkButton}; })));
return unique;
}
function matches(items, pattern, predicate) {
return items.filter(function (item) {
return pattern.test(item.text) && (!predicate || predicate(item));
});
}
function first(items, pattern, predicate) {
var found = matches(items, pattern, predicate);
return found.length ? found[0] : null;
}
function tap(item) {
if (!item) skipStep("没有目标标签,执行下一步骤");
if (!commonHandling) {
var freshPage = snapshot();
var original = item;
item = first(freshPage, {test: function (value) { return value === original.text; }}, function (candidate) {
return Math.abs(candidate.rect.top - original.rect.top) < 40 &&
Math.abs(candidate.rect.left - original.rect.left) < 40;
});
if (!item) skipStep("通用处理后目标标签已改变,跳过旧坐标点击");
}
if (foregroundPackage() !== CONFIG.packageName) stopWith("点击前页面已离开七猫免费小说,已停止。");
var tapX = Math.round((item.rect.left + item.rect.right) / 2);
var tapY = Math.round((item.rect.top + item.rect.bottom) / 2);
writeRunLog("点击:" + item.text + " @" + tapX + "," + tapY);
var ok = false;
if (item.node) {
// 不向上寻找大范围可点击容器,以免触发相邻任务。
try { if (item.node.clickable()) ok = item.node.click(); } catch (e) { ok = false; }
}
if (!ok) ok = press(tapX, tapY, 80);
writeRunLog("点击结果:" + ok);
if (!ok) stopWith("点击失败:" + item.text);
actionSerial++;
sleep(CONFIG.pollMs);
}
function waitFor(pattern, timeout, predicate) {
var deadline = Date.now() + (timeout || CONFIG.pageTimeoutMs);
while (Date.now() < deadline) {
var found = first(snapshot(), pattern, predicate);
if (found) return found;
sleep(CONFIG.pollMs);
}
return null;
}
function isTopRight(item) {
// 倒计时长文字会向左延伸,按文字中心判断,不能只检查左边界。
return (item.rect.left + item.rect.right) / 2 >= device.width * 0.55 &&
item.rect.top < device.height * 0.30;
}
function originalAdCountdown(items) {
return first(items, /(?:\d+(?:\.\d+)?(?:s|S|秒)|倒计时\d*|\d+后(?:关闭|可关闭|领取|可领取))/, function (item) {
if (!isTopRight(item)) return false;
// 广告侧栏“60秒/已完成/点击领取”是完成的时长档位,不是待关闭倒计时。
var completedMilestone = /^\d+(?:s|S|秒)$/.test(item.text.replace(/[^\dA-Za-z\u4e00-\u9fff]/g, "")) && first(items, /^已完成$/, function (label) {
return label.rect.top >= item.rect.bottom &&
label.rect.top - item.rect.bottom < device.height * 0.06 &&
Math.abs(label.rect.left - item.rect.left) < device.width * 0.08;
});
return !completedMilestone;
});
}
function findTopRightClose(items) {
var mainNavigation = bottomNavigation(items, /^(?:首页|书城)$/) && bottomNavigation(items, /^赚钱$/);
var advertisement = isAdvertisementPage(items);
// 首页浮层的无障碍Close Button是真实控件,优先于图片内局部OCR疑似X。
// 现场该关闭在右侧中部,不能只因不在顶端而忽略,随后误点书籍内容。
if (!advertisement && mainNavigation) {
var nativeClose = first(items, /^(?:关闭|关闭广告|关闭窗口|关闭弹窗)$/, function (item) {
return !!item.node && (item.rect.left + item.rect.right) / 2 > device.width * 0.85 &&
item.rect.top < device.height * 0.7 && item.rect.right - item.rect.left < device.width * 0.2 &&
item.rect.bottom - item.rect.top < device.height * 0.12;
});
if (nativeClose) return nativeClose;
}
var close = first(items, /^(关闭|关闭广告|[xX×✕])$/, function (item) {
if (!isTopRight(item)) return false;
// OPPO首页书封被局部放大OCR识别成7×10像素的X,点击实际会打开书。
// 仅排除主导航页中尺寸不足的OCR单字形;原生关闭、明确关闭文案和广告规则保留。
return !(mainNavigation && !advertisement && !item.node && /^[xX×✕]$/.test(item.text) &&
(item.rect.right - item.rect.left < device.width * 0.012 ||
item.rect.bottom - item.rect.top < device.height * 0.008));
});
if (close) return close;
var merged = first(items, /^(领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕]$/, isTopRight);
if (!merged) return null;
// OCR 将状态和 X 合框时,只取末尾关闭字形所在区域,不点击状态文字中心。
var rect = merged.rect;
var glyphWidth = (rect.right - rect.left) / merged.text.length;
return {text: "关闭(" + merged.text + ")", node: null, rect: {
left: rect.right - glyphWidth, right: rect.right, top: rect.top, bottom: rect.bottom
}};
}
// 奖励到账确认是前景弹窗,不能被背景任务、倒计时或领取入口抢占。
function isCenteredPopupItem(item) {
var center = (item.rect.left + item.rect.right) / 2;
return center >= device.width * 0.2 && center <= device.width * 0.8 &&
item.rect.top >= device.height * 0.20 && item.rect.top < device.height * 0.82;
}
function findFlipSettlementHeading(items) { return null; }
function findFlipSettlementButton(items) { return null; }
function findMoreCoinsButton(items) {
return first(items, /^[领颌]更多金币$/, isCenteredPopupItem);
}
function rewardReceiptHeading(items) {
return first(items,/^(?:恭喜(?:你)?(?:已)?(?:累计)?获得(?:奖励)?|恭喜你|获得(?:早餐|早饭|午饭|午餐|晚饭|晚餐|夜宵)补贴)$/,isCenteredPopupItem);
}
function findReceiptEligibleClaim(items) {
var heading = rewardReceiptHeading(items);
if (!heading) return null;
return first(items, /^(?:领|看视频(?:再得|再领|领))\d+金币$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom &&
Number(item.text.replace(/[^\d]/g, "")) >= CONFIG.rewardThreshold;
});
}
function findRewardReceiptClose(items) {
if (flipPopupHasAction(items)) return null;
if (findFlipSettlementHeading(items) || findMoreCoinsButton(items)) return null;
var heading = rewardReceiptHeading(items);
if (!heading) return null;
if (findReceiptEligibleClaim(items)) return null;
var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom;
});
if (close) return close;
// 透明弹窗下方的 X 可能与背景文字合框,只提取末尾字形,不点整段文字。
var merged = first(items, /[xX×✕]$/, function (item) {
var glyphWidth = (item.rect.right - item.rect.left) / item.text.length;
var glyphCenter = item.rect.right - glyphWidth / 2;
return item.rect.top >= heading.rect.bottom && item.rect.top > device.height * 0.45 &&
item.rect.top < device.height * 0.92 && glyphCenter > device.width * 0.35 && glyphCenter < device.width * 0.65;
});
if (!merged) return null;
var width = (merged.rect.right - merged.rect.left) / merged.text.length;
return {text: "关闭奖励弹窗(" + merged.text + ")", node: null, rect: {
left: merged.rect.right - width, right: merged.rect.right,
top: merged.rect.top, bottom: merged.rect.bottom
}};
}
function findEmptyRewardPopupClose(items, ignoreCoinClaim) {
// 前景现金邀请提示不属于金币领取;背景任务行的金币不能阻止关闭。
var cashHeading = first(items, /^送你现金红包$/, isCenteredPopupItem);
if (cashHeading && (first(items, /^邀[请靖]好友立得$/, isCenteredPopupItem) ||
first(items, /^\d+(?:\.\d+)?元$/, isCenteredPopupItem))) {
var cashClose = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
var center = (item.rect.left + item.rect.right) / 2;
return center >= device.width * 0.35 && center <= device.width * 0.65 &&
item.rect.top >= cashHeading.rect.bottom && item.rect.bottom <= device.height * 0.92;
});
if (cashClose) return cashClose;
}
// 中央活动提示没有金币领取入口,只关闭遮挡层,不执行邀请或参与。
var participation = first(items, /^立即参与$/, isCenteredPopupItem);
if (participation) {
var participationClose = first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= participation.rect.bottom;
});
if (participationClose) return participationClose;
}
// 翻卡操作弹窗不是空奖励弹窗;背景“完成阅读任务…奖励”等说明不能触发关闭。
if (flipPopupHasAction(items)) return null;
// 非右上角的 X 需要弹窗文字作依据,不能把普通页面上的 X 当作奖励弹窗。
var heading = first(items, /弹窗|温馨提示|签到|领取成功|恭喜|奖励|再看.*视频|暂无金币|暂无奖励|明日再来|今日已领/);
if (!heading) return null;
// 7天签到累计总额不是本次立即领取金额;关闭遮挡任务列表的无明确金币领取弹窗。
var weekly = first(items, /^7天签到必得[\d.万亿]+金币$/, isCenteredPopupItem);
if (weekly && !first(items, /^(?:领\d+金币|看视频领\d+金币)$/)) {
var weeklyClaim = first(items, /^立即[领颌]取$/, isCenteredPopupItem);
var weeklyClose = weeklyClaim && first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top > weeklyClaim.rect.bottom;
});
if (weeklyClose) return weeklyClose;
}
var claim = first(items, /^(?:立即[领颌]取|领更多金币|领取奖励|看视频领取|领\d+金币|看视频(?:再得|再领|领)\d+金币)$/,
function (item) { return item.rect.top >= heading.rect.top; });
if (claim && !ignoreCoinClaim) return null;
return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
return item.rect.top >= heading.rect.top && item.rect.top < device.height * 0.92;
});
}
function findCoinChoiceClaim(items) {
if (first(items, /签到/, isCenteredPopupItem)) return null;
var heading = first(items, /请选择宝箱奖励|开宝箱奖励|再看.*(?:视频|秒)|额外奖励|领取奖励|恭喜|一共.*金币/);
if (!heading) return null;
var marker = first(items, /^[||]?看视[频頻]奖励$/);
var candidates = matches(items, /^[||]?(?:选|领(?:取)?|直接领(?:取)?|看视频(?:再得|再领|领|得))(\d+(?:,\d{3})*)金币$/, function (item) {
return item.rect.top >= heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.55;
});
if (!candidates.length) return null;
// 仅比较同一行的领取选项,不混入余额、标题金额或其他任务行。
candidates.sort(function (a, b) { return a.rect.top - b.rect.top; });
for (var i = 0; i < candidates.length; i++) {
var anchor = candidates[i];
var row = candidates.filter(function (item) {
return Math.abs(item.rect.top - anchor.rect.top) < device.height * 0.04;
});
if (row.length < 2) continue;
row.sort(function (a, b) {
var amountA = Number(a.text.replace(/[^\d]/g, ""));
var amountB = Number(b.text.replace(/[^\d]/g, ""));
return amountB - amountA || a.rect.left - b.rect.left;
});
if (Number(row[0].text.replace(/[^\d]/g, "")) < CONFIG.rewardThreshold) row.reverse();
return row[0];
}
// 单选视频入口仍可使用明确的“看视频奖励”标签,不对多选位置作假设。
if (marker) return first(candidates, /^[||]?领\d+(?:,\d{3})*金币$/, function (item) {
return Math.abs(item.rect.top - marker.rect.bottom) < device.height * 0.10;
});
return null;
}
function offerAmount(items) {
var heading = first(items, /再看(?:一个|1个|一段|1段)?视频|再[看香]\d+秒|看视频(?:再得|再领|领)\d+金币|看视频.*(?:最高可领|额外|奖励)|^(?:最高可领|最多可领)/,
function (item) {
// 福利列表的收益日报等说明含“看视频/奖励”,须有前景弹窗控件才作为追加奖励。
if (isWelfarePage(items) && !rewardReceiptHeading(items) && !findMoreCoinsButton(items) &&
!first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false;
// 广告右上角“再看19秒后得300金币X”是倒计时状态,不是前景追加奖励弹窗。
if (isTopRight(item) && /\d+(?:\.\d+)?(?:s|S|秒)/.test(item.text)) return false;
// 补贴页常驻“看视频最高可领”说明不是独立弹窗。
if (first(items, MEAL_PAGE) && /看视频.*最高可领/.test(item.text) && !rewardReceiptHeading(items) &&
!first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false;
return true;
});
if (!heading) {
var claimAction = first(items, /^(?:继续领金币|领取奖励)$/, isCenteredPopupItem);
var exitAction = claimAction && first(items, /^[||]?坚持退出$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= claimAction.rect.bottom &&
item.rect.top - claimAction.rect.bottom < device.height * 0.2;
});
// 标题OCR缺失时,用同一前景层的领取/坚持退出组合确认挽留弹窗,金额不猜测。
if (exitAction) return {amount: null, heading: claimAction};
}
var moreButton = findMoreCoinsButton(items);
if (!heading && moreButton) {
var values = [];
var region = items.filter(function (item) {
return isCenteredPopupItem(item) && item.rect.top >= moreButton.rect.top - device.height * 0.4 &&
item.rect.bottom <= moreButton.rect.bottom &&
!/最高|最多|至多|上限|已获得|已领取|本次得|一共|余额|补贴|预约|签到/.test(item.text);
});
region.forEach(function (item) {
var coins = /(\d+(?:,\d{3})*)金币/.exec(item.text);
var split = /^(\d+(?:,\d{3})*)[.。]?$/.exec(item.text);
if (!coins && split && !first(region, /^金币$/, function (unit) {
return Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08;
})) split = null;
var match = coins || split;
if (match) {
var value = Number(match[1].replace(/,/g, ""));
if (values.indexOf(value) < 0) values.push(value);
}
});
var top = Math.max(device.height * 0.2, moreButton.rect.top - device.height * 0.4);
return {amount: values.length === 1 ? values[0] : null, heading: {
text: "领更多金币弹窗", rect: {left: moreButton.rect.left, right: moreButton.rect.right, top: top, bottom: moreButton.rect.bottom}
}};
}
if (!heading) return null;
// 明确写在额外奖励按钮里的金额优先,不能混入弹窗背后“已攒0金币”等文字。
var explicit = /^看视频(?:再得|再领|领)(\d+)金币$/.exec(heading.text);
if (explicit) return {amount: Number(explicit[1]), heading: heading};
if (/最高|量高|最多|至多|上限/.test(heading.text)) return {amount: null, heading: heading};
// 只解析该提示附近的明确金额;“最高可领”是上限,不是已确认奖励。
var nearby = items.filter(function (item) {
return item.rect.top >= heading.rect.top - 30 &&
item.rect.top < heading.rect.bottom + device.height * 0.25;
});
var amounts = [];
for (var i = 0; i < nearby.length; i++) {
if (/最高|最多|至多|上限|补贴|已获得|已领取|领取成功|恭喜/.test(nearby[i].text)) continue;
var amountPattern = /(?:^|[^\d.,])([\d]+(?:,[\d]{3})*)(?:个)?金币/g;
var match;
while ((match = amountPattern.exec(nearby[i].text)) !== null) {
var amount = Number(match[1].replace(/,/g, ""));
if (amounts.indexOf(amount) < 0) amounts.push(amount);
}
}
if (amounts.length !== 1) return {amount: null, heading: heading};
return {amount: amounts[0], heading: heading};
}
function handleVideos(returnPattern, launchGraceMs) {
var previous = commonHandling;
commonHandling = true;
try { return handleVideosLoop(returnPattern, launchGraceMs); }
finally { commonHandling = previous; }
}
function handleVideosLoop(returnPattern, launchGraceMs) {
var launchDeadline = Date.now() + (launchGraceMs || 0);
var deadline = Date.now() + CONFIG.videoTimeoutMs;
var accepted = 0;
var stableReturn = 0;
var actions = 0;
var sawCountdown = false;
var lastWaitLog = 0;
var lastCloseKey = "";
var repeatedClose = 0;
var liveExitAttempts = 0;
var qimaoMissingClose = 0;
while (Date.now() < deadline) {
var items = snapshot();
var qimaoDirect = findQimaoDirectClaim(items);
if (qimaoDirect) {
if (++actions > CONFIG.maxVideos * 4) stopWith("七猫直接领取弹窗多次未响应");
writeRunLog("七猫奖励确认:点击直接领取,不选择最高金额的视频推广选项。");
tap(qimaoDirect);
continue;
}
if (isMallPage(items)) return;
if(isStreetScrollAd(items)){writeRunLog("STREET RESUME: 处理右下角计时的下滑浏览广告。");finishStreetVisit();continue;}
if (isWelfarePage(items) || isMealPage(items)) {
var qimaoClose=findQimaoPopupClose(items) || findSignInPopupClose(items);
if(qimaoClose) { if(++actions>20) stopWith("七猫弹窗关闭多次未响应"); tap(qimaoClose); continue; }
if(rewardReceiptHeading(items)) {
var earnedClaim=findReceiptEligibleClaim(items);
if(earnedClaim){if(++actions>20)stopWith("七猫奖励按钮未响应");tap(earnedClaim);continue;}
if(++qimaoMissingClose<2){sleep(CONFIG.pollMs);continue;}
if(++actions>20)stopWith("七猫奖励弹窗返回关闭未响应");
writeRunLog("QIMAO RECEIPT BACK: 已确认任务到账弹窗,无符合领取按钮,关闭图标未识别,返回关闭后复查。");
back();actionSerial++;sleep(CONFIG.pollMs);qimaoMissingClose=0;continue;
}
if(Date.now()<launchDeadline) { sleep(CONFIG.pollMs); continue; }
return;
}
var surveyDismiss = findVideoSurveyDismiss(items);
if (surveyDismiss) {
if (++actions > CONFIG.maxVideos * 4) stopWith("视频反馈提示关闭未响应");
writeRunLog("视频反馈提示:点击我知道了关闭提示,继续当前任务。");
tap(surveyDismiss);
continue;
}
var signClose = findSignInPopupClose(items);
if (signClose) {
if (++actions > CONFIG.maxVideos * 4) stopWith("签到遮挡弹窗关闭未响应");
writeRunLog("签到流程已移除:关闭签到弹窗,继续当前流程。");
tap(signClose);
continue;
}
var liveExit = liveExitAction(items);
if (liveExit) {
if (++liveExitAttempts > 6) stopWith("连续六次退出直播仍未离开,跳过本步骤并保留现场");
writeRunLog("直播退出优先:" + liveExit.reason + ";不等待直播倒计时,不领取直播奖励。");
if (liveExit.button) tap(liveExit.button);
else {
if (back() === false) stopWith("退出直播的返回键执行失败");
actionSerial++;
sleep(CONFIG.pollMs);
}
continue;
}
liveExitAttempts = 0;
// 重试保护只计算按钮持续存在时的连续失败;新倒计时或按钮消失说明页面已推进。
// 不可把不同广告在同一坐标的X累计为同一按钮未响应。
var observedClose = findTopRightClose(items) || findEmptyRewardPopupClose(items);
if (countdown(items) || !observedClose) {
lastCloseKey = "";
repeatedClose = 0;
}
var listeningClose = findListeningPopupClose(items);
if (listeningClose) {
if (++actions > CONFIG.maxVideos * 4) stopWith("听读弹窗关闭未响应");
writeRunLog("听读选项已取消:直接关闭听读弹窗,不点击听读按钮。");
tap(listeningClose);
continue;
}
var signClaim = findCoinChoiceClaim(items);
if (signClaim) {
if (++actions > CONFIG.maxVideos * 4) stopWith("金币选项多次点击无响应,跳过本步骤");
writeRunLog("通用双金额规则:有>=" + CONFIG.rewardThreshold + "选较大,否则选最小;本次 " + signClaim.text);
tap(signClaim);
continue;
}
var singleDecision = singleButtonPopupDecision(items);
if (singleDecision) {
if (!singleDecision.button) stopWith("单按钮弹窗不符合领取条件,但尚未识别到关闭按钮,保留页面重查");
if (++actions > CONFIG.maxVideos * 4) stopWith("单按钮弹窗处理达到上限");
writeRunLog("通用单按钮规则:正文金币=" + singleDecision.amount + ";" + (singleDecision.take ? "点击深色按钮" : "关闭弹窗"));
tap(singleDecision.button);
if (singleDecision.settlement) { flipSettlementDone = true; flipActionDone = true; }
continue;
}
var settlement = findFlipSettlementButton(items);
if (settlement) {
if (++actions > CONFIG.maxVideos * 4) stopWith("翻卡结算按钮多次未响应");
writeRunLog("翻卡结算:点击开心收下,完成翻卡流程。");
tap(settlement);
flipSettlementDone = true;
flipActionDone = true;
continue;
}
if (findFlipSettlementHeading(items)) stopWith("未识别到翻卡结算的开心收下按钮,等待重新识别");
var receipt = findRewardReceiptClose(items);
if (receipt) {
if (++actions > CONFIG.maxVideos * 4) stopWith("奖励确认多次点击未响应");
writeRunLog("通用规则:奖励弹窗没有金币领取按钮,点击关闭");
tap(receipt);
continue;
}
var eligibleClaim = findReceiptEligibleClaim(items);
// 广告正文也会显示“恭喜获得/金币”;只有实际领取入口才进入领取分支。
// 缺少入口时继续判断倒计时和右上关闭,不能让背景文案中断通用处理。
if (eligibleClaim && !findMoreCoinsButton(items)) {
if (++actions > CONFIG.maxVideos * 4 || accepted >= CONFIG.maxVideos) stopWith("奖励弹窗处理达到上限");
writeRunLog("通用规则:奖励按钮金额>=" + CONFIG.rewardThreshold + "金币,点击领取");
tap(eligibleClaim);
accepted++;
continue;
}
var offer = offerAmount(items);
if (offer && (!flipPopupHasAction(items) || offer.amount >= CONFIG.rewardThreshold)) {
stableReturn = 0;
if (++actions > CONFIG.maxVideos * 4) stopWith("弹窗处理次数达到上限,页面可能没有响应,已停止。");
var take = offer.amount !== null && offer.amount >= CONFIG.rewardThreshold;
var button = first(items, take ? /^(领取奖励|领更多金币|颌更多金币|确认|继续领金币|看视频领取|看视频领\d+金币|看视频(?:再得|再领|领)\d+金币)$/ : /^[||]?(坚持退出|退出|[xX×✕])$/,
function (item) { return item.rect.top >= offer.heading.rect.top &&
item.rect.top < offer.heading.rect.bottom + device.height * 0.30; });
if (!button && !take) button = findEmptyRewardPopupClose(items, true);
if (!button) stopWith("未识别到额外奖励的" + (take ? "确认" : "退出") + "按钮,已停止。");
if (take && accepted >= CONFIG.maxVideos) stopWith("已达到本次视频数量上限,停止继续领取。");
writeRunLog("额外奖励 " + (offer.amount === null ? "金额不明确" : offer.amount + " 金币") + ":" + (take ? "继续观看" : "退出"));
tap(button);
if (take) { accepted++; sawCountdown = false; }
deadline = Date.now() + CONFIG.videoTimeoutMs;
continue;
}
var popupClose = findEmptyRewardPopupClose(items);
var foregroundClose = popupClose && !isTopRight(popupClose) ? popupClose : null;
// 前景弹窗的动作先处理,背景倒计时和背景右上X不能抢占。
var timer = foregroundClose ? null : countdown(items);
if (timer) {
if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) {
writeRunLog("通用规则等待倒计时:" + timer.text);
lastWaitLog = Date.now();
}
sawCountdown = true;
stableReturn = 0;
sleep(CONFIG.pollMs);
continue;
}
if (flipPopupHasAction(items) && !findTopRightClose(items) && !foregroundClose) {
writeRunLog("翻卡优先:仍有带翻字的按钮,不执行通用弹窗关闭,继续翻卡。");
return;
}
var close = foregroundClose || findTopRightClose(items) || popupClose;
if (close) {
if (++actions > CONFIG.maxVideos * 4) stopWith("关闭次数达到上限,页面可能没有响应,已停止。");
stableReturn = 0;
// 再取一次本机页面,避免倒计时刚刷新时点到关闭。
sleep(CONFIG.pollMs);
var fresh = snapshot();
if (liveExitAction(fresh)) continue;
if (flipPopupHasAction(fresh) && !findTopRightClose(fresh) && !findEmptyRewardPopupClose(fresh)) continue;
if (findRewardReceiptClose(fresh) || offerAmount(fresh) || findCoinChoiceClaim(fresh)) continue;
var freshPopupClose = findEmptyRewardPopupClose(fresh);
var freshForegroundClose = freshPopupClose && !isTopRight(freshPopupClose) ? freshPopupClose : null;
if (!freshForegroundClose && countdown(fresh)) { sawCountdown = true; continue; }
close = freshForegroundClose || findTopRightClose(fresh) || freshPopupClose;
if (close) {
var closeKey = close.text + ":" + Math.round(close.rect.left / 20) + ":" + Math.round(close.rect.top / 20);
repeatedClose = closeKey === lastCloseKey ? repeatedClose + 1 : 1;
lastCloseKey = closeKey;
if (repeatedClose > 3) stopWith("同一关闭按钮连续三次未响应,跳过本步骤");
tap(close);
}
continue;
}
if (isAdvertisementPage(items)) {
if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) {
writeRunLog("广告仍在前台,等待倒计时/关闭控件刷新,不把背景任务判为缺失。");
lastWaitLog = Date.now();
}
sleep(CONFIG.pollMs);
continue;
}
// 广告可能在点击领取数秒后才出现;启动宽限期内继续识别,避免提前结束。
if (Date.now() < launchDeadline) { sleep(CONFIG.pollMs); continue; }
// 无倒计时、无关闭、无额外奖励就交还调度,不等待旧的返回页标签。
writeRunLog("通用规则:当前无可执行条件,继续下一步骤。");
return;
}
stopWith("等待视频结束或目标页面超时,已停止;未用返回键跳过倒计时。");
}
function bottomNavigation(items, pattern) {
return first(items, pattern, function (item) { return item.rect.top > device.height * 0.9; });
}
function findSignInPopupClose(items) {
if (flipPopupHasAction(items)) return null;
var heading = first(items, /签到/, isCenteredPopupItem);
if (!heading) return null;
return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom;
});
}
function searchTaskAction(finder, actionName, relatedPattern, logPrefix) {
var entry = finder(snapshot());
if (entry) return entry;
for (var direction = 0; direction < 2; direction++) {
var lastKey = "";
var stationary = 0;
for (var i = 0; i < CONFIG.taskSearchScrolls; i++) {
var moved = swipe(Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.8 : 0.35)),
Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.35 : 0.8)), 450);
sleep(CONFIG.pollMs);
var page = snapshot();
writeRunLog((logPrefix || "TASK SEARCH") + ": " + actionName + ";" + (direction ? "向下" : "向上") + (i + 1) + ";滑动=" + moved + ";相关文字=" +
matches(page, relatedPattern || /补贴|翻卡|海量|立即领取/).map(function (item) { return item.text; }).join("、"));
entry = finder(page);
if (entry) return entry;
var nativePage=page.filter(function(item){return !!item.node && item.text.length<60 && !/^[A-Za-z0-9_=+\/]{12,}$/.test(item.text);});
var key = (nativePage.length ? nativePage : page).map(function (item) {
return item.text.replace(/\d+/g, "#") + ":" + Math.round(item.rect.top / 80);
}).sort().join("|");
stationary = key === lastKey ? stationary + 1 : 0;
lastKey = key;
if (stationary >= 2) break;
}
}
return null;
}
function rawPage() { return readPage("七猫任务识别"); }
function tapKnown(item) {
var previous=commonHandling; commonHandling=true;
try { tap(item); } finally { commonHandling=previous; }
}
function topTab(items, name) {
return first(items, {test:function(t){return t===name;}}, function(i){return i.rect.top<device.height*0.14;});
}
function isMallPage(items) {
var mall=topTab(items,"福利商城"), center=topTab(items,"福利中心");
if(!mall || !bottomNavigation(items,/^福利$/))return false;
if(center && Math.abs((mall.rect.bottom-mall.rect.top)-(center.rect.bottom-center.rect.top))>8)
return mall.rect.bottom-mall.rect.top>center.rect.bottom-center.rect.top;
return !!first(items,/^签到浏览商品可领|^成功浏览商城|^抖音商城推荐$/);
}
function isWelfarePage(items) {
var center=topTab(items,"福利中心"), mall=topTab(items,"福利商城");
if (!center || !bottomNavigation(items,/^福利$/) || isMallPage(items)) return false;
return !!(!mall || center.rect.bottom-center.rect.top>(mall.rect.bottom-mall.rect.top)*1.12 ||
first(items,/^日常福利$|^吃饭补贴|^逛[街衛衔商城]+[赚賺嫌]金[币市]/));
}
function isMealPage(items) {
if (bottomNavigation(items,/^福利$/)) return false;
return !!(first(items,/^领取(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)补贴/) ||
(first(items,/^(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)$/) && first(items,/^看视频补领(?:一次补贴)?$|可领.*补贴|^吃饭补贴$/)));
}
function findQimaoDirectClaim(items) {
if (streetCountdown(items) || isAdvertisementPage(items)) return null;
var heading=first(items,/^(?:获得.*奖励|恭喜(?:你)?获得)/,isCenteredPopupItem);
if (!heading) return null;
var buttons=matches(items,/^直[接援]领取$/,function(i){return isCenteredPopupItem(i)&&i.rect.top>heading.rect.bottom;});
buttons.sort(function(a,b){return b.rect.top-a.rect.top;});
return buttons.length ? buttons[0] : null;
}
function findQimaoPopupClose(items) {
var heading=first(items,/^(?:恭喜|获得.*奖励|温馨提示|今日签到|签到奖励)/,isCenteredPopupItem);
if (!heading || findQimaoDirectClaim(items)) return null;
return first(items,/^(?:关闭|关闭弹窗|[xX×✕])$/,function(i){
return i.rect.top>=heading.rect.top-device.height*0.18 && i.rect.top<device.height*0.90 &&
i.rect.left>device.width*0.15 && i.rect.right<device.width*0.92;
});
}
function streetLowerCountdown(items) {
if(bottomNavigation(items,/^福利$/)||!first(items,/^穿山甲广告$/))return null;
return first(items,/^\d{1,3}\s*(?:秒|s|S)$/,function(i){
return i.rect.left>device.width*0.75&&i.rect.top>device.height*0.65&&i.rect.bottom<device.height*0.92;
});
}
function streetScrollReward(items) {
if(bottomNavigation(items,/^福利$/)||!first(items,/^穿山甲广告$/))return null;
return first(items,/^(?:已发放|奖励已发放[~~。!!]?|已领取|奖励已到账)$/,function(i){
return i.rect.left>device.width*0.75&&i.rect.top>device.height*0.65&&i.rect.bottom<device.height*0.92;
});
}
function isStreetScrollAd(items) {
if(bottomNavigation(items,/^福利$/)||!first(items,/^穿山甲广告$/))return false;
return !!(streetLowerCountdown(items)||streetScrollReward(items)||first(items,/需要下滑浏览更多.*领取奖励|奖励已发放/,function(i){return i.rect.top<device.height*0.2;}));
}
function findStreetClose(items) {
var close=findTopRightClose(items);if(close)return close;
if(!isStreetScrollAd(items))return null;
return first(items,/^(?:关闭|关闭广告|[xX×✕])$/,function(i){return i.rect.left<device.width*0.22&&i.rect.top<device.height*0.14;});
}
function streetCountdown(items) {
return first(items,/(?:浏览页面.*秒后|秒后即可获得奖|秒后可.*奖励)/,function(i){return i.rect.top<device.height*0.14;})||streetLowerCountdown(items);
}
function streetFinished(items) {
return streetScrollReward(items)||first(items,/恭喜.*获得奖励|奖励已到账|奖励已发放|领取成功|已获得奖励/,function(i){return i.rect.top<device.height*0.14;});
}
function countdown(items) { return streetCountdown(items) || originalAdCountdown(items); }
function findMallTimer(items) {
return first(items,/^\d{1,3}\s*(?:[sS秒]|秒后.*)$/,function(i){return i.rect.left>device.width*0.78 && i.rect.top>device.height*0.55 && i.rect.bottom<device.height*0.9;});
}
function findMallClaim(items) {
return first(items,/^[||]?领金[币市]$/,function(i){return i.rect.left>device.width*0.78 && i.rect.top>device.height*0.55 && i.rect.bottom<device.height*0.9;});
}
function findMallContinue(items) {
var heading=first(items,/^成功浏览商城.*奖励|^恭喜(?:你)?获得/,isCenteredPopupItem);
if (!heading) return null;
return first(items,/^(?:去|继续)?逛商城$/,function(i){return isCenteredPopupItem(i)&&i.rect.top>heading.rect.bottom&&i.rect.top<device.height*0.82;});
}
function waitQimaoNavigation(page, finder, name) {
var until=Date.now()+CONFIG.navigationTimeoutMs, logged=false, previous=null;
while(true) {
var target=finder(page);
// 启动动画中导航会先出现在屏幕边缘,再移动到最终位置;稳定两帧才点击。
if(target && previous && Math.abs(target.rect.top-previous.rect.top)<device.height*0.005 &&
Math.abs(target.rect.bottom-previous.rect.bottom)<device.height*0.005 &&
Math.abs(target.rect.left-previous.rect.left)<device.width*0.01 &&
Math.abs(target.rect.right-previous.rect.right)<device.width*0.01)return {page:page,target:target};
previous=target;
if(Date.now()>=until)stopWith("等待"+name+"加载超时,尚未确认进入福利中心");
if(!logged){writeRunLog("NAV WAIT: 等待"+name+"加载,启动画面或过渡帧不作为任务无匹配。");logged=true;}
sleep(CONFIG.pollMs);
page=snapshot(); // 弹窗/广告通用规则仍优先,之后重新取当前导航。
}
}
function openWelfareCenter(force) {
var page=snapshot();
// 重启时可能仍在商城领奖弹窗;先点已识别的继续按钮,避免导航点击落在遮罩上。
for(var pending=0;pending<2 && findMallContinue(page);pending++) {
writeRunLog("NAV MODAL: 先处理商城领奖弹窗,再返回福利中心。");
tapKnown(findMallContinue(page));sleep(CONFIG.pollMs);page=rawPage();
}
if(findMallContinue(page))stopWith("商城领奖弹窗尚未响应,保留现场");
if(!force && isWelfarePage(page)) return page;
if(isMealPage(page) && !rewardReceiptHeading(page)){back();actionSerial++;sleep(CONFIG.pollMs);page=snapshot();}
var navigation=waitQimaoNavigation(page,function(items){return bottomNavigation(items,/^福利$/);},"底部福利导航");
tapKnown(navigation.target);
page=rawPage();
navigation=waitQimaoNavigation(page,function(items){return topTab(items,"福利中心");},"顶部福利中心");
tapKnown(navigation.target);
var until=Date.now()+CONFIG.pageTimeoutMs;
do {page=snapshot();if(isWelfarePage(page))return page;sleep(CONFIG.pollMs);}while(Date.now()<until);
stopWith("点击顶部福利中心后仍未确认任务页");
}
function taskRowButton(items, labelPattern, actionPattern) {
var labels=matches(items,labelPattern,function(i){return i.rect.top>device.height*0.10&&i.rect.bottom<device.height*0.91&&i.rect.left<device.width*0.5;});
return first(items,actionPattern,function(button){
if(button.rect.left<device.width*0.68 || /已完成|明日|上限|已领完|次数用完|冷却/.test(button.text))return false;
return labels.some(function(label){return Math.abs((button.rect.top+button.rect.bottom-label.rect.top-label.rect.bottom)/2)<device.height*0.05;});
});
}
function searchQimaoTask(labelPattern, actionPattern, name) {
var seen=false;
var button=searchTaskAction(function(page){if(first(page,labelPattern))seen=true;return taskRowButton(page,labelPattern,actionPattern);},name,labelPattern,"QIMAO SEARCH");
if(button && (button.rect.top>device.height*0.72 || button.rect.top<device.height*0.24)) {
var low=button.rect.top>device.height*0.72;
writeRunLog("TASK CENTER: "+name+"入口靠近屏幕边缘,滑到中部后重新识别,避开浮动宝箱。");
swipe(Math.round(device.width*0.45),Math.round(device.height*(low?0.78:0.32)),Math.round(device.width*0.45),Math.round(device.height*(low?0.48:0.56)),450);
sleep(CONFIG.pollMs);
button=taskRowButton(snapshot(),labelPattern,actionPattern);
}
return {labelFound:seen,button:button};
}
function mealClaimKey(item) { var name=item.text.replace(/^[||]/, "").replace(/\d+金[币市]$/, ""); return name+(/^领取/.test(name)?":main":":"+Math.round((item.rect.left+item.rect.right)/160)); }
function findQimaoMealClaim(items, unavailable) {
if(!isMealPage(items))return null;
function available(i){return !unavailable[mealClaimKey(i)];}
return first(items,/领一次补贴$/,available) ||
first(items,/^领取(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)补贴(?:\d+金[币市])?$/,available) ||
first(items,/^[||]?看视频补领$/,available);
}
function findMealEntry(items) {
return first(items,/^吃饭补贴$/,function(i){return i.rect.top>device.height*0.10 && i.rect.top<device.height*0.32;}) ||
taskRowButton(items,/^吃饭补贴/,/^(?:去领取|去补领|领金币)$/);
}
function searchMealEntry() {
return searchTaskAction(findMealEntry,"吃饭补贴(含去补领)",/^吃饭补贴/,"QIMAO SEARCH");
}
function waitForMealPage() {
var until=Date.now()+CONFIG.pageTimeoutMs;
do {
var page=snapshot();
if(isMealPage(page))return page;
sleep(CONFIG.pollMs);
} while(Date.now()<until);
stopWith("等待吃饭补贴页面加载超时,不把空白过渡帧当作任务完成");
}
function qimaoMealStep() {
var page=snapshot();
if(!isMealPage(page)) {
openWelfareCenter(false);
page=snapshot();
var entry=searchMealEntry();
if(!entry) {writeRunLog("MEAL SKIP: 没有吃饭补贴对应领取入口,继续逛街。");return;}
tapKnown(entry);
page=waitForMealPage();
}
var unavailable={},repeats={},empty=0;
var deadline=Date.now()+CONFIG.mealSessionTimeoutMs;
while(Date.now()<deadline) {
page=snapshot();
if(isWelfarePage(page)) {
var resumeEntry=searchMealEntry();
if(!resumeEntry)skipStep("奖励弹窗退出后没有补贴入口,继续下一步骤");
tapKnown(resumeEntry);page=waitForMealPage();
}
if(!isMealPage(page))stopWith("补贴领取后尚未回到补贴页,不把未知页面当作领取结束");
var claim=findQimaoMealClaim(page,unavailable);
if(!claim) {
empty++;writeRunLog("MEAL EMPTY: 当前饭点与看视频补领均无可执行项 "+empty+"/2");
if(empty<2){sleep(CONFIG.pollMs);continue;}
back();actionSerial++;sleep(CONFIG.pollMs);openWelfareCenter(false);
writeRunLog("MEAL DONE: 补贴页连续两次无领取入口,返回福利中心。");return;
}
empty=0;
var key=mealClaimKey(claim);
if((repeats[key]||0)>=3){unavailable[key]=true;writeRunLog("MEAL UNAVAILABLE: 同一补贴按钮三次未消失,本轮跳过并查其他补贴。");continue;}
repeats[key]=(repeats[key]||0)+1;
writeRunLog("MEAL CLAIM: "+claim.text+";本位置第"+repeats[key]+"次");
var beforeClaim=actionSerial;
tapKnown(claim);
handleVideos(MEAL_PAGE,10000);
if(actionSerial>beforeClaim+1)repeats[key]=0; // 广告关闭或奖励处理说明已推进,不累计为未响应重试。
}
stopWith("吃饭补贴达到异常保护时限,保留现场");
}
function finishStreetVisit() {
var until=Date.now()+CONFIG.browseCycleTimeoutMs,lastLog=0;
while(Date.now()<until) {
var page=rawPage(),timer=streetCountdown(page)||originalAdCountdown(page);
if(timer) {
if(!lastLog||Date.now()-lastLog>15000){writeRunLog("STREET WAIT: "+timer.text+(isStreetScrollAd(page)?";下滑浏览推进计时":""));lastLog=Date.now();}
if(isStreetScrollAd(page))swipe(Math.round(device.width*0.45),Math.round(device.height*0.78),Math.round(device.width*0.45),Math.round(device.height*0.40),450);
sleep(CONFIG.pollMs);continue;
}
var done=streetFinished(page);
if(done) {
// X在倒计时期间也存在,必须先识别完成文案再允许关闭。
var close=findStreetClose(page);
if(close){writeRunLog("STREET CLOSE: 完成标记="+done.text);tapKnown(close);}
else {writeRunLog("STREET BACK: 已确认获得奖励,关闭未识别,返回任务页。");back();sleep(CONFIG.pollMs);}
var returned=snapshot();
if(isWelfarePage(returned))return true;
continue;
}
if(isWelfarePage(page)){snapshot();return true;}
sleep(CONFIG.pollMs);
}
stopWith("逛街倒计时或关闭超时,未用返回键跳过计时");
}
function mallCycle() {
var until=Date.now()+CONFIG.browseCycleTimeoutMs,empty=0,claimedAt=0,lastLog=0,up=true;
while(Date.now()<until) {
var page=rawPage();
var again=findMallContinue(page);
if(again){writeRunLog("MALL CONTINUE: 点击红包弹窗的"+again.text);tapKnown(again);return {again:true};}
if(!isMallPage(page)) {
if(isWelfarePage(page))return {done:true};
stopWith("商城循环进入未知页面,保留现场,不把它当作红包已结束");
}
var timer=findMallTimer(page),claim=findMallClaim(page);
if(claim && !timer) {
writeRunLog("MALL CLAIM: 右下角倒计时结束,点击红包领金币。");
tapKnown(claim);claimedAt=Date.now();empty=0;continue;
}
if(timer) {
empty=0;
if(!lastLog||Date.now()-lastLog>15000){writeRunLog("MALL WAIT: 右下角红包="+timer.text+";交替上下滑动。");lastLog=Date.now();}
swipe(Math.round(device.width*0.45),Math.round(device.height*(up?0.78:0.42)),Math.round(device.width*0.45),Math.round(device.height*(up?0.42:0.78)),450);
up=!up;sleep(CONFIG.pollMs);continue;
}
if(claimedAt && Date.now()-claimedAt<10000){sleep(CONFIG.pollMs);continue;}
empty++;writeRunLog("MALL EMPTY: 没有红包倒计时、领金币或继续逛商城,复查"+empty+"/2");
if(empty>=2) {
var close=findQimaoPopupClose(page);if(close)tapKnown(close);
openWelfareCenter(false);
return {done:true};
}
sleep(5000);
}
stopWith("商城单轮红包等待超时,保留现场,不继续点击商品");
}
function runMallLoop() {
var rounds=0;
while(true) {
var result=runStep("商城红包第"+(rounds+1)+"轮",mallCycle,CONFIG.browseCycleTimeoutMs+5000);
if(!result.ok||result.skipped)return {ok:false};
rounds++;
writeRunLog("MALL ROUND: 第"+rounds+"轮处理结束。");
if(result.value.done){writeRunLog("MALL DONE: 没有下一步符合条件的红包或继续入口,已退出商城。");return {ok:true,rounds:rounds};}
}
}
function shoppingAction(mode, button) {
var before=rawPage();
tapKnown(button);
var until=Date.now()+15000,responded=false;
while(Date.now()<until) {
var page=rawPage();
if(mode==="mall"&&isMallPage(page))return {mall:true};
if(streetCountdown(page)||streetFinished(page))return {street:finishStreetVisit(),responded:true};
if(findQimaoDirectClaim(page)||findQimaoPopupClose(page)) {handleVideos(/福利中心/,3000);return {responded:true};}
if(!isWelfarePage(page)) {
if(isAdvertisementPage(page)||originalAdCountdown(page)||findTopRightClose(page)){handleVideos(/福利中心/,10000);return {responded:true};}
sleep(CONFIG.pollMs);continue;
}
var updated=taskRowButton(page,mode==="street"?STREET_LABEL:MALL_LABEL,/逛|^领金[币市]$/);
if(!updated || updated.text!==button.text)responded=true;
sleep(CONFIG.pollMs);
}
if(!isWelfarePage(rawPage()))stopWith("点击任务后等待页面加载超时,保留现场");
return {responded:responded};
}
function runShoppingTask(mode) {
var label=mode==="street"?STREET_LABEL:MALL_LABEL,name=mode==="street"?"逛街赚金币":"逛商城赚金币";
var rounds=0,empty=0,unresponsive=0,foregroundRetries=0;
while(true) {
var searched=runStep("查找"+name,function(){openWelfareCenter(false);return searchQimaoTask(label,/逛|^领金[币市]$/,name);});
if(!searched.ok||searched.skipped) {
if(searched.retryable && foregroundRetries++<2){sleep(CONFIG.pollMs);continue;}
return {ok:false};
}
var target=searched.value;
if(!target.button) {
empty++;writeRunLog("TASK EMPTY: "+name+";"+(target.labelFound?"标签存在但右侧没有逛字或领金币按钮":"没有找到标签")+";复查"+empty+"/2");
if(empty<2){sleep(CONFIG.pollMs);continue;}
writeRunLog("TASK DONE: "+name+"连续两次无符合入口,共"+rounds+"轮。");return {ok:true};
}
empty=0;
var acted=runStep(name+"第"+(rounds+1)+"轮",function(){return shoppingAction(mode,target.button);},CONFIG.browseCycleTimeoutMs+20000);
if(!acted.ok||acted.skipped) {
if(acted.retryable && foregroundRetries++<2){writeRunLog("TASK RETRY: 系统遮挡后重新识别同一任务,不使用旧按钮坐标。");sleep(CONFIG.pollMs);continue;}
return {ok:false};
}
foregroundRetries=0;
if(acted.value.mall)return runMallLoop();
rounds++;
unresponsive=acted.value.responded?0:unresponsive+1;
if(unresponsive>=2){writeRunLog("TASK UNAVAILABLE: 两次点击后没有页面或按钮变化,跳过当前任务以继续后续流程。");return {ok:false,skipped:true};}
writeRunLog("TASK RECHECK: "+name+"第"+rounds+"轮结束,重新查找同一任务标签和按钮。");
}
}
function runDaily() {
files.write(CONFIG.logPath,"");
writeRunLog("START: version="+CONFIG.version+";七猫;仅手机本地识别。");
var me=engines.myEngine();writeRunLog("SOURCE: "+me.getSource());
engines.all().forEach(function(e){if(e.id!==me.id && /(?:fanqie-daily|hongguo-daily|qimao-(?:daily|inspect))\.auto\.js$/.test(String(e.getSource())))e.forceStop();});
keepScreenAwake();
var init=runStep("初始化本地OCR",initLocalOcr,CONFIG.capturePermissionTimeoutMs+5000);
if(!init.ok||!localOcrEnabled)stopWith("本地OCR未就绪");
var startup=runStep("启动七猫免费小说",restartTargetApp,45000);
if(!startup.ok)stopWith("七猫启动失败");
var entered=runStep("底部福利与顶部福利中心",function(){openWelfareCenter(true);});
if(!entered.ok||entered.skipped){writeRunLog("END: 福利中心导航未完成,保留现场与文字日志。");return;}
writeRunLog("FLOW: 福利中心 -> 吃饭补贴 -> 逛街赚金币循环 -> 逛商城赚金币红包循环。");
var meal=runStep("吃饭补贴",qimaoMealStep,CONFIG.mealSessionTimeoutMs+5000);
if(!meal.ok&&!isWelfarePage(rawPage())){writeRunLog("END INCOMPLETE: 吃饭补贴异常且尚未返回福利中心,保留现场。");return;}
var street=runShoppingTask("street");
if(!street.ok&&!isWelfarePage(rawPage())){writeRunLog("END: 逛街流程异常未返回福利中心,保留现场与文字日志。");return;}
var mall=runShoppingTask("mall");
// 商城没有红包只代表商城结束。此前逛街可能被系统浮层打断,必须再查同一标签。
var recheck=runStep("结束前复查逛街剩余入口",function(){
openWelfareCenter(false);
return searchQimaoTask(STREET_LABEL,/逛|^领金[币市]$/,"复查逛街赚金币");
});
if(recheck.ok && !recheck.skipped && recheck.value.button) {
writeRunLog("FLOW RESUME: 商城结束后仍有逛街入口,继续剩余逛街与领取流程。");
street=runShoppingTask("street");
} else if(recheck.ok && !recheck.skipped) street={ok:true};
else street={ok:false};
writeRunLog(mall.ok && street.ok ? "END: 已配置流程执行结束,逛街入口已复查。" :
"END INCOMPLETE: 仍有步骤异常或未响应,不能判定全部任务完成;查看最近的 STEP SKIP/TASK UNAVAILABLE。");
}
// 管理器暂停/超时强停引擎时也释放本脚本的亮屏锁。
if (typeof events !== "undefined" && typeof events.on === "function") events.on("exit", releaseScreenAwake);
try { runDaily(); }
catch(error){writeRunLog("ERROR: "+error+"\n"+error.stack);toastLog("七猫本轮结束:"+error);throw error;}
finally {
try{images.stopScreenCapture();}catch(e){}
if(captureWorker&&captureWorker.isAlive())captureWorker.interrupt();
try{releaseScreenAwake();}catch(e){}
// 业务返回后清理本脚本的事件资源及空闲等待,让管理器收到正常结束事件。
// 保留 catch 中的原异常;不能用 exit() 把结束变成 ScriptInterruptedException。
try{if(typeof events!=="undefined"&&typeof events.recycle==="function")events.recycle();}catch(e){log(String(e));}
}