app_auto_all/fanqie_auto/fanqie-daily.auto.js

3596 lines
190 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.

"auto";
// Auto.js / AutoX.js / AutoJs6:启动后打开番茄小说,并识别可恢复的当前页面。
// 页面识别:无障碍文字 + 可选的本地 $ocr.detect;图片不上传、不写入日志。
// 签到、翻卡循环、预约/现金签到、红包10连开、出版物阅读与挑战;通用弹窗优先。
var CONFIG = {
version: "2026-10-27-tasks-124-common-progress",
packageName: "com.dragon.read",
rewardThreshold: 500,
pollMs: 1200,
pageTimeoutMs: 5000,
videoTimeoutMs: 180000,
maxVideos: 15,
maxScrolls: 1,
stepTimeoutMs: 240000,
mealSessionTimeoutMs: 1800000,
mealBusyRetries: 2,
mealBusyRetryMs: 5000,
redPacketSessionTimeoutMs: 21600000,
flipSessionTimeoutMs: 1800000,
flipTaskTimeoutMs: 21600000,
dramaRoundWatchMs: 180000,
dramaEpisodeStallMs: 150000,
dramaPollMs: 4000,
readingPagePauseMs: 1800,
readingCountdownClearMs: 2000,
readingSessionTimeoutMs: 21600000,
recognitionTimeoutMs: 15000,
captureRecoveryLimit: 2,
capturePermissionTimeoutMs: 60000,
useLocalOcr: true,
logPath: "/sdcard/Download/fanqie-daily-run.log",
publicationStatePath: "/sdcard/Download/fanqie-publication-state.json",
pageTextPath: "/sdcard/Download/fanqie-daily-page.json"
};
var localOcrEnabled = false;
var commonHandling = false;
var liveReturnPending = false;
var actionSerial = 0;
var mealPageDone = false;
var mealUnavailableClaims = {};
var mealBusyFeedback = null;
var activeTaskFlow = null;
var lastTaskFlowAction = null;
var activityBusyObserverActive = false;
var treasureAttemptedAmounts = {};
var topCoinAttemptedAmounts = {};
var readingChallengeClaims = {};
var readingChallengeClaimActive = false;
var additionalTasksChecked = false;
var dramaClaimAttempts = {};
var dramaClaimActive = false;
var dramaBusySkipped = false;
var flipEntryOpened = false;
var flipActionDone = false;
var flipSettlementDone = false;
var FLIP_BUTTON = /翻/;
var captureQueue = null;
var captureWorker = null;
var captureRecoveries = 0;
var MEAL_PAGE = /饭点领金[币市而][补孙朴]贴/;
var MEAL_ENTRY = /^[||]?(?:领)?(?:吃饭补贴|饭点补贴)(?:$|[O0〇○●©◎:\d])/;
var PUBLICATION_LABEL = /^(?:[||「『]?读出版物|.{0,3}出版物[赚賺嫌廉][金全][币市])/;
var STREAK_SECTION = /连续(?:(?:5|五)(?:天|日)|[领颌]{1,2}吃饭补贴第\d+天)/;
function writeRunLog(message) {
var line = new Date().toISOString() + " " + message;
log(line);
files.append(CONFIG.logPath, line + "\n");
}
// BEGIN SHARED SCREEN AWAKE
// 独立亮屏锁 + 可恢复的系统超时租约;多引擎只在最后一个使用者退出时恢复原设置。
function createScreenAwake(runtime) {
var nextRefresh = 0, active = false, settingHeld = false, permissionLogged = false;
function report(message) { if (runtime.log) runtime.log("SCREEN AWAKE: " + message); }
function livingOwners(state) {
var alive = runtime.aliveOwners();
return (state.owners || []).filter(function (owner) { return alive.indexOf(owner) >= 0; });
}
function claimSetting() {
if (!runtime.canWrite()) {
if (!permissionLogged) { report("未获修改系统设置权限,仅使用独立亮屏锁。"); permissionLogged = true; }
return;
}
runtime.locked(function () {
var current = runtime.readTimeout(), state = runtime.readState();
if (!state) state = {originalTimeout: current, owners: []};
state.owners = livingOwners(state);
// 崩溃遗留的24小时值沿用日志中的原值,用户另行修改过则以当前值为准。
if (!state.owners.length && current !== runtime.timeoutMs) state.originalTimeout = current;
if (state.owners.indexOf(runtime.owner) < 0) state.owners.push(runtime.owner);
runtime.writeState(state); // 先保存原值,进程被杀后下一次运行仍可恢复。
if (current < runtime.timeoutMs && !runtime.writeTimeout(runtime.timeoutMs)) throw new Error("设置熄屏超时失败");
settingHeld = true;
});
}
return {
keep: function () {
if (active && runtime.now() < nextRefresh) return;
// 先建立每引擎独立的锁,不调用会被其他脚本cancelKeepingAwake释放的共享Device锁。
runtime.acquire();
active = true;
nextRefresh = runtime.now() + 60000;
if (!settingHeld) {
try { claimSetting(); }
catch (error) { report("超时兜底暂不可用:" + error); }
}
},
release: function () {
nextRefresh = 0;
try {
if (settingHeld) runtime.locked(function () {
var state = runtime.readState();
if (!state) return;
state.owners = livingOwners(state).filter(function (owner) { return owner !== runtime.owner; });
if (state.owners.length) runtime.writeState(state);
else {
// 运行中用户手动改了设置时不覆盖用户的新值。
if (runtime.readTimeout() === runtime.timeoutMs && !runtime.writeTimeout(state.originalTimeout))
throw new Error("恢复原熄屏超时失败");
runtime.clearState();
}
});
settingHeld = false;
} catch (error) { report("恢复超时设置失败,保留恢复记录:" + error); }
finally {
if (active) runtime.release();
active = false;
}
}
};
}
function createAndroidScreenAwake(options) {
var ctx = options.context, api = options.android, screenDevice = options.device;
// 兼容没有Android桥的单元测试或旧宿主;手机上始终使用下面的独立锁。
if (!ctx || !api) {
var next = 0, held = false;
return {keep: function () {
if (!screenDevice || typeof screenDevice.keepScreenOn !== "function" || (held && Date.now() < next)) return;
screenDevice.keepScreenOn(3600000); held = true; next = Date.now() + 60000;
}, release: function () {
if (screenDevice && typeof screenDevice.cancelKeepingAwake === "function") screenDevice.cancelKeepingAwake();
held = false; next = 0;
}};
}
var statePath = "/sdcard/Download/autojs-screen-awake-state.json";
var pid = String(api.os.Process.myPid()), owner = pid + ":" + options.engines.myEngine().id;
var pm = ctx.getSystemService(api.content.Context.POWER_SERVICE);
var wakeLock = pm.newWakeLock(api.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK | api.os.PowerManager.ON_AFTER_RELEASE,
"autojs6:screen-awake:" + owner);
wakeLock.setReferenceCounted(false);
var system = api.provider.Settings.System, resolver = ctx.getContentResolver();
var store = options.files;
var runtime = {
owner: owner, timeoutMs: 86400000, now: function () { return Date.now(); }, log: options.log,
acquire: function () { wakeLock.acquire(3600000); },
release: function () { if (wakeLock.isHeld()) wakeLock.release(); },
canWrite: function () { return api.os.Build.VERSION.SDK_INT < 23 || system.canWrite(ctx); },
readTimeout: function () { return Number(system.getInt(resolver, system.SCREEN_OFF_TIMEOUT, 30000)); },
writeTimeout: function (value) { return !!system.putInt(resolver, system.SCREEN_OFF_TIMEOUT, value); },
aliveOwners: function () {
return options.engines.all().map(function (engine) { return pid + ":" + engine.id; });
},
readState: function () { return store.exists(statePath) ? JSON.parse(String(store.read(statePath))) : null; },
writeState: function (state) { store.write(statePath + ".tmp", JSON.stringify(state));
if (!new java.io.File(statePath + ".tmp").renameTo(new java.io.File(statePath))) throw new Error("保存常亮恢复记录失败"); },
clearState: function () { store.remove(statePath); },
locked: function (action) {
var file = new java.io.RandomAccessFile(statePath + ".lock", "rw"), channel = file.getChannel(), lock = null;
try {
var deadline = Date.now() + 1500;
while (!lock && Date.now() < deadline) {
try { lock = channel.tryLock(); } catch (error) {
if (!/OverlappingFileLockException/.test(String(error))) throw error;
}
if (!lock) java.lang.Thread.sleep(20);
}
if (!lock) throw new Error("等待常亮设置锁超时");
return action();
} finally {
if (lock) lock.release();
channel.close(); file.close();
}
}
};
return createScreenAwake(runtime);
}
// END SHARED SCREEN AWAKE
var screenAwakeController = null;
function keepScreenAwake() {
if (!screenAwakeController) screenAwakeController = createAndroidScreenAwake({
context: typeof context === "undefined" ? null : context,
android: typeof android === "undefined" ? null : android,
device: typeof device === "undefined" ? null : device,
files: typeof files === "undefined" ? null : files,
engines: typeof engines === "undefined" ? null : engines,
log: function (message) { if (typeof log === "function") log(message); }
});
screenAwakeController.keep();
}
function releaseScreenAwake() {
if (screenAwakeController) screenAwakeController.release();
else if (typeof context === "undefined" && 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 activityBusyMessage(text) {
var message = compact(text);
return /^活动繁忙(?:[,,。::]?请稍[后候]再试)?[。.!!]?$/.test(message) ? message : null;
}
function checkActivityBusy(items, flow) {
if (arguments.length < 2) flow = activeTaskFlow;
if (!flow || flow !== activeTaskFlow) return;
for (var i = 0; items && i < items.length; i++) {
var message = activityBusyMessage(items[i].text);
if (message) flow.busyMessage = message;
}
if (!flow.busyMessage) return;
var error = new Error(flow.busyMessage + ";跳过当前流程“" + flow.name + "”");
error.activityBusy = true;
throw error;
}
function startActivityBusyObserver() {
if (activityBusyObserverActive) return;
try {
events.observeToast();
events.onToast(receiveMealToast);
activityBusyObserverActive = true;
} catch (error) {
stopActivityBusyObserver();
writeRunLog("ACTIVITY BUSY: Toast监听不可用,仍检查无障碍/OCR页面提示;" + error);
}
}
function stopActivityBusyObserver() {
try { events.removeListener("toast", receiveMealToast); } catch (ignore) {}
try { events.removeToastObserver(); } catch (ignore) {}
activityBusyObserverActive = false;
}
function recoverAfterActivityBusy() {
return runStep("活动繁忙后返回赚钱页", function () {
var page = readPage("活动繁忙后识别当前位置");
var heading = first(page, {test: function (text) { return !!activityBusyMessage(text); }});
if (heading) {
var close = first(page, /^(?:我知道了|知道了|确定|确认|关闭|返回|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.3;
});
if (close) tap(close);
}
if (!earningPage(snapshot())) returnHomeAndOpenEarning();
}, 30000);
}
function runTaskFlow(name, action) {
var previous = activeTaskFlow;
var flow = {name: name, busyMessage: null};
activeTaskFlow = flow;
try {
var result = action();
checkActivityBusy();
return result === undefined ? {ok: true} : result;
} catch (error) {
if (!error.activityBusy || error.unsafeWorker || error.captureFatal) throw error;
// 先结束当前流程及其线程,再恢复页面;不能让内层runStep吞掉繁忙信号继续循环。
activeTaskFlow = null;
writeRunLog("FLOW BUSY SKIP: " + name + ";" + (flow.busyMessage || error.message) + ";本次不重试该流程,继续下一流程。");
recoverAfterActivityBusy();
return {ok: true, skipped: true, busy: true};
} finally { activeTaskFlow = previous; }
}
function runTaskStep(name, action, timeoutMs) {
return runTaskFlow(name, function () { return runStep(name, action, timeoutMs); });
}
// 现场修复重载时的一次性续跑指令;默认启动流程不变,过期/不匹配的指令不生效。
function consumePublicationResume() {
var path = "/sdcard/Download/fanqie-publication-resume-once.json";
if (!files.exists(path)) return false;
var command;
try { command = JSON.parse(String(files.read(path))); }
catch (error) { writeRunLog("REPAIR RESUME: 指令无效,按正常顺序启动。"); }
if (!files.remove(path)) throw new Error("一次性续跑指令无法清除,不能重复使用");
var valid = !!(command && command.version === CONFIG.version && command.flow === "publication" &&
Date.now() >= command.createdAt && Date.now() - command.createdAt < 300000);
if (valid && command.topCoinAttemptedAmounts) Object.keys(command.topCoinAttemptedAmounts).forEach(function (amount) {
if (/^\d+$/.test(amount) && Number(amount) >= 1000 && command.topCoinAttemptedAmounts[amount] === true)
topCoinAttemptedAmounts[amount] = true;
});
return valid;
}
// 任务和识别分别限时;结束旧线程后才允许后续任务使用屏幕。
function boundedCall(name, timeoutMs, action) {
var flow = activeTaskFlow;
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) { checkActivityBusy(null, flow); 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 || error.activityBusy) throw error;
writeRunLog("STEP SKIP: " + name + ";原因=" + error + ";继续下一步骤");
return {ok: !!error.noMatch, skipped: true};
}
}
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) {
var flow = activeTaskFlow;
checkActivityBusy();
try {
var currentPage = captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot);
checkActivityBusy(currentPage, flow);
return currentPage;
} 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: 本机页面识别已恢复。");
checkActivityBusy(page, flow);
return page;
} catch (recoveryError) {
if (recoveryError.activityBusy) throw recoveryError;
recoveryError.captureFatal = true;
throw recoveryError;
}
}
}
function flipPopupHasAction(items) {
return !!(findFlipButton(items) && (flipEntryOpened || first(items, /^继续翻卡/, isCenteredPopupItem)));
}
function isPopupAction(item) {
return isCenteredPopupItem(item) && /^[||]?(?:立即[领颌颁頒]取|直[按接][领颌]取|领取奖励|开心收下|确认|继续领金币|[领颌]更多金币|看视频领取|看视频[领颌]更多|立即阅读|领\d+金币吃饭补贴)$/.test(item.text);
}
function piggybankColumnAmount(items, label, button) {
if (!label) return null;
var center = (button.rect.left + button.rect.right) / 2;
var numbers = matches(items, /^\d+(?:,\d{3})*$/, function (item) {
var r = item.rect, height = r.bottom - r.top;
return r.bottom <= label.rect.top && r.top >= label.rect.top - device.height * 0.12 &&
height >= device.height * 0.018 &&
Math.abs((r.left + r.right) / 2 - center) < device.width * 0.12;
});
var values = [];
// 原生控件可能每个数字一个节点;和OCR分开组装,避免把1144再拼成11441144。
[true, false].forEach(function (nativeSource) {
var row = numbers.filter(function (item) { return !!item.node === nativeSource; });
row.sort(function (a, b) { return a.rect.left - b.rect.left; });
var unique = [];
row.forEach(function (item) {
if (!unique.some(function (other) {
return item.text === other.text && Math.abs(item.rect.left - other.rect.left) < 8 &&
Math.abs(item.rect.top - other.rect.top) < 8 && Math.abs(item.rect.right - other.rect.right) < 8;
})) unique.push(item);
});
if (!unique.length) return;
var text = "", previous = null, firstRect = unique[0].rect;
for (var i = 0; i < unique.length; i++) {
var item = unique[i], r = item.rect;
if (Math.abs(r.top - firstRect.top) > device.height * 0.012 ||
Math.abs(r.bottom - firstRect.bottom) > device.height * 0.012 ||
(previous && (r.left < previous.right - 4 || r.left - previous.right > device.width * 0.035))) return;
text += item.text.replace(/,/g, ""); previous = r;
}
var value = Number(text);
if (isFinite(value) && values.indexOf(value) < 0) values.push(value);
});
// 两种来源冲突或有多行/重叠数字时重识别,不猜测金币金额。
return values.length === 1 ? values[0] : null;
}
function piggybankRewardDecision(items) {
// “存钱罐奖励”是左侧选项标签;优先用上方选择奖励标题定位整个弹窗。
var heading = first(items, /^(?:[靖请]选择奖励|选择奖励)$/, isCenteredPopupItem) ||
first(items, /^存钱罐奖励$/, isCenteredPopupItem);
if (!heading) return null;
var buttons = matches(items, /^[||]?(?:直[按接援][领颌]取|看视频[领颌]更多)$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top > heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.45;
});
var direct = first(buttons, /^直[按接援][领颌]取$/);
var video = first(buttons, /^看视频[领颌]更多$/);
if (!direct || !video) return null;
var options = [];
[direct, video].forEach(function (button) {
var center = (button.rect.left + button.rect.right) / 2;
var label = first(items, button === direct ? /^存钱罐奖励$/ : /^看视频奖励$/, function (item) {
return item.rect.bottom <= button.rect.top && button.rect.top - item.rect.bottom < device.height * 0.14 &&
Math.abs((item.rect.left + item.rect.right) / 2 - center) < device.width * 0.12;
});
var amount = piggybankColumnAmount(items, label, button);
if (amount !== null) options.push({button: button, amount: amount});
});
// 弹窗已确认但金额暂缺时继续等待,不能交给背景金币或追加奖励规则。
if (options.length !== 2) return {button: null, amount: null};
options.sort(function (a, b) { return b.amount - a.amount; });
return options[0].amount >= 1000 ? options[0] : first(options, {test: function () { return true; }},
function (option) { return option.button === direct; });
}
// 只在手机当前帧采样按钮文字周边背景,不上传像素或图片。
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;
var signClaim = findSingleSignPopupClaim(items);
if (signClaim) return {button: signClaim, amount: null, take: true, signIn: true};
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 (!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) || findFlipRewardReceiptHeading(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 room = first(items, /本场点赞|在线观众/, function (item) {
return item.rect.top < device.height * 0.2;
}) || first(items, /^(?:[·「|]?更多直播[>〉]?|[·]?左滑查看更多直播)$/);
var chat = first(items, /^说点什么$/) && first(items, /^(?:礼物|连线|商品列表|粉丝团)$/);
var confirmation = first(items, /(?:确定|确认|是否|即将).*?(?:退出|离开).*?直播|退出直播间后|离开直播间后/);
var continueWatching = first(items, /^(?:继续观看|继续看直播|留在直播间)$/, isCenteredPopupItem);
var exit = first(items, /^[||]?(?:退出直播间|离开直播间|退出直播|确认退出|确定退出|立即退出|坚持退出|退出|离开)$/,
isCenteredPopupItem);
if (exit && (confirmation || room || chat || liveReturnPending ||
(!/坚持退出/.test(exit.text) && continueWatching))) {
return {button: exit, reason: /坚持退出/.test(exit.text) ? "点击直播挽留弹窗的坚持退出" : "确认退出直播间"};
}
// 用直播间自身控件判定,不能仅因任务列表或广告文案提及“直播”就返回。
if (room || chat) return {back: true, reason: "已进入直播页面,立即返回"};
return null;
}
function findAdvertisementExitAction(items) {
return first(items, /^<?关闭.{0,3}退.{0,1}出$/, function (item) {
return item.rect.top < device.height * 0.15 && item.rect.left < device.width * 0.55;
});
}
function isAdvertisementPage(items) {
return !!(findAdvertisementExitAction(items) || first(items, /^(?:广告(?:[|!!1ご))((].*)?|.*直播间)$/, function (item) {
return item.rect.top < device.height * 0.15;
}));
}
function findEarningTreasureClaim(items) {
if (!first(items, /^(?:福利中心|日常福利)$/) || !bottomNavigation(items, /^赚钱$/)) return null;
var buttons = matches(items, /^[||]?(?:点击)?[领颌領](?:取)?(?:\d+(?:,\d{3})*(?:金币)?|金币)$/, function (item) {
return item.rect.left > device.width * 0.72 && item.rect.top > device.height * 0.72 &&
item.rect.bottom < device.height * 0.93;
});
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
var inline = /(?:[领颌領](?:取)?)(\d+(?:,\d{3})*)/.exec(button.text);
var amount = inline ? Number(inline[1].replace(/,/g, "")) : null;
if (amount === null) {
var nearby = items.filter(function (item) {
return item.rect.left > device.width * 0.72 && item.rect.bottom <= button.rect.top &&
item.rect.top >= button.rect.top - device.height * 0.12 &&
Math.abs((item.rect.left + item.rect.right - button.rect.left - button.rect.right) / 2) < device.width * 0.1;
});
if (!first(nearby, /宝箱/)) continue;
var coins = matches(nearby, /^(\d+(?:,\d{3})*)金币$/);
if (coins.length !== 1) continue;
amount = Number(coins[0].text.replace(/[^\d]/g, ""));
}
if (amount > 1000 && !treasureAttemptedAmounts[String(amount)]) return {button: button, amount: amount};
}
return null;
}
// 与宝箱同门槛;只认赚钱页右上角待领取按钮,不读取账户余额或任务最高金额。
function findEarningTopCoinClaim(items) {
if (!first(items, /^(?:福利中心|日常福利)$/) || !bottomNavigation(items, /^赚钱$/)) return null;
var candidates = matches(items, /^[||]?(?:(?:点击)?[领颌領](?:取)?(?:\d+(?:,\d{3})*金币|金币)?|去领取)$/,
function (item) {
return item.rect.left > device.width * 0.72 && item.rect.top > device.height * 0.09 &&
item.rect.bottom < device.height * 0.30;
}).map(function (button) {
var inline = /([\d,]+)金币/.exec(button.text);
var amount = inline ? Number(inline[1].replace(/,/g, "")) : null;
if (amount === null) {
var nearby = matches(items, /^[\d,]+$/, function (item) {
return item.rect.left > device.width * 0.72 && item.rect.top > device.height * 0.09 &&
item.rect.bottom < device.height * 0.30 &&
Math.abs((item.rect.left + item.rect.right - button.rect.left - button.rect.right) / 2) < device.width * 0.12 &&
Math.abs((item.rect.top + item.rect.bottom - button.rect.top - button.rect.bottom) / 2) < device.height * 0.12;
}).filter(function (item) {
return !!first(items, /^金币$/, function (coin) {
return Math.abs((coin.rect.left + coin.rect.right - item.rect.left - item.rect.right) / 2) < device.width * 0.16 &&
Math.abs((coin.rect.top + coin.rect.bottom - item.rect.top - item.rect.bottom) / 2) < device.height * 0.08;
});
});
if (nearby.length === 1) amount = Number(nearby[0].text.replace(/[^\d]/g, ""));
}
return amount !== null && amount >= 1000 && !topCoinAttemptedAmounts[String(amount)] ?
{button: button, amount: amount} : null;
}).filter(function (item) { return !!item; });
candidates.sort(function (a, b) { return b.amount - a.amount; });
return candidates.length ? candidates[0] : null;
}
// 与宝箱一样在赚钱页持续检查,但读书挑战只要明确可领取即可,不设金额门槛。
function findEarningReadingChallengeClaim(items) {
if (!activeTaskFlow || !/^读书挑战赛/.test(activeTaskFlow.name) ||
readingChallengeClaimActive || !earningPage(items) || isAdvertisementPage(items)) return null;
var labels = matches(items, /^[||「『]?(?:读)?书挑战[赛塞賽]/, function (item) {
return item.rect.top > device.height * 0.09 && item.rect.bottom < device.height * 0.92;
});
for (var i = 0; i < labels.length; i++) {
var label = labels[i];
var button = first(items, /^[||]?(?:(?:立即|去|可)?[领颌颁頒]{1,2}取(?:金币)?|(?:点击)?[领颌](?:取)?\d+(?:,\d{3})*金币)$/, function (item) {
return item.rect.left > device.width * 0.7 && item.rect.bottom < device.height * 0.92 &&
Math.abs((item.rect.top + item.rect.bottom - label.rect.top - label.rect.bottom) / 2) < device.height * 0.04;
});
if (!button) continue;
var key = "readingChallenge:" + (label.text.replace(/[^\d]/g, "") || "unknown") + ":" + button.text.replace(/[^\d]/g, "");
if (!readingChallengeClaims[key]) return {button: button, key: key};
}
return null;
}
function claimReadingChallengeCoins(target) {
readingChallengeClaimActive = true;
try {
var result = runTaskFlow("读书挑战赛金币领取", function () {
writeRunLog("通用读书挑战规则:看到同一任务行可领取,点击后执行通用弹窗/广告规则。");
try { tap(target.button); }
catch (error) {
if (error.activityBusy) readingChallengeClaims[target.key] = "busy";
throw error;
}
readingChallengeClaims[target.key] = "attempted";
handleVideos(/./);
readingChallengeClaims[target.key] = "handled";
});
if (result.busy) readingChallengeClaims[target.key] = "busy";
return result;
} finally { readingChallengeClaimActive = false; }
}
function needsCommonHandling(items) {
if (dismissOnlyPromoPopupHeading(items)) return true;
if (completedTaskPopupHeading(items)) return true;
if (liveExitAction(items)) return true;
if (findFlipRewardReceiptHeading(items)) return true;
if (cappedRewardPopup(items)) return true;
if (findListeningPopupClose(items) || findPlaybackPopupDismiss(items) || piggybankRewardDecision(items) || singleButtonPopupDecision(items) || isAdvertisementPage(items)) return true;
if (flipPopupHasAction(items)) {
// 翻卡弹窗保留中央操作;不能阻止用户最新要求的右上角倒计时/关闭规则。
var flipOffer = offerAmount(items);
return !!(countdown(items) || findTopRightClose(items) || findHigherCoinClaim(items) || findEmptyRewardPopupClose(items) ||
(rewardReceiptHeading(items) && findReceiptEligibleClaim(items)) ||
(flipOffer && flipOffer.amount >= CONFIG.rewardThreshold));
}
var reader = publicationReadingSurface(items);
var popupClose = findEmptyRewardPopupClose(items);
if (reader && popupClose && isTopRight(popupClose)) popupClose = null;
return !!(findFlipSettlementHeading(items) || findMoreCoinsButton(items) || findReceiptEligibleClaim(items) || findRewardReceiptClose(items) || (first(items, /^继续领金币$/) && first(items, /^[||]?坚持退出$/)) || (!reader && (countdown(items) || findTopRightClose(items))) || findHigherCoinClaim(items) || popupClose || offerAmount(items) || findEarningTreasureClaim(items) || findEarningTopCoinClaim(items) || findEarningReadingChallengeClaim(items) || findEarningDramaClaim(items));
}
function snapshot() {
var page = readPage("页面识别");
var deadline = Date.now() + CONFIG.stepTimeoutMs;
while (!commonHandling && needsCommonHandling(page)) {
if (Date.now() >= deadline) stopWith("通用页面处理超时,保留当前页面");
writeRunLog("通用规则优先:暂停当前任务,先处理倒计时、关闭或额外奖励。");
var beforeAction = actionSerial;
handleVideos(/./);
page = readPage("通用处理后重新识别");
// 连续奖励可能跨越多个广告,操作已推进时按停滞时间计时,不能沿用第一轮的期限。
// handleVideos仍独立约束单轮广告等待;无操作进展则保留原超时保护。
if (actionSerial !== beforeAction) deadline = Date.now() + CONFIG.stepTimeoutMs;
// 广告切换或弹窗动画中关闭按钮可能晚一帧出现;重新执行通用规则,不能全局退出。
}
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();
}
}
// 仅在已确认推广层的按钮下方识别白色X,要求四条亮色斜臂和暗色间隙。
function readPromoCross(frame, items, action) {
var unit = device.width / 1080;
function bright(x, y) {
var color = images.pixel(frame, Math.round(x), Math.round(y));
var r = (color >>> 16) & 255, g = (color >>> 8) & 255, b = color & 255;
return Math.min(r, g, b) > 205 && Math.max(r, g, b) - Math.min(r, g, b) < 30;
}
var top = action.rect.bottom + device.height * 0.03;
var bottom = Math.min(device.height * 0.87, action.rect.bottom + device.height * 0.20);
for (var y = Math.floor(top); y < bottom; y += 2) {
for (var x = Math.floor(device.width * 0.45); x < device.width * 0.55; x += 2) {
if (!bright(x, y)) continue;
var hits = 0;
for (var d = 5; d <= 11; d += 3) {
var offset = d * unit;
if (bright(x-offset,y-offset)) hits++;
if (bright(x+offset,y-offset)) hits++;
if (bright(x-offset,y+offset)) hits++;
if (bright(x+offset,y+offset)) hits++;
}
var gap = 12 * unit;
if (hits < 11 || bright(x-gap,y) || bright(x+gap,y) ||
bright(x,y-gap) || bright(x,y+gap)) continue;
items.push({text: "关闭推广弹窗", rect: {left:x-gap,top:y-gap,right:x+gap,bottom:y+gap},node:null});
writeRunLog("推广白色叉号图形识别:" + x + "," + y);
return;
}
}
}
function readReceiptCloseRegion(frame, items) {
if (dismissOnlyPromoPopupHeading(items) && !findInviteCashPopupClose(items)) {
var promoAction = first(items, /^(?:前[往住]抽奖|查看权益)$/, isCenteredPopupItem);
if (promoAction) {
readPromoCross(frame, items, promoAction);
if (findInviteCashPopupClose(items)) return;
var promoTop = Math.floor(promoAction.rect.bottom + device.height * 0.02);
var promoBottom = Math.min(Math.floor(device.height * 0.90),
Math.floor(promoAction.rect.bottom + device.height * 0.22));
if (promoTop < promoBottom) readCloseRegion(frame, items, {
left: Math.floor(device.width * 0.42), top: promoTop,
width: Math.floor(device.width * 0.16), height: promoBottom - promoTop
});
}
}
var completed = completedTaskPopupHeading(items);
if (completed) {
if (!findCompletedTaskPopupClose(items)) {
var completedTop = Math.floor(completed.rect.bottom);
var completedBottom = Math.floor(device.height * 0.92);
if (completedTop < completedBottom) readCloseRegion(frame, items, {
left: Math.floor(device.width * 0.2), top: completedTop,
width: Math.floor(device.width * 0.6), height: completedBottom - completedTop
});
}
return;
}
var capped = cappedRewardPopup(items);
if (capped && !capped.close) {
var cappedTop = Math.floor(capped.heading.rect.bottom);
var cappedBottom = Math.floor(device.height * 0.92);
if (cappedTop < cappedBottom) readCloseRegion(frame, items, {
left: Math.floor(device.width * 0.35), top: cappedTop,
width: Math.floor(device.width * 0.3), height: cappedBottom - cappedTop
});
return;
}
var heading = rewardReceiptHeading(items);
if (!heading || flipPopupHasAction(items) || findRewardReceiptClose(items)) return;
var action = first(items, /^看视频.*最高(?:可)?领\d+金[币市而]$/, isCenteredPopupItem) ||
(findFlipRewardReceiptHeading(items) && first(items, /^看视频继续[赚賺]金币$/, isCenteredPopupItem));
if (!action || action.rect.top < heading.rect.bottom) return;
var top = Math.floor(action.rect.bottom);
var bottom = Math.floor(device.height * 0.92);
if (top >= bottom) return;
// 仅在已确认的领取确认层下方放大找明确X,不推测关闭坐标。
readCloseRegion(frame, items, {left: Math.floor(device.width * 0.35), top: top,
width: Math.floor(device.width * 0.3), height: bottom - top});
}
function appendNativeReceiptClose(items) {
var heading = completedTaskPopupHeading(items) || rewardReceiptHeading(items);
if (!heading || flipPopupHasAction(items) || typeof id !== "function") return;
// 真机领取确认框的关闭图标无文字/描述,只在已确认奖励弹窗内使用该控件。
var nodes = id(CONFIG.packageName + ":id/eoy").find();
for (var i = 0; i < nodes.size(); i++) {
var node = nodes.get(i);
var rect = rectOf(node.bounds());
if (!rect || !node.visibleToUser() || !node.clickable()) continue;
var center = (rect.left + rect.right) / 2;
if (center < device.width * 0.4 || center > device.width * 0.6 ||
rect.top < heading.rect.bottom || rect.top > device.height * 0.92) continue;
items.push({text: "关闭弹窗", rect: rect, node: node});
}
}
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) stopWith("当前不是番茄小说页面(" + foreground + "),已停止。");
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;原生控件已确认直播时直接交给退出规则。
var nativeLiveExit = liveExitAction(items);
// 第一次看到原生直播直接返回;已按过返回后允许本地OCR找前景挽留按钮。
if (localOcrEnabled && (!nativeLiveExit || (liveReturnPending && !nativeLiveExit.button))) {
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);
readReceiptCloseRegion(frame, items);
items.forEach(function (item) {
if (isPopupAction(item) || isSignClaimButton(item)) item.darkButton = isDarkButton(frame, item);
});
} finally {
if (frame && typeof frame.recycle === "function") frame.recycle();
}
}
appendNativePromoClose(items);
appendNativeReceiptClose(items);
// 同一按钮可能同时被无障碍和 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, refreshTarget) {
checkActivityBusy();
if (!item) skipStep("没有目标标签,执行下一步骤");
if (!commonHandling) {
var freshPage = snapshot();
var original = item;
item = refreshTarget ? refreshTarget(freshPage) : 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;
});
// 红包入口和中央开按钮的OCR偶尔整帧漏字,只在指定重新关联器时短暂复查。
for (var refresh = 0; !item && refreshTarget && refresh < 3; refresh++) {
sleep(CONFIG.pollMs);
item = refreshTarget(snapshot());
}
if (!item) skipStep("通用处理后目标标签已改变,跳过旧坐标点击");
}
if (foregroundPackage() !== CONFIG.packageName) stopWith("点击前页面已离开番茄小说,已停止。");
if (activeTaskFlow) lastTaskFlowAction = {flow: activeTaskFlow, time: Date.now()};
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);
checkActivityBusy();
}
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 countdown(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 first(items, /^[.,,。||]*一共[赢贏]取\d+(?:,\d{3})*金币$/, isCenteredPopupItem);
}
function findFlipSettlementButton(items) {
var heading = findFlipSettlementHeading(items);
if (!heading) return null;
return first(items, /^开心收下$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.45;
});
}
function findMoreCoinsButton(items) {
return first(items, /^[领颌]更多金币$/, isCenteredPopupItem);
}
function rewardReceiptHeading(items) {
// OPPO现场把“获得”识别为“荻得”;翻卡到账层优先于背景奖励文字。
return first(items, /[获荻]得翻卡奖励/, isCenteredPopupItem) ||
first(items, /^[.,,。||]*恭喜(?:你)?(?:已)?(?:累计)?获得(?:翻卡)?(?:奖励)?$/, isCenteredPopupItem);
}
function findFlipRewardReceiptHeading(items) {
var heading = rewardReceiptHeading(items);
return heading && /翻卡/.test(heading.text) ? heading : null;
}
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 inviteCashPopupHeading(items) {
var heading = first(items, /^送你现金红包$/, isCenteredPopupItem);
return heading && first(items, /^邀请好友立得$/, isCenteredPopupItem) ? heading : null;
}
function dismissOnlyPromoPopupHeading(items) {
var cash = inviteCashPopupHeading(items);
if (cash) return cash;
var raffle = first(items, /^抽奖[赢贏嘉]好礼$/, isCenteredPopupItem);
if (raffle && first(items, /^前[往住]抽奖$/, isCenteredPopupItem)) return raffle;
var recommendation = first(items, /^小说推荐官$/, isCenteredPopupItem);
return recommendation && first(items, /^赠送好友VIP会员$/, isCenteredPopupItem) &&
first(items, /^查看权益$/, isCenteredPopupItem) ? recommendation : null;
}
function appendNativePromoClose(items) {
if (!dismissOnlyPromoPopupHeading(items) || typeof className !== "function") return;
var benefit = first(items, /^查看权益$/, isCenteredPopupItem);
if (!benefit) return;
var nodes = className("android.widget.ImageView").packageName(CONFIG.packageName).find();
for (var i = 0; i < nodes.size(); i++) {
var node = nodes.get(i), rect = rectOf(node.bounds());
var parent = node.parent(), panel = parent ? rectOf(parent.bounds()) : null;
if (!rect || !panel || !node.visibleToUser()) continue;
var width = rect.right - rect.left, height = rect.bottom - rect.top;
var center = (rect.left + rect.right) / 2;
if (center < device.width * 0.4 || center > device.width * 0.6 ||
rect.top <= benefit.rect.bottom || rect.bottom >= device.height * 0.9 ||
width < device.width * 0.04 || width > device.width * 0.15 || Math.abs(width - height) > width * 0.25 ||
panel.right - panel.left > device.width * 0.85 || panel.top >= benefit.rect.top ||
Math.abs(panel.bottom - rect.bottom) > device.height * 0.02) continue;
items.push({text: "关闭推广弹窗", rect: rect, node: node});
}
}
function findInviteCashPopupClose(items) {
var heading = dismissOnlyPromoPopupHeading(items);
if (!heading) return null;
return 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 > heading.rect.bottom && item.rect.top > device.height * 0.55 &&
item.rect.bottom < device.height * 0.9;
});
}
function completedTaskPopupHeading(items) {
return first(items, /^[.,,。!!||]*(?:你|您)?(?:已|已经)完成(?:了)?(?:此|该|本|当前)任务[!!。]*$/, isCenteredPopupItem);
}
function findCompletedTaskPopupClose(items) {
var heading = completedTaskPopupHeading(items);
if (!heading) return null;
return 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;
});
}
function findRewardReceiptClose(items) {
var heading = rewardReceiptHeading(items);
if (!heading) return null;
if (!findFlipRewardReceiptHeading(items) && (flipPopupHasAction(items) ||
findFlipSettlementHeading(items) || findMoreCoinsButton(items) || 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 isSignClaimButton(item) {
return isCenteredPopupItem(item) && /^[||]?(?:立即[领颌颁頒]取|立即签到|签到领取|签到|领取奖励|领(?:取)?\d+(?:,\d{3})*金币)$/.test(item.text);
}
function findSingleSignPopupClaim(items) {
var heading = first(items, /签到/, isCenteredPopupItem);
if (!heading) return null;
// 用位于按钮下方的中央X确认前景弹窗,排除赚钱页的签到任务行。
var buttons = matches(items, {test: function () { return true; }}, function (item) {
return isSignClaimButton(item) && item.rect.top >= heading.rect.bottom &&
item.rect.top < heading.rect.bottom + device.height * 0.58;
});
var unique = [];
buttons.forEach(function (item) {
var existing = first(unique, {test: function () { return true; }}, function (other) {
return Math.abs((item.rect.left + item.rect.right - other.rect.left - other.rect.right) / 2) < 40 &&
Math.abs((item.rect.top + item.rect.bottom - other.rect.top - other.rect.bottom) / 2) < 40;
});
if (!existing) unique.push(item);
else if (item.darkButton === true) existing.darkButton = true;
});
if (unique.length !== 1 || unique[0].darkButton !== true) return null;
var button = unique[0];
var close = first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= button.rect.bottom;
});
var fullPage = first(items, /^(?:back|返回)$/, function (item) { return item.rect.top < device.height * 0.2; }) &&
first(items, /今日签到|已签\d+[\//]\d+/) && first(items, /活动时间/);
if (!close && !fullPage) return null;
return button;
}
function findStartupSignClaim(items) {
return findSingleSignPopupClaim(items);
}
function cappedRewardPopup(items) {
var heading = first(items, /^看视频(?:最高|最多)(?:可)?再领(?:\d+(?:,\d{3})*金[币市而])?$/, isCenteredPopupItem);
if (!heading) return null;
var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) {
return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom &&
item.rect.top - heading.rect.bottom < device.height * 0.2;
});
// 透明弹窗的X会与背景“……来袭,X”合框,只提取处于中央下方的末尾字形。
if (!close) {
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 - heading.rect.bottom < device.height * 0.2 &&
glyphCenter >= device.width * 0.35 && glyphCenter <= device.width * 0.65;
});
if (merged) close = {text: "关闭宝箱弹窗(" + merged.text + ")", node: null, rect: {
left: merged.rect.right - (merged.rect.right - merged.rect.left) / merged.text.length,
right: merged.rect.right, top: merged.rect.top, bottom: merged.rect.bottom
}};
}
// 最高金额是上限;宝箱标题或其下关闭按钮证明是前景层,背景任务不能抢占。
if (!close && !first(items, /^(?:今日宝箱无限开|倒计时结束才能开宝箱)$/, isCenteredPopupItem)) return null;
return {heading: heading, close: close};
}
function findEmptyRewardPopupClose(items, ignoreCoinClaim) {
var capped = cappedRewardPopup(items);
if (capped && capped.close) return capped.close;
// 前景现金邀请提示不属于金币领取;背景任务行的金币不能阻止关闭。
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 isCenteredPopupItem(item) && 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 findHigherCoinClaim(items) {
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 (/^看视频开大额奖励[-—]?$/.test(item.text) && first(items, RED_PACKET_LABEL) &&
first(items, /^已开[0-9Oo]+[//]10$/)) 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) {
var previous = commonHandling;
commonHandling = true;
try { return handleVideosLoop(returnPattern); }
finally { commonHandling = previous; }
}
function dismissCappedPopupByBack() {
if (foregroundPackage() !== CONFIG.packageName) stopWith("宝箱弹窗返回前应用已切换");
writeRunLog("通用宝箱弹窗:关闭图标持续未识别,尝试一次返回并复查弹窗是否消失。");
if (back() === false) stopWith("宝箱弹窗返回键执行失败,保留现场");
actionSerial++;
sleep(CONFIG.pollMs);
var page = snapshot();
if (cappedRewardPopup(page)) stopWith("宝箱弹窗返回后仍未关闭,保留现场,不重复返回或点击背景任务");
writeRunLog("通用宝箱弹窗:返回后已确认该弹窗消失,继续通用流程。");
}
function handleVideosLoop(returnPattern) {
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 cappedCloseMissingSince = null;
var flipReceiptMissingSince = null;
var completedCloseMissingSince = null;
var completedCloseAttempts = 0;
var offerButtonMissingSince = null;
var piggybankMissingSince = null;
var inviteCloseMissingSince = null, inviteCloseAttempts = 0;
while (Date.now() < deadline) {
var items = snapshot();
// 邀请现金红包只关闭,不操作现金金额或弹窗背后的任务导航。
if (dismissOnlyPromoPopupHeading(items)) {
var inviteClose = findInviteCashPopupClose(items);
if (inviteClose) {
if (++inviteCloseAttempts > 3) stopWith("推广弹窗连续三次关闭未响应,保留现场");
writeRunLog("INVITE CASH CLOSE: 关闭邀请现金、推荐官或抽奖推广弹窗,继续原流程。");
tap(inviteClose, findInviteCashPopupClose);
} else {
if (inviteCloseMissingSince === null) inviteCloseMissingSince = Date.now();
if (Date.now() - inviteCloseMissingSince < CONFIG.pageTimeoutMs) { sleep(CONFIG.pollMs); continue; }
writeRunLog("INVITE CASH CLOSE: 叉号暂未识别,返回一次关闭推广弹窗并复查。");
if (back() === false) stopWith("推广弹窗返回关闭失败,保留现场");
actionSerial++; sleep(CONFIG.pollMs);
if (dismissOnlyPromoPopupHeading(snapshot())) stopWith("推广弹窗返回后仍存在,保留现场");
}
stableReturn = 0;
continue;
}
inviteCloseMissingSince = null; inviteCloseAttempts = 0;
// 明确已完成的任务弹窗只关闭,不能被高金币、继续观看或背景倒计时抢占。
if (completedTaskPopupHeading(items)) {
var completedClose = findCompletedTaskPopupClose(items);
if (completedClose) {
if (++completedCloseAttempts > 3) stopWith("已完成任务弹窗连续三次关闭未响应,保留现场");
writeRunLog("TASK COMPLETED CLOSE: 弹窗提示你已完成此任务,直接关闭,不再看视频或领取。");
tap(completedClose);
} else {
if (completedCloseMissingSince === null) completedCloseMissingSince = Date.now();
if (Date.now() - completedCloseMissingSince < CONFIG.pageTimeoutMs) {
sleep(CONFIG.pollMs);
continue;
}
writeRunLog("TASK COMPLETED CLOSE: 关闭未识别,返回一次并确认已完成弹窗消失。");
if (back() === false) stopWith("已完成任务弹窗返回关闭失败,保留现场");
actionSerial++;
sleep(CONFIG.pollMs);
if (completedTaskPopupHeading(snapshot())) stopWith("已完成任务弹窗返回后仍存在,保留现场");
}
stableReturn = 0;
continue;
}
completedCloseMissingSince = null;
completedCloseAttempts = 0;
// 翻卡到账确认层直接关闭,不能被其中的广告或背景领取按钮抢占。
if (findFlipRewardReceiptHeading(items)) {
var flipClose = findRewardReceiptClose(items);
if (flipClose) {
if (++actions > CONFIG.maxVideos * 4) stopWith("翻卡奖励关闭按钮多次未响应,保留现场");
writeRunLog("FLIP RECEIPT CLOSE: 获得翻卡奖励弹窗直接点击关闭。");
tap(flipClose);
} else {
if (flipReceiptMissingSince === null) flipReceiptMissingSince = Date.now();
if (Date.now() - flipReceiptMissingSince < CONFIG.pageTimeoutMs) {
sleep(CONFIG.pollMs);
continue;
}
writeRunLog("FLIP RECEIPT CLOSE: 关闭图标未识别,执行一次返回关闭并复查。");
if (back() === false) stopWith("翻卡奖励弹窗返回关闭失败,保留现场");
actionSerial++;
sleep(CONFIG.pollMs);
if (findFlipRewardReceiptHeading(snapshot())) stopWith("翻卡奖励弹窗返回后仍存在,保留现场");
}
flipSettlementDone = true;
flipActionDone = true;
flipReceiptMissingSince = null;
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("退出直播的返回键执行失败");
liveReturnPending = true;
actionSerial++;
sleep(CONFIG.pollMs);
}
continue;
}
liveReturnPending = false;
liveExitAttempts = 0;
var adExit = findAdvertisementExitAction(items);
if (adExit) {
if (++actions > CONFIG.maxVideos * 4) stopWith("广告退出按钮处理达到上限");
writeRunLog("广告商品页:识别到关闭广告并退出,点击后恢复当前任务流程。");
tap(adExit);
stableReturn = 0;
continue;
}
// 重试保护只计算按钮持续存在时的连续失败;新倒计时或按钮消失说明页面已推进。
// 不可把不同广告在同一坐标的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 capped = cappedRewardPopup(items);
if (capped) {
if (!capped.close) {
if (cappedCloseMissingSince === null) cappedCloseMissingSince = Date.now();
if (Date.now() - cappedCloseMissingSince >= CONFIG.pageTimeoutMs) {
dismissCappedPopupByBack();
cappedCloseMissingSince = null;
continue;
}
writeRunLog("通用宝箱弹窗:等待关闭按钮重新识别,不搜索背景任务。");
sleep(CONFIG.pollMs);
continue;
}
cappedCloseMissingSince = null;
if (++actions > CONFIG.maxVideos * 4) stopWith("宝箱弹窗处理达到本轮上限");
var cappedKey = "capped:" + Math.round(capped.close.rect.left / 20) + ":" + Math.round(capped.close.rect.top / 20);
repeatedClose = lastCloseKey === cappedKey ? repeatedClose + 1 : 1;
lastCloseKey = cappedKey;
if (repeatedClose > 3) stopWith("宝箱弹窗同一关闭按钮连续三次未响应,保留现场");
writeRunLog("通用宝箱弹窗:最高再领不是确定金币,点击关闭;不等待宝箱冷却倒计时。");
tap(capped.close);
continue;
}
cappedCloseMissingSince = null;
var piggybank = piggybankRewardDecision(items);
if (piggybank) {
if (!piggybank.button) {
if (piggybankMissingSince === null) piggybankMissingSince = Date.now();
if (Date.now() - piggybankMissingSince >= CONFIG.pageTimeoutMs) stopWith("存钱罐奖励两个选项金额尚未完整识别,保留现场");
writeRunLog("存钱罐奖励:等待本弹窗两侧金额重新识别,不点击背景任务。");
sleep(CONFIG.pollMs);
continue;
}
piggybankMissingSince = null;
if (++actions > CONFIG.maxVideos * 4) stopWith("存钱罐奖励选择弹窗处理达到上限");
writeRunLog("存钱罐奖励:选项=" + piggybank.amount + "金币;" + piggybank.button.text + (piggybank.amount >= 1000 ? "(优先最大且>=1000)" : "(没有>=1000选项,直接领取)"));
tap(piggybank.button);
stableReturn = 0;
continue;
}
var signClaim = findHigherCoinClaim(items);
if (signClaim) {
if (++actions > CONFIG.maxVideos * 4) stopWith("签到弹窗多次点击无响应,跳过本步骤");
writeRunLog("通用双金额规则:有>=500选较大,否则选最小;本次 " + signClaim.text);
tap(signClaim);
continue;
}
var singleDecision = singleButtonPopupDecision(items);
if (singleDecision) {
if (!singleDecision.button) stopWith("单按钮弹窗不符合领取条件,但尚未识别到关闭按钮,保留页面重查");
if (++actions > CONFIG.maxVideos * 4) stopWith("单按钮弹窗处理达到上限");
writeRunLog(singleDecision.signIn ? "签到单按钮规则:点击深色领取按钮,不套额外奖励金额门槛。" : "通用单按钮规则:正文金币=" + 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("通用规则:奖励按钮金额大于500金币,点击领取");
tap(eligibleClaim);
accepted++;
continue;
}
var offer = offerAmount(items);
if (!offer) offerButtonMissingSince = null;
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) {
if (offerButtonMissingSince === null) offerButtonMissingSince = Date.now();
if (Date.now() - offerButtonMissingSince >= CONFIG.pageTimeoutMs)
stopWith("未识别到额外奖励的" + (take ? "确认" : "退出") + "按钮,已停止。");
writeRunLog("通用追加奖励:弹窗过渡中,等待确认/关闭按钮出现,不点击背景任务。");
sleep(CONFIG.pollMs);
continue;
}
offerButtonMissingSince = null;
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;
if (!foregroundClose && publicationReadingSurface(items)) {
writeRunLog("阅读页倒计时交给阅读流程:继续翻页,不在通用规则中原地等待或关闭阅读页。");
return;
}
// 前景弹窗的动作先处理,背景倒计时和背景右上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) || findHigherCoinClaim(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;
}
var topCoins = findEarningTopCoinClaim(items);
if (topCoins) {
if (++actions > CONFIG.maxVideos * 4) stopWith("右上金币及通用弹窗操作达到本轮上限");
writeRunLog("通用右上金币规则:优先领取右上角最大金币;当前" + topCoins.amount + "金币(>=1000)。");
tap(topCoins.button);
topCoinAttemptedAmounts[String(topCoins.amount)] = true;
stableReturn = 0;
deadline = Date.now() + CONFIG.videoTimeoutMs;
continue;
}
var treasure = findEarningTreasureClaim(items);
if (treasure) {
if (++actions > CONFIG.maxVideos * 4) stopWith("宝箱及通用弹窗操作达到本轮上限,保留现场");
writeRunLog("通用宝箱规则:赚钱页右下宝箱" + treasure.amount + "金币>1000,点击下方领取后继续通用流程。");
tap(treasure.button);
// 同金额未变化时本轮不连点,不阻塞签到、补贴或阅读;下次运行重新检查。
treasureAttemptedAmounts[String(treasure.amount)] = true;
stableReturn = 0;
deadline = Date.now() + CONFIG.videoTimeoutMs;
continue;
}
var challenge = findEarningReadingChallengeClaim(items);
if (challenge) {
if (++actions > CONFIG.maxVideos * 4) stopWith("读书挑战及通用弹窗操作达到本轮上限");
claimReadingChallengeCoins(challenge);
stableReturn = 0;
deadline = Date.now() + CONFIG.videoTimeoutMs;
continue;
}
var dramaClaim = findEarningDramaClaim(items);
if (dramaClaim) {
if (++actions > CONFIG.maxVideos * 4) stopWith("追剧挑战及通用弹窗操作达到本轮上限");
claimDramaCoins(dramaClaim);
stableReturn = 0;
deadline = Date.now() + CONFIG.videoTimeoutMs;
continue;
}
// 无倒计时、无关闭、无额外奖励就交还调度,不等待旧的返回页标签。
writeRunLog("通用规则:当前无可执行条件,继续下一步骤。");
return;
}
stopWith("等待视频结束或目标页面超时,已停止;未用返回键跳过倒计时。");
}
function findEarningTaskAction(items, labelPattern, actionPattern) {
var labels = matches(items, labelPattern);
for (var i = 0; i < labels.length; i++) {
var row = labels[i];
var actions = matches(items, actionPattern, function (item) {
return item.rect.left > row.rect.left && item.rect.left > device.width * 0.6 &&
Math.abs((item.rect.top + item.rect.bottom - row.rect.top - row.rect.bottom) / 2) < device.height * 0.04;
});
if (actions.length) {
actions.sort(function (a, b) {
var center = row.rect.top + row.rect.bottom;
return Math.abs(a.rect.top + a.rect.bottom - center) - Math.abs(b.rect.top + b.rect.bottom - center);
});
return actions[0];
}
// 用户确认:赚钱页看到任务标签即可点击;不因右侧按钮OCR漏识别而继续滚动。
return row;
}
return null;
}
function searchEarningTask(labelPattern, actionPattern, name) {
return searchPublicationAction(function (items) {
return findEarningTaskAction(items, labelPattern, actionPattern);
}, name, labelPattern, "EARNING SEARCH");
}
function findMealEntry() {
return searchEarningTask(MEAL_ENTRY, /^[||]?(?:去领取|立即领取|领补贴)$/, "吃饭补贴");
}
function finishStreak() {
var page = null;
var streak = null;
for (var i = 0; i <= CONFIG.maxScrolls; i++) {
page = snapshot();
streak = first(page, STREAK_SECTION);
if (streak) break;
if (i < CONFIG.maxScrolls) {
swipe(device.width * 0.5, device.height * 0.75, device.width * 0.5, device.height * 0.4, 400);
sleep(CONFIG.pollMs);
}
}
if (!streak) {
for (var j = 0; j < CONFIG.maxScrolls; j++) {
swipe(device.width * 0.5, device.height * 0.4, device.width * 0.5, device.height * 0.75, 350);
sleep(250);
}
writeRunLog("跳过:当前页面没有连续奖励类目。");
return;
}
var pending = matches(page, /^待领取$/, function (item) {
return mealClaimAvailable(item) && item.rect.top >= streak.rect.bottom && item.rect.top < streak.rect.bottom + device.height * 0.30;
});
if (!pending.length) {
writeRunLog("跳过:连续奖励类目没有待领取项目。");
return;
}
if (pending.length !== 1) stopWith("连续奖励的待领取项目无法唯一确认,已停止。");
var returnPattern = first(page, MEAL_PAGE) ? MEAL_PAGE : STREAK_SECTION;
claimMealButton(pending[0], returnPattern);
if (!mealClaimAvailable(pending[0])) return;
page = snapshot();
streak = first(page, STREAK_SECTION);
if (streak && first(page, /^待领取$/, function (item) {
return item.rect.top >= streak.rect.bottom && item.rect.top < streak.rect.bottom + device.height * 0.30;
})) stopWith("已点击连续奖励,但页面仍显示待领取,请检查当前状态。");
writeRunLog("完成:连续奖励待领取标记已消失。");
}
function findMealOnceClaim(items) {
var heading = first(items, MEAL_PAGE);
if (!heading) return null;
return first(items, /领一次补(?:贴|[見见]贴)$/, function (item) {
return mealClaimAvailable(item) && item.rect.top > heading.rect.bottom && item.rect.top < device.height * 0.92;
});
}
function mealClaimKey(item) {
return item.text.replace(/^[||]/, "").replace(/金[市而]/g, "金币");
}
function mealClaimAvailable(item) {
return !mealUnavailableClaims[mealClaimKey(item)];
}
function receiveMealToast(toast) {
if (String(toast.getPackageName()) !== CONFIG.packageName) return;
var message = compact(String(toast.getText()));
if (!activityBusyMessage(message)) return;
mealBusyFeedback = {time: Date.now(), message: message};
// 延迟抵达的旧操作反馈仍归原流程,不能误伤刚开始的下一流程。
var flow = lastTaskFlowAction && Date.now() - lastTaskFlowAction.time < 8000 ? lastTaskFlowAction.flow : activeTaskFlow;
if (flow) flow.busyMessage = message;
writeRunLog("ACTIVITY BUSY TOAST: " + message + (flow ? ";流程=" + flow.name : ""));
}
function claimMealButton(claim, returnPattern) {
var key = mealClaimKey(claim);
for (var retry = 0; retry <= CONFIG.mealBusyRetries; retry++) {
checkActivityBusy();
var started = Date.now();
tap(claim);
handleVideos(returnPattern || MEAL_PAGE);
checkActivityBusy();
// 提示可能晚于tap的等待时间,须在通用处理后检查,不能漏掉迟到的繁忙反馈。
if (!mealBusyFeedback || mealBusyFeedback.time < started) return true;
if (retry < CONFIG.mealBusyRetries) {
writeRunLog("饭点繁忙重试:" + claim.text + ";等待5秒后重新识别,第" + (retry + 1) + "/" + CONFIG.mealBusyRetries + "次。");
sleep(CONFIG.mealBusyRetryMs);
var page = snapshot();
if (!first(page, MEAL_PAGE) && !first(page, STREAK_SECTION)) return true;
claim = first(page, {test: function () { return true; }}, function (item) {
return mealClaimKey(item) === key;
});
if (!claim) return true;
}
}
mealUnavailableClaims[key] = true;
writeRunLog("饭点跳过:" + claim.text + "重试后仍收到活动繁忙提示,本轮不再重复点击;继续检查其他奖励和后续任务,下次运行重新尝试。");
return true;
}
function findMealCoinClaim(items) {
var heading = first(items, MEAL_PAGE);
if (!heading) return null;
var streak = first(items, STREAK_SECTION);
var bottom = streak ? streak.rect.top : device.height * 0.92;
// 饭点页的整段金额按钮也可领取,不要求固定的“领早餐/午餐补贴”文案。
// 只查主补贴区;余额、已领取说明和连续奖励档位不作为金额按钮。
return first(items, /^[||]?(?:(?:领(?:取)?|补领|点击领(?:取)?|看视频(?:再得|再领|领(?:取)?|补领|得)?)(?:(?:早餐|午餐|午饭|晚餐|晚饭|夜宵|吃饭|饭点|一次)?补贴)?)?\d+(?:,\d{3})*金[币市而]$/, function (item) {
return mealClaimAvailable(item) && item.rect.top > heading.rect.bottom && item.rect.bottom < bottom;
});
}
function finishMealPage(resuming) {
var page = snapshot();
var onceClaim = findMealOnceClaim(page);
if (onceClaim) {
writeRunLog("饭点优先:先点击一次补贴按钮 " + onceClaim.text);
return claimMealButton(onceClaim);
}
var claim = findMealCoinClaim(page) || first(page, /^[||]?领(?:早餐|午餐|午饭|晚餐|晚饭|夜宵)补贴$/, mealClaimAvailable);
if (claim) {
writeRunLog("饭点领取:点击补贴按钮 " + claim.text + ";领取后先执行通用规则,再重新扫描补贴页。");
return claimMealButton(claim);
}
writeRunLog("本轮饭点扫描:没有一次补贴、XX金币或当前时段领取按钮,继续查连续奖励。");
return false;
}
function confirmMealPage() {
var page = snapshot();
if (first(page, MEAL_PAGE)) return page;
if (first(page, STREAK_SECTION)) {
swipe(device.width * 0.5, device.height * 0.4, device.width * 0.5, device.height * 0.75, 350);
sleep(CONFIG.pollMs);
}
if (!waitFor(MEAL_PAGE)) stopWith("尚未确认返回吃饭补贴页,不能把未知页面当作标签都不存在");
return snapshot();
}
function runMealPageLoop() {
mealUnavailableClaims = {};
mealBusyFeedback = null;
runMealPageLoopBody();
}
function runMealStep() {
// 正常运行由主线程全程监听,饭点结束不能解除后续出版物等流程的Toast监听。
if (activityBusyObserverActive) return runStep("吃饭补贴", mealStep, CONFIG.mealSessionTimeoutMs + 30000);
// 监听绑定主线程,避免带事件循环的任务线程结束动作后仍存活,阻塞runStep。
try {
events.observeToast();
events.onToast(receiveMealToast);
return runStep("吃饭补贴", mealStep, CONFIG.mealSessionTimeoutMs + 30000);
} finally {
try {
events.removeListener("toast", receiveMealToast);
} finally {
// removeListener 只解绑回调;observeToast 的空闲等待必须单独取消。
// 否则业务已结束,引擎仍驻留,任务管理器无法启动下一次。
events.removeToastObserver();
}
}
}
function runMealPageLoopBody() {
var deadline = Date.now() + CONFIG.mealSessionTimeoutMs;
var emptyPasses = 0;
var pass = 0;
while (Date.now() < deadline) {
pass++;
writeRunLog("MEAL LOOP: 第" + pass + "轮,重新检查补贴页全部已配置标签。");
confirmMealPage();
var before = actionSerial;
if (finishMealPage(true)) {
emptyPasses = 0;
continue;
}
// 一次补贴、XX金币和时段领取均不存在,才检查连续奖励;每次动作后重头扫描。
finishStreak();
confirmMealPage();
if (actionSerial !== before) {
emptyPasses = 0;
continue;
}
emptyPasses++;
writeRunLog("MEAL EMPTY: 全部已配置领取标签无可执行项 " + emptyPasses + "/2");
if (emptyPasses >= 2) {
// 仅在明确处于补贴页、全部类别连续两轮无可执行项后退出。
confirmMealPage();
if (actionSerial !== before) { emptyPasses = 0; continue; }
if (finishMealPage(true)) { emptyPasses = 0; continue; }
writeRunLog("MEAL EXIT: 补贴页连续两轮没有可执行标签,返回福利中心。");
if (back() === false) stopWith("返回键执行失败,尚未退出补贴页");
actionSerial++;
if (!waitFor(/福利中心|日常福利/)) stopWith("已尝试退出补贴页,但尚未确认回到福利中心");
mealPageDone = true;
return;
}
sleep(CONFIG.pollMs);
}
stopWith("补贴页循环达到30分钟异常保护上限;未确认全部无匹配,保留页面,不自动退出");
}
function claimStartupSignIn() {
var page = snapshot();
var heading = first(page, /签到/);
if (!heading) {
writeRunLog("跳过启动签到弹窗:未识别到签到提示。");
return;
}
// OCR 偶尔把“领取”识别成“颌取”;仍要求完整按钮文字及签到标题。
var claim = findStartupSignClaim(page);
if (!claim) {
if (first(page, /再看(?:一个|1个|一段|1段)?视频|再[看香]\d+秒|看视频(?:再得|再领|领)\d+金币|看视频.*(?:最高可领|额外|奖励)/)) {
writeRunLog("启动签到已领取,继续处理现有额外奖励弹窗。");
handleVideos(/福利中心|日常福利|饭点领金币补贴/);
} else writeRunLog("跳过启动签到弹窗:没有立即领取按钮。");
return;
}
tap(claim);
writeRunLog("已点击启动签到弹窗的立即领取,按通用规则处理后续弹窗。");
handleVideos(/福利中心|日常福利|饭点领金币补贴/);
}
function ensureTaskPage() {
var page = snapshot();
if (countdown(page) || first(page, /再看(?:一个|1个|一段|1段)?视频|再[看香]\d+秒|看视频(?:再得|再领|领)\d+金币|视频广告|广告剩余/)) {
stopWith("上一步仍停留在广告或额外奖励页,不跳过倒计时、不在广告上查找下一任务");
}
if (!first(page, /福利中心|日常福利/) && !first(page, MEAL_PAGE) && !first(page, STREAK_SECTION)) {
skipStep("没有当前任务对应的福利或饭点标签,执行下一步骤");
}
return page;
}
function returnFromSignPage() {
var page = snapshot();
if (first(page, /福利中心|日常福利/)) return;
var backButton = first(page, /^(?:back|返回)$/, function (item) { return item.rect.top < device.height * 0.2; });
if (backButton && first(page, /今日签到|已签\d+[\//]\d+/) && first(page, /活动时间/)) {
writeRunLog("签到页领取处理结束,返回赚钱页继续翻卡。");
tap(backButton);
waitFor(/福利中心|日常福利/);
}
}
function signInStep() {
var page = ensureTaskPage();
if (first(page, MEAL_PAGE)) {
writeRunLog("跳过签到:当前位于饭点补贴页,继续处理饭点任务。");
return;
}
var sign = searchEarningTask(/^[||]?(?:签到|每日签到)(?:领金币.*)?$/, /^[||]?(?:去签到|立即签到|签到)$/, "签到");
if (!sign) {
writeRunLog("跳过签到:赚钱页未找到对应签到入口或今日已签到。");
return;
}
writeRunLog("赚钱页签到:找到对应标签,直接点击,不依赖日常福利标题。");
tap(sign);
var deadline = Date.now() + CONFIG.pageTimeoutMs;
while (Date.now() < deadline) {
var before = actionSerial;
snapshot(); // 前景签到弹窗由通用规则处理,包括单个深色领取按钮。
if (actionSerial > before) {
writeRunLog("签到弹窗已按通用规则处理,继续翻卡。");
returnFromSignPage();
return;
}
sleep(CONFIG.pollMs);
}
writeRunLog("签到入口已点击,当前没有可执行的签到弹窗,继续翻卡。");
returnFromSignPage();
}
function mealStep() {
if (mealPageDone) { writeRunLog("跳过:本次补贴页已扫描完成并退出。"); return; }
var page = ensureTaskPage();
if (!first(page, MEAL_PAGE) && !first(page, STREAK_SECTION)) {
var meal = findMealEntry();
if (!meal) return;
writeRunLog("赚钱页补贴:找到对应标签,直接点击,不依赖日常福利标题。");
tap(meal);
if (!waitFor(MEAL_PAGE)) skipStep("没有饭点补贴页面标签,执行下一步骤");
}
runMealPageLoop();
}
function findFlipEntry(items) {
var labels = matches(items, /翻卡.{0,16}(?:金|全)[币市]/);
return first(items, /翻卡/, function (button) {
var text = button.text.replace(/^[||]/, "");
if (/最高|奖励|已翻|已完成|明日|不可翻|次数已/.test(text)) return false;
return labels.some(function (label) {
return button.rect.left > device.width * 0.7 && button.rect.left > label.rect.left &&
button.rect.top > device.height * 0.09 && button.rect.bottom < device.height * 0.92 &&
button.rect.top >= label.rect.top - device.height * 0.02 &&
button.rect.top <= label.rect.bottom + device.height * 0.18 &&
Math.abs((button.rect.top + button.rect.bottom - label.rect.top - label.rect.bottom) / 2) < device.height * 0.18;
});
});
}
function searchFlipEntry() {
var current = snapshot();
if (!earningPage(current)) stopWith("翻卡搜索未确认赚钱页,不能判成任务不可做");
var entry = findFlipEntry(current);
if (entry) return entry;
// 小幅慢滑覆盖相邻任务卡片,避免大幅快滑跨过翻卡入口。
for (var direction = 0; direction < 2; direction++) {
var previous = "", stationary = 0;
for (var i = 0; i < 22; i++) {
var moved = direction === 0 ?
swipe(device.width * 0.5, device.height * 0.40, device.width * 0.5, device.height * 0.64, 800) :
swipe(device.width * 0.5, device.height * 0.72, device.width * 0.5, device.height * 0.48, 800);
sleep(CONFIG.pollMs);
var page = snapshot();
if (!earningPage(page)) stopWith("翻卡扫描已离开赚钱页,保留未完成状态");
entry = findFlipEntry(page);
writeRunLog("FLIP SEARCH: " + (direction ? "向下" : "向上") + (i + 1) + ";滑动=" + moved + ";入口=" + !!entry +
";可见翻卡文字=" + matches(page, /翻卡|立即翻卡|去翻卡/).map(function (item) { return item.text; }).join("、"));
if (entry) return entry;
var key = page.map(function (item) {
return item.text.replace(/\d+/g, "#") + ":" + Math.round(item.rect.top / 80);
}).sort().join("|");
stationary = key === previous ? stationary + 1 : 0;
previous = key;
if (stationary >= 2) break;
}
}
return null;
}
function isFlipButton(item) {
if (!isCenteredPopupItem(item) || item.rect.top <= device.height * 0.4) return false;
// 按钮文字允许任意“翻”字,但标题、状态及背景介绍不是操作按钮。
var text = item.text.replace(/^[||.,,。\s]+/, "");
return !/^(?:恭喜.*翻卡奖励|翻卡奖励.*|已翻.*|(?:看)?继续翻卡领更多.*|翻卡[赢贏嘉羸].*|翻多少得多少.*)$/.test(text);
}
function findFlipButton(items) {
return first(items, FLIP_BUTTON, isFlipButton);
}
function flipCardStep() {
var rounds = 0, emptyRounds = 0;
while (true) {
var page = snapshot();
var popup = findFlipButton(page);
if (!popup) {
ensureEarningPage();
var entry = searchFlipEntry();
if (!entry || entry.enabled === false) {
flipEntryOpened = false;
writeRunLog("FLIP LOOP DONE: 完整复查后没有可用的右侧翻卡按钮,共执行" + rounds + "轮。");
return;
}
}
// 上一轮结算只结束当轮;新一轮必须重新识别入口及翻卡按钮。
flipActionDone = false;
flipSettlementDone = false;
flipEntryOpened = true;
if (!popup) tap(entry);
writeRunLog("FLIP ROUND: 第" + (++rounds) + "轮,持续操作直到本轮没有翻卡按钮。");
var roundActions;
try { roundActions = flipCardRound(); }
catch (error) {
if (!error.noMatch) throw error;
roundActions = 0;
writeRunLog("FLIP RECHECK: 本轮未识别翻卡操作,回赚钱页复查入口,不能直接判为完成。");
}
ensureEarningPage();
if (roundActions === 0) {
if (++emptyRounds >= 2) stopWith("翻卡仍有入口但连续两轮没有可执行翻卡操作,保留未完成状态,不进入后续任务");
writeRunLog("FLIP RECHECK: 奖励弹窗已关闭,继续检查右侧翻卡入口。");
} else emptyRounds = 0;
writeRunLog("FLIP RECHECK: 本轮结束,回赚钱页重新检查右侧翻卡按钮。");
}
}
function flipCardRound() {
if (flipActionDone || flipSettlementDone) return 0;
if (!flipEntryOpened) {
var page = snapshot();
// 可从已经打开的翻卡弹窗继续,不再点击弹窗背后的入口。
if (findFlipButton(page)) flipEntryOpened = true;
else {
if (!first(page, /福利中心|日常福利/)) skipStep("尚未返回福利中心,暂不进入翻卡");
var entry = searchFlipEntry();
if (!entry) skipStep("没有翻卡赢金币对应的立即翻卡入口,继续下一步骤");
writeRunLog("进入翻卡赢金币。");
tap(entry);
flipEntryOpened = true;
}
}
var deadline = Date.now() + CONFIG.flipSessionTimeoutMs;
var emptyPasses = 0;
var clicks = 0;
var flipActions = 0;
var transientRetries = 0;
while (Date.now() < deadline) {
try {
if (flipSettlementDone) return flipActions;
var flip = waitFor(FLIP_BUTTON, CONFIG.pageTimeoutMs, isFlipButton);
if (flipSettlementDone) return flipActions;
if (!flip) {
var returnedPage = snapshot();
var popupTitle = first(returnedPage, /^继续翻卡/, isCenteredPopupItem);
var nextEntry = !popupTitle && first(returnedPage, /^福利中心$/) ? searchFlipEntry() : null;
if (nextEntry) {
if (++clicks > 20) stopWith("翻卡达到20次异常保护上限,未确认全部完成,保留页面");
writeRunLog("FLIP RETURN: 返回福利页仍有立即翻卡,继续进入下一张卡。");
tap(nextEntry);
emptyPasses = 0;
continue;
}
emptyPasses++;
writeRunLog("FLIP EMPTY: 没有翻卡按钮 " + emptyPasses + "/2");
if (emptyPasses >= 2) {
if (!flipActionDone) skipStep("已进入翻卡页但没有翻卡按钮,跳过该操作");
writeRunLog("完成:翻卡按钮已处理,连续两次未找到后续翻卡按钮。");
return flipActions;
}
sleep(CONFIG.pollMs);
continue;
}
if (++clicks > 20) stopWith("翻卡达到20次异常保护上限,未确认全部完成,保留页面");
emptyPasses = 0;
writeRunLog("FLIP ACTION: 第" + clicks + "次,点击 " + flip.text);
tap(flip);
flipActions++;
flipActionDone = true;
handleVideos(/翻卡/);
sleep(CONFIG.pollMs);
snapshot();
transientRetries = 0;
} catch (error) {
if (error.captureFatal || error.unsafeWorker) throw error;
var retryable = /未识别到额外奖励的.*按钮|通用页面仍未处理完成|通用处理后目标标签已改变|未识别到翻卡结算的开心收下按钮/.test(String(error));
if (!retryable || ++transientRetries > 3) throw error;
emptyPasses = 0;
writeRunLog("FLIP RETRY: 通用处理或页面刷新后重新识别,第" + transientRetries + "次;" + error);
sleep(CONFIG.pollMs);
}
}
stopWith("翻卡达到30分钟异常保护上限,未确认全部完成,保留页面");
}
function findPublicationAction(items, actionPattern) {
var labels = matches(items, PUBLICATION_LABEL);
return first(items, actionPattern, function (button) {
return labels.some(function (label) {
return button.rect.left > device.width * 0.65 && button.rect.left > label.rect.left &&
Math.abs((button.rect.top + button.rect.bottom - label.rect.top - label.rect.bottom) / 2) < device.height * 0.045;
});
});
}
function findPublicationEntry(items) {
return findPublicationAction(items, /^[||]?去[领颌颁頒]取$/) ||
findPublicationAction(items, /^[||]?(?:去)?阅读$/);
}
function findPublicationClaim(items) {
return findPublicationAction(items, /^[||]?去[领颌颁頒]取$/) ||
findPublicationAction(items, /^[||]?立即[领颌颁頒]取$/);
}
function searchPublicationAction(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 < 8; 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 || "PUBLICATION SEARCH") + ": " + actionName + ";" + (direction ? "向下" : "向上") + (i + 1) + ";滑动=" + moved + ";相关文字=" +
matches(page, relatedPattern || /出版|阅读|立即领取/).map(function (item) { return item.text; }).join("、"));
entry = finder(page);
if (entry) return entry;
var key = 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 searchPublicationEntry() {
return searchPublicationAction(findPublicationEntry, "去领取/去阅读");
}
function publicationClaimPending() {
if (!files.exists(CONFIG.publicationStatePath)) return false;
try { return JSON.parse(files.read(CONFIG.publicationStatePath)).pendingClaim === true; }
catch (error) { writeRunLog("PUBLICATION STATE: 状态文件无法解析,按当前页面识别;" + error); return false; }
}
function savePublicationClaimState(pending, evidence, claimTapped) {
files.write(CONFIG.publicationStatePath, JSON.stringify({pendingClaim: pending, claimTapped: !!claimTapped, nextTask: pending ? "publicationClaim" : "readingChallenge",
evidence: evidence, updatedAt: new Date().toISOString()}));
}
function bottomNavigation(items, pattern) {
return first(items, pattern, function (item) { return item.rect.top > device.height * 0.9; });
}
function selectedNavigation(item) {
try { return !!(item && item.node && item.node.selected()); }
catch (error) { return false; }
}
function returnHomeAndOpenEarning() {
var phase = "home";
var homeConfirmed = false;
var backAttempts = 0;
var homeAttempts = 0;
var earnAttempts = 0;
var earnTappedAt = 0;
var deadline = Date.now() + 90000;
while (Date.now() < deadline) {
var page = snapshot(); // 每次返回和点击后先处理当前真实前景弹窗。
if (foregroundPackage() !== CONFIG.packageName) stopWith("返回首页时已离开番茄,保留现场");
var home = bottomNavigation(page, /^(?:首页|书城)$/);
var earn = bottomNavigation(page, /^赚钱$/);
if (!home || !earn) {
// 首页或赚钱点击后被推荐/其他页面带走,也回到返回流程,不把一帧缺导航当作结束。
phase = "home";
homeConfirmed = false;
if (++backAttempts > 12) stopWith("返回首页超过12次仍未确认底部导航,保留现场,不冒充已返回赚钱页");
writeRunLog("PUBLICATION RETURN: 尚未到带底部导航的首页,继续返回,第" + backAttempts + "次。");
if (back() === false) stopWith("返回首页的返回键执行失败");
actionSerial++;
sleep(CONFIG.pollMs);
continue;
}
if (phase === "home") {
if (!homeConfirmed && !selectedNavigation(home)) {
if (++homeAttempts > 6) stopWith("首页导航多次点击仍未稳定,保留现场");
writeRunLog("PUBLICATION RETURN: 已见底部导航,点击首页/书城,再重新确认赚钱按钮。");
tap(home);
homeConfirmed = true;
phase = "homeConfirm";
continue;
}
writeRunLog("PUBLICATION RETURN: 已确认首页底部导航,下一步点击底部赚钱。");
phase = "earning";
}
if (phase === "homeConfirm") {
if (!selectedNavigation(home) && selectedNavigation(earn)) {
writeRunLog("PUBLICATION RETURN: 点击首页后仍在赚钱标签,等待刷新再确认首页。");
sleep(CONFIG.pollMs);
phase = "home";
homeConfirmed = false;
continue;
}
writeRunLog("PUBLICATION RETURN: 已确认首页,重新识别当前底部赚钱按钮。");
phase = "earning";
}
if (phase === "earning") {
if (++earnAttempts > 6) stopWith("底部赚钱多次点击仍未进入福利中心,保留现场");
writeRunLog("PUBLICATION RETURN: 点击当前首页底部赚钱,第" + earnAttempts + "次。");
tap(earn);
earnTappedAt = Date.now();
phase = "confirm";
continue;
}
if (first(page, /福利中心|日常福利/)) {
writeRunLog("PUBLICATION RETURN DONE: 已从首页点击底部赚钱,并确认福利中心。");
return;
}
if (Date.now() - earnTappedAt < CONFIG.pageTimeoutMs) {
sleep(CONFIG.pollMs);
continue;
}
// 页面仍在加载时先等待,再从当前导航重新识别,绝不复用旧按钮坐标。
sleep(CONFIG.pollMs);
phase = selectedNavigation(home) ? "earning" : "home";
homeConfirmed = false;
}
stopWith("返回首页并点击底部赚钱超时,保留现场,不记录为任务条件消失");
}
function publicationTaskTarget(items) {
if (!first(items, /福利中心|日常福利/)) return null;
var label = first(items, PUBLICATION_LABEL);
if (!label) return null;
var claim = findPublicationClaim(items);
var reading = findPublicationEntry(items);
var button = claim || reading;
var fullyVisible = label.rect.top >= device.height * 0.095 && button &&
button.rect.top >= device.height * 0.095 && button.rect.bottom < device.height * 0.92;
if (!fullyVisible && (label.rect.top > device.height * 0.78 || label.rect.top < device.height * 0.095))
return {alignTask: true, label: label};
return {label: label, button: button, action: claim ? "claim" : reading ? "read" : "none"};
}
function searchPublicationTask() {
for (var alignment = 0; alignment < 4; alignment++) {
var target = searchPublicationAction(publicationTaskTarget, "出版物去领取/去阅读", /出版|阅读|(?:立即|去)[领颌颁頒]取/);
if (!target || !target.alignTask) return target;
var nearBottom = target.label.rect.top > device.height * 0.78;
writeRunLog("PUBLICATION ALIGN: 出版物任务行靠近边缘,滑到中部后重新识别右侧按钮。");
swipe(Math.round(device.width * 0.5), Math.round(device.height * (nearBottom ? 0.7 : 0.3)),
Math.round(device.width * 0.5), Math.round(device.height * (nearBottom ? 0.58 : 0.42)), 800);
sleep(CONFIG.pollMs);
}
var aligned = publicationTaskTarget(snapshot());
if (aligned && !aligned.alignTask) return aligned;
stopWith("出版物任务行仍未完整显示,不能误报无匹配,保留现场");
}
function publicationClaimStep(button) {
if (!button) skipStep("没有出版物任务对应的领取按钮,重新识别当前任务");
writeRunLog("PUBLICATION CLAIM: 点击出版物任务右侧" + button.text + ",不依赖历史待领奖状态。");
tap(button);
savePublicationClaimState(true, "已点击" + button.text + ",等待通用处理和当前任务复查", true);
handleVideos(/福利中心|日常福利/);
var page = snapshot();
if (first(page, /福利中心|日常福利/) && first(page, PUBLICATION_LABEL) && !findPublicationClaim(page)) {
savePublicationClaimState(false, "已点击出版物领取按钮,通用处理后对应领取按钮已变化");
writeRunLog("PUBLICATION CLAIM CHANGED: 原领取按钮已变化,继续复查去领取/去阅读,不据此推断金币入账。");
}
return {resumeReader: isPublicationReader(page) || !!publicationEnd(page)};
}
function publicationPageCounter(items) {
var counters = matches(items, /^\d+[\//]\d+$/, function (item) { return item.rect.top > device.height * 0.92; });
for (var i = 0; i < counters.length; i++) {
var parts = counters[i].text.split(/[\//]/);
var current = Number(parts[0]);
var total = Number(parts[1]);
if (current > 0 && total > 1 && current <= total) return {current: current, total: total, item: counters[i]};
}
return null;
}
function isPublicationReader(items) {
if (first(items, /福利中心|日常福利/) || first(items, MEAL_PAGE)) return false;
// 书城分类/推荐页会混有阅读工具词;底部主导航同时出现时绝不是阅读器。
var bottomTabs = matches(items, /^(?:书城|短剧|赚钱|书架|我的)$/,
function (item) { return item.rect.top > device.height * 0.9; });
var tabNames = [];
bottomTabs.forEach(function (item) {
if (tabNames.indexOf(item.text) < 0) tabNames.push(item.text);
});
if (tabNames.length >= 3) return false;
if (first(items, /^左滑开始阅读$/) || publicationPageCounter(items)) return true;
return matches(items, /^(?:上一章|下一章|目录|夜间|设置|加入书架|阅读设置)$/).length >= 2;
}
function publicationEnd(items) {
var counter = publicationPageCounter(items);
if (counter && counter.current === counter.total) return counter.item;
return first(items, /^(?:全书完|全文完|本书完|本书已读完|已读完本书|阅读完毕|已读完|已到最后一页|已经是最后一页|已经是最后一章|没有下一章|本书已完结|全书阅读完成)[。.!!]?$/) ||
publicationOcrEnd(items) ||
first(items, /^(?:阅读进度[::]?)100(?:\.0)?[%%]$/);
}
function publicationOcrEnd(items) {
// OPPO 实测“全书完”被 OCR 读成“上书完”。仅接受居中的书末标记,
// 且下方同时出现同一行的讨论/感悟入口,不能把正文错字当作读完。
var ending = first(items, /^上书完[。.!!]?$/, 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 >= device.height * 0.2 && item.rect.bottom <= device.height * 0.75;
});
if (!ending) return null;
var discuss = first(items, /^发讨论$/, function (item) {
return item.rect.top >= ending.rect.bottom &&
item.rect.top - ending.rect.bottom <= device.height * 0.15 &&
item.rect.right < ending.rect.left;
});
var note = first(items, /^写点感悟$/, function (item) {
return item.rect.top >= ending.rect.bottom && item.rect.left > ending.rect.right;
});
if (discuss && note && Math.abs(discuss.rect.top - note.rect.top) <= device.height * 0.03) return ending;
return null;
}
function publicationReadingSurface(items) {
return !isAdvertisementPage(items) && !liveExitAction(items) &&
!!(isPublicationReader(items) || publicationEnd(items));
}
function publicationStart(items) {
var counter = publicationPageCounter(items);
if (counter && counter.current === 1) return counter.item;
return first(items, /^(?:左滑开始阅读|已到第一页|已经是第一页|已经是第一[页頁]|本书首页)[。.!!]?$/);
}
function readingPageKey(items) {
return items.filter(function (item) {
return item.rect.top > device.height * 0.12 && item.rect.bottom < device.height * 0.88 &&
!/^(?:上一章|下一章|目录|夜间|设置|加入书架|下载|听书|新背景)$/.test(item.text);
}).map(function (item) { return item.text; }).sort().join("|");
}
function publicationToolbarVisible(items) {
if (publicationPageCounter(items) &&
matches(items, /^(?:上一章|下一章|目录|夜间|设置|阅读设置)$/).length >= 2) return true;
// 书末可能只显示“全书完”,没有页码;用底部同排工具按钮识别菜单。
// 原生节点与 OCR 常重复,按不同按钮计数,避免正文或单个“设置”误触发。
var tools = matches(items, /^(?:目录|夜间|设置|阅读设置)$/, function (item) {
return item.rect.top >= device.height * 0.88;
});
var chapter = first(items, /^(?:上一章|下一章)$/, function (item) {
return item.rect.top >= device.height * 0.75;
});
for (var i = 0; i < tools.length; i++) {
var names = [], left = device.width, right = 0;
tools.forEach(function (item) {
if (Math.abs(item.rect.top - tools[i].rect.top) > device.height * 0.04) return;
var name = item.text === "阅读设置" ? "设置" : item.text;
if (names.indexOf(name) < 0) names.push(name);
left = Math.min(left, item.rect.left);
right = Math.max(right, item.rect.right);
});
if (right - left >= device.width * 0.3 &&
(names.length >= 3 || (names.length >= 2 && chapter))) return true;
}
return false;
}
function publicationCountdown(items) {
var seconds = countdown(items);
if (seconds) return seconds;
function isClock(value) {
return /^\d{1,2}[::][0-5]\d(?:得\d+金[币市而][>〉]?)?$/.test(value);
}
var clock = first(items, /./, function (item) { return isTopRight(item) && isClock(item.text); });
if (clock) return clock;
// OPPO原生无障碍把01:58拆成五个控件;同排紧邻数字拼合,不依赖OCR恰好合框。
var fragments = matches(items, /^[\d::]+$/, function (item) { return !!item.node && isTopRight(item); });
for (var i = 0; i < fragments.length; i++) {
var colon = fragments[i];
if (!/^[::]$/.test(colon.text)) continue;
var row = fragments.filter(function (item) {
return Math.abs(item.rect.top - colon.rect.top) < device.height * 0.01 &&
Math.abs(item.rect.left - colon.rect.left) < device.width * 0.1;
}).sort(function (a, b) { return a.rect.left - b.rect.left; });
var value = "", adjacent = true;
for (var j = 0; j < row.length; j++) {
if (j && (row[j].rect.left < row[j - 1].rect.right - 2 ||
row[j].rect.left - row[j - 1].rect.right > device.width * 0.025)) adjacent = false;
value += row[j].text;
}
if (adjacent && isClock(value)) return {text: value, rect: colon.rect, node: null};
}
return null;
}
function dismissPublicationToolbar(page) {
if (!publicationToolbarVisible(page)) return page;
if (foregroundPackage() !== CONFIG.packageName) stopWith("阅读菜单收起前应用已切换");
writeRunLog("READ MENU: 收起阅读工具栏后继续翻页,不在菜单层上反复滑动。");
if (press(device.width * 0.5, device.height * 0.45, 80) === false) stopWith("收起阅读工具栏点击失败");
actionSerial++;
sleep(CONFIG.pollMs);
return snapshot();
}
function publicationSwipeY(items, turns) {
var rows = [0.38, 0.55, 0.65];
var panel = first(items, /^第\d+轮[·•]\d+[\//]\d+次$/);
var blockedTop = 0, blockedBottom = 0;
if (panel) {
// 管理器悬浮窗会截获落在其中的手势;文字边界外留出面板内边距。
blockedTop = panel.rect.top - device.height * 0.06;
blockedBottom = panel.rect.bottom + device.height * 0.14;
matches(items, /^(?:暂停|继续|停止[整螯]组)$/, function (item) {
return Math.abs(item.rect.left - panel.rect.left) < device.width * 0.35 &&
Math.abs(item.rect.top - panel.rect.top) < device.height * 0.25;
}).forEach(function (item) {
blockedTop = Math.min(blockedTop, item.rect.top - device.height * 0.03);
blockedBottom = Math.max(blockedBottom, item.rect.bottom + device.height * 0.03);
});
}
// 按实际尝试次数轮换,无页码或 OCR 内容变化也不能一直停留在同一高度。
for (var i = 0; i < rows.length; i++) {
var y = device.height * rows[(turns + i) % rows.length];
if (!panel || y < blockedTop || y > blockedBottom) return y;
}
stopWith("阅读滑动区域均被任务管理器悬浮窗遮挡,请移动悬浮窗");
}
function finishPublicationCountdown(page, deadline, tryEntryRight, reason) {
var firstRightPending = !!tryEntryRight;
var noTimerSince = null;
var rightMode = false;
var turns = 0;
var unchanged = 0;
var previous = publicationPageCounter(page);
while (Date.now() < deadline) {
if (!publicationReadingSurface(page)) stopWith("阅读倒计时处理时已离开阅读页面,保留现场,不记录阅读任务完成");
var entryRight = firstRightPending;
if (!entryRight && publicationStart(page)) {
writeRunLog("READ REWIND DONE: 已右滑到书本首页;共右滑" + turns + "次。");
return;
}
// 进入即在书末时先实际尝试一次右滑,之后才开始计时及首页判断。
var timer = entryRight ? null : publicationCountdown(page);
if (timer) {
noTimerSince = null;
if (!rightMode) writeRunLog("READ REWIND START: " + (reason || "已到书末") + ",右上倒计时未结束,改为持续右滑。");
rightMode = true;
} else if (!entryRight) {
if (noTimerSince === null) noTimerSince = Date.now();
if (Date.now() - noTimerSince >= CONFIG.readingCountdownClearMs) {
writeRunLog("READ REWIND DONE: 右上角连续2秒未识别到倒计时;共右滑" + turns + "次。");
return;
}
}
if (foregroundPackage() !== CONFIG.packageName) stopWith("应用已切换,停止阅读右滑");
if (publicationToolbarVisible(page)) {
page = dismissPublicationToolbar(page);
continue;
}
if (rightMode || entryRight) {
if (entryRight) writeRunLog("READ ENTRY RIGHT: 进入阅读即在最后一页,先尝试右滑,再判断倒计时或首页。");
var y = publicationSwipeY(page, turns);
if (swipe(device.width * 0.18, y, device.width * 0.82, y, 650) === false)
stopWith("阅读右滑执行失败,保留当前处理状态");
actionSerial++;
turns++;
firstRightPending = false;
sleep(CONFIG.readingPagePauseMs);
} else sleep(Math.min(CONFIG.pollMs, CONFIG.readingCountdownClearMs - (Date.now() - noTimerSince)));
page = snapshot();
var current = publicationPageCounter(page);
unchanged = current && previous && current.total === previous.total && current.current === previous.current ? unchanged + 1 : 0;
previous = current;
if (rightMode || entryRight) writeRunLog("READ RIGHT TURN: 第" + turns + "次右滑;页码=" + (current ? current.current + "/" + current.total : "未识别"));
}
stopWith("阅读右滑达到阅读时限,尚未确认无倒计时或回到首页,保留页面");
}
function runPublicationPages() {
var deadline = Date.now() + CONFIG.readingSessionTimeoutMs;
var page = snapshot();
if (!isPublicationReader(page) && !publicationEnd(page)) stopWith("未确认已进入出版物阅读页,暂不连续左滑");
var previousKey = readingPageKey(page);
var previousCounter = publicationPageCounter(page);
var unchanged = 0;
var turns = 0;
var recoveries = 0;
writeRunLog("READ START: 已确认出版物页面,按提示左滑开始并持续翻页。");
try {
keepScreenAwake();
while (Date.now() < deadline) {
var ending = publicationEnd(page);
if (ending) {
finishPublicationCountdown(page, deadline, turns === 0);
writeRunLog(turns > 0 ? "READ FINISHED: " + ending.text + ";共左滑" + turns + "次。" :
"READ END HANDLED: 进入时已在书末,已先尝试右滑再完成后续判断;不记为本轮重新读完整本。");
savePublicationClaimState(true, ending.text);
return true;
}
if (first(page, /^(?:解锁本章|购买本章|立即订阅|充值阅读|开通会员|付费阅读)$/))
stopWith("当前阅读页需要额外操作才能继续,保留页面");
if (first(page, /福利中心|日常福利/)) {
if (++recoveries > 3) stopWith("阅读反复返回福利中心超过3次,保留页面;尚未读完");
writeRunLog("READ RECOVER: 阅读未完成却回到福利中心,重新进入读出版物的去阅读,第" + recoveries + "/3次。");
page = enterPublicationReader(page);
previousKey = readingPageKey(page);
previousCounter = publicationPageCounter(page);
unchanged = 0;
continue;
}
if (foregroundPackage() !== CONFIG.packageName) stopWith("当前应用已切换,停止阅读左滑");
if (publicationToolbarVisible(page)) {
page = dismissPublicationToolbar(page);
previousKey = readingPageKey(page);
previousCounter = publicationPageCounter(page);
continue;
}
// 连续两次以页码/正文确认左滑不推进时,复用书末倒计时的反向阅读流程。
if (unchanged >= 2 && publicationReadingSurface(page) && publicationCountdown(page)) {
writeRunLog("READ STALLED: 左滑连续" + unchanged + "次未推进且右上仍有倒计时,切换持续右滑。");
finishPublicationCountdown(page, deadline, false, "左滑连续" + unchanged + "次未推进");
writeRunLog("READ STALL HANDLED: 已确认连续2秒无倒计时或到书本首页,返回首页后复查任务;不记为全书读完。");
return true;
}
var swipeY = publicationSwipeY(page, turns);
if (swipe(device.width * 0.82, swipeY, device.width * 0.18, swipeY, 650) === false)
stopWith("阅读左滑执行失败");
actionSerial++;
turns++;
sleep(CONFIG.readingPagePauseMs);
page = snapshot();
if (!isPublicationReader(page) && !publicationEnd(page))
stopWith("左滑后已离开出版物阅读页面,停止连续滑动并保留现场");
var currentKey = readingPageKey(page);
var counter = publicationPageCounter(page);
// 有页码时以页码为准,避免OCR噪声让未翻页被误报为进展。
var changed = counter && previousCounter && counter.total === previousCounter.total ?
counter.current !== previousCounter.current : currentKey && currentKey !== previousKey;
var comparable = counter && previousCounter && counter.total === previousCounter.total ||
currentKey && previousKey;
unchanged = changed || !comparable ? 0 : unchanged + 1;
if (changed && isPublicationReader(page)) recoveries = 0;
previousKey = currentKey;
previousCounter = counter;
if (turns <= 3 || turns % 10 === 0 || unchanged || changed) {
writeRunLog("READ TURN: 第" + turns + "次左滑;页码=" + (counter ? counter.current + "/" + counter.total : "未识别") + ";连续无变化=" + unchanged);
}
if (publicationEnd(page)) continue;
if (unchanged >= 5 && unchanged % 5 === 0) {
if (!isPublicationReader(page)) stopWith("卡页后未确认仍在阅读页面,保留页面检查,不能误报读完");
writeRunLog("READ RETRY: 尚未读完,重新检查菜单并切换左滑位置继续阅读。");
}
if (turns % 100 === 0) keepScreenAwake();
}
stopWith("阅读达到6小时异常保护上限,未识别到阅读结束,保留页面");
} finally {
keepScreenAwake(); // 阅读结束后仍需领奖,保持整次运行的亮屏租约。
}
}
function publicationReadingStep() {
enterPublicationReader(snapshot());
runPublicationPages();
}
function enterPublicationReader(page) {
if (!isPublicationReader(page) && !publicationEnd(page)) {
if (!first(page, /福利中心|日常福利/)) skipStep("当前没有读出版物任务页标签,跳过该步骤");
var entry = searchPublicationEntry();
if (!entry) skipStep("没有读出版物赚金币对应的去领取或去阅读按钮,跳过该步骤");
if (/^[||]?去[领颌颁頒]取$/.test(entry.text)) skipStep("出版物当前按钮已变为去领取,交回循环执行领取,不在领取入口等待正文");
for (var attempt = 1; attempt <= 3; attempt++) {
writeRunLog("PUBLICATION ENTRY: 点击读出版物赚金币的" + entry.text + ",第" + attempt + "次。");
tap(entry);
var deadline = Date.now() + CONFIG.pageTimeoutMs;
while (Date.now() < deadline) {
page = snapshot();
if (isPublicationReader(page) || publicationEnd(page)) break;
sleep(CONFIG.pollMs);
}
if (isPublicationReader(page) || publicationEnd(page)) break;
entry = findPublicationEntry(snapshot());
if (!entry) stopWith("出版物入口点击后尚未确认阅读页,原入口已变化,保留页面");
}
if (!isPublicationReader(page) && !publicationEnd(page)) stopWith("出版物入口三次点击仍未确认阅读页,保留页面");
}
return page;
}
var RESERVATION_LABEL = /^[||「『]?预[约約]领金币/;
var CASH_SIGN_LABEL = /^[||「『]?连续签到领现金188元/;
var DRAMA_LABEL = /^[||「『]?追剧挑战[赛塞賽]/;
var RESERVATION_ACTION = /^[||]?(?:立即预[约約]|去预[约約]|预[约約](?:领金币|领取)?|立即[领颌]{1,2}取|去[领颌]{1,2}取|领取|领\d+金币)$/;
var CASH_SIGN_ACTION = /^[||]?(?:去签到|立即签到|签到(?:领现金)?|签到领取|去领取|立即领取|去完成)$/;
var DRAMA_ACTION = /^[||]?(?:去看[剧劇]|去看剧情|继续看[剧劇]|立即[领颌]{1,2}取|去[领颌]{1,2}取)$/;
function earningPage(items) {
return !!(first(items, /^(?:福利中心|日常福利)$/) && bottomNavigation(items, /^赚钱$/));
}
// 任务名、按钮及完成状态必须位于同一行,不能借用相邻任务的“立即领取”。
function earningRowTarget(items, labelPattern, actionPattern, donePattern) {
if (!earningPage(items)) return null;
var label = first(items, labelPattern, function (item) {
return item.rect.top > device.height * 0.09 && item.rect.bottom < device.height * 0.91;
});
if (!label) return null;
var row = items.filter(function (item) {
return item.rect.top >= label.rect.top - device.height * 0.015 &&
item.rect.bottom <= label.rect.bottom + device.height * 0.06;
});
var button = first(row, actionPattern, function (item) {
return item.rect.left > device.width * 0.70 && item.rect.bottom < device.height * 0.92 &&
Math.abs(item.rect.top + item.rect.bottom - label.rect.top - label.rect.bottom) < device.height * 0.09;
});
var done = donePattern && first(row, donePattern);
return {label: label, button: button, done: !!done, status: done ? done.text : ""};
}
function findReservationTarget(items) {
return earningRowTarget(items, RESERVATION_LABEL, RESERVATION_ACTION, /明日领取|已预[约約]|明日可领/);
}
function findCashSignTarget(items) {
return earningRowTarget(items, CASH_SIGN_LABEL, CASH_SIGN_ACTION, /今日签到已完成|今日[已己]签到|明日再[来來采]|已完成/);
}
var RED_PACKET_LABEL = /^[||「『]?(?:红包(?:10|十)连(?:开|抽)|(?:10|十)连(?:开|抽)红包)/;
function pageSignature(items) {
return items.map(function (item) {
return item.text + ":" + Math.round(item.rect.left / 40) + ":" + Math.round(item.rect.top / 40);
}).sort().join("|");
}
var RED_PACKET_ENTRY_ACTION = /^(?!.*(?:已[领颌颁頒顿頓]{1,2}取|已完成|明日|领完))[||]?(?:.*[领颌颁頒顿頓]{1,2}取.*|去开红包|去完成|领红包|开红包|免费开红包|免费抽红包|开始(?:10|十)连(?:开|抽)|立即(?:10|十)连(?:开|抽))$/;
var RED_PACKET_OPEN_ACTION = /^[||]?(?:免费(?:开|抽)红包|(?:10|十)连(?:开|抽)|连(?:开|抽)(?:10|十)次|(?:开|抽)(?:启)?(?:10|十)个红包|(?:开|抽)(?:启)?(?:10|十)次|再(?:开|抽)(?:10|十)次|继续(?:开|抽)(?:10|十)次)$/;
var RED_PACKET_TASK_ACTION = /^(?!.*(?:已[领颌颁頒顿頓]{1,2}取|已完成|明日|领完))[||]?(?:.*[领颌颁頒顿頓]{1,2}取.*|去开红包|去完成|领红包|开红包|免费(?:开|抽)红包|开始(?:10|十)连(?:开|抽)|立即(?:10|十)连(?:开|抽)|(?:10|十)连(?:开|抽)|连(?:开|抽)(?:10|十)次|(?:开|抽)(?:启)?(?:10|十)个红包|(?:开|抽)(?:启)?(?:10|十)次|再(?:开|抽)(?:10|十)次|继续(?:开|抽)(?:10|十)次)$/;
function findRedPacketTarget(items) {
var target = earningRowTarget(items, RED_PACKET_LABEL, RED_PACKET_TASK_ACTION,
/(?:今日)?(?:红包)?(?:已领完|已开完|次数已用完|机会已用完)|今日已完成|明日再来|已完成/);
if (!target || target.button || target.done) return target;
// 只关联红包任务卡右侧按钮,兼容多行卡片及包含“领取”的按钮文案。
var label = target.label;
var nextTask = first(items, /^(?:预约领金币|连续签到领现金188元|红包(?:10|十)连(?:开|抽)|(?:10|十)连(?:开|抽)红包|读书挑战赛|追剧挑战赛|翻卡赢金币|吃饭补贴)$/, function (item) {
return item.rect.left < device.width * 0.7 && item.rect.top >= label.rect.bottom &&
item.rect.top - label.rect.bottom < device.height * 0.35;
});
var cardBottom = nextTask ? nextTask.rect.top : Math.min(device.height * 0.91, label.rect.bottom + device.height * 0.22);
var action = first(items, RED_PACKET_TASK_ACTION, function (item) {
return item.enabled !== false && item.rect.left > device.width * 0.7 &&
item.rect.top >= label.rect.top - device.height * 0.02 && item.rect.bottom <= cardBottom &&
item.rect.top - label.rect.bottom <= device.height * 0.22;
});
if (action) target.button = action;
return target;
}
function findRedPacketOpenAction(items) {
var action = first(items, RED_PACKET_OPEN_ACTION, function (item) {
return item.enabled !== false && item.rect.top > device.height * 0.2 && item.rect.bottom < device.height * 0.92;
});
if (action) return action;
// 十连开详情的大红包中央“开”;底部进度缩略图也含“开”,不能点击。
if (!first(items, RED_PACKET_LABEL) || !(first(items, /^已开[0-9Oo]+[//]10$/) || first(items, /^今天第\d+个红包$/))) return null;
return first(items, /^开$/, function (item) {
return item.enabled !== false && item.rect.left > device.width * 0.3 &&
item.rect.right < device.width * 0.7 && item.rect.top > device.height * 0.4 &&
item.rect.bottom < device.height * 0.7;
});
}
function redPacketUnavailable(items) {
if (first(items, RED_PACKET_LABEL) && first(items, /^已开10[//]10$/)) return true;
return !!first(items, /^(?:红包已领完|红包已开完|红包次数已用完|今日红包已领完|今日红包已开完|今日机会已用完|今日次数已用完|今日已达上限|次数已用完|机会已用完|明日再来|今日任务已完成)$/);
}
function refreshRedPacketEntry(page) {
var target = findRedPacketTarget(page);
return target && !target.done && target.button && target.button.enabled !== false ? target.button : null;
}
function redPacketTenOpenStep() {
var initialPage = snapshot();
if (redPacketUnavailable(initialPage)) { writeRunLog("RED PACKET DONE: 当前十连开已完成。"); return; }
var initialOpen = findRedPacketOpenAction(initialPage);
var detailHeading = first(initialPage, RED_PACKET_LABEL, function (item) { return item.rect.top < device.height * 0.2; });
for (var initialRetry = 0; detailHeading && !initialOpen && initialRetry < 5; initialRetry++) {
sleep(CONFIG.pollMs);
initialPage = snapshot();
if (redPacketUnavailable(initialPage)) { writeRunLog("RED PACKET DONE: 当前十连开已完成。"); return; }
initialOpen = findRedPacketOpenAction(initialPage);
}
if (detailHeading && !initialOpen) stopWith("红包十连开详情暂未识别可执行按钮,保留当前页面,不搜索背景任务");
var target = initialOpen ? {button: initialOpen} : searchPublicationAction(findRedPacketTarget, "红包10连开", /红包|连开|连抽|次数|机会/,
"RED PACKET SEARCH");
if (!target || target.done) {
writeRunLog(target ? "RED PACKET DONE: 红包10连开任务已显示完成或次数用完。" : "RED PACKET SKIP: 赚钱页没有红包10连开入口。");
return;
}
if (!target.button || target.button.enabled === false) {
writeRunLog("RED PACKET DONE: 红包任务当前没有可点击入口。");
return;
}
var deadline = Date.now() + CONFIG.redPacketSessionTimeoutMs;
var button = target.button;
var lastTapKey = "", stable = "", unchanged = 0;
if (!initialOpen && !RED_PACKET_OPEN_ACTION.test(button.text)) {
lastTapKey = pageSignature(snapshot()) + ":" + button.text;
tap(button, refreshRedPacketEntry);
}
while (Date.now() < deadline) {
var page = snapshot();
if (redPacketUnavailable(page)) {
writeRunLog("RED PACKET DONE: 页面明确显示红包次数或机会已用完。");
return;
}
if (earningPage(page)) {
target = findRedPacketTarget(page);
if (!target || target.done || !target.button) {
writeRunLog("RED PACKET DONE: 红包入口已消失、禁用或显示完成。");
return;
}
button = target.button;
if (!RED_PACKET_TASK_ACTION.test(button.text)) {
writeRunLog("RED PACKET DONE: 当前红包入口不可执行。");
return;
}
var cardKey = pageSignature(page) + ":" + button.text;
if (cardKey === lastTapKey) {
if (++unchanged >= 5) {
writeRunLog("RED PACKET DONE: 红包任务入口连续复查未变化,停止重复点击。");
return;
}
sleep(CONFIG.pollMs);
continue;
}
lastTapKey = cardKey;
unchanged = 0;
tap(button, refreshRedPacketEntry);
continue;
}
var open = findRedPacketOpenAction(page);
if (open) {
var key = pageSignature(page) + ":" + open.text;
if (key === stable) {
if (++unchanged >= 5) {
writeRunLog("RED PACKET DONE: 十连抽按钮连续复查未变化,停止重复点击。");
return;
}
sleep(CONFIG.pollMs);
continue;
}
stable = key;
unchanged = 0;
writeRunLog("RED PACKET OPEN: 点击" + open.text + ",完成一轮后重新检查可用次数。");
tap(open, findRedPacketOpenAction);
handleVideos(/./);
continue;
}
var signature = pageSignature(page);
if (signature && signature === stable) unchanged++;
else { stable = signature; unchanged = 0; }
if (unchanged >= 5) {
writeRunLog("RED PACKET DONE: 当前页面连续复查没有可执行的十连抽按钮。");
return;
}
sleep(CONFIG.pollMs);
}
stopWith("红包10连开流程运行超时,保留当前页面");
}
// 追剧只依据当前任务卡片,旧的固定集数和本地累计文件不参与完成判断。
var DRAMA_CLAIM = /^[||]?(?:(?:立即|去|可|待|点击)?[领颌颁頒]{1,2}取(?:金币)?|[领颌](?:取)?金币|(?:[领颌](?:取)?|看视频领)\d+(?:,\d{3})*金币)$/;
function findDramaTarget(items) {
if (isAdvertisementPage(items)) return null;
var target = earningRowTarget(items, DRAMA_LABEL, DRAMA_ACTION, null);
if (!target) return null;
var label = target.label;
var limit = Math.min(label.rect.bottom + device.height * 0.18, device.height * 0.92);
var nextCard = first(items, /^(?:[||「『]?(?:组队开红包|读书挑战|阅读挑战|读出版物|预约领金币|连续签到|看广告|看视频|吃饭补贴|饭点补贴|翻卡|听书赚|走路赚|逛街赚))/, function (item) {
return item.rect.left < device.width * 0.65 && item.rect.top > label.rect.bottom;
});
if (nextCard) limit = Math.min(limit, nextCard.rect.top - device.height * 0.015);
var milestones = matches(items, /^[||]?(\d+)集$/, function (item) {
return item.rect.top > label.rect.bottom && item.rect.bottom < limit;
}).map(function (item) { return {episodes: Number(item.text.replace(/[^\d]/g, "")), item: item, status: "unknown"}; });
// 奖励横排的尾部限定卡片范围,不能借用下一张任务卡片的领取按钮。
if (milestones.length) limit = Math.min(limit, Math.max.apply(null, milestones.map(function (m) { return m.item.rect.bottom; })) + device.height * 0.035);
var card = items.filter(function (item) { return item.rect.top >= label.rect.top - device.height * 0.015 && item.rect.bottom <= limit; });
var states = matches(card, /^(?:已领取|已领完|可领取|待领取|领取|立即领取|未解锁|未达标|不可领取|未完成)$/);
milestones.forEach(function (milestone) {
var nearby = states.filter(function (state) {
return Math.abs(state.rect.left + state.rect.right - milestone.item.rect.left - milestone.item.rect.right) < device.width * 0.18 &&
Math.abs(state.rect.top - milestone.item.rect.top) < device.height * 0.10;
});
if (nearby.some(function (item) { return /^(?:已领取|已领完)$/.test(item.text); })) milestone.status = "claimed";
else if (nearby.some(function (item) { return /^(?:未解锁|未达标|不可领取|未完成)$/.test(item.text); })) milestone.status = "locked";
else if (nearby.some(function (item) { return /^(?:可领取|待领取|领取|立即领取)$/.test(item.text); })) milestone.status = "claimable";
});
var remaining = [], progress = [], watched = [];
card.forEach(function (item) {
var rest = /(?:再(?:看|观看)|还(?:需|要)?(?:再)?(?:看|观看)?)(\d+)集/.exec(item.text);
if (rest) remaining.push(Number(rest[1]));
var count = /^(?:今日)?已(?:观看|看|追剧)[::]?(\d+)集$/.exec(item.text);
if (count) watched.push(Number(count[1]));
var value = /^(?:(?:今日)?(?:已(?:观看|看|追剧)|观看进度)[::]?)?(\d+)[\//](\d+)集?$/.exec(item.text);
if (value && Number(value[2]) > 0 && Number(value[1]) <= Number(value[2])) progress.push({watched: Number(value[1]), total: Number(value[2])});
});
target.progress = progress.length && progress.every(function (p) { return p.watched === progress[0].watched && p.total === progress[0].total; }) ? progress[0] : null;
target.watched = target.progress ? target.progress.watched : watched.length && watched.every(function (n) { return n === watched[0]; }) ? watched[0] : null;
target.remaining = remaining.length ? Math.min.apply(null, remaining) : null;
if (target.remaining === null && target.watched !== null) {
var future = milestones.filter(function (m) { return m.status !== "claimed" && m.episodes > target.watched; });
if (future.length) target.remaining = Math.min.apply(null, future.map(function (m) { return m.episodes; })) - target.watched;
else if (target.progress) target.remaining = target.progress.total - target.watched;
}
target.milestones = milestones;
target.done = !!first(card, /^(?:今日(?:追剧)?任务已完成|追剧挑战(?:赛)?已完成|全部奖励已领取|所有奖励已领取|今日奖励已领完)$/) ||
!!(milestones.length && milestones.every(function (m) { return m.status === "claimed"; }) && !(target.remaining > 0)) ||
!!(target.progress && target.progress.watched >= target.progress.total && target.remaining === 0 &&
!milestones.some(function (m) { return m.status === "locked" || m.episodes > target.progress.watched && m.status !== "claimed"; }));
var claim = first(card, DRAMA_CLAIM, function (item) {
if (item.rect.top < device.height * 0.09 || item.rect.bottom >= device.height * 0.92) return false;
if (item.rect.left > device.width * 0.7 && Math.abs(item.rect.top + item.rect.bottom - label.rect.top - label.rect.bottom) < device.height * 0.09) return true;
return milestones.some(function (m) {
return m.status !== "claimed" && m.status !== "locked" &&
Math.abs(item.rect.left + item.rect.right - m.item.rect.left - m.item.rect.right) < device.width * 0.18 &&
item.rect.top > label.rect.bottom && Math.abs(item.rect.top - m.item.rect.top) < device.height * 0.10;
});
});
target.action = claim ? "claim" : target.button && /看[剧劇]|看剧情/.test(target.button.text) ? "watch" : null;
if (claim) target.button = claim;
var claimed = matches(card, /^(?:已领取|已领完)$/).map(function (item) { return Math.round((item.rect.left + item.rect.right) / (device.width * 0.1)); }).sort().join(",");
target.claimKey = "drama:" + label.text.replace(/[^\d]/g, "") + ":" +
(claim ? Math.round((claim.rect.left + claim.rect.right) / (device.width * 0.1)) + ":" + claim.text.replace(/[^\d]/g, "") : "") +
":" + claimed + ":" + milestones.map(function (m) { return m.episodes + "=" + m.status; }).join(",") + ":" + target.remaining +
":" + (target.progress ? target.progress.watched + "/" + target.progress.total : "?");
target.claimAttempted = !!dramaClaimAttempts[target.claimKey];
target.needsAlign = label.rect.bottom > device.height * 0.74 && !milestones.length;
return target;
}
function findEarningDramaClaim(items) {
if (!activeTaskFlow || activeTaskFlow.name !== "追剧挑战赛" || dramaClaimActive || dramaBusySkipped) return null;
var target = findDramaTarget(items);
return target && target.action === "claim" && !target.claimAttempted ? target : null;
}
function claimDramaCoins(target) {
dramaClaimActive = true;
try {
var result = runTaskFlow("追剧挑战赛金币领取", function () {
writeRunLog("通用追剧规则:当前有可领金币,优先领取,再重新检查奖励档位和剩余集数。");
try { tap(target.button); }
catch (error) {
if (error.activityBusy) dramaClaimAttempts[target.claimKey] = true;
throw error;
}
dramaClaimAttempts[target.claimKey] = true;
handleVideos(/./);
});
if (result.busy) dramaBusySkipped = true;
return result;
} finally { dramaClaimActive = false; }
}
function ensureEarningPage() {
var page = snapshot();
if (!earningPage(page)) { returnHomeAndOpenEarning(); page = snapshot(); }
if (!earningPage(page)) stopWith("尚未确认回到赚钱页,不能判断新任务是否完成");
return page;
}
function searchNewEarningTask(finder, name, pattern) {
ensureEarningPage();
var target = searchPublicationAction(finder, name, pattern, "NEW TASK SEARCH");
for (var attempt = 0; target && (target.needsAlign || !target.done && !target.button && target.label.rect.bottom > device.height * 0.86); attempt++) {
if (attempt >= 3) stopWith(name + "任务行仍在导航边缘,不能认定按钮已消失");
// 先收掉前景弹窗,再小幅上移任务行,不能直接把底部被遮挡的按钮判成不存在。
var page = snapshot();
if (!earningPage(page)) stopWith(name + "对齐前已离开赚钱页");
if (swipe(Math.round(device.width * 0.5), Math.round(device.height * 0.72),
Math.round(device.width * 0.5), Math.round(device.height * 0.60), 800) === false) stopWith(name + "任务行对齐失败");
sleep(CONFIG.pollMs);
target = finder(snapshot());
if (!target) target = searchPublicationAction(finder, name, pattern, "NEW TASK SEARCH");
}
return target;
}
function reservationStep() {
var target = searchNewEarningTask(findReservationTarget, "预约领金币", /预[约約]|明日领取/);
if (!target) skipStep("赚钱页没有预约领金币任务,继续下一步");
if (target.done && !target.button) { writeRunLog("RESERVATION DONE: " + target.status + ",不等待明天。"); return; }
if (!target.button) skipStep("预约任务没有可执行按钮,继续下一步");
var lastListAction = target.button.text, listActions = 1;
tap(target.button);
var deadline = Date.now() + CONFIG.pageTimeoutMs * 3, attempts = 0;
while (Date.now() < deadline) {
var page = snapshot();
if (earningPage(page)) {
target = findReservationTarget(page);
if (!target || !target.button) { writeRunLog("RESERVATION RETURN: 已处理当前预约入口,继续下一任务。"); return; }
if (target.button.text !== lastListAction && listActions < 3) {
lastListAction = target.button.text;
listActions++;
writeRunLog("RESERVATION NEXT: 领取后入口变为" + lastListAction + ",继续完成明日预约。");
tap(target.button);
deadline = Date.now() + CONFIG.pageTimeoutMs * 3;
continue;
}
// 列表未变化不连点;下次启动仍按最新页面检查。
skipStep("预约入口点击后仍未变化,不重复点击旧任务");
}
var heading = first(page, /预[约約]领金币|预[约約]奖励/);
if (!heading) { sleep(CONFIG.pollMs); continue; }
if (first(page, /已预[约約]|明日可领|明日领取/)) break;
var action = first(page, RESERVATION_ACTION, function (item) {
return item.rect.top > device.height * 0.3 && item.rect.bottom < device.height * 0.92;
});
if (action && attempts++ < 2) { tap(action); continue; }
sleep(CONFIG.pollMs);
}
ensureEarningPage();
}
function cashSignStep() {
var target = searchNewEarningTask(findCashSignTarget, "连续签到领现金188元", /连续签到|188元|去签到/);
if (!target) skipStep("赚钱页没有连续签到领现金188元任务,继续下一步");
if (target.done && !target.button) { writeRunLog("CASH SIGN DONE: " + target.status + ",继续下一任务。"); return; }
if (!target.button) skipStep("现金签到任务没有可执行的签到按钮,继续下一步");
tap(target.button);
var deadline = Date.now() + CONFIG.pageTimeoutMs * 3, attempted = false;
while (Date.now() < deadline) {
var page = snapshot();
if (earningPage(page)) { writeRunLog("CASH SIGN RETURN: 签到入口已处理,复用通用规则后继续。"); return; }
if (!first(page, /签到领188元现金|连续签到领现金188元|签到进度/)) { sleep(CONFIG.pollMs); continue; }
if (first(page, /今日[已己]签到|今日签到已完成|明日可再领/)) {
writeRunLog("CASH SIGN DONE: 现金签到详情确认今日已签到。"); break;
}
var sign = first(page, /^[||]?(?:立即)?签到(?:领取|领(?:取)?[\d.]+元(?:现金)?|领现金)?$/, function (item) {
return item.rect.top > device.height * 0.4 && item.rect.bottom < device.height * 0.68;
});
if (sign && !attempted) { attempted = true; tap(sign); continue; }
sleep(CONFIG.pollMs);
}
// 不点提现、签到提醒或未来日期奖励;处理完当日入口返回赚钱页。
ensureEarningPage();
}
function runAdditionalEarningTasks() {
if (additionalTasksChecked) return;
additionalTasksChecked = true;
var tasks = [{name: "预约领金币", action: reservationStep}, {name: "连续签到领现金188元", action: cashSignStep},
{name: "红包10连开", action: redPacketTenOpenStep, timeoutMs: CONFIG.redPacketSessionTimeoutMs}];
for (var i = 0; i < tasks.length; i++) {
var result = runTaskStep(tasks[i].name, tasks[i].action, tasks[i].timeoutMs);
if (!result.ok) {
writeRunLog("NEW TASK RETRY: " + tasks[i].name + "首次识别异常,通用弹窗稳定后再试一次。");
sleep(CONFIG.pollMs);
runTaskStep(tasks[i].name + ":重试", tasks[i].action);
}
}
}
function dramaPreviewEntry(items) {
if (!bottomNavigation(items, /^短剧$/)) return null;
return first(items, /观看完整短剧/, function (item) { return item.rect.top > device.height * 0.7; });
}
function dramaEpisode(items) {
return first(items, /^[<く〈]?第\d+集$/, function (item) { return item.rect.top < device.height * 0.2; });
}
function dramaPlayer(items) {
return !!(dramaEpisode(items) && first(items, /选集|已完结.*全\d+集/, function (item) {
return item.rect.top > device.height * 0.85;
}));
}
function watchDramaRound(remainingEpisodes) {
// 本轮集数只用于提前回卡片复查,最终是否达标始终以平台奖励状态为准。
var candidate = null, stableEpisode = null, completed = 0;
var started = Date.now(), enteredAt = started, lastEpisode = "", lastProgressAt = started;
var fullEntryAttempts = 0, resumeAttempts = 0;
while (Date.now() - started < CONFIG.dramaRoundWatchMs) {
var page = snapshot(); // 广告、直播与弹窗仍优先处理,绝不在遮挡层上滑动播放器。
var full = dramaPreviewEntry(page);
if (full) {
if (++fullEntryAttempts > 3) stopWith("观看完整短剧入口连续三次未响应");
writeRunLog("DRAMA FULL: 从短剧推荐页进入完整短剧。");
tap(full);
enteredAt = Date.now();
continue;
}
if (earningPage(page)) { writeRunLog("DRAMA RETURN: 已返回赚钱页,重新检查挑战赛。"); return; }
if (!dramaPlayer(page)) {
if (Date.now() - enteredAt > CONFIG.pageTimeoutMs * 3) stopWith("未识别到完整短剧播放页,回赚钱页重查入口");
sleep(CONFIG.pollMs);
continue;
}
var episode = dramaEpisode(page).text;
var number = Number(episode.replace(/[^\d]/g, ""));
if (candidate === number && stableEpisode !== number) {
if (stableEpisode !== null && number === stableEpisode + 1) completed++;
stableEpisode = number;
}
candidate = number;
if (remainingEpisodes > 0 && completed >= remainingEpisodes) {
writeRunLog("DRAMA RECHECK: 已观察到本轮所需" + remainingEpisodes + "次连续换集,返回赚钱页核实达标和领取状态,不以播放器集号宣告完成。");
return;
}
if (episode !== lastEpisode) {
lastEpisode = episode;
lastProgressAt = Date.now();
resumeAttempts = 0;
writeRunLog("DRAMA WATCH: 正在播放" + episode + ";保持亮屏,等待自动连播。");
}
var next = first(page, /^(?:播放下一集|下一集|继续播放)$/, function (item) {
return item.rect.top > device.height * 0.25 && item.rect.bottom < device.height * 0.9;
});
if (next && resumeAttempts++ < 2) { tap(next); continue; }
if (first(page, /^(?:全剧终|全剧完|播放结束|已看完全部剧集)$/)) {
var nextDrama = first(page, /^(?:观看下一部|看下一部|下一部短剧|换部短剧|看看其他短剧)$/, function (item) {
return item.rect.top > device.height * 0.25 && item.rect.bottom < device.height * 0.93;
});
if (nextDrama) {
writeRunLog("DRAMA NEXT: 当前短剧结束,进入明确的下一部短剧入口,之后回挑战卡片核实奖励。");
tap(nextDrama);
enteredAt = Date.now();
continue;
}
writeRunLog("DRAMA END: 当前剧集播放结束,返回赚钱页检查奖励及下一轮。"); return;
}
if (Date.now() - lastProgressAt > CONFIG.dramaEpisodeStallMs) {
writeRunLog("DRAMA RECHECK: 同集长时间未变化,返回赚钱页重查,不连续盲滑。"); return;
}
sleep(CONFIG.dramaPollMs);
}
writeRunLog("DRAMA WATCH ROUND: 本轮观看结束,回赚钱页复查领取/去看剧。");
}
function runDramaTaskLoop() {
var emptyPasses = 0, rounds = 0, failures = 0, pending = false;
writeRunLog("DRAMA LOOP: 按挑战卡片的剩余集数和未领取奖励推进;可领先领,补看后回赚钱页重新检查,不设固定集数。");
while (true) {
if (dramaBusySkipped) return {ok: true, busy: true, skipped: true};
keepScreenAwake();
var found = runStep("追剧挑战赛:返回赚钱页并查找入口", function () {
return searchNewEarningTask(findDramaTarget, "追剧挑战赛", /追剧|去看[剧劇]|立即领取/);
});
// 通用领取可能在查找过程中触发繁忙;只跳过追剧,不阻塞原业务流程。
if (dramaBusySkipped) return {ok: true, busy: true, skipped: true};
if (!found.ok || found.skipped) {
failures++;
writeRunLog("DRAMA RETRY: 页面识别或返回异常,不把它记为任务消失;第" + failures + "次。");
sleep(failures < 3 ? 5000 : 15000);
continue;
}
var target = found.value;
var action = target && (target.action || (target.button ? (/看[剧劇]|看剧情/.test(target.button.text) ? "watch" : "claim") : null));
if (target) {
pending = action === "claim" || target.remaining > 0 || (target.milestones || []).some(function (m) { return m.status !== "claimed"; });
}
// 即使同时读到完成文案,也先处理当前明确的可领取按钮。
if (action === "claim" && !target.claimAttempted) {
var claimed = runStep("追剧挑战赛:领取当前金币", function () { return claimDramaCoins(target); });
if (claimed.ok && claimed.value && claimed.value.busy) return claimed.value;
emptyPasses = 0;
sleep(CONFIG.pollMs);
continue;
}
if (target && target.done && action !== "claim") {
writeRunLog("DRAMA LOOP DONE: 挑战卡片确认当前奖励已完成,没有待领取金币。");
return {ok: true};
}
if (!target || !target.button || action !== "watch") {
if (++emptyPasses >= 2) {
writeRunLog(pending ? "DRAMA INCOMPLETE: 仍有待达标或未确认领取的奖励,但两次复查没有可执行入口;不误报完成。" :
"DRAMA LOOP DONE: 赚钱页连续两次复查,没有可执行的追剧或领取条件。");
return {ok: !pending, incomplete: pending};
}
writeRunLog("DRAMA EMPTY: 当前无新操作,回赚钱页完整复查一次,不重复点击未变化的领取按钮。");
sleep(CONFIG.pollMs);
continue;
}
emptyPasses = 0;
var result = runStep("追剧挑战赛:" + target.button.text, function () {
writeRunLog("DRAMA ROUND: 第" + (++rounds) + "轮;" + (target.remaining === null || target.remaining === undefined ? "剩余集数未识别,分段观看后复查" : "当前奖励还需" + target.remaining + "集"));
tap(target.button);
watchDramaRound(target.remaining);
}, CONFIG.dramaRoundWatchMs + CONFIG.stepTimeoutMs);
failures = result.ok ? 0 : failures + 1;
if (!result.ok) writeRunLog("DRAMA RETRY: 本轮未完成,稍后回赚钱页复查,不能记录完成。");
sleep(failures ? 5000 : CONFIG.pollMs);
}
}
function findReadingChallengeClaim(items) {
var target = findEarningReadingChallengeClaim(items);
return target ? target.button : null;
}
function hasPendingReadingChallenge() {
if (!files.exists(CONFIG.publicationStatePath)) return false;
try {
var state = JSON.parse(files.read(CONFIG.publicationStatePath));
return state.pendingClaim === false && (state.nextTask === "readingChallenge" ||
(!state.nextTask && /^(?:恢复已点击领取后的流程,确认原任务按钮已变化|已点击立即领取,通用处理后原任务领取按钮不再显示)$/.test(state.evidence || "")));
} catch (error) { return false; }
}
function readingChallengeClaimStep() {
var before = Object.keys(readingChallengeClaims).length;
ensureTaskPage();
var target = searchPublicationAction(function (items) {
return Object.keys(readingChallengeClaims).length > before ? {commonHandled: true} : findEarningReadingChallengeClaim(items);
}, "读书挑战赛可领取金币", /挑战|阅读|[领颌颁頒]取/, "CHALLENGE SEARCH");
if (!target) skipStep("没有未尝试的读书挑战赛领取按钮,继续下一流程");
if (!target.commonHandled) claimReadingChallengeCoins(target);
writeRunLog("CHALLENGE CLAIM CHECKED: 当前读书挑战已按通用规则处理,不重复点击相同奖励。");
}
function runNextReadingChallenge() {
var result = runTaskStep("读书挑战赛:立即领取", readingChallengeClaimStep);
var challengeBusy = Object.keys(readingChallengeClaims).some(function (key) { return readingChallengeClaims[key] === "busy"; });
if (result.ok && !result.busy && !challengeBusy && files.exists(CONFIG.publicationStatePath)) {
var state = JSON.parse(files.read(CONFIG.publicationStatePath));
if (state.pendingClaim === false) {
state.nextTask = "done";
state.challengeResult = result.skipped ? "没有对应立即领取,已跳过" : "已点击立即领取并执行通用处理";
state.updatedAt = new Date().toISOString();
files.write(CONFIG.publicationStatePath, JSON.stringify(state));
}
}
writeRunLog(result.busy || challengeBusy ? "READING CHALLENGE: 活动繁忙,本次跳过,继续追剧挑战。" :
result.ok ? (result.skipped ? "READING CHALLENGE: 没有立即领取,继续追剧挑战。" : "READING CHALLENGE: 领取及通用处理结束,继续追剧挑战。") : "READING CHALLENGE: 本步骤异常,回赚钱页继续追剧挑战。");
var drama = runTaskFlow("追剧挑战赛", runDramaTaskLoop);
writeRunLog(drama.busy ? "END: 追剧挑战赛活动繁忙,本次跳过;前序流程已检查。" :
drama.incomplete ? "END INCOMPLETE: 追剧卡片仍有未达标或未确认领取的奖励,当前无可执行入口;下次重新检查。" :
"END: 出版物和读书挑战已检查,追剧已按当前奖励卡片检查观看及领取条件。");
return result;
}
function runNextPublication(resumeReader) {
var result = runTaskFlow("读出版物赚金币", function () { return runPublicationLoop(resumeReader); });
if (result && (result.ok === false || result.incomplete || result.skipped)) return result;
return runNextReadingChallenge();
}
function runPublicationLoop(resumeReader) {
var rounds = 0, readingFailures = 0, retryFailures = 0;
var emptyPasses = 0;
writeRunLog("PUBLICATION LOOP: 以当前出版物任务标签及右侧按钮为准,循环执行直到确认没有匹配;历史状态不限制进入。");
while (true) {
if (resumeReader) {
var reading = runStep("读出版物赚金币:持续左滑阅读", publicationReadingStep, CONFIG.readingSessionTimeoutMs + 30000);
if (!reading.ok || reading.skipped) {
writeRunLog("PUBLICATION RECOVERY: 阅读页面异常离开,保留未完成状态;先返回赚钱页复查并恢复阅读。");
var recovered = runStep("出版物异常后返回赚钱页", function () {
var current = snapshot();
if (foregroundPackage() !== CONFIG.packageName) stopWith("出版物异常后番茄不在前台,保留现场");
if (!earningPage(current)) returnHomeAndOpenEarning();
if (!earningPage(snapshot())) stopWith("出版物异常后未确认返回赚钱页,保留现场");
});
readingFailures++;
emptyPasses = 0;
resumeReader = false;
writeRunLog("PUBLICATION RETRY: 第" + readingFailures + "次阅读中断;" +
(recovered.ok && !recovered.skipped ? "已返回赚钱页" : "暂未确认赚钱页,下轮继续恢复") +
";继续复查去阅读/去领取,不因重试次数退出、不进入后续挑战。");
sleep(Math.min(15000, CONFIG.pollMs * readingFailures));
continue;
}
readingFailures = 0;
writeRunLog(reading.skipped ? "PUBLICATION RECHECK: 阅读入口已变化,重新识别当前任务。" :
"PUBLICATION RECHECK: 本轮阅读结束,返回赚钱页继续检查去领取/去阅读。");
resumeReader = false;
}
var returned = runStep("返回赚钱页复查出版物任务", function () {
var page = snapshot(); // 前景弹窗、直播退出、广告和宝箱规则先执行。
if (!first(page, /福利中心|日常福利/) || !bottomNavigation(page, /^赚钱$/)) returnHomeAndOpenEarning();
});
if (!returned.ok || returned.skipped) {
emptyPasses = 0;
writeRunLog("PUBLICATION RETRY: 尚未确认回到赚钱页,等待后继续恢复,不认定流程不可做。");
sleep(Math.min(15000, CONFIG.pollMs * ++retryFailures));
continue;
}
runAdditionalEarningTasks();
var found = runStep("识别出版物任务当前按钮", searchPublicationTask);
if (!found.ok || found.skipped) {
emptyPasses = 0;
writeRunLog("PUBLICATION RETRY: 出版物任务识别异常,等待后重新检查,不冒充无匹配。");
sleep(Math.min(15000, CONFIG.pollMs * ++retryFailures));
continue;
}
var target = found.value;
if (target !== null && (!target || (!target.button && target.action !== "none"))) {
emptyPasses = 0;
writeRunLog("PUBLICATION RETRY: 未取得有效任务状态,不能判定流程不可做。");
sleep(Math.min(15000, CONFIG.pollMs * ++retryFailures));
continue;
}
retryFailures = 0;
if (!target || !target.button) {
emptyPasses++;
writeRunLog("PUBLICATION EMPTY: " + (target ? "出版物标签存在但右侧无去领取/去阅读" : "未找到出版物标签") + ";复查" + emptyPasses + "/2。");
if (emptyPasses < 2) { sleep(CONFIG.pollMs); continue; }
writeRunLog("PUBLICATION LOOP DONE: 连续两次没有符合条件的出版物入口,继续下一任务;共执行" + rounds + "轮。");
return {ok: true};
}
emptyPasses = 0;
rounds++;
writeRunLog("PUBLICATION ROUND: 第" + rounds + "轮;右侧按钮=" + target.button.text + ";每轮结束后重新检查,不因曾读完或曾领取而跳过。");
if (target.action === "read") {
resumeReader = true;
continue;
}
var claimed = runStep("领取出版物奖励并执行通用规则", function () { return publicationClaimStep(target.button); });
if (!claimed.ok || claimed.skipped) {
writeRunLog("PUBLICATION RETRY: 出版物领取操作未确认,等待后重新识别,不退出、不记录为无匹配。");
sleep(CONFIG.pollMs);
continue;
}
resumeReader = !!(claimed.value && claimed.value.resumeReader);
// 按钮点击后已由tap及通用循环等待页面刷新,下一轮始终重新识别当前标签。
}
}
function runDaily() {
files.write(CONFIG.logPath, "");
writeRunLog("START: version=" + CONFIG.version + ";通用优先循环版;仅本地识别。");
var thisEngine = engines.myEngine();
writeRunLog("SOURCE: " + thisEngine.getSource());
startActivityBusyObserver();
var stoppedOldEngine = false;
engines.all().forEach(function (engine) {
if (engine.id !== thisEngine.id && /fanqie-(?:daily|publication-live)\.auto\.js$/.test(String(engine.getSource()))) {
writeRunLog("停止旧的同名脚本实例:" + engine.getSource());
engine.forceStop();
stoppedOldEngine = true;
}
});
if (stoppedOldEngine) sleep(500); // 等旧实例释放截图会话,避免新实例授权被其清理打断。
keepScreenAwake();
runStep("初始化本地 OCR", initLocalOcr, CONFIG.capturePermissionTimeoutMs + 5000);
if (CONFIG.useLocalOcr && !localOcrEnabled) {
writeRunLog("END: 本地 OCR 尚未就绪,请完成截屏授权后重试。");
return;
}
var startup = runStep("启动番茄小说", restartTargetApp, 45000);
if (!startup.ok) {
writeRunLog("END: 番茄启动失败,后续任务均无可操作页面。");
return;
}
if (consumePublicationResume()) {
writeRunLog("REPAIR RESUME: 恢复时仍先检查翻卡、预约/现金签到及红包10连开,再进入出版物流程。");
ensureEarningPage();
var repairFlip = runTaskStep("恢复前置:翻卡赢金币", flipCardStep, CONFIG.flipTaskTimeoutMs + 30000);
if (!repairFlip.ok) { writeRunLog("END: 恢复前置翻卡未完成,保留现场。"); return; }
runAdditionalEarningTasks();
runNextPublication(false);
return;
}
// 中断后若仍停留在翻卡弹窗,直接恢复当前任务,不滚动弹窗背后的福利列表。
var resumedPage = snapshot();
if (first(resumedPage, /活动时间/) && first(resumedPage, /今日签到|已签\d+[\//]\d+/)) {
returnFromSignPage();
resumedPage = snapshot();
}
// 状态文件只说明历史阅读奖励,不能据此跳过本次签到/补贴/翻卡。
// 仅当前屏幕确实为阅读现场时提前续读;历史待领奖留到阅读阶段处理。
if (publicationEnd(resumedPage) || isPublicationReader(resumedPage)) {
writeRunLog("RESUME: 当前处于出版物阅读现场;按新顺序先返回赚钱页检查翻卡和红包,再重新识别出版物入口。");
ensureEarningPage();
var readerFlip = runTaskStep("阅读前置:翻卡赢金币", flipCardStep, CONFIG.flipTaskTimeoutMs + 30000);
if (!readerFlip.ok) { writeRunLog("END: 阅读恢复前置翻卡未完成,保留现场。"); return; }
runAdditionalEarningTasks();
runNextPublication(false);
return;
}
writeRunLog("FLOW: 签到 -> 翻卡循环 -> 预约/现金签到 -> 红包10连开 -> 阅读/领奖 -> 读书挑战 -> 追剧挑战;已移除吃饭补贴及连续奖励。");
if (flipSettlementDone || findFlipButton(resumedPage)) {
writeRunLog("RESUME: 当前已有翻卡按钮,直接继续翻卡任务。");
var resumed = runTaskStep("恢复翻卡赢金币", flipCardStep, CONFIG.flipTaskTimeoutMs + 30000);
if (resumed.ok) {
writeRunLog(flipActionDone ? "翻卡流程结束:继续读出版物任务。" : "当前没有可执行翻卡按钮,继续读出版物任务。");
runAdditionalEarningTasks();
runNextPublication();
} else {
writeRunLog("END: 当前翻卡流程未完成,保留页面和文字日志。");
toastLog("翻卡流程未完成,请查看文字日志。");
}
return;
}
var results = [];
results.push(runTaskStep("当前页面及启动签到弹窗", claimStartupSignIn));
results.push(runStep("进入赚钱页面", function () {
var page = snapshot();
if (first(page, /福利中心|日常福利/) || first(page, MEAL_PAGE)) return;
var earn = first(page, /^赚钱$/, function (item) { return item.rect.top > device.height * 0.65; });
if (!earn) skipStep("没有底部赚钱标签,执行下一步骤");
tap(earn);
}, 30000));
results.push(runTaskStep("签到", signInStep));
var flipResult = runTaskStep("翻卡赢金币", flipCardStep, CONFIG.flipTaskTimeoutMs + 30000);
results.push(flipResult);
if (!flipResult.ok) {
writeRunLog("END: 翻卡循环未确认结束,保留页面,不将异常当成不可做。");
toastLog("翻卡流程未完成,请查看文字日志。");
return;
}
runAdditionalEarningTasks();
runNextPublication();
return;
}
function drainCommonBeforeExit() {
if (!localOcrEnabled || foregroundPackage() !== CONFIG.packageName) return;
for (var check = 0; check < 2; check++) {
snapshot(); // snapshot会持续执行通用规则,直到当前没有匹配。
if (check === 0) sleep(CONFIG.pollMs);
}
writeRunLog("COMMON FINAL: 结束前已复查通用条件,当前无可执行弹窗或广告规则。");
}
// 管理器暂停/超时强停引擎时也释放本脚本的亮屏锁。
if (typeof events !== "undefined" && typeof events.on === "function") {
events.on("exit", stopActivityBusyObserver);
events.on("exit", releaseScreenAwake);
}
try {
runDaily();
drainCommonBeforeExit();
} catch (error) {
writeRunLog("ERROR: " + error + "\n" + error.stack);
toastLog("本次运行异常结束:" + error);
throw error;
}
finally {
stopActivityBusyObserver();
// 授权超时后可能迟到返回;失败路径也必须释放截图会话。
try { images.stopScreenCapture(); } catch (releaseError) { log(String(releaseError)); }
if (captureWorker && captureWorker.isAlive()) captureWorker.interrupt();
releaseScreenAwake();
}