From ec26e73bbad838690d07351df90df0d363f0d77b Mon Sep 17 00:00:00 2001 From: hmz Date: Wed, 21 Oct 2026 15:14:07 +0800 Subject: [PATCH] init --- fanqie_auto/fanqie-daily.auto.js | 2164 ++++++++++++++++++++++++ fanqie_auto/fanqie-flow.md | 433 +++++ fanqie_auto/tests/flow-order.test.js | 1421 ++++++++++++++++ hongguo_auto/README.md | 76 + hongguo_auto/hongguo-daily.auto.js | 1622 ++++++++++++++++++ hongguo_auto/tests/mass-video.test.js | 225 +++ hongguo_auto/tests/meal.test.js | 59 + hongguo_auto/tests/sign-in.test.js | 147 ++ qimao_auto/README.md | 19 + qimao_auto/qimao-daily.auto.js | 1323 +++++++++++++++ qimao_auto/tests/recovery.test.js | 124 ++ task_manager/README.md | 90 + task_manager/deploy-oppo.sh | 13 + task_manager/dist/任务管理器.zip | Bin 0 -> 16941 bytes task_manager/examples/smoke-failure.js | 5 + task_manager/examples/smoke-success.js | 7 + task_manager/examples/smoke-wait.js | 9 + task_manager/lib/autojs-adapter.js | 108 ++ task_manager/lib/scheduler.js | 217 +++ task_manager/task-manager.auto.js | 335 ++++ task_manager/tests/adapter.test.js | 109 ++ task_manager/tests/scheduler.test.js | 180 ++ task_manager/tests/ui.test.js | 154 ++ yingyongbao_auto | 1 + 24 files changed, 8841 insertions(+) create mode 100644 fanqie_auto/fanqie-daily.auto.js create mode 100644 fanqie_auto/fanqie-flow.md create mode 100644 fanqie_auto/tests/flow-order.test.js create mode 100644 hongguo_auto/README.md create mode 100644 hongguo_auto/hongguo-daily.auto.js create mode 100644 hongguo_auto/tests/mass-video.test.js create mode 100644 hongguo_auto/tests/meal.test.js create mode 100644 hongguo_auto/tests/sign-in.test.js create mode 100644 qimao_auto/README.md create mode 100644 qimao_auto/qimao-daily.auto.js create mode 100644 qimao_auto/tests/recovery.test.js create mode 100644 task_manager/README.md create mode 100755 task_manager/deploy-oppo.sh create mode 100644 task_manager/dist/任务管理器.zip create mode 100644 task_manager/examples/smoke-failure.js create mode 100644 task_manager/examples/smoke-success.js create mode 100644 task_manager/examples/smoke-wait.js create mode 100644 task_manager/lib/autojs-adapter.js create mode 100644 task_manager/lib/scheduler.js create mode 100644 task_manager/task-manager.auto.js create mode 100644 task_manager/tests/adapter.test.js create mode 100644 task_manager/tests/scheduler.test.js create mode 100644 task_manager/tests/ui.test.js create mode 160000 yingyongbao_auto diff --git a/fanqie_auto/fanqie-daily.auto.js b/fanqie_auto/fanqie-daily.auto.js new file mode 100644 index 0000000..1f28a1b --- /dev/null +++ b/fanqie_auto/fanqie-daily.auto.js @@ -0,0 +1,2164 @@ +"auto"; + +// Auto.js / AutoX.js / AutoJs6:启动后打开番茄小说,并识别可恢复的当前页面。 +// 页面识别:无障碍文字 + 可选的本地 $ocr.detect;图片不上传、不写入日志。 +// 执行已确认的签到、吃饭补贴、连续奖励、翻卡及读出版物连续阅读任务。 +var CONFIG = { + version: "2026-10-21-monitor-84", + packageName: "com.dragon.read", + rewardThreshold: 500, + pollMs: 1200, + pageTimeoutMs: 5000, + videoTimeoutMs: 180000, + maxVideos: 15, + maxScrolls: 1, + stepTimeoutMs: 240000, + mealSessionTimeoutMs: 1800000, + mealBusyRetries: 2, + mealBusyRetryMs: 5000, + flipSessionTimeoutMs: 1800000, + 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 treasureAttemptedAmounts = {}; +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"); +} + +function stopWith(message) { + throw new Error(message.replace(/已停止/g, "本步骤跳过")); +} + +// 任务和识别分别限时;结束旧线程后才允许后续任务使用屏幕。 +function boundedCall(name, timeoutMs, action) { + var result; + var failure; + var worker = threads.start(function () { + try { result = action(); } catch (error) { failure = error; } + }); + var deadline = Date.now() + timeoutMs; + try { + while (worker.isAlive() && Date.now() < deadline) sleep(100); + if (worker.isAlive()) { + worker.interrupt(); + worker.join(1500); + var timeout = new Error(name + "超时(" + timeoutMs + "ms)"); + if (worker.isAlive()) timeout.unsafeWorker = true; + throw timeout; + } + if (failure) throw failure; + return result; + } finally { + if (worker.isAlive()) { + worker.interrupt(); + worker.join(1500); + if (worker.isAlive()) { + var unsafe = new Error(name + "的线程无法终止,不能让旧任务与下一任务同时点击"); + unsafe.unsafeWorker = true; + throw unsafe; + } + } + } +} + +function runStep(name, action, timeoutMs) { + writeRunLog("STEP START: " + name); + try { + var value = boundedCall(name, timeoutMs || CONFIG.stepTimeoutMs, action); + writeRunLog("STEP DONE: " + name); + return {ok: true, value: value}; + } catch (error) { + if (error.unsafeWorker || error.captureFatal) throw error; + writeRunLog("STEP SKIP: " + name + ";原因=" + error + ";继续下一步骤"); + return {ok: !!error.noMatch, skipped: true}; + } +} + +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 (!requestScreenCapture(false)) stopWith("未获得本机截屏权限;无需上传图片。"); + localOcrEnabled = true; + }); +} + +function isProjectionFailure(error) { + return /MediaProjection|VirtualDisplay|resultData|projection instance|Failed to capture screen|截图通道不可用/.test(String(error)); +} + +function readPage(name) { + try { + return captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot); + } catch (error) { + if (error.unsafeWorker || !isProjectionFailure(error)) throw error; + if (captureRecoveries >= CONFIG.captureRecoveryLimit) { + error.captureFatal = true; + writeRunLog("截图通道连续失效,结束本次运行;不能将识别故障当作类目缺失。"); + throw error; + } + captureRecoveries++; + writeRunLog("CAPTURE RECOVER: " + captureRecoveries + "/" + CONFIG.captureRecoveryLimit + ";释放失效投影并重新申请本机截屏。"); + try { + captureCall("恢复截图授权", CONFIG.capturePermissionTimeoutMs, function () { + images.stopScreenCapture(); + if (!requestScreenCapture(false)) throw new Error("恢复截图授权未获允许"); + sleep(500); + }); + var page = captureCall("恢复后重新识别", CONFIG.recognitionTimeoutMs, readSnapshot); + writeRunLog("CAPTURE RECOVERED: 本机页面识别已恢复。"); + return page; + } catch (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 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 isAdvertisementPage(items) { + return !!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 needsCommonHandling(items) { + if (liveExitAction(items)) return true; + if (findFlipRewardReceiptHeading(items)) return true; + if (cappedRewardPopup(items)) return true; + if (findListeningPopupClose(items) || findPlaybackPopupDismiss(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)); +} + +function snapshot() { + var page = readPage("页面识别"); + var deadline = Date.now() + CONFIG.stepTimeoutMs; + while (!commonHandling && needsCommonHandling(page)) { + if (Date.now() >= deadline) stopWith("通用页面处理超时,保留当前页面"); + writeRunLog("通用规则优先:暂停当前任务,先处理倒计时、关闭或额外奖励。"); + handleVideos(/./); + page = readPage("通用处理后重新识别"); + // 广告切换或弹窗动画中关闭按钮可能晚一帧出现;重新执行通用规则,不能全局退出。 + } + return page; +} + +// 小号X常被整屏OCR漏掉;只在手机内存裁剪放大右上区域再识别。 +function readCloseRegion(frame, items, region) { + var left = region ? region.left : Math.floor(device.width * 0.55); + var top = region ? region.top : Math.floor(device.height * 0.045); + var width = region ? region.width : device.width - left; + var height = region ? region.height : Math.floor(device.height * 0.22); + var crop = null; + var enlarged = null; + try { + crop = images.clip(frame, left, top, width, height); + enlarged = images.resize(crop, [width * 3, height * 3]); + var results = $ocr.detect(enlarged); + if (!Array.isArray(results)) return; + for (var i = 0; i < results.length; i++) { + var raw = results[i].bounds; + if (!raw) continue; + function at(key) { return Number(typeof raw[key] === "function" ? raw[key]() : raw[key]); } + var rect = rectOf({left: left + at("left") / 3, top: top + at("top") / 3, + right: left + at("right") / 3, bottom: top + at("bottom") / 3}); + var value = compact(results[i].text); + if (rect && /^(?:关闭|关闭广告|[xX×✕✖✗✘]|(?:领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕])$/.test(value)) { + items.push({text: /^[xX×✕✖✗✘]$/.test(value) ? "X" : value, rect: rect, node: null}); + writeRunLog("局部放大识别关闭:" + value + " @" + Math.round(rect.left) + "," + Math.round(rect.top)); + } + } + } finally { + if (enlarged) enlarged.recycle(); + if (crop) crop.recycle(); + } +} + +function readReceiptCloseRegion(frame, items) { + var 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 = 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() { + 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(); + } + } + 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) { + if (!item) skipStep("没有目标标签,执行下一步骤"); + if (!commonHandling) { + var freshPage = snapshot(); + var original = item; + item = first(freshPage, {test: function (value) { return value === original.text; }}, function (candidate) { + return Math.abs(candidate.rect.top - original.rect.top) < 40 && + Math.abs(candidate.rect.left - original.rect.left) < 40; + }); + if (!item) skipStep("通用处理后目标标签已改变,跳过旧坐标点击"); + } + if (foregroundPackage() !== CONFIG.packageName) stopWith("点击前页面已离开番茄小说,已停止。"); + var tapX = Math.round((item.rect.left + item.rect.right) / 2); + var tapY = Math.round((item.rect.top + item.rect.bottom) / 2); + writeRunLog("点击:" + item.text + " @" + tapX + "," + tapY); + var ok = false; + if (item.node) { + // 不向上寻找大范围可点击容器,以免触发相邻任务。 + try { if (item.node.clickable()) ok = item.node.click(); } catch (e) { ok = false; } + } + if (!ok) ok = press(tapX, tapY, 80); + writeRunLog("点击结果:" + ok); + if (!ok) stopWith("点击失败:" + item.text); + actionSerial++; + sleep(CONFIG.pollMs); +} + +function waitFor(pattern, timeout, predicate) { + var deadline = Date.now() + (timeout || CONFIG.pageTimeoutMs); + while (Date.now() < deadline) { + var found = first(snapshot(), pattern, predicate); + if (found) return found; + sleep(CONFIG.pollMs); + } + return null; +} + +function isTopRight(item) { + // 倒计时长文字会向左延伸,按文字中心判断,不能只检查左边界。 + return (item.rect.left + item.rect.right) / 2 >= device.width * 0.55 && + item.rect.top < device.height * 0.30; +} + +function 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) { + return 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 findRewardReceiptClose(items) { + if (flipPopupHasAction(items)) return null; + if (findFlipSettlementHeading(items) || findMoreCoinsButton(items)) return null; + var heading = rewardReceiptHeading(items); + if (!heading) return null; + if (findReceiptEligibleClaim(items)) return null; + var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + }); + if (close) return close; + // 透明弹窗下方的 X 可能与背景文字合框,只提取末尾字形,不点整段文字。 + var merged = first(items, /[xX×✕]$/, function (item) { + var glyphWidth = (item.rect.right - item.rect.left) / item.text.length; + var glyphCenter = item.rect.right - glyphWidth / 2; + return item.rect.top >= heading.rect.bottom && item.rect.top > device.height * 0.45 && + item.rect.top < device.height * 0.92 && glyphCenter > device.width * 0.35 && glyphCenter < device.width * 0.65; + }); + if (!merged) return null; + var width = (merged.rect.right - merged.rect.left) / merged.text.length; + return {text: "关闭奖励弹窗(" + merged.text + ")", node: null, rect: { + left: merged.rect.right - width, right: merged.rect.right, + top: merged.rect.top, bottom: merged.rect.bottom + }}; +} + +function 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 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) { + // 广告右上角“再看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 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; + while (Date.now() < deadline) { + var items = snapshot(); + 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; + // 重试保护只计算按钮持续存在时的连续失败;新倒计时或按钮消失说明页面已推进。 + // 不可把不同广告在同一坐标的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) + stopWith("宝箱最高再领弹窗仍在前台,但关闭按钮未识别,保留现场,不搜索背景任务"); + 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 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); + if (findFlipRewardReceiptHeading(items)) { + flipSettlementDone = true; + flipActionDone = true; + writeRunLog("FLIP RECEIPT DONE: 已关闭翻卡奖励确认弹窗,继续后续阅读,不重复进入翻卡。"); + } + flipReceiptMissingSince = null; + continue; + } + if (findFlipRewardReceiptHeading(items) && !findReceiptEligibleClaim(items) && !findMoreCoinsButton(items)) { + if (flipReceiptMissingSince === null) flipReceiptMissingSince = Date.now(); + if (Date.now() - flipReceiptMissingSince >= CONFIG.pageTimeoutMs) + stopWith("翻卡奖励弹窗仍在前台但关闭未识别,不搜索背景任务"); + writeRunLog("翻卡奖励确认:等待关闭控件刷新,不搜索背景任务。"); + sleep(CONFIG.pollMs); + continue; + } + flipReceiptMissingSince = null; + 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 && (!flipPopupHasAction(items) || offer.amount >= CONFIG.rewardThreshold)) { + stableReturn = 0; + if (++actions > CONFIG.maxVideos * 4) stopWith("弹窗处理次数达到上限,页面可能没有响应,已停止。"); + var take = offer.amount !== null && offer.amount >= CONFIG.rewardThreshold; + var button = first(items, take ? /^(领取奖励|领更多金币|颌更多金币|确认|继续领金币|看视频领取|看视频领\d+金币|看视频(?:再得|再领|领)\d+金币)$/ : /^[||]?(坚持退出|退出|[xX×✕])$/, + function (item) { return item.rect.top >= offer.heading.rect.top && + item.rect.top < offer.heading.rect.bottom + device.height * 0.30; }); + if (!button && !take) button = findEmptyRewardPopupClose(items, true); + if (!button) stopWith("未识别到额外奖励的" + (take ? "确认" : "退出") + "按钮,已停止。"); + if (take && accepted >= CONFIG.maxVideos) stopWith("已达到本次视频数量上限,停止继续领取。"); + writeRunLog("额外奖励 " + (offer.amount === null ? "金额不明确" : offer.amount + " 金币") + ":" + (take ? "继续观看" : "退出")); + tap(button); + if (take) { accepted++; sawCountdown = false; } + deadline = Date.now() + CONFIG.videoTimeoutMs; + continue; + } + var popupClose = findEmptyRewardPopupClose(items); + var foregroundClose = popupClose && !isTopRight(popupClose) ? popupClose : null; + 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 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; + } + // 无倒计时、无关闭、无额外奖励就交还调度,不等待旧的返回页标签。 + 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 (!/^活动繁忙[,,]?请稍后再试[。!!]?$/.test(message)) return; + mealBusyFeedback = {time: Date.now(), message: message}; + writeRunLog("饭点应用提示:" + message); +} + +function claimMealButton(claim, returnPattern) { + var key = mealClaimKey(claim); + for (var retry = 0; retry <= CONFIG.mealBusyRetries; retry++) { + var started = Date.now(); + tap(claim); + handleVideos(returnPattern || MEAL_PAGE); + // 提示可能晚于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() { + // 监听绑定主线程,避免带事件循环的任务线程结束动作后仍存活,阻塞runStep。 + try { + events.observeToast(); + events.onToast(receiveMealToast); + return runStep("吃饭补贴", mealStep, CONFIG.mealSessionTimeoutMs + 30000); + } finally { + events.removeListener("toast", receiveMealToast); + } +} + +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, /^翻卡[赢贏嘉羸]金币/); + return first(items, /^立即翻卡$/, function (button) { + return labels.some(function (label) { + return 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 searchFlipEntry() { + var entry = findFlipEntry(snapshot()); + if (entry) return entry; + // 上一步可能把福利列表停在下方;先向列表顶部找,再有界向下搜索。 + for (var i = 0; i < 2; i++) { + swipe(device.width * 0.5, device.height * 0.35, device.width * 0.5, device.height * 0.8, 400); + sleep(CONFIG.pollMs); + entry = findFlipEntry(snapshot()); + if (entry) return entry; + } + for (var j = 0; j < 4; j++) { + swipe(device.width * 0.5, device.height * 0.8, device.width * 0.5, device.height * 0.35, 400); + sleep(CONFIG.pollMs); + entry = findFlipEntry(snapshot()); + if (entry) return entry; + } + 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() { + if (flipActionDone || flipSettlementDone) return; + 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 transientRetries = 0; + while (Date.now() < deadline) { + try { + if (flipSettlementDone) return; + var flip = waitFor(FLIP_BUTTON, CONFIG.pageTimeoutMs, isFlipButton); + if (flipSettlementDone) return; + 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; + } + sleep(CONFIG.pollMs); + continue; + } + if (++clicks > 20) stopWith("翻卡达到20次异常保护上限,未确认全部完成,保留页面"); + emptyPasses = 0; + writeRunLog("FLIP ACTION: 第" + clicks + "次,点击 " + flip.text); + tap(flip); + 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; + 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, /^(?:全书完|全文完|本书完|本书已读完|已读完本书|阅读完毕|已读完|已到最后一页|已经是最后一页|已经是最后一章|没有下一章|本书已完结|全书阅读完成)[。.!!]?$/) || + first(items, /^(?:阅读进度[::]?)100(?:\.0)?[%%]$/); +} + +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) { + return !!publicationPageCounter(items) && + matches(items, /^(?:上一章|下一章|目录|夜间|设置|阅读设置)$/).length >= 2; +} + +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 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 = device.height * [0.38, 0.55, 0.65][unchanged % 3]; + 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 { + if (typeof device.keepScreenOn === "function") device.keepScreenOn(3600000); + 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 = [0.38, 0.55, 0.65][unchanged % 3]; + if (swipe(device.width * 0.82, device.height * swipeY, device.width * 0.18, device.height * swipeY, 650) === false) + stopWith("阅读左滑执行失败"); + actionSerial++; + turns++; + sleep(CONFIG.readingPagePauseMs); + page = snapshot(); + 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 && typeof device.keepScreenOn === "function") device.keepScreenOn(3600000); + } + stopWith("阅读达到6小时异常保护上限,未识别到阅读结束,保留页面"); + } finally { + if (typeof device.cancelKeepingAwake === "function") device.cancelKeepingAwake(); + } +} + +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; +} + +function findReadingChallengeClaim(items) { + var labels = matches(items, /^[||「『]?(?:读)?书挑战[赛塞賽]/); + return first(items, /^[||]?立即[领颌颁頒]取$/, function (button) { + return labels.some(function (label) { + return button.rect.left > label.rect.right && + Math.abs((button.rect.top + button.rect.bottom - label.rect.top - label.rect.bottom) / 2) < device.height * 0.045; + }); + }); +} + +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() { + ensureTaskPage(); + var claim = searchPublicationAction(findReadingChallengeClaim, "读书挑战赛立即领取", /挑战|阅读|立即[领颌颁頒]取/, "CHALLENGE SEARCH"); + if (!claim) skipStep("没有读书挑战赛对应的立即领取,跳过下一流程"); + writeRunLog("CHALLENGE CLAIM: 点击读书挑战赛同一行的立即领取。"); + tap(claim); + handleVideos(/福利中心|日常福利/); + writeRunLog("CHALLENGE CLAIM CLICKED: 已点击立即领取并完成通用处理。"); +} + +function runNextReadingChallenge() { + var result = runStep("读书挑战赛:立即领取", readingChallengeClaimStep); + if (result.ok && 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.ok ? (result.skipped ? "END: 读书挑战赛立即领取不存在,已跳过。" : "END: 已点击读书挑战赛立即领取并处理通用流程。") : "END: 读书挑战赛处理遇到异常,保留页面和文字日志。"); + return result; +} + +function runNextPublication(resumeReader) { + var rounds = 0; + var emptyPasses = 0; + writeRunLog("PUBLICATION LOOP: 以当前出版物任务标签及右侧按钮为准,循环执行直到确认没有匹配;历史状态不限制进入。"); + while (true) { + if (resumeReader) { + var reading = runStep("读出版物赚金币:持续左滑阅读", publicationReadingStep, CONFIG.readingSessionTimeoutMs + 30000); + if (!reading.ok) { + writeRunLog("END: 出版物阅读遇到异常,保留现场和状态,不记录为无匹配或已完成。"); + return reading; + } + 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) { + writeRunLog("END: 尚未确认回到赚钱页,保留现场,不能认定出版物条件已消失。"); + return returned; + } + var found = runStep("识别出版物任务当前按钮", searchPublicationTask); + if (!found.ok || found.skipped) { + writeRunLog("END: 出版物任务识别异常,保留现场,不冒充无匹配。"); + return found; + } + var target = found.value; + if (!target || !target.button) { + emptyPasses++; + writeRunLog("PUBLICATION EMPTY: " + (target ? "出版物标签存在但右侧无去领取/去阅读" : "未找到出版物标签") + ";复查" + emptyPasses + "/2。"); + if (emptyPasses < 2) { sleep(CONFIG.pollMs); continue; } + writeRunLog("PUBLICATION LOOP DONE: 连续两次没有符合条件的出版物入口,继续下一任务;共执行" + rounds + "轮。"); + return runNextReadingChallenge(); + } + 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) { + writeRunLog("END: 出版物领取操作异常,保留现场,不记录为无匹配。"); + return claimed; + } + 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()); + 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); // 等旧实例释放截图会话,避免新实例授权被其清理打断。 + runStep("初始化本地 OCR", initLocalOcr, CONFIG.capturePermissionTimeoutMs + 5000); + if (CONFIG.useLocalOcr && !localOcrEnabled) { + writeRunLog("END: 本地 OCR 尚未就绪,请完成截屏授权后重试。"); + return; + } + var startup = runStep("启动番茄小说", function () { + auto.waitFor(); + if (foregroundPackage() !== CONFIG.packageName && !app.launchPackage(CONFIG.packageName)) stopWith("无法打开番茄小说"); + var deadline = Date.now() + CONFIG.pageTimeoutMs; + while (foregroundPackage() !== CONFIG.packageName && Date.now() < deadline) sleep(300); + if (foregroundPackage() !== CONFIG.packageName) stopWith("等待番茄进入前台超时"); + sleep(CONFIG.pollMs); + }, 25000); + if (!startup.ok) { + writeRunLog("END: 番茄启动失败,后续任务均无可操作页面。"); + return; + } + // 中断后若仍停留在翻卡弹窗,直接恢复当前任务,不滚动弹窗背后的福利列表。 + var resumedPage = snapshot(); + if (first(resumedPage, /活动时间/) && first(resumedPage, /今日签到|已签\d+[\//]\d+/)) { + returnFromSignPage(); + resumedPage = snapshot(); + } + // 状态文件只说明历史阅读奖励,不能据此跳过本次签到/补贴/翻卡。 + // 仅当前屏幕确实为阅读现场时提前续读;历史待领奖留到阅读阶段处理。 + if (publicationEnd(resumedPage) || isPublicationReader(resumedPage)) { + writeRunLog("RESUME: 当前确认为出版物阅读现场,恢复阅读或完读领取。"); + runNextPublication(true); + return; + } + writeRunLog("FLOW: 签到 -> 吃饭补贴 -> 翻卡 -> 阅读 -> 领奖励;历史领奖状态不抢占前置任务。"); + if (flipSettlementDone) { + writeRunLog("翻卡流程结束:已点击开心收下,继续读出版物任务。"); + runNextPublication(); + return; + } + if (findFlipButton(resumedPage)) { + writeRunLog("RESUME: 当前已有翻卡按钮,直接继续翻卡任务。"); + var resumed = runStep("恢复翻卡赢金币", flipCardStep, CONFIG.flipSessionTimeoutMs + 30000); + if (resumed.ok) { + writeRunLog(flipActionDone ? "翻卡流程结束:继续读出版物任务。" : "当前没有可执行翻卡按钮,继续读出版物任务。"); + runNextPublication(); + } else { + writeRunLog("END: 当前翻卡流程未完成,保留页面和文字日志。"); + toastLog("翻卡流程未完成,请查看文字日志。"); + } + return; + } + var results = []; + results.push(runStep("当前页面及启动签到弹窗", 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(runStep("签到", signInStep)); + results.push(runMealStep()); + results.push(runStep("连续5天当日奖励", function () { + if (mealPageDone) { writeRunLog("跳过:连续奖励已在补贴页循环检查。"); return; } + ensureTaskPage(); + finishStreak(); + })); + var flipResult = runStep("翻卡赢金币", flipCardStep, CONFIG.flipSessionTimeoutMs + 30000); + results.push(flipResult); + if (flipActionDone && !flipResult.ok) { + writeRunLog("END: 已点击翻卡,但后续通用弹窗处理未完成;保留页面,不重复翻卡。"); + toastLog("已点击翻卡,后续弹窗未处理完成,请查看文字日志。"); + return; + } + if (flipActionDone) { + writeRunLog("翻卡流程结束:继续读出版物任务。"); + runNextPublication(); + return; + } + if (flipEntryOpened) { + if (flipResult.ok && flipResult.skipped) { + writeRunLog("翻卡入口已打开,但当前没有可执行翻卡按钮;跳过本轮,继续读出版物任务。"); + runNextPublication(); + return; + } + writeRunLog("END: 已进入翻卡页,但未完成翻卡按钮操作;保留页面及文字日志。"); + toastLog("已进入翻卡页,未完成翻卡操作,请查看文字日志。"); + return; + } + 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: 结束前已复查通用条件,当前无可执行弹窗或广告规则。"); +} + +try { + runDaily(); + drainCommonBeforeExit(); +} catch (error) { + writeRunLog("ERROR: " + error + "\n" + error.stack); + toastLog("本次运行异常结束:" + error); + throw error; +} + +finally { + // 授权超时后可能迟到返回;失败路径也必须释放截图会话。 + try { images.stopScreenCapture(); } catch (releaseError) { log(String(releaseError)); } + if (captureWorker && captureWorker.isAlive()) captureWorker.interrupt(); +} diff --git a/fanqie_auto/fanqie-flow.md b/fanqie_auto/fanqie-flow.md new file mode 100644 index 0000000..63ec61c --- /dev/null +++ b/fanqie_auto/fanqie-flow.md @@ -0,0 +1,433 @@ +# 番茄小说流程记录 + +按用户现场指示逐步补充,不自行增加其他每日任务。 + +用户最新要求:不上传图片。截图(如需)仅在本机内存中交给本地 OCR,识别后释放;仅用文字日志反馈状态,不上传截图、图片附件或 Base64。 + +## 当前有效规则(2026-10-20,优先于下文历史记录) + +- 最新更正:听读选项取消,“立即听读/去听读/继续听读”弹窗直接关闭,金币数字不触发听读。签到弹窗若只有一个深色领取按钮则点击,不套额外奖励500金币门槛。签到、吃饭补贴在赚钱页任何位置可识别,不要求日常福利分类;当前标签已可见时优先同排按钮,按钮漏识别则点标签,不继续滚动找分类。 + +- 总流程:签到 → 吃饭补贴(含连续奖励)→ 翻卡 → 阅读 → 领奖励。福利中心启动时,历史出版物待领奖状态不得跳过前置任务;当前确实位于阅读页或翻卡弹窗时保留现场恢复。 +- monitor-70阅读补充:真实阅读页的右上倒计时交由阅读流程处理,普通广告和前景弹窗仍按通用规则优先。持续左滑到书末后,若右上角倒计时未结束则持续右滑,直到连续2秒未识别到倒计时,或已到书本首页。中途倒计时再次出现则重置2秒窗口。仅在这段流程成功后保存完读待领奖状态;右滑失败、离开阅读页或达到阅读时限不当作完成。当前在阅读现场时,历史待领奖记录也不能跳过该流程。 +- 吃饭补贴页主补贴区只要仍有完整“XX金币/领取XX金币/看视频领XX金币”等金额按钮就继续点击,不套弹窗500金币门槛。每次领取后先执行通用规则,返回后重新检查;没有主领取按钮才查连续奖励。余额、已领取说明及连续奖励区的金额不按主领取按钮点击。 +- 若点击补贴后番茄明确提示“活动繁忙,请稍后再试”,本轮跳过同一按钮,继续其他奖励及后续步骤,下次运行恢复尝试;不把点击返回true当作领取成功。 +- monitor-64起,活动繁忙先等待5秒重新识别并重试,额外重试最多2次,仍繁忙才本轮跳过;在通用处理后检查迟到Toast,避免漏掉错误。阅读检测到工具栏先收起;左滑未推进时轮换上部、中部和下部位置,按页码核实进度,不因5次卡页就直接结束。未读完返回福利页时,重新进入对应出版物去阅读,反复失败仍保留明确异常保护。 +- 无金币领取入口的现金邀请弹窗直接关闭,例如“送你现金红包/121元/邀请好友立得”;背后的金币任务行不能当作该弹窗的领取按钮。正常结束前再等待一轮并复查通用规则,避免晚出现的弹窗留在前台。 +- monitor-66起,翻字按钮不再阻止右上角关闭:前景弹窗先处理,右上角有真实倒计时则等待,没有倒计时有关闭则点击。原翻卡保护仅保留中央翻卡操作弹窗,不覆盖右上角关闭。 +- 直播退出为最高优先:识别到直播页面立即返回,不等直播倒计时、不领取直播奖励;出现确认退出或悬浮窗提示时选择退出、暂不使用,离开后继续原流程。 +- 其余页面前景弹窗优先,处理完才检查背景广告。背景右上有真实倒计时则等待,无倒计时且识别到关闭就点击;仍在广告过渡页时继续识别,不在广告上把后续任务标签判成缺失。 +- monitor-71起,页面文字中的視/頻统一为视/频;追加奖励标题漏识别时,同一中央区域的“领取奖励/继续领金币+坚持退出”按钮组可确认挽留弹窗,金额不明确则退出,不能反复点击弹窗背后的右上X。 +- 两个金币按钮:至少一个金额>=500时选较大金额;两个金额都<500时选较小金额,不固定左右。 +- 不带金额的单操作按钮:弹窗正文必须有唯一明确金币金额且>=500,并在手机当前帧确认按钮背景为深色,才点击;否则关闭弹窗。最高/累计等上限不当作确定金额;关闭没有识别到则报告,不能盲点。 +- 截图、裁剪、按钮色彩采样仅在手机内存执行,不上传图片或像素。 + +## 已确认的步骤(历史初版,冲突处以当前有效规则为准) + +1. 点击底部「赚钱」。 +2. 找到「日常福利」,点击「去签到」。 +3. 签到弹窗点击右侧深色的金币按钮(现场显示「领967金币」,标注「看视频奖励」;金额会变化)。 +4. 视频页面右上角出现倒计时,等倒计时结束,再点击右上角关闭。 +5. 出现「再看一个视频额外获得」等视频额外奖励弹窗,先读取额外奖励金币数:大于500时点击深色的「领取奖励/确认」按钮;小于或等于500时点击浅色的「坚持退出/退出」按钮。 +6. 重复应用第4、5步,直到退出并回到没有倒计时、没有额外视频奖励弹窗的页面,按用户下一步指示继续。 +7. 回到「日常福利」,点击「吃饭补贴」右侧「去领取」,进入「饭点领金币补贴」页,等待下一步指示。 +8. 点击「领XX补贴」主按钮,XX按当时时段变化(现场为「领夜宵补贴105金币」)。 +9. 处理领取成功后的额外视频奖励,沿用通用的倒计时、500金币门槛规则。 +10. 领取下方连续5天奖励中标为「待领取」的当日奖励(现场为44金币)。 + +## 上次现场记录(历史状态,不能当作当前页面) + +- 现场为夜宵时段(21:00—24:00),已点击「领夜宵补贴105金币」,弹窗确认获得105金币。 +- 早餐、午饭、晚饭分别有「看视频补领」入口,尚未操作。 +- 领取成功弹窗提供「看视频最高可领1750金币」,正在按通用规则处理。 +- 下方连续5天奖励,今天显示44金币待领取,用户已要求领取,待额外奖励流程结束后操作。 + +## 通用规则 + +- 只要页面右上角出现倒计时,都等倒计时结束后,再点右上角关闭。 +- 看视频额外奖励大于500金币:点击深色的奖励确认按钮。 +- 看视频额外奖励小于或等于500金币(含500):点击浅色退出按钮。 +- 奖励金额和广告内容会变化,不应写死金额。 + +## 现场环境与实现状态(2026-10-18 更新) + +- 上次现场手机:OPPO PLJ110,截图分辨率1080×2374,当时通过 USB ADB 连接;本轮未检查连接状态。 +- 应用包名:com.dragon.read。 +- 实际操作应使用最新页面文字和边界确认目标;不用历史截图坐标盲点。 +- 上次现场中,日常福利文字未出现在 ADB UI 层级中;只靠文字选择器可能无法继续,需要手机端本地 OCR。 +- `scripts/fanqie-daily.auto.js` 已补充签到奖励入口、视频循环、吃饭补贴及连续5天当日待领取流程;尚未在手机端验证,不代表已领取完成。 +- 本轮只修改本地文件,没有操作手机,也没有上传图片。 + + +## 本地脚本运行方式 + +1. 在手机安装并打开兼容的 Auto.js / AutoX.js,启用无障碍服务。手动打开番茄小说主页面后运行 `scripts/fanqie-daily.auto.js`。此脚本运行在手机端,不是电脑端 Node.js 脚本。 +2. 脚本优先收集无障碍文字,同时在存在本地 `$ocr.detect` 时启用本机截屏识别。授权截屏不等于上传图片;脚本无图片上传、云端 OCR 或远程请求代码。 +3. 当前 OCR 适配器要求 `$ocr.detect(image)` 同步返回 `[{ text, bounds: { left, top, right, bottom } }]`,边界为屏幕像素坐标。不同版本接口如不一致,需在 `snapshot()` 内适配;不会自动下载 OCR 插件。 +4. 若本地 OCR 不可用,继续尝试无障碍文字。无法识别目标就停止,反馈页面文字即可,无需上传截图。 +5. 只有页面金额与按钮能明确识别时才执行下一步;出现异常后保留当前手机页面,确认状态再继续,不反复重跑尝试。 + +## 已实现的判断与停止条件 + +- 金币门槛:明确额外奖励 `> 500` 才确认;`<= 500`(含500)退出。初次签到的领金币按钮按已确认步骤点击,不套用额外奖励门槛。 +- 页面右上角存在倒计时,先等待;已观察到倒计时结束(或明确显示视频结束/奖励已到账),且识别到右上角明确关闭文字或 X,重新读取页面、确认无倒计时后再点。图标无法识别时停止,不假设关闭坐标。 +- “最高可领/最多”等仅表示上限,不作为确定奖励;附近有多个不同金额或没有明确金额时停止。OCR 把数字与“金币”拆成不同块时,也需适配或文字确认,不猜金额。 +- 按钮按已确认文字和所在区域匹配。无障碍/OCR 不能可靠判断深浅色时,不仅凭颜色点击;页面文案变化会停止等待适配。 +- 每段视频最多等待180秒,每次奖励处理最多接受15个额外视频,并限制弹窗/关闭点击总次数,防止卡住后无限循环。 +- 连续两次观察到目标页面、无倒计时、无已识别额外奖励提示,才继续后续步骤。 +- 吃饭补贴只点当前时段主领取按钮,不点早餐、午饭、晚饭的“看视频补领”。 +- 连续5天区域只在“待领取”目标唯一时点击;点击后再次检查待领取标记是否消失。不领取其他日期,不把点击成功当作金币到账证明。 +- 当前不在 `com.dragon.read`、识别失败、页面结构变化或等待超时,都会停止并输出文字原因;不自动启动其他应用、安装应用或操作广告落地页。 + +## 待手机端验证 + +- 手机实际使用的 Auto.js / AutoX.js 版本及本地 OCR 返回格式。 +- 签到弹窗按钮是否能完整识别为“领XX金币”,签到视频结束后是否直接返回日常福利。 +- 视频倒计时、关闭图标、额外奖励金额与按钮的实际文字边界。 +- 饭点补贴页面标题、当前时段领取按钮及连续5天待领取区域的实际布局。 +- 若签到后停留在新的中间弹窗,或当天已领过饭点补贴/连续奖励,目前停止等待现场文字确认;不自动推断下一步。 + +## 本轮验证 + +- 通过 JavaScript 语法检查及13项本地模拟/静态检查:500/501门槛、最高金额与多个金额拦截、倒计时等待、关闭前重新识别、弹窗无响应上限、任务行匹配及离开应用停止等。 +- 未做手机端实测;模拟检查不能证明 OCR、无障碍服务或实际页面布局已经兼容。 + +## 手机加载进度(2026-10-18) + +- 已确认 OPPO PLJ110 通过 ADB 连接;AutoJs6 6.7.0(org.autojs.autojs6)已安装,无障碍已启用。 +- 手机端只读探测已运行,验证 `$ocr.detect(captureScreen())` 可在本机返回文字及边界;未上传图片。 +- 探测时处于饭点补贴页面:夜宵105金币显示已领取,连续5日区域44金币显示待领取;这只是当次观察,不可当作后续实时状态。 +- 脚本补充了启动番茄、识别当前饭点页面后继续,以及“连续5日”文案适配;新增文字运行日志,当前修改仅做语法检查,正式流程尚未真机执行。 +- 按用户“先把脚本加载到AutoJs”要求,已传至 `/sdcard/Download/fanqie-daily.auto.js` 并打开 AutoJs6 编辑器,标题为 `fanqie-daily.auto`。正式脚本未点击运行;没有领取44金币。 +- 正式运行时文字日志路径为 `/sdcard/Download/fanqie-daily-run.log`,最近识别文字为 `/sdcard/Download/fanqie-daily-page.json`,均不含图片。 +- 后续流程规则:启动番茄后直接找并点击底部「赚钱」;没有「日常福利」就跳过签到;没有吃饭补贴类目或「去领取」入口就继续查找连续奖励;没有饭点领取按钮、连续奖励类目或待领取项目时也跳过该项。缺失类目写入文字日志并继续,不停在该步骤。 +- 签到类目、签到入口或签到领奖标签未识别时,记录跳过签到,继续查找后续类目。 + +## OPPO 分步骤容错更新(2026-10-19,以下取代旧版全局停止规则) + +- 已核实手机 `/sdcard/Download/fanqie-daily.auto.js` 是旧版本:日志在“未识别到签到入口或已签到状态”时全局退出。本地既有跳过规则未同步到手机。 +- 新版签到、吃饭补贴、连续5天当日奖励分别执行;缺失、识别异常或步骤超时记录 `STEP SKIP` 并继续下一项。全部检查后写入 `END`,不代表金币领取成功。 +- 页面识别最多15秒;任务步骤最多240秒;启动25秒、OCR初始化30秒、赚钱页30秒。超时先中断并等待旧线程结束,再运行下一步骤。线程仍无法终止时整次运行报错,防止旧任务继续操作手机;不保证可强制终止所有原生调用。 +- 前台检测改为无障碍窗口包名,避免 `currentPackage()` 的潜在 shell 阻塞。 +- 下一任务必须重新识别已确认的福利/饭点页面;仍在广告、倒计时、奖励弹窗或外部应用时跳过,不盲点、不用返回键跳过广告倒计时。无法确定奖励金额时仅跳过当前任务,不猜金额。 +- 用户新增规则:启动后出现签到弹窗就点击“立即领取”。在 OCR 初始化后、进入赚钱页前检查;同时要求签到标题及其下方完整按钮。兼容本机 OCR 把“领取”识别为“颌取”。不新增其他奖励任务。 +- 已备份手机旧脚本到电脑 `/tmp/fanqie-daily.oppo-before.js`,更新手机 Download 下的脚本;语法检查及5项行为测试通过。 +- 首次真机文字日志确认:签到未找到后继续检查吃饭补贴、连续奖励,最终正常写入 END;该次被启动签到弹窗挡住,未证明已领取奖励。新增立即领取规则后的结果继续以最新真机文字日志为准。 +- 不上传图片,截图仅用于手机内存中的本地 OCR;日志和页面快照均仅含文字及边界。 +- 后续真机日志确认启动签到弹窗“立即领取”(OCR 为“立即颌取”)已点击;出现“看视频再得2000金币”。新增用户要求:签到领取后的弹窗继续沿用通用规则。已将 `看视频再得/再领N金币` 接入明确金额及按钮识别,已领取后的同一弹窗也可恢复处理;<=500 时优先退出文字,也支持奖励标题下方局部范围内的明确 X。视频倒计时仍优先等待。 +- 新版共7项本地测试通过,覆盖500/501分流、启动签到及已领取弹窗恢复;已同步手机并启动一次,以实际文字日志验证,不上传图片。 +- 真机修正:背景“已攒0金币”曾混入弹窗金额造成多金额判断;明确 `看视频再得/再领N金币` 按钮现优先按按钮自身金额判断。对应回归测试通过。最新真机文字日志已确认“额外奖励2000金币:继续观看”并点击该按钮;视频关闭和完整领奖仍待后续实测。 +- 用户补充关闭规则:右上角没有倒计时、有关闭就点关闭;不再要求之前观察过倒计时。关闭前仍重新识别。优先关闭,再判断额外奖励。支持“领取成功X”等合框,仅取末尾 X 的区域;无效边界单条 OCR 忽略并写文字日志。 +- 9项行为测试通过并已同步 OPPO。真机日志确认点击“关闭(领取成功x)”。随后下一次截图报 MediaProjection SecurityException(不能复用投影授权/创建多个 virtual display),本次恢复流程已结束。按用户“停止先报告、由用户指导”约定,未继续修改投影或重启每日任务。后续需排查逐次新建识别线程与投影会话的关系,不能把关闭动作日志当作整个流程成功。 +- 用户明确“页面只要满足通用规则就优先执行”:已把通用判断接入统一 snapshot 入口,所有任务读取页面后先处理倒计时/右上关闭/额外奖励,再重新取页。通用处理期间有重入保护;失败后恢复标记,下一步骤仍优先判断通用页面。处理后仍有通用弹窗时不允许直接进行任务点击。11项行为测试通过,已同步手机。 +- 最新要求:持续循环,直到所有规则均不符合才正常结束。实现每轮通用优先+签到/饭点/连续奖励检查;有点击或步骤异常继续下一轮。连续两轮全部检查成功且无规则点击才正常 END,不把异常当作没有任务。无法终止线程、截图通道失效等运行错误仍单独 ERROR 报告,不伪称规则全部完成。 +- 截图改为单个常驻线程队列,授权与截图都通过该线程;复制 captureScreen 原图后仅回收复制图,避免逐帧新线程/回收原图干扰投影。12项行为测试通过。 +- 已更新 OPPO 并运行;目前实测停在“申请截图超时(28秒)”,未进入循环验证。ADB 修改 PROJECT_MEDIA 被 OPPO 拒绝(缺少 MANAGE_APP_OPS_MODES),未取得新投影授权。需要继续诊断授权调用/系统弹窗,不能声称截图修复已验证或所有规则都不符合。 +- 调度进一步收紧:每次任务点击前重新 snapshot,先执行通用规则;通用处理后旧标签/坐标不再存在就跳过。无通用条件时立即交还调度,不为旧返回页标签等180秒。签到领奖、饭点页、赚钱入口改为当次识别,标签缺失就下一项;滚动搜索降为最多1次。真实倒计时仍按已确认规则等待。 +- 已发现旧版在截图失效后运行了数百轮无效重试,已停止并修正:连续两轮有运行错误且无任何操作时报 ERROR 等用户指导,不伪报“全部规则不符合”;普通标签不存在则算正常跳过,可以走正常无规则结束条件。15项测试通过,新版已同步手机。 +- 本轮真机截图/OCR已连续工作,日志进入第1至第4轮并发生操作,未再出现本轮投影错误。最新停点:签到弹窗同时出现“领2868金币”“领4868金币”“看视频奖励”,被通用额外奖励金额判断视作多金额,连续两轮无操作后按错误退出。不是规则全部完成。按用户停止后指导约定,先报告该页并等待确认,不自行改选按钮。 +- 新增通用规则:识别到奖励/签到/提示类弹窗,且没有可领取金币按钮时,点击识别到的关闭按钮(支持非右上角明确 X)。金币余额不视为可领取入口;有“立即领取/领取奖励/领N金币/看视频再得N金币”等按钮时不按空奖励弹窗关闭。倒计时优先,关闭前重新识别确认。17项测试通过,已同步 `/sdcard/Download/fanqie-daily.auto.js`;该新增分支尚无真机触发证据。 +- 用户确认签到双金额弹窗按右侧“看视频奖励”领取,金额动态(本次4868)。新增通用签到分支:签到标题+看视频奖励标记+同区域右侧“领N金币”,先于额外奖励金额解析;初次签到不套额外视频500门槛。18项测试通过。 +- 截图授权移到启动番茄之前;本次真机授权成功,日志确认“通用签到规则:选择右侧看视频奖励按钮 领4868金币”及点击,之后进入视频/额外奖励页面。随后投影再次失效,仍存在系统截图会话问题,不能声称完整领奖成功。 +- 最新双金额规则取代固定右侧:同一弹窗、同一行的“领N金币”选项按数值降序选择,位置和“看视频奖励”标记不决定多选优先级。支持千分位,忽略其他任务行和余额文字;单选签到视频入口保留原标签定位。19项测试通过(包括左侧金额更大、千分位、不同任务行隔离),已同步 OPPO Download 下脚本。此轮未重新运行手机流程,投影会话异常仍是已知限制。 + +- 2026-10-19 实时监控 monitor-4:修复广告“60秒/已完成”静态档位被当作倒计时;支持纯秒OCR尾部符号。前景追加奖励弹窗优先于背景X,兼容“再香60秒”“量高”和“|坚持退出”等实测OCR结果,并用“继续领金币+坚持退出”按钮组合兜底。仅有上限或金额不明确时不追加视频,点击明确退出按钮继续任务。坐标点击改80ms短按并记录坐标/结果,同位置关闭最多尝试三次。21项行为测试通过。真机确认退出遮挡弹窗、点击立即领取、继续等待广告;一次截图授权超时后重试成功。最终09:49:39Z连续两轮无匹配结束,页面仍是广告结束卡,只有“已完成/待颌取/(点击领取)”,未识别到关闭X;此侧栏待领取尚未配置通用规则,不能认定全部任务完成。日志留存 /tmp/fanqie-monitor-final.log。 + +- monitor-5 用户明确前景弹窗优先:调整通用处理顺序,签到多金额、追加奖励、居中无金币弹窗关闭均先于背景倒计时/背景右上X;关闭前重新识别,若出现领取弹窗立即交由弹窗分支。22项行为测试通过,包含背景20秒+背景X时仍选择签到大金额、居中弹窗不被背景倒计时阻塞。同步手机Download正式脚本。之前广告结束卡没有识别出X是识别缺口,不能称用户没有此规则;未增加猜坐标点击。 + +- monitor-6 关闭漏识别修复:整屏没有右上关闭时,在手机内存裁剪右上区域放大3倍本地OCR,只接收明确关闭/X,坐标按比例映射回原屏;裁剪图和放大图均释放,不上传/保存图片,不使用固定点击坐标。23项测试通过,含坐标转换与释放验证。真机日志10:04:20Z识别X,10:04:24Z点击X成功,10:04:26Z前景弹窗点击|坚持退出,随后继续任务;10:05:09Z进入下一广告真实倒计时,未结束脚本。本轮已确认关闭链路,不代表全部奖励完成。曾两次截图授权超时,重启AutoJs并重绑无障碍后成功,系统授权偶发问题仍存在。证据/tmp/fanqie-close-fixed.log。 + + +## 2026-10-19 真机排查与 monitor-7 修复 + +本目录的 fanqie-daily.auto.js 为本次交付版本。手机默认脚本位置为 /sdcard/脚本/fanqie-daily.auto.js;Download 和 Scripts 中的同名副本已同步,启动日志打印版本及实际来源路径,同名旧实例会先退出。 + +已定位的停滞原因: +- 实际从“脚本”目录运行的是旧副本,Download 里的更新没有生效。 +- Android 16 的截图投影令牌失效,旧副本把截图错误当作单步骤错误,一直轮询所有步骤;AUTO 方向模式可能重建 VirtualDisplay,复用已失效的令牌。 +- 广告右上的“再看19秒后得300金币X”被误判成追加奖励弹窗,去寻找不存在的退出按钮;长倒计时文字左边界又低于原先右上区域门槛。 +- 实测文字变成“吃饭补贴O1048”“饭点领金市补贴”“饭点領金而补贴”“连续領吃饭补贴第2天”,精确匹配漏掉实际存在的任务。 + +处理方式:固定竖屏申请截图;投影异常先释放再重新授权,恢复最多2次;截图错误单独报告,不视为缺失类目。截屏授权等待改为60秒。右上区域改用文字中心判断,行内倒计时从额外奖励识别中排除,前景奖励弹窗仍先处理。支持带金额的吃饭补贴标签、已观测到的标题误识别及新连续奖励标题;进入补贴页后最多等待5秒加载。正常无匹配结束和异常结束均提供手机文字提示,点击失败不计作有效操作。 + +验证:8项回归检查通过(debug/regression.test.mjs),覆盖真实倒计时样本、前景弹窗、标题变体、关闭X定位、截图恢复及恢复上限。真机日志确认广告关闭、退出追加奖励、回到福利中心、进入补贴页,并点击197金币“待领取”;随后显示“明天来可得248金币”,当日待领取标记消失。未以此推断全部任务或余额到账。 + +排查证据仅包含脚本、文字日志和 OCR 文字 JSON,保存于 debug/2026-10-19/;图片未上传、未导出。截图只在手机内存中用于本地 OCR。 + +最终复验(2026-10-19 20:44,monitor-7):在系统截屏授权中选择“整个屏幕→开始”后,本机连续完成两轮检查;签到、饭点当前时段领取项及连续奖励待领取不存在时均直接跳过,日志最终为 END:连续两轮确认所有已配置规则均无可执行项。此次未出现投影错误,结束后 dumpsys media_projection 为 null,截图会话已释放。完整文字日志为 debug/2026-10-19/run-verified-final.log;最近文字页面为 page-verified-final.json。正常结束只表示当前页面没有匹配的已配置项目,不表示所有每日奖励均已领取。 + +截屏授权仍属于 Android 系统交互:若运行停在“初始化本地 OCR”,需在60秒内完成“整个屏幕→开始”;无需上传图片。未授权会明确提示并结束,不能把它当作普通类目缺失。此前 Settings 前台或空窗口造成的失败记录保留,不作为正常结束证据。 + +电脑输出脚本与手机“脚本”、Download、Scripts 三处同名文件 SHA-256 一致:5e951adb79b37d01004fb85b8302f6667d0d2ce4c971232e694134a846780e9b。8项回归检查再次通过。 + + +## 2026-10-19 后续现场修复(monitor-8-close / monitor-9,以下为当前规则) + +实际卡点为“恭喜你已累计获得奖励”弹窗,按钮“开心收下”没有纳入原通用规则;背景任务行“立即领取”又被误当签到弹窗,导致重复视频。monitor-7 随后将弹窗遮挡下的所有标签缺失算作无匹配而结束,此结论只适用于当时扫描,不能说明奖励弹窗已处理。 + +按用户最新要求:弹窗没有符合金币范围的领取按钮就点击关闭,不能专门点击“开心收下”。金额明确大于500金币才领取,500及以下或没有合格领取按钮关闭/退出。累计奖励数字和背景任务按钮都不算弹窗可领取入口。支持明确X以及已观测到的弹窗下方X与背景文字合框,只提取末尾字形;没有识别到关闭则记录异常,不猜固定坐标、不伪报全部规则无匹配。早期monitor-8调试曾点击“开心收下”解除现场;该专门分支已被最终关闭规则取代。关闭分支使用保存的真实文字现场及金额边界回归验证,尚无同一弹窗再次出现后的真机关闭证据。 + +签到启动按钮限制在中央弹窗区域及签到标题下方,防止点击背景行右侧立即领取。每轮结束额外确认仍处于已识别任务页,未知遮挡不能算正常无匹配。monitor-8-close 真机两轮无匹配后正常结束,文字日志为 debug/2026-10-19/run-monitor8-close.log。 + +monitor-9 用户新增:进入吃饭补贴页优先点击“……领一次补贴”,然后处理当前时段及连续奖励;本次运行仅触发一次,避免返回后重复观看。支持现场“看视频补领一次补見貼/补见貼”,缺失按钮继续下一项。普通早餐/午饭“看视频补领”不因本规则自动点击。原先“不点补领”的规则由此更新为允许这个完整的一次补贴按钮。最新连续奖励OCR“连续领颌吃饭补貼第2天”也已兼容。 + +17项回归检查通过,包含真实卡页关闭字形、前景优先、500/501门槛、背景误点防护、饭点补贴优先顺序和本次运行去重。截图只用于手机本地OCR;文字证据保存在debug/2026-10-19,不上传图片。 + +monitor-9 真机验证(20:56—20:57):日志确认优先点击“看视频补领一次补见贴”@540,1779;等待45秒倒计时;点击右上“领取成功X”关闭,退出金额不明确的追加奖励,再点击弹窗X;随后已返回饭点补贴页。没有重复触发同一运行的一次补贴按钮。仅据页面变化确认流程已返回,不推断金币入账。证据:debug/2026-10-19/run-monitor9-priority.log 与 page-monitor9-after-priority.json。手机三处副本与电脑文件SHA-256一致:2bbce9cda42b0b7e8434e27c1e85fa2cef5366dbfd7fa19e9e94e8cdcf57836b。 + +monitor-9 最终复验:完成优先补贴链路后,连续两轮确认当前没有其余已配置待领取项目,日志正常END;截图会话已释放。正常结束不代表所有每日任务均已领取。 + + +## 2026-10-19 补贴页面循环(monitor-10,取代monitor-9的同次运行只点一次限制) + +用户要求返回吃饭补贴页后继续查找之前配置的全部标签,直到都找不到才退出页面。当前每轮先确认补贴页,再按“一次补贴→当前时段领取→连续奖励待领取”顺序扫描。每次动作、视频或弹窗处理后回到首项重新识别;同一个一次补贴按钮仍存在时允许再次触发,不再使用本次运行去重。连续两轮完整扫描均无动作,才按返回键退出并确认福利中心;本次退出后总调度不会再次进入补贴页。未知页面或识别异常不算无匹配。 + +21项回归检查通过,新增覆盖多次返回重查、连续奖励后从头扫描、两轮无匹配才返回、未回到补贴页不得退出,以及总调度不重复进入。30分钟为异常保护上限,不是正常完成条件;超限保留页面并报告原因,不视为标签全部不存在。 + +真机已确认 monitor-10 点击一次补贴、等待倒计时、关闭视频及退出追加弹窗后,返回并进入 MEAL LOOP 第2轮。现场新增OCR将“领夜宵补贴106金币”和连续标题中的“补贴”读作“朴贴”;monitor-10-r1 已做文字归一化并增加行为回归,22项检查通过,避免已出现的新标签被漏掉。 + +monitor-10-r2 最终真机验证(21:03—21:04):已兼容标题“饭点领金币孙贴”,以及补贴标题缺失但连续奖励标签仍可识别时恢复页面循环。日志确认点击“领夜宵补贴106金币”;追加奖励弹窗最初两次未识别到退出,后续重新识别X并关闭,未据异常退出补贴页。再次进入页面循环后,连续两轮全部标签无可执行项,13:03:58Z记录MEAL EXIT,确认返回福利中心;此后没有再次进入补贴页,13:04:25Z总流程正常END。23项回归检查通过。完整文字证据debug/2026-10-19/run-monitor10-final.log;点击日志不作为金币入账证明。 + + +## 2026-10-19 补贴后的翻卡任务(monitor-11) + +用户新增步骤:吃饭补贴流程完成并返回福利中心后,查找“翻卡赢金币”同一任务行右侧的“立即翻卡”;进入后寻找完整“翻卡”按钮并点击。兼容真实福利页标题OCR“翻卡嘉金币O最高9999”。入口标签或按钮缺失就记录跳过,不点击邻近任务、不用固定坐标。仍停留在补贴页时不抢先进入翻卡。 + +翻卡按钮点击后继续执行已有通用视频/弹窗规则,记录点击结果,避免总流程循环重复翻卡。本次新增范围止于这一翻卡动作及其既有通用处理,未新增其他卡片、兑换或抽奖动作。按钮点击成功不视为金币到账。27项回归检查通过,新增任务行隔离、执行顺序、补贴页拦截和缺失跳过。 + + +## 2026-10-19 翻xx卡按钮(monitor-12) + +真机已成功点击“立即翻卡”,实际出现的是福利页上方的翻卡弹窗,按钮为“看1个视频翻十位卡”,并非完整“翻卡”二字。用户明确看到“翻xx卡”的按钮就点击。当前支持“翻卡”“翻十位卡”“看1个视频翻十位卡”“看视频翻百位卡”等完整按钮,限定弹窗中央区域;不将背景“立即翻卡”或任务标题当作翻卡按钮。 + +按钮动作后遵循原通用倒计时/关闭/额外奖励门槛规则,再重新查找后续翻卡按钮,连续两次没有后续按钮才结束。支持直接恢复已经打开的翻卡弹窗,避免滚动其背后福利页。20次点击或30分钟仅为异常保护,上限触发会报告流程未完成,不能伪报所有翻卡奖励完成。29项回归检查通过,包括真实卡页文字及十位卡到百位卡的连续执行。 + + +## 2026-10-19 所有翻字按钮与返回入口循环(monitor-13/14) + +用户进一步明确:只要是带“翻”字的按钮就点击。按真实现场补充“立即翻开十位数”,翻卡操作不再限制为完整“翻xx卡”格式;中央弹窗操作区域中的含翻字按钮可匹配,标题“继续翻卡领更多金币”、状态和背景任务标题排除。真机monitor-13已确认点击立即翻开十位数,弹窗关闭后福利任务行显示“已翻出十位数”。 + +monitor-14 将奖励弹窗关闭后返回福利中心的“立即翻卡”也接入循环,继续下一张卡;只有弹窗内按钮和已返回福利页的对应入口都找不到才累计无匹配,避免翻完一位就提前结束。前景翻卡弹窗存在时不点背景入口。31项回归检查通过。 + + +## 2026-10-19 翻卡全流程持续识别与通用优先(monitor-15) + +最新规则:翻卡流程持续识别含“翻”字的按钮并点击;只要符合通用视频/弹窗规则,先执行通用规则,再重新识别翻卡目标。旧标签因通用处理改变时不直接结束,而是重查;额外奖励退出按钮短暂漏识别时允许最多3次重新识别,运行级截图故障仍单独报告。 + +福利列表可能被前一步滚动到底部,增加先向顶部恢复再有界向下搜索翻卡入口,避免当前视口没有入口就提前认定不存在。翻卡返回福利页也使用同样搜索。流程只在两次未找到弹窗翻字按钮及可继续的对应入口后正常结束。35项回归检查通过,新增通用优先、旧标签变化重试、短暂退出按钮缺失重试和列表恢复搜索。 + + +## 2026-10-19 领更多金币及最终开心收下(monitor-17,用户最新规则) + +视频后的“领更多金币”加入通用奖励确认按钮,支持其本身作为弹窗识别入口;金额仍明确大于500才点击。新增对按钮上方数字与金币分块OCR的解析,忽略最高/余额/已获得等无关或上限文字。500及以下、金额不明确时沿用关闭/退出规则;不因按钮漏列而跳过已符合条件的奖励。 + +用户明确翻卡流程最终需点击“开心收下”结束。本条取代monitor-16对翻卡总额弹窗的关闭X规则。识别“一共赢取N金币”(兼容标题前OCR标点)与其下方开心收下按钮,优先确认并标记翻卡完成,随后不再点击背景立即翻卡。不把其他一般奖励弹窗的开心收下视为新的领取授权。40项回归检查通过,含领更多金币、分块金额、500边界、结算标记与禁止重复进入。 + + +monitor-17 真机补充:13:24:37Z日志确认点击翻卡总额弹窗“开心收下”成功,13:24:39Z结束翻卡。证据:debug/2026-10-19/run-monitor17-final.log。 + +## 2026-10-19 翻卡后天天领金币(monitor-18) + +按用户追加顺序,翻卡结算点击开心收下后继续查找“天天领金币”同一行右侧的“去领取”并点击。启动时已由通用规则完成结算、恢复翻卡和常规翻卡三条路径均接入此步骤;翻卡类目缺失也继续查找下一项。兼容真实OCR“天天颌金币”,不把同页其他去领取或“点击领344”误当作此入口。当前视口缺失时先向上搜索2次、向下4次,仍无对应项则记录跳过。点击后执行已配置通用视频/弹窗规则,本次新增范围止于该入口及已有通用处理。 + +46项行为回归及语法检查通过。手机脚本、Download、Scripts三处正式副本已同步且SHA-256一致。调试仅读取手机本地OCR文字、UI XML及日志,不上传图片。 + +monitor-18 真机验证:13:29:21Z识别并点击“天天领金币”对应“去领取”@889,1498,点击结果true。13:29:23Z完成通用检查并结束。后续本地OCR显示“我的钱包”“今日可领10”“领取今日奖励”等,确认入口已打开;尚未配置钱包内部新任务,不点击填车牌、绑卡或申卡。证据:debug/2026-10-19/run-monitor18-daily-coins.log 与 page-monitor18-daily-coins.json。首次运行因前台切到设置而中断,第二次未再使用并行UI层级抓取后成功;仅记录观察,不据此认定无障碍服务根因。 + + +## 2026-10-19 取消天天领金币入口(monitor-19,取代monitor-18) + +按用户最新指示取消“天天领金币 → 去领取”的识别、滚动查找与点击步骤。恢复翻卡结算点击“开心收下”后结束当前流程;通用“领更多金币”及原有金额判断、吃饭补贴、翻卡循环规则保留。monitor-18为历史记录,不再执行。 + + +## 2026-10-19 翻卡后读书挑战赛阅读(monitor-20) + +用户将下一标签改为“读书挑战赛 → 阅读”。翻卡点击开心收下结算后继续此步骤;启动时完成结算、恢复翻卡及常规翻卡结束均接入。翻卡类目缺失也继续下一项。已取消的天天领金币入口保持取消。 + +识别读书挑战赛同一行右侧完整“阅读”或“去阅读”(兼容现场竖线前缀和OCR漏掉标题首字“读”),不点击“阅读1分钟”等进度文字或相邻任务入口。当前视口没有入口时向上2次、向下4次有界查找,仍缺失就跳过。点击后按原通用规则处理弹窗;本次只增加入口点击,未配置阅读时长和翻页。 + +46项回归和语法检查通过,覆盖任务行隔离、现场OCR、入口缺失跳过与三条翻卡结束路径。 + + +## 2026-10-19 实时运行与阅读跳转校验(monitor-21) + +按用户要求在手机启动正式脚本并读取日志。monitor-20真机签到和饭点类目缺失均正常跳过;翻卡入口已不显示时继续读书挑战赛,21:35:12点击去阅读返回true,但随后仍在福利中心,暴露出只按注入点击成功就结束的缺陷。证据run-monitor20-live.log、page-monitor20-after-reading.json。 + +monitor-21新增跳转检查:点击后继续通用处理,并连续两次识别非空且已离开福利中心/日常福利的页面,才报告跳转完成。仍停留原页面则重查原入口,最多再试两次;三次仍未跳转报告异常,保留页面。49项回归及语法检查通过,已同步手机正式三处副本并再次启动真机验证。 + + +monitor-22/23 实时修复:现场OCR把任务标题识别为“翻卡贏全币O最高99999”,原标题排除条件要求精确“金币”,导致标题被当成含翻字按钮。现排除翻卡赢/贏/嘉/羸开头的任务标题。 + +另定位到反复打开后关闭:通用空奖励弹窗规则会取背景“完成阅读任务,获得相应金币奖励”或“收下当前奖励”,背景立即领取偶尔漏识别时,把正常翻卡操作弹窗X当成关闭目标。现在已有继续翻卡标题与可执行翻字按钮时,不按空奖励弹窗关闭;明确的前景恭喜/额外奖励弹窗仍优先处理。真实文字样本page-flip-common-close-loop.json纳入回归。读书标题新增“赛/塞/賽”,同排阅读按钮兼容现场“<阅读”。53项回归及语法检查通过,monitor-23已同步三处手机副本并继续运行。 + + +## 2026-10-19 翻字按钮先于通用关闭(monitor-24,用户最新规则) + +翻卡弹窗只要仍有带“翻”字的可执行按钮,不执行通用弹窗关闭(包括普通空弹窗、奖励确认关闭、右上关闭及低额追加奖励退出)。只有没有翻字按钮时,才恢复这些关闭分支。真实视频倒计时仍等待,符合金额规则的领取仍按通用规则执行。最终开心收下结算规则保留。关闭前再次识别到翻字按钮也取消关闭,交回翻卡。 + +本条取代monitor-23中“有翻字按钮但出现明确奖励标题仍可关闭”的例外。55项回归及语法检查通过,已同步手机正式脚本并重启实时验证。 + + +## 2026-10-19 取消读书挑战赛入口(monitor-26,用户最新指示) + +取消读书挑战赛及其阅读/去阅读按钮的识别、滚动搜索、点击和后续跳转重试。翻卡结算后结束当前已配置流程,不再进入阅读。保留monitor-24的有翻字按钮时禁止通用关闭规则,以及翻卡标题OCR误识别修复。已移除手机Download中专用于阅读的调试启动脚本,正式三处副本已同步。45项回归及语法检查通过。 + + +## 2026-10-19 读出版物赚金币连续左滑(monitor-27) + +用户新增真正的阅读任务为“读出版物赚金币”同一行的“去阅读”;读书挑战赛入口仍不查找、不点击。兼容任务标题赚/賺/嫌及按钮竖线前缀。福利列表逐屏双向搜索,每向最多8次,到边界连续两次稳定就改向;找不到即跳过。翻卡结束后进入出版物任务,已有书籍详情/阅读工具栏或左滑开始阅读提示时可直接续读,不重新启动应用覆盖当前页面。 + +确认书籍页后执行右向左水平滑动,逐页识别,默认每页等待1.8秒。识别明确全书完/全文完/最后一页或阅读进度100%才正常结束;连续5次左滑页面无变化记录异常,不伪报读完。阅读期间延长亮屏;离开应用、退出阅读或出现需解锁操作时保留页面停止。6小时为异常保护上限,不是正常结束条件。任务级超时同步调整,防止原240秒限制提前中断长书。 + +52项回归及语法检查通过,新增真实任务行隔离、进入确认、持续左滑、完读提示、卡住保护及应用切换等覆盖。正式脚本已同步手机三处并启动真机运行。截图只在手机内存用于本地OCR,不上传图片。 + + +monitor-28/29 真机验证:21:57:22点击实际“读出版物賺金币”的同排去阅读按钮,21:57:25确认书籍页,连续左滑后正文和页码均变化。任务标题仅以唯一“读出版物”前缀与同排阅读按钮定位,避免金币金额文字OCR误差;增加逐屏搜索日志。 + +真机出版物为《王阳明心学》,总页数1592。monitor-29新增底部“当前页/总页数”的识别,可直接恢复已在正文的阅读,并到当前页=总页数时结束;页码只接受屏幕底部区域,正文中的分数不作为页码。正式脚本启动时停止旧出版物调试实例,避免两个脚本同时滑动。21:58:37正式脚本记录24/1592,确认从当前阅读位置续读。54项回归及语法检查通过。尚未到达全书末页,不能称已读完。 + +连续运行复验:正式脚本第1/2/3次左滑分别识别24/1592、25/1592、26/1592,第10次识别33/1590,正文持续变化,无卡住计数。总页数会随阅读排版或OCR动态变化,结束判断使用当前页实际识别结果。启动运行日志保存在debug/2026-10-19/run-monitor29-reading-start.log;手机脚本继续运行,未停止。 + + +## 2026-10-19 出版物读完后返回首页领取(monitor-30/31) + +已从monitor-29真机完整日志确认23:08:44识别“全书完”,共左滑1462次;实际末次总页数1432,页码总数随排版变化。用户新增:读完回应用首页,再选择底部赚钱,寻找“读出版物赚金币”同一行的“立即领取”。现在仅明确读完后记录手机本地待领取状态;正常阅读后或中断恢复均可接入领取。最多六次返回寻找主界面,再点击首页/书城和赚钱,逐屏有界搜索对应任务行,缺少入口跳过。不是按Android Home离开应用。 + +立即领取与去阅读独立匹配;绝不选择邻行视频任务的立即领取。点击后执行原通用倒计时、额外奖励金额和关闭规则,再确认原任务行领取按钮变化;未确认时保留状态,不伪报完成或推断余额。阅读异常不会提前领取,待领取恢复不重新阅读全书。 + +monitor-30真机23:16:47点击书城、23:16:49点击赚钱、23:16:56点击对应立即领取@889,1299,随后弹出“恭喜你获得608金币”。这也是原通用规则漏识别的原因:标题没有“奖励”尾缀,且关闭按钮是无文字ImageView。monitor-31补充精确奖励标题与当前版本真实原生关闭控件com.dragon.read:id/eoy的识别,只在已确认奖励弹窗、中心下方且可见可点击时使用;按用户通用规则点击关闭,不点击此一般弹窗的开心收下。66项行为回归及语法检查通过。证据只含文字日志、XML及本地OCR结果,没有上传图片。 + + +monitor-32现场分档修复:monitor-31已经实际领取前三档193、193、385,页面显示“今日已赚1379金币”和三个已领取(另有最初608确认弹窗)。立即领取持续显示并不代表点击失败。改为比较该任务行的今日已赚数字与已领取档位,进度变化则继续处理后续立即领取;连续三次无进度才报异常。20次总点击仅为异常保护上限,不作为完成条件。领取完成须原任务行不再显示立即领取并连续两次确认。69项行为回归和语法检查通过,已同步手机并继续实测。 + + +monitor-33:用户明确一直领取直到该任务没有立即领取。修复monitor-32任务标题位于屏幕底部1986px时误判按钮缺失:现在领取前先将出版物任务行滑到屏幕中部,行不完整不作为结束;连续两次在完整可见任务行确认立即领取消失才清除待领取状态。任务按钮兼容现场OCR“立即颁取/颌取”,仍限制同排,不影响邻行。monitor-32的结束日志由本条纠正,不能用作全部领取完成证据。71项回归与语法检查通过。 + + +monitor-34—37最终修复与实测:兼容真实任务标题“C使出版物賺金币”和立即颌取/颁取;避开内嵌区域滑动,完整可见范围按应用顶部栏与底部栏判断,修复过严居中范围导致的来回滚动。任务行不完整时保留待领取,不误报领取完毕;今日已赚兼容賺和竖线前缀。 + +monitor-36真机23:28:50与23:28:57继续点击对应立即领取,处理578、770奖励确认弹窗;23:29:03连续确认完整出版物任务行已改为“去阅读”,没有立即领取,正常结束。五个基础阅读档位显示已领取;仍显示的数值或后续阅读进度不作为新立即领取授权。证据debug/2026-10-19/run-monitor36-claim-complete.log及page-publication-claim-complete.json。75项行为回归及语法检查通过。monitor-37已同步手机三处并运行最终复验,无图片上传。 + +monitor-37最终手机复验:23:30:20确认当前任务已无立即领取,没有再次点击去阅读或相邻任务,正常END并清除待领取状态。三处手机脚本与电脑SHA-256一致96aceb6a28dd5a8d582bd8b53215fece080612941af0bd14f2d3fa0129dd7728。最终文字证据run-monitor37-final.log、page-monitor37-final.json、state-monitor37-final.json。 + + +## 2026-10-20 出版物领取结束后接读书挑战赛立即领取(monitor-38) + +用户新增下一流程:出版物连续领取结束后,在赚钱页找“读书挑战赛”同一行右侧的“立即领取”并点击,之后执行已有通用倒计时、额外奖励及关闭规则。本次恢复的是立即领取,不恢复此前取消的读书挑战赛去阅读入口;天天领金币仍不执行。只匹配对应任务行,兼容挑战赛/塞/賽、竖线前缀和立即颌取等现场OCR。双向最多各8次滑动搜索,缺少类目或领取按钮时跳过。 + +出版物领取正常完成才衔接;异常或未确认完成时保留原流程。手机本地保存nextTask,在出版物已完成后重新运行会直接继续挑战赛,避免重跑阅读。兼容上一版已经确认领取完成的历史状态;挑战赛正常点击或入口缺失跳过后标记本次流程结束。81项行为回归及语法检查通过,新版已同步手机三处并进行真实运行。仅读取手机文字日志与本地OCR,不上传图片。 + +monitor-39实测修复:monitor-38跨日运行遇到“7天签到必得18万金币”弹窗遮挡列表,其累计总额不是本次明确领取金额;补充识别该弹窗的中心关闭X,符合原通用规则时关闭,仍保留有翻字按钮时禁止关闭的优先级。真实弹窗文字样本加入回归,82项检查通过。 + +00:02:20手机恢复出版物已完成后的挑战赛流程;00:02:56完成双向搜索,当前页面未识别到读书挑战赛同排立即领取,正常STEP SKIP和END。没有点击其他任务的立即领取、去阅读。当前没有实际挑战赛领取成功证据,不宣称已领取。文字证据debug/2026-10-20/run-monitor39-challenge-search.log、page-monitor39-final.json和state-monitor39-final.json。正式三处手机副本已同步;未上传图片。 + +## monitor-40—47 本轮排查与修复 + +- 本次OPPO PLJ110(3B15A700QEL00000)原日志SOURCE为/storage/emulated/0/脚本/fanqie-daily.auto.js;该副本与电脑monitor-39、Download一致,排除运行了旧文件。 +- 原日志启动直接RESUME出版物领取,状态为pendingClaim=true/evidence=全书完。修复状态文件抢占总流程:仅当前确实在阅读页才提前恢复,其他情况执行前置签到/补贴/翻卡,历史待领奖留到阅读阶段处理,未删除用户状态。 +- 删除finishMealPage中错误写入出版物pendingClaim的调用。 +- 现场双按钮OCR为领1928金币与|领3928金币,标记为看视頻奖励;兼容竖线和頻字,避免弹窗未处理导致所有后续任务跳过。等待签到弹窗出现,不仅立即读取一帧。 +- 通用规则下一帧重新出现时重新处理,不全局抛“通用页面仍未处理完成”;广告过渡帧仍留在通用处理,缺标签不当作没有任务。直播退出悬浮窗提示选择暂不使用。日常福利从有限单向1次改为有限双向搜索。 +- 按最新指示更新500边界和双金额/单按钮正文金额规则;双金币选择优先于旧奖励确认关闭分支。单按钮背景亮度仅手机当前帧本地采样,无法确认深色不冒充识别成功。 +- 新建本轮19项针对性测试(原目录已无历史测试,未声称历史82项重新通过),语法检查通过。覆盖启动顺序、真实阅读恢复、补贴不污染状态、真实OCR竖线、高低金额与500边界、单按钮与背景色、广告过渡状态。 +- 真机已确认点击3928金币、等待倒计时、点击领取成功X、400金币选择退出;仍存在签到弹窗再次出现的广告循环,本轮未完成签到→补贴→翻卡→阅读→领奖全部真实流程。系统截图授权多次停在“单个应用/下一步”,已通过UI树选择整个屏幕并开始,图片仍未上传。 + +## monitor-48 倒计时后不关闭的真实原因与修复 + +本次日志02:22:21Z显示ERROR“同一关闭按钮连续三次未响应”,而此前02:20:24Z和02:21:27Z均点击同坐标关闭并进入额外奖励/下一段广告。原因是lastCloseKey/repeatedClose跨广告累计,成功关闭后的新倒计时/关闭消失均未清零。现每轮观察到倒计时或关闭控件不存在时清零,只对持续同一关闭按钮保留连续三次保护。21项针对性测试通过,新增四段广告同坐标X不会误触保护与真实连续三次失败仍保护。已同步OPPO三处正式脚本并启动monitor-48;真机02:30:11Z已点击先前停住的领取成功X,随后进入下一段广告;后续也记录新的关闭与倒计时,尚未宣称全任务完成。证据/tmp/fanqie-close-counter-before.log及/tmp/fanqie-close-counter-after.log。 + +## monitor-49—54 vivo任务入口与听读排除 + +目标vivo V2072A无线192.168.31.112:43441。真实文字“签到领金币/|去签到”“领吃饭补贴991/去领取”均不在日常福利标题下;移除签到和补贴对findDaily/dailyAction的依赖,按当前任务行匹配按钮,看到标签但按钮缺失则按用户指示点标签。单按钮签到单独识别中央签到标题、唯一深色领取按钮及弹窗关闭证据,优先于普通单按钮金额规则,低于500或仅累计金额时也允许签到领取。手机本地采样深色,未改成猜固定坐标。 + +vivo关闭控件无障碍文案为closebutton,现标准化为关闭。听读曾在monitor-51短暂纳入单按钮候选,随后用户明确取消,monitor-52起删除听读操作候选并新增仅关闭听读弹窗规则,后续金币无论多少均不点击听读。保留其他阅读任务。中央“立即参与”遮挡弹窗按无金币领取入口关闭,不执行参与或邀请。31项针对性测试通过。已同步vivo Download及脚本目录并重启;本轮仅核验所述规则与阶段运行,不声称签到、补贴或全流程全部完成。 + +monitor-55—56:补充vivo独立签到页(活动时间、back、已签0/7今日签到、单个立即领取),允许无X时确认该签到现场。无障碍大按钮与其内部OCR文本按中心合并,避免被误算成两个按钮;若OCR确认深色则保留证据。领取后返回赚钱页继续补贴。现场首次完成奖励“看视频领1198金币”此前不匹配“再得/再领”,已按明确金额扩展识别。33项针对性检查通过,vivo两处脚本同步并运行。真机03:25:07Z点击领取成功X、03:25:09Z退出追加奖励、03:25:14Z继续签到检查;仍未宣称完整流程完成。听读排除规则保留,立即听读/去听读/继续听读不执行,优先关闭。 + +monitor-57:修复饭点领取仅匹配固定时段文案的问题,在明确饭点主补贴区支持完整XX金币、领取XX金币和看视频领XX金币等金额按钮;兼容竖线前缀与千分位,不套通用弹窗500金币门槛。连续奖励区域的金额、带余额或已领取说明的文字不按主按钮点击。每次点击后执行通用规则,回页继续检查,退出前增加最后一次主按钮检查。语法检查及39项回归通过,包含连续两次同文案领取和无匹配后退出。本轮vivo旧无线地址192.168.31.112:43441拒绝连接、ADB未发现vivo,尚未同步或真机核验当前页面。 + +monitor-58:vivo重新开启无线调试后通过mDNS连接192.168.31.112:38721。真机确认monitor-57能点击“领午饭补贴303金币”,但页面不变;独立Toast文字监听在03:53:16Z和03:53:33Z均捕获番茄提示“活动繁忙,请稍后再试”,这是反复点击而未领取的直接应用反馈。新增补贴步骤内Toast监听,遇该明确提示则将按钮本轮标为不可执行,继续其他奖励与后续任务;结束补贴步骤移除监听,下次运行清除本轮跳过记录。兼容现场金币OCR“金市”和连续奖励标题“连续颌吃饭补贴第2天”。语法与42项回归通过,已同步vivo的Download和脚本目录并启动;未据点击返回true认定金币到账。 + +monitor-59:03:56:34Z真机捕获午饭主按钮“活动繁忙”,随后按新规则跳过主按钮,03:56:40Z继续点击连续奖励待领取;该项也返回活动繁忙。将相同处理覆盖连续奖励,忙碌项目本轮不重复点击,不因待领取仍存在而抛错阻断补贴页循环。43项检查及语法检查通过,两处手机脚本与本地SHA256一致,03:58:18Z确认monitor-59启动。 + +monitor-60—62:Toast监听改在主线程注册和移除,避免补贴工作线程被事件循环保持存活、使runStep持续等待。真机补贴页返回会出现“吃饭还能赚金币/限时加餐991金币/领991金币吃饭补贴”挽留弹窗;补充该按钮到通用单按钮候选,仍按唯一明确金额>=500及深色证据领取,否则关闭。单按钮弹窗关闭区域下限扩展至屏幕92%,适配现场关闭框1976—2120,原82%边界会漏。45项回归及语法检查通过。手机熄屏曾导致截屏授权失败,唤醒后04:15:35Z确认按通用规则点击深色“领991金币吃饭补贴”,恢复补贴页处理;未声明金币到账。 + +monitor-62后续真机:04:16:35Z退出补贴页,04:16:39Z记录STEP DONE吃饭补贴,开始翻卡;04:17:06Z未找到对应翻卡入口后跳过并进入出版物阅读步骤。确认补贴页不再阻断后续任务。午饭303金币和连续奖励均收到应用活动繁忙提示,本轮跳过,不声明领取成功。 + +monitor-63—64:本轮复核手机自行启动的monitor-62日志,饭点303金币及连续奖励确有点击,但番茄均返回活动繁忙;阅读停在2177/2189,曾返回福利中心直接退出,另一次现场复现工具栏前景下5次左滑无变化后退出。补贴现等待5秒重新识别重试,额外最多2次,通用处理后再读取繁忙提示,修复迟到反馈遗漏。阅读工具栏先收起;有页码时按页码判定推进,避免OCR噪声冒充翻页;无进展轮换38%、55%、65%高度持续左滑,不在5次无变化时退出;中途返回福利中心重新找对应出版物去阅读,连续无法恢复有异常保护。新实例等待旧实例释放截屏会话后再申请本机授权。 + +现场已将阅读翻页设置选为平移、收起工具栏;最初中部左滑仍不推进,切换位置后推进至2178。monitor-64同步vivo两处,04:41:48Z起连续记录2182、2183、2184、2185、2186、2187、2188,04:42:19Z明确识别“全书完”,随后进入返回首页领奖步骤。49项回归及语法检查通过,包括工具栏收起后翻页、5次卡页后继续、返回福利中心恢复、延迟繁忙反馈重试及重试耗尽后继续任务。未将点击或阅读完成当作金币已到账。 + +04:43:13Z领奖搜索结束:当前对应出版物任务只识别到去阅读,没有立即领取,按既有规则跳过领取并保留待领取状态。证据见debug/2026-10-20/monitor64-reading-finished.log;本次确认的是全文读完,不声明奖励已领取。 + +monitor-65:用户指出当前弹窗应关闭。现场文字为“送你现金红包/121元/邀靖好友立得”,中央X在526,1724—554,1751,背景包含天天领金币、去领取及立即参与。新增该现金邀请弹窗的前景关闭识别,不混入背景金币任务;按钮金额与现金数字均不触发邀请操作。正常runDaily返回后、释放截图会话前,执行两轮snapshot,中间等待pollMs,确保晚出现的通用弹窗先处理。52项回归及语法检查通过,已同步vivo两处脚本并启动。 + +monitor-65真机04:48:30Z按通用规则点击中央X@540,1738,点击返回true;04:48:33Z已无通用条件并继续任务。文字日志留存debug/2026-10-20/monitor65-popup-close.log,无截图上传。 + +monitor-66:用户指出右上角无倒计时未关闭。源码审查发现flipPopupHasAction会在通用入口、关闭调度及关闭前复查三处拦截,现三处均允许已识别的右上角关闭,同时保留前景弹窗优先和真实倒计时等待。55项回归及语法检查通过,新增翻字与右上关闭同时出现、倒计时等待、中央翻卡弹窗保护三条行为回归。本轮无线ADB列表显示vivo,但shell读取页面与日志均无响应,旧地址连接超时且mDNS暂无设备,暂未确认当前现场或同步新版。 + +monitor-67:vivo重新打开无线调试后,通过192.168.31.112:39933恢复连接。补取旧日志确认实际阻塞:广告正文“恭喜获得/5182金币”被当作必须处理的奖励弹窗,没有领取或关闭控件便抛错,抢在倒计时和右上关闭之前中断。改为仅在识别到实际领取控件时进入该领取分支,只有标题和金额不单独触发通用处理;广告本身仍继续等待倒计时/关闭。保留monitor-66的右上关闭修复。57项回归及语法检查通过,两处手机副本SHA-256与本机一致。真机05:03:48Z已点击“关闭(领取成功×)”,05:03:50Z点击“坚持退出”,随后按双金额规则选择2136金币并进入新倒计时;未据此认定全部任务完成。 + +monitor-67追加真机验证:05:03:56Z开始52秒倒计时,持续识别38秒、21秒、5秒,05:04:51Z倒计时结束后点击右上关闭成功,05:04:53Z退出追加奖励,随后继续按金币规则进入下一广告;本次未复现旧的“奖励弹窗没有符合金币范围”中断。日志留存debug/2026-10-20/monitor67-countdown-close.log。脚本继续运行,本轮尚未验证全部任务完成。 + +monitor-68:用户要求所有直播页面都退出。新增最高优先直播退出规则,以本场点赞/在线观众、更多直播/左滑查看更多直播、聊天+礼物等实际直播控件判定,不因普通任务文案提及直播而返回。直播优先于倒计时、金币和翻卡;退出确认选择退出,悬浮窗提示选择暂不使用。原生控件确认直播时跳过截屏OCR,关闭前复查若变成直播也交回退出规则;连续6次退出无响应有界报错。62项回归及语法检查通过,两处vivo副本与本机SHA-256一致。真机05:22:16Z执行直播返回,05:22:19Z回到普通广告结束页并点击领取成功×,05:22:21Z坚持退出,随后继续双金额规则和新广告倒计时。文字页面确认已不含直播控件;未上传图片。证据debug/2026-10-20/monitor68-live-exit.log;不据此宣称全部任务完成。 + +monitor-70:OPPO用户报告停止并新增书末倒计时右滑规则。现场旧日志06:10:27Z起“未识别到额外奖励的退出按钮”导致补贴、连续奖励、翻卡及领奖连续跳过,06:10:33Z结束前通用复查再次报同错。文字页面同时含饭点补贴背景、恭喜获得奖励层和看视频最高可领50金币,但没有关闭控件;不能将此归因于服务器繁忙。增加已确认奖励层下方中心区域的本机放大OCR找明确X,并排除补贴页无奖励层时常驻最高可领说明的弹窗误判。新增书末持续右滑与2秒稳定窗口,保护原有普通广告倒计时及前景弹窗优先。70项回归及语法检查通过,新版已同步OPPO Download和脚本目录。首次启动因Dozing未获截图权限,唤醒后确认密码锁屏showing=true、secure=true,已请用户手动解锁;此时尚未真机验证新关闭和书末右滑。原日志及页面证据debug/2026-10-20/oppo-monitor68-before-reading-fix.log和oppo-monitor68-before-reading-fix-page.json。 + +monitor-70解锁后复核:OPPO已解锁,首次重启在脚本首行auto阶段提示无障碍服务未启用(系统配置仍显示开启),保留OPPO原有自动填充服务并重新绑定AutoJs6无障碍后恢复。06:37:28Z正式启动,OCR和番茄启动通过;06:38:57Z进入吃饭补贴,06:39:07Z两轮无匹配后退出,06:39:10Z补贴步骤完成,未再次复现之前“找不到额外奖励退出按钮”。随后翻卡个位、十位成功;06:40:29Z倒计时结束后关闭广告,06:40:31Z退出追加奖励,继续翻百位卡的视频。本轮尚未触发书末右滑规则,不宣称真机验证该分支;70项回归已覆盖其行为。运行日志debug/2026-10-20/oppo-monitor70-resumed.log,脚本继续运行。 + +monitor-71:修复OPPO前景追加奖励弹窗OCR“再看一个视頻颜外狭得”未命中视频规则,导致反复点击背景领取成功X并触发三次关闭保护。页面文字归一新增視/頻→视/频,追加奖励标题缺失时用同一中央区域内的领取奖励(或继续领金币)与下方坚持退出组合兜底;金额不明确时退出。72项回归与语法检查通过,包含真实最高800金币、背景X/倒计时并存及标题完全缺失场景。已同步OPPO两处副本且哈希一致。因系统截屏授权多次超时,重启AutoJs并保留OPPO自动填充服务重新绑定无障碍,依据UI树选择整个屏幕并开始后恢复,未修改脚本截图超时配置。真机07:04:29Z点击坚持退出true,07:04:33Z继续翻开千位数,07:04:38Z触发万位卡视频并正常等待倒计时。证据debug/2026-10-20/oppo-monitor71-popup-fixed.log,原故障日志oppo-monitor70-popup-before-fix.log。脚本继续运行,未据此宣称全部任务完成或书末右滑已真机触发。 + +monitor-72:修复旧pendingClaim=true使阅读阶段只查旧领奖、入口缺失后直接结束的问题。现在旧领奖入口缺失会回落到本次阅读;当前任务行只有去阅读时立即结束旧领奖搜索,不继续反复滚动。阅读入口缺失或读完后领奖入口缺失均继续读书挑战赛的奖励检查,仍保留待领奖记录;真实阅读错误不写完读状态。当前阅读现场优先恢复,书末有倒计时持续右滑、无倒计时连续2秒或到首页结束的原规则保持。 + +按用户新增指示,出版物任务同排优先匹配去领取,同时兼容去阅读及领奖时立即领取;不点击其他任务行的同名按钮。标题OCR兼容现场“己使出版物廉金币最高5805”,长标题OCR不再依赖其右边界分隔按钮。手机文字复核确认上一轮同屏立即领取实际位于上方“刷视频领取双重奖励”任务行,不能把它当出版物领奖。 + +新增赚钱页右下宝箱通用规则:福利页与底部赚钱导航同时确认、右下领取按钮带明确金币金额且严格>1000,或宝箱标题与明确金币金额在领取按钮上方对应时点击。前景弹窗、直播退出、广告倒计时及关闭仍优先处理;点击宝箱后继续通用循环。相同金额本轮不连续点击阻塞任务,下次启动重新检查。88项行为回归及语法检查通过,覆盖旧状态回落、缺领奖继续后续、去领取、真实标题OCR、其他任务按钮排除、1000边界、宝箱与前景弹窗顺序等。已同步OPPO PLJ110的Download和脚本目录,SHA256一致。07:56:57Z真机识别宝箱2209并点击“点击领2209”返回true,07:56:59Z按通用规则关闭金额不明确的后续弹窗;不据此认定金币入账。当前从阅读阶段恢复验证,不重复签到/补贴/翻卡;完整阅读与领奖结果待后续文字日志确认。仅手机本地OCR,无图片上传。旧结束证据oppo-monitor71-reading-early-end.log,同屏文字证据oppo-monitor71-publication-row.json,首次新版验证oppo-monitor72-initial-verification.log,均在debug/2026-10-20。 + +monitor-73:monitor-72真机宝箱弹出“请选择宝箱奖励/开宝箱奖励/选204金币/选2204金币”,因双金币选项仅支持领/领取,漏掉“选”字而误入背景额外奖励判断并中断。将该前景宝箱标题及选XX金币纳入通用双金额规则,先按>=500选较大、都<500选较小执行,优先于背景广告/宝箱按钮;无障碍原生关闭按钮文字统一成关闭。90项回归及语法检查通过,其中保留真实手机文字样本验证前景2204选择及低金额边界。OPPO两处正式脚本与本机SHA256一致,08:00:39Z真机已识别并点击“选2204金币”返回true,后续广告及阅读恢复继续观察。原始异常和弹窗文字见debug/2026-10-20/oppo-monitor72-treasure-popup-error.log及oppo-monitor72-treasure-popup.json。 + +monitor-73完整真机验证:08:01:30Z倒计时结束点击右上领取成功×,08:01:32Z坚持退出追加奖励;08:01:57Z识别出版物当前只有去阅读,旧待领奖检查立即跳过并回落阅读;08:02:00Z点击同任务行去阅读,08:02:08—18Z页码连续推进1587→1588→1589→1590/1591,08:02:23Z明确全书完并确认连续2秒无倒计时(本次右滑0次,不声称实测有倒计时右滑分支)。08:02:35Z返回赚钱页,出版物仍无对应领取入口,保留新的全书完pendingClaim记录并继续读书挑战赛;08:03:25Z挑战赛双向搜索也无同排立即领取,跳过,08:03:28Z结束前通用复查无匹配后正常结束。未点击其他任务的立即领取,未认定奖励到账。最终正式手机两处脚本哈希与本地一致;仅澄清了一条跳过日志文字,90项检查再次通过。完整文字证据debug/2026-10-20/oppo-monitor73-reading-recovered.log。 + +monitor-74:按用户最新要求将出版物阶段改为以当前任务行驱动的循环。只要“读出版物赚金币”标签右侧存在去领取、去阅读(兼容旧立即领取),就继续执行对应操作;每次阅读、领取和通用弹窗处理后返回赚钱页重新识别。同标签同按钮重复出现也继续,不再按旧完读/待领奖状态、单本已读完或旧三次领取无变化计数跳到下一任务。原书末倒计时反向翻页与2秒无倒计时规则保持。正常退出条件为连续两次未找到出版物标签,或标签存在但右侧无符合按钮;一次漏识别后按钮重现会重置计数。当前标签可见时直接检查,不混点其他任务;边缘任务行先对齐。领取时无需旧pendingClaim,记录真实点击与通用处理,不把点击当入账。去领取直接进入阅读页时恢复阅读;进入阅读前按钮已变去领取时交回循环,避免等待不存在的正文。返回页面或真实操作异常仍单独记录,不冒充正常无匹配。 + +95项回归及语法检查通过,包含5轮重复阅读、去领取重复出现、无旧状态领取、读/领切换、当前阅读恢复、无匹配两次退出、短暂漏识别重置及其他任务排除。新版已同步OPPO Download、脚本目录,SHA256与本机一致。从出版物阶段恢复验证;首次验证辅助启动等待不足导致番茄未在前台,已让临时验证入口使用与正式启动相同的前台等待,未改正式启动逻辑。真机循环结果待后续文字日志确认。 + +monitor-74真机循环确认:08:14:59Z第1轮找到出版物对应去阅读并进入;当前书本仍为全书完,确认2秒无倒计时后返回赚钱页复查。08:15:17Z继续第2轮,08:15:34Z继续第3轮并再次点击同任务去阅读;没有因为上轮完读或缺少领取入口退出,也未进入挑战赛。每轮当前均为已完读书末、左滑0次,不声称重新读完整本或金币到账。脚本保持运行,按用户规则等待任务行或符合按钮消失后再结束出版物循环。文字证据debug/2026-10-20/oppo-monitor74-publication-loop.log;未上传图片。 + +monitor-75:按用户明确补充“点去阅读看到全书完,先尝试右滑,再开始后续判断”,进入阅读即处于书末(本轮左滑0次)时强制先执行一次真实右滑,成功后重新识别页面,再开始倒计时、首页及连续2秒无倒计时判断。首次右滑前仍先确认阅读现场、应用前台并收起工具栏,前景弹窗照常由snapshot优先处理;右滑失败不保存完成状态。本轮正常左滑到书末且无倒计时时仍只确认2秒,不额外强制右滑。日志将“进入时已在书末处理”与“本轮翻页到书末”分开,避免左滑0次报成本轮重新读完。去阅读入口只有全书完、没有页码或工具栏时,也承认已进入阅读现场。98项回归及语法检查通过,覆盖先右滑后倒计时的顺序、首次右滑失败、无页码全书完入口,以及既有普通倒计时和连续出版物循环。已同步OPPO两处正式脚本,真机验证继续。 + +monitor-75真机分支确认:08:22:02Z识别进入即在书末,执行READ ENTRY RIGHT;08:22:06Z明确右滑后1590/1591,08:22:08Z再确认右上连续2秒无倒计时,共右滑1次,并记录READ END HANDLED而非本轮重新完读。新规则顺序已实机验证。后续返回赚钱页期间,仍有其他页面右上X及阅读现场反复出现,正在原有有限返回流程内复查;不将这部分未经确认的返回视为成功。文字证据debug/2026-10-20/oppo-monitor75-entry-right.log,未上传图片。 + +monitor-75后续状态:08:23:28Z返回赚钱页达到6次原有返回上限仍未识别底部导航,日志END明确保留现场;08:23:32Z结束前通用复查完成。返回期间反复出现本机局部OCR X@987,548,点击后又识别阅读页,尚未确认是否为错误关闭识别或推荐页面跳转,不能断言其原因。按用户此前“停止时先报告、由用户指导”约定报告该后续导航问题,未在本次首次右滑修复中擅改通用关闭策略。98项检查通过,正式两处脚本均为monitor-75且哈希一致;首次右滑已真机成功,不宣称后续整个循环仍在运行。 + +monitor-76/77:按用户“阅读结束,回到首页,再点击底部赚钱”修复返回流程。每次操作后重新识别前景与底部导航,先确认首页/书城,再点击当前底部赚钱,并等待福利中心确认;一帧漏掉导航或被其他阅读页面打断时继续有限返回,不直接当成任务条件消失。首页点击未生效时重试,加载赚钱页期间等待,真实返回失败、应用切走及超时仍保留现场。主界面右侧原生Close Button优先于图片OCR。monitor-76真机仍反复点击X@987,548后进入其他书;停止后文本UI确认返回书城时该位置属于书籍区域,底部书城已选中。monitor-77只排除带首页和赚钱导航、非广告场景中尺寸不足的OCR单字X(现场7×10像素),保留正常大小X、明确关闭文字、原生关闭与广告关闭规则。105项行为检查及语法检查通过,包含导航恢复、加载等待、失败现场、原生关闭优先和微小书封X排除。 + +monitor-77已同步OPPO PLJ110(3B15A700QEL00000)的Download及脚本目录,两正式副本与本机SHA256均为408e70da83f048a40a5e2fe03a2fde388a2ad67f145eb98b4958f6d466c98c15。用户手动解锁后,从当前现场恢复出版物阶段验证:09:20:55Z点击底部赚钱,09:20:57Z确认福利中心;第1轮去阅读后09:21:08Z全书完,本轮左滑1次、无倒计时右滑0次;09:21:09Z返回,09:21:11Z确认首页底部导航,09:21:12Z点击赚钱,09:21:14Z再次确认福利中心;09:21:15Z开始第2轮。OCR仍记录同一个微小X,但未再将其作为关闭点击。该证据确认本次阅读结束后的返回链路恢复,不宣称所有奖励到账或整日任务完成。脚本保持运行,按现有任务匹配规则继续。仅本地OCR与文字证据,无截图上传。日志见debug/2026-10-20/oppo-monitor76-return-retry.log及oppo-monitor77-return-home-earning.log。 + +monitor-78:用户补充左滑没反应或到书末、右上仍有倒计时时持续右滑,直到连续2秒无倒计时或书本首页。原书末分支保留,新增连续两次有可比页码/正文且左滑未推进时切换同一右滑流程;无可比信息不累积卡页次数,一次停顿后恢复前进则清零,无倒计时保持原左滑。卡页右滑处理后返回首页→赚钱重新识别任务,不保存全书完状态、不输出READ FINISHED。前景通用处理、支付页保护、工具栏收起及真实操作失败保护保留。检查现场同时发现右上“01:58得1353金市>”及原生逐字0/1/:/5/8,旧countdown只识别秒数文字,导致错误确认无倒计时。新增仅阅读分支使用的分秒识别,兼容完整合框及同排紧邻原生数字;底部手机时间和无效秒数不参与。110项行为检查及语法检查通过,覆盖卡页反向、无页码正文卡页、2秒窗口、无倒计时继续左滑、短暂停顿不切换,以及分秒OCR/原生碎片。 + +新版已同步OPPO两处正式脚本且SHA256与本机一致:13f83d5ac17eea9bdb886f42b7ffb09f32da5ea18a0ea18faa0be8efc0a1771c。从当前阅读恢复真机验证,09:25:02Z进入即书末先右滑,09:25:05Z识别倒计时并进入READ REWIND START,随后持续右滑1590→1589→1588→1587→1586→1585→1584→1583→1582,未再误报2秒无倒计时退出。本次真机验证的是书末分秒倒计时持续右滑,新增非书末卡页触发由自动化测试覆盖,不声称已实机触发该分支或完成全部任务。脚本保持运行,仅本地OCR,无截图上传。文字证据debug/2026-10-20/oppo-monitor78-reading-timer.json及oppo-monitor78-rewind.log。 + +monitor-78后续真机确认:09:26:26Z右滑共27次后确认右上连续2秒无倒计时并结束反向阅读;09:26:28Z返回首页,09:26:32Z点击底部赚钱,09:26:34Z确认福利中心,09:26:38Z再次点击同任务去阅读。书末分秒倒计时→持续右滑→无倒计时2秒→首页→赚钱→复查下一轮链路已实际完成,脚本继续运行。新增非书末左滑卡页触发仍仅由行为测试覆盖。 + +monitor-79(2026-10-21):补充OPPO现场“今日宝箱无限开/看视频最高再领150金币”前景弹窗规则。最高/最多再领属于上限,直接选择其下方明确关闭,不等待宝箱中部冷却计时、不使用背景高金额或去阅读。兼容标题与金额原生拆字,只有宝箱标题或其下中央关闭证明前景才触发;关闭漏识别在本机裁剪放大找回,暂时缺失则最多等待页面时限,超时报真实弹窗错误,不返回背景给任务搜索;同一关闭三次未响应保留现场。116项检查及语法检查通过,其中真实文字样本的通用分流、延迟关闭、缺关闭保护、最高金额不作确定领取、局部OCR回收及点击保护均覆盖。已同步OPPO两处正式脚本,SHA256与本机一致a129620206eba76c3043a28e56cef5ca2af13215dc5d66de8e3635a41f9e2adc。 + +10:41:38本地时间启动正式monitor-79,完成截屏授权并停止旧同名引擎;实际当前弹窗已变为双金额选择,10:41:50点击选1342金币,随后进入带直播画面的广告并触发直播退出。10:42:44连续六次返回未离开,触发保护异常退出;保留的最后文字帧含前景“再看44秒可领奖励/继续观看/坚持退出/X”,以及背景“本场点赞10.9万”。现有直播判定仍先返回,未处理这类挽留层中的坚持退出。本次宝箱修复已安装、正式脚本已重启,但未实机再次遇到原最高再领150弹窗,不能宣称已实机关闭该弹窗;新增直播挽留故障按用户此前“停止时先报告、由用户指导”约定报告,未在宝箱修复范围内扩改直播规则。运行日志debug/2026-10-21/oppo-monitor79-restart.log,最后文字帧oppo-monitor79-live-exit-popup.json;未上传图片。 + +monitor-80(2026-10-21):修复直播背景仍有本场点赞时,前景“坚持退出”挽留弹窗被重复返回抢占的问题。直播退出先识别其前景明确退出按钮,再决定返回;首次原生直播仍直接返回,按过返回后允许手机本地OCR识别挽留层,避免原生直播背景导致一直跳过OCR。直播返回进行中即使背景标志漏识别仍处理明确退出,离开直播处理后清理该状态;没有直播证据的普通广告坚持退出仍由原通用金币规则处理。六次退出无响应保护保留。119项行为检查及语法检查通过,覆盖真实OPPO直播挽留样本、背景标志漏识别、状态清理及返回后本地OCR。正式两处手机副本与本机SHA256一致:4e5c01ebe8abfc0abf6ed98e1f00b39d7e65e7afb80a5a1ed30e46786396ff7d。 + +10:47:17(北京时间)启动正式monitor-80,10:47:28实际点击直播挽留层坚持退出并返回true,随后进入其他通用流程;普通广告倒计时正常等待,10:48:21关闭领取成功×,10:48:22坚持退出追加奖励;10:48:25按monitor-79新增宝箱规则点击最高再领弹窗X并成功离开,10:48:28进入签到→补贴→翻卡→阅读→领奖的正常流程。至记录时正在搜索签到标签,未再出现直播六次返回退出错误。该证据同时实机确认直播挽留修复及此前宝箱最高再领关闭修复,脚本保持运行,不宣称全部任务完成或金币到账。运行日志debug/2026-10-21/oppo-monitor80-live-exit-recovered.log;仅本地OCR及文字日志,未上传图片。 + +monitor-81—82(2026-10-21):本次实际停止于“|恭喜获得翻卡奖励/3476./金币/看视频继续赚金币”确认弹窗。旧标题规则漏掉翻卡及竖线前缀,又被背景“明日签到领350金币/立即领取”干扰,错误退出翻卡步骤并结束后续流程。新增该前景标题识别、独立与合框关闭定位,关闭成功后标记本轮翻卡已处理,直接继续出版物任务;缺关闭或点击失败不伪报完成、不搜索背景。普通两次无可执行翻卡按钮按无匹配跳到阅读,不再被外层重复重试;真实异常仍保留现场。monitor-81真机10:57:33点击奖励X,10:57:34记录FLIP RECEIPT DONE,确认原阻塞解除。 + +后续验证发现宝箱“最高再领150金币”弹窗X可能与背景“新玩法一大波红包来袭,X”合成整行,旧独立X规则漏识别。monitor-82按已确认宝箱前景标题下方中央末尾X单独提取字形,仅点击该字形,不点击整行背景;右侧、标题上方或文字中间X均不接受。128项行为回归及语法检查通过,包含真实两类弹窗样本、前景优先、关闭失败保护、无匹配继续和实际错误保留。已同步OPPO两处正式脚本,SHA256与本机一致:3ef9c788bb92817c4bed424a3b557a926a092c68815b032221e14368bda13a2c。11:02:20启动正式monitor-82,11:02:32宝箱X关闭成功,11:02:35恢复签到→补贴→翻卡→阅读流程;本次关闭帧是独立X,合框分支由真实文字样本回归验证,未宣称已再次实机触发合框。仅本地OCR及文字日志,未上传图片。 + +monitor-82继续验证:11:04:29倒计时结束后自动关闭广告,11:04:31坚持退出,11:04:33关闭宝箱;11:04:51进入吃饭补贴,11:05:00点击领午饭补贴445金币,11:05:02关闭奖励弹窗,11:05:19补贴步骤完成并进入翻卡。随后真实翻卡弹窗OCR标题为“|翻卡赢金币最高99999”,旧排除规则未处理此处竖线前缀,先于真正“看1个视频翻百位卡”被错误选中并重复点击。现场证据debug/2026-10-21/oppo-monitor82-flip-title.json和对应.log。 + +monitor-83:统一在翻卡标题/状态排除前去掉OCR行首竖线、标点和空白,同时排除“看继续翻卡领更多”标题;保留真正立即翻开、看1个视频翻卡按钮及已有通用优先规则。新增真实现场回归,确认选中翻百位卡而非标题,129项行为检查及语法检查通过。两处正式手机副本与本机SHA256一致:91166225b1c2264b82bae4c0fffadeaf9a8babc20d556f887252f48174944a36。11:08:05正式重启并停止旧同名实例。 + +monitor-83真机:11:10:13正确点击看1个视频翻百位卡,随后依次翻开百位、千位、万位;倒计时结束自动关闭广告并退出不明确的追加奖励。11:13:19按正文11778金币点击开心收下,11:13:23翻卡步骤完成并进入出版物循环,未再误点标题。但出版物标签在底部可见时强制对齐,原950像素手势把任务标题滑到顶部栏下方,反复全列表搜索与对齐四次后11:15:08识别异常退出;证据debug/2026-10-21/oppo-monitor83-publication-align.log及.json。 + +monitor-84:出版物任务标签及其右侧按钮完整可见时直接执行,不因任务行位于底部22%强制对齐;真正被顶部栏/底部导航遮挡时才进行0.12屏高、800ms的小幅慢滑,四次对齐后补查最后一帧,仍异常则保留现场。131项行为回归及语法检查通过,新增底部完整任务行不滑动、遮挡后小幅滑动重新识别两条行为检查。OPPO两正式副本与本机SHA256一致:7e32d23f2c04b0e0e6db091a173967aec06736d1fef8845aff779f8cef12a3a8,已重新启动正式脚本验证。 + +monitor-84真机恢复确认:11:17:53吃饭补贴步骤完成;11:18:15未找到翻卡入口,按无匹配继续出版物而非停止。11:18:41识别边缘出版物行后小幅慢滑,11:18:44任务识别成功,11:18:46点击当前对应去阅读@889,1761,11:18:48确认阅读现场,11:18:53开始真实左滑,页码1569/1589。该证据确认本次原翻卡阻塞、标题误点及后续出版物对齐停止已解除,正式脚本进入阅读并保持运行;未宣称本轮全部任务完成或金币入账。日志与文字页面见debug/2026-10-21/oppo-monitor84-reading-recovered.log及.json;131项检查通过,不上传截图。 diff --git a/fanqie_auto/tests/flow-order.test.js b/fanqie_auto/tests/flow-order.test.js new file mode 100644 index 0000000..8a89fe7 --- /dev/null +++ b/fanqie_auto/tests/flow-order.test.js @@ -0,0 +1,1421 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const source = fs.readFileSync(path.join(__dirname, '../fanqie-daily.auto.js'), 'utf8'); +function load(state, page = []) { + const context = vm.createContext({console, Date, JSON, Math, Error, isFinite}); + vm.runInContext(source.slice(0, source.lastIndexOf('\ntry {\n runDaily();')), context); + const calls = []; + context.files = {write() {}, exists: () => true, read: () => JSON.stringify(state)}; + context.engines = {myEngine: () => ({id: 1, getSource: () => '/sdcard/脚本/fanqie-daily.auto.js'}), all: () => []}; + context.events = {observeToast() {}, onToast() {}, removeListener() {}}; + context.writeRunLog = () => {}; + context.localOcrEnabled = true; + context.snapshot = () => page; + context.publicationEnd = () => false; + context.isPublicationReader = () => false; + context.findFlipButton = () => null; + context.runStep = name => {calls.push(name); return {ok: true};}; + context.runNextPublication = () => calls.push('阅读与领奖'); + return {context, calls}; +} +for (const state of [{pendingClaim: true}, {pendingClaim: false, nextTask: 'readingChallenge'}]) { + test('历史状态不跳过福利中心的前置任务:' + JSON.stringify(state), () => { + const {context, calls} = load(state); + context.runDaily(); + assert.deepEqual(calls.slice(2), ['当前页面及启动签到弹窗', '进入赚钱页面', '签到', '吃饭补贴', '连续5天当日奖励', '翻卡赢金币', '阅读与领奖']); + }); +} +test('当前确实在阅读正文时仍能恢复,不强行退出重跑签到', () => { + const {context, calls} = load({pendingClaim: false}); + context.isPublicationReader = () => true; + context.runDaily(); + assert.deepEqual(calls.slice(2), ['阅读与领奖']); +}); +test('领取饭点补贴不会污染出版物待领奖状态', () => { + const {context} = load({pendingClaim: false}, [popupItem('饭点领金币补贴', 200, 200), popupItem('领早餐补贴', 300, 1000)]); + context.device = {width: 1080, height: 2400}; + let written = 0, tapped = 0; + context.savePublicationClaimState = () => written++; + context.tap = () => tapped++; + context.handleVideos = () => {}; + assert.equal(context.finishMealPage(), true); + assert.equal(tapped, 1); + assert.equal(written, 0); +}); +for (const label of ['105金币', '|领午饭补贴105金币', '领取300金币', '看视频领1,000金币', '|领午饭补贴303金市']) { + test('饭点页金额按钮可领取,不套弹窗500金币门槛:' + label, () => { + const button = popupItem(label, 300, 1000); + const page = [popupItem('饭点领金币补贴', 200, 200), button]; + const {context} = load({}, page); + context.device = {width: 1080, height: 2400}; + const actions = []; + context.tap = item => actions.push(item); + context.handleVideos = pattern => { + assert.equal(pattern.test('饭点领金币补贴'), true); + actions.push('通用规则'); + }; + assert.equal(context.finishMealPage(), true); + assert.deepEqual(actions, [button, '通用规则']); + }); +} +test('金额规则限定饭点主补贴区,不领取余额、已领取说明或连续奖励数字', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const page = [popupItem('饭点领金币补贴', 200, 200), + popupItem('已领取105金币', 300, 600), popupItem('余额1000金币', 300, 650), + popupItem('连续5天', 200, 1300), popupItem('44金币', 300, 1500)]; + assert.equal(context.findMealCoinClaim(page), null); + assert.equal(context.findMealCoinClaim([popupItem('105金币', 300, 1000)]), null); +}); +test('同文案金额按钮领取后继续检查,直到消失才查连续奖励并退出补贴页', () => { + const heading = popupItem('饭点领金币补贴', 200, 200); + const button = popupItem('105金币', 300, 1000); + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + let remaining = 2, inPopup = false; + const actions = []; + context.snapshot = () => { + assert.equal(inPopup, false, '不能越过前景弹窗扫描下一任务'); + return remaining ? [heading, button] : [heading]; + }; + context.tap = item => { + assert.equal(item, button); + assert.ok(remaining > 0); + remaining--; + inPopup = true; + context.actionSerial++; + actions.push('领取'); + }; + context.handleVideos = () => {actions.push('通用规则'); inPopup = false;}; + context.finishStreak = () => { + assert.equal(remaining, 0); + actions.push('查连续奖励'); + }; + context.back = () => {actions.push('返回'); return true;}; + context.waitFor = () => true; + context.sleep = () => {}; + context.runMealPageLoop(); + assert.deepEqual(actions, ['领取', '通用规则', '领取', '通用规则', '查连续奖励', '查连续奖励', '返回']); + assert.equal(context.mealPageDone, true); +}); +test('现场活动繁忙Toast阻止本轮重复点击,继续连续奖励并退出,下轮重新尝试', () => { + const button = popupItem('领午饭补贴303金币', 300, 1000); + const {context} = load({}, [popupItem('饭点领金币补贴', 200, 200), button]); + context.device = {width: 1080, height: 2400}; + let tapped = 0, streaks = 0; + context.tap = () => { + tapped++; + context.actionSerial++; + context.receiveMealToast({getPackageName: () => 'com.dragon.read', getText: () => '活动繁忙,请稍后再试'}); + }; + context.handleVideos = () => {}; + context.finishStreak = () => streaks++; + context.back = () => true; + context.waitFor = () => true; + context.sleep = () => {}; + context.runMealPageLoop(); + assert.equal(tapped, 3); + assert.equal(streaks, 2); + assert.equal(context.findMealCoinClaim([popupItem('饭点领金币补贴', 200, 200), popupItem('|领午饭补贴303金市', 300, 1000)]), null); + context.runMealPageLoop(); + assert.equal(tapped, 6, '每轮最多3次繁忙尝试,跳过只在本轮生效'); +}); +test('Toast监听在runStep外注册和移除,不让补贴任务线程保持事件循环', () => { + const {context} = load({}); + const order = []; + context.events.observeToast = () => order.push('监听'); + context.events.onToast = fn => {assert.equal(fn, context.receiveMealToast);}; + context.runStep = (name, action) => { + assert.equal(name, '吃饭补贴'); + assert.equal(action, context.mealStep); + order.push('任务'); + return {ok: true}; + }; + context.events.removeListener = (event, fn) => { + assert.equal(event, 'toast'); + assert.equal(fn, context.receiveMealToast); + order.push('移除'); + }; + assert.equal(context.runMealStep().ok, true); + assert.deepEqual(order, ['监听', '任务', '移除']); +}); +test('其他应用相同Toast不影响饭点按钮,真实连续颌标题可识别', () => { + const {context} = load({}); + context.receiveMealToast({getPackageName: () => 'other.app', getText: () => '活动繁忙,请稍后再试'}); + assert.equal(context.mealBusyFeedback, null); + assert.equal(context.STREAK_SECTION.test('连续颌吃饭补贴第2天'), true); +}); +test('补贴退出挽留弹窗领991金币吃饭补贴仍优先执行通用规则', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const button = {...popupItem('领991金币吃饭补贴', 261, 1770, 819, 1846), darkButton: true}; + const close = popupItem('关闭', 468, 1976, 612, 2120); + const page = [popupItem('吃饭还能赚金币', 288, 473, 792, 552), + popupItem('991', 443, 1516, 556, 1594), popupItem('金币', 556, 1541, 638, 1583), button, close]; + assert.equal(context.needsCommonHandling(page), true); + assert.equal(context.singleButtonPopupDecision(page).button, button); + button.darkButton = false; + assert.equal(context.singleButtonPopupDecision(page).button, close); +}); +test('连续奖励也遇活动繁忙时本轮跳过,继续扫描而非抛错', () => { + const pending = popupItem('待领取', 492, 2286, 589, 2318); + const {context} = load({}, [popupItem('饭点领金币补贴', 200, 200), + popupItem('连续颌吃饭补贴第2天', 111, 1885, 473, 1920), pending]); + context.device = {width: 1080, height: 2400}; + context.swipe = () => {throw Error('连续奖励可见时不应滚动');}; + let taps = 0; + context.tap = () => { + taps++; + context.receiveMealToast({getPackageName: () => 'com.dragon.read', getText: () => '活动繁忙,请稍后再试'}); + }; + context.handleVideos = () => {}; + context.sleep = () => {}; + context.finishStreak(); + context.finishStreak(); + assert.equal(taps, 3); +}); +test('现场签到高金额含OCR竖线时仍选3928而非1928', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const item = (text, left, top, right, bottom) => ({text, rect: {left, top, right, bottom}}); + const high = item('|领3928金币', 602, 1467, 852, 1508); + const page = [item('今日签到领1928金币', 113, 549, 518, 590), + item('领1928金币', 168, 1467, 409, 1508), high, + item('看视頻奖励', 808, 1420, 940, 1445)]; + assert.equal(context.findHigherCoinClaim(page), high); +}); +test('广告切换后下一帧出现关闭按钮时继续通用处理,不全局抛错', () => { + const {context} = load({}); + const pages = [[{text: '第一广告'}], [{text: '直播关闭'}], []]; + context.readPage = () => pages.shift(); + context.needsCommonHandling = page => page.length > 0; + let handled = 0; + context.handleVideos = () => handled++; + // 恢复真正snapshot,load里的snapshot仅用于调度隔离。 + vm.runInContext(source.slice(source.indexOf('function snapshot() {'), source.indexOf('\n// 小号X')), context); + assert.equal(context.snapshot().length, 0); + assert.equal(handled, 2); +}); +test('直播退出提示优先选择暂不使用,不点击立即开启', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const item = text => ({text, rect: {left: 100, top: 1100, right: 500, bottom: 1200}}); + const dismiss = item('暂不使用'); + assert.equal(context.findPlaybackPopupDismiss([item('悬浮窗播放功能上线啦'), dismiss, item('立即开启')]), dismiss); + assert.equal(context.needsCommonHandling([item('悬浮窗播放功能上线啦'), dismiss]), true); + assert.equal(context.findPlaybackPopupDismiss([dismiss]), null); +}); +function popupItem(text, left, top, right = left + 200, bottom = top + 40) { + return {text, rect: {left, top, right, bottom}}; +} +test('真实视頻误识别的前景追加奖励弹窗优先坚持退出,不反复点击背景X', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + assert.equal(context.compact('再看一个視頻颜外狭得'), '再看一个视频颜外狭得'); + const exit = popupItem('坚持退出', 458, 1424, 618, 1462); + const page = [popupItem(context.compact('再看一个视頻颜外狭得'), 252, 922, 816, 976), + popupItem('最高(', 297, 1057, 438, 1131), popupItem('800', 410, 1010, 668, 1122), + popupItem('金币', 684, 1072, 776, 1118), popupItem('领取奖励', 446, 1273, 631, 1317), exit, + popupItem('领取成功×', 804, 151, 994, 184), popupItem('广告)', 75, 147, 254, 184), + popupItem('20秒后可领奖励', 850, 150)]; + assert.equal(context.offerAmount(page).amount, null); + let exited = false; + context.snapshot = () => exited ? [] : page; + context.tap = item => {assert.equal(item, exit); exited = true;}; + context.handleVideos(/./); + assert.equal(exited, true); +}); +test('追加奖励标题完全漏识别时,领取奖励与坚持退出组合仍选择退出', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const exit = popupItem('|坚持退出', 458, 1424, 618, 1462); + const page = [popupItem('领取奖励', 446, 1273, 631, 1317), exit, popupItem('领取成功×', 804, 151, 994, 184)]; + assert.equal(context.offerAmount(page).amount, null); + let exited = false; + context.snapshot = () => exited ? [] : page; + context.tap = item => {assert.equal(item, exit); exited = true;}; + context.handleVideos(/./); + assert.equal(exited, true); + assert.equal(context.offerAmount([page[0]]), null, '普通领取按钮不能单独冒充挽留弹窗'); +}); +test('直播退出高于倒计时、金币和翻卡,确认退出并拒绝悬浮窗后继续', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const room = [popupItem('58万本场点赞', 180, 205), popupItem('60秒后可领奖励', 850, 150), + popupItem('恭喜获得', 400, 800), popupItem('领2136金币', 700, 1500), + popupItem('领2868金币', 200, 1500)]; + const exit = popupItem('退出直播间', 300, 1400); + const dismiss = popupItem('暂不使用', 300, 1400); + const pages = [room, [popupItem('是否退出直播间', 300, 900), exit, popupItem('继续观看', 600, 1400)], + [popupItem('退出直播间后也能继续观看', 300, 900), dismiss, popupItem('立即开启', 600, 1400)], []]; + assert.equal(context.needsCommonHandling(room), true); + const actions = []; + context.snapshot = () => pages.shift() || []; + context.sleep = () => {}; + context.back = () => {actions.push('返回'); return true;}; + context.tap = button => actions.push(button.text); + context.handleVideos(/./); + assert.deepEqual(actions, ['返回', '退出直播间', '暂不使用']); +}); +test('更多直播或底部聊天工具可识别直播,普通任务文案不触发退出', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + for (const page of [[popupItem('更多直播', 793, 298)], [popupItem('1万在线观众', 816, 167)], + [popupItem('说点什么', 86, 2234), popupItem('礼物', 734, 2234)]]) { + assert.equal(context.liveExitAction(page).back, true); + } + assert.equal(context.liveExitAction([popupItem('看直播赚金币', 100, 1500), popupItem('去观看', 800, 1500)]), null); +}); +test('原生控件已确认直播时不调用截屏OCR,避免识别超时阻挡退出', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + context.foregroundPackage = () => context.CONFIG.packageName; + const rect = {left: 180, top: 205, right: 377, bottom: 244}; + const node = {bounds: () => rect, text: () => '58万本场点赞', visibleToUser: () => true}; + context.textMatches = () => ({find: () => ({size: () => 1, get: () => node})}); + context.descMatches = () => ({find: () => ({size: () => 0})}); + context.captureScreen = () => {throw Error('直播页面不应截屏');}; + context.images = {copy: () => {throw Error('直播页面不应复制截图');}}; + assert.equal(context.readSnapshot()[0].text, '58万本场点赞'); +}); +test('广告关闭复查时进入直播,优先返回,不点击直播右上关闭或等倒计时', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const close = popupItem('关闭', 970, 150, 1030, 195); + const live = [popupItem('更多直播', 793, 298), close, popupItem('60秒后可领奖励', 850, 150)]; + const pages = [[close], live, live, []]; + context.snapshot = () => pages.shift() || []; + context.sleep = () => {}; + let backs = 0; + context.back = () => {backs++; return true;}; + context.tap = () => {throw Error('直播应优先返回');}; + context.handleVideos(/./); + assert.equal(backs, 1); +}); +test('直播连续返回未响应时有界退出,不无限发送返回键', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + context.snapshot = () => [popupItem('更多直播', 793, 298)]; + context.sleep = () => {}; + let backs = 0; + context.back = () => {backs++; return true;}; + assert.throws(() => context.handleVideos(/./), /连续六次退出直播/); + assert.equal(backs, 6); +}); +const liveRetentionPage = JSON.parse(fs.readFileSync(path.join(__dirname, + '../debug/2026-10-21/oppo-monitor79-live-exit-popup.json'), 'utf8')); +test('OPPO真实直播挽留层点击坚持退出,背景点赞和高金币不触发重复返回', () => { + const context = loadReader(liveRetentionPage); + context.device.height = 2374; + const decision = context.liveExitAction(liveRetentionPage); + assert.equal(decision.button.text, '坚持退出'); + assert.equal(decision.back, undefined); + let exited = false; + context.snapshot = () => exited ? [] : liveRetentionPage; + context.back = () => {throw Error('前景有退出按钮时不应按返回');}; + context.tap = item => {assert.equal(item.text, '坚持退出'); exited = true;}; + context.handleVideos(/./); + assert.equal(exited, true); + assert.equal(context.liveReturnPending, false); +}); +test('已执行直播返回后背景标志漏识别,仍点坚持退出,退出后清除状态', () => { + const context = loadReader([]); + const exit = popupItem('|坚持退出', 301, 1426); + let phase = 0; + context.snapshot = () => phase === 0 ? [popupItem('本场点赞10.9万', 145, 391)] : + phase === 1 ? [exit, popupItem('再看44秒可领奖励', 324, 926)] : []; + context.back = () => {assert.equal(phase, 0); phase++; return true;}; + context.tap = item => {assert.equal(item, exit); assert.equal(phase, 1); phase++;}; + context.handleVideos(/./); + assert.equal(phase, 2); + assert.equal(context.liveReturnPending, false); + assert.equal(context.liveExitAction([exit, popupItem('继续观看', 446, 1272)]), null, + '普通广告没有直播证据时仍交给原金币规则'); +}); +test('原生直播按返回后允许本地OCR识别挽留按钮,不再一直跳过前景识别', () => { + const context = loadReader([]); + context.liveReturnPending = true; + const rect = {left: 145, top: 391, right: 290, bottom: 411}; + const node = {bounds: () => rect, text: () => '本场点赞10.9万', visibleToUser: () => true}; + context.textMatches = () => ({find: () => ({size: () => 1, get: () => node})}); + context.descMatches = () => ({find: () => ({size: () => 0})}); + let captures = 0, recycled = 0; + context.captureScreen = () => {captures++; return {};}; + context.images = {copy: () => ({recycle: () => recycled++})}; + context.$ocr = {detect: () => [ + {text: '坚持退出', bounds: {left: 301, top: 1426, right: 461, bottom: 1464}}, + {text: 'X', bounds: {left: 970, top: 150, right: 1000, bottom: 180}} + ]}; + const page = context.readSnapshot(); + assert.equal(context.liveExitAction(page).button.text, '坚持退出'); + assert.equal(captures, 1); + assert.equal(recycled, 1); +}); +test('翻字按钮不能阻止无倒计时的右上角关闭', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const flip = popupItem('立即翻开十位数', 400, 1400); + const close = popupItem('关闭', 970, 150, 1030, 195); + const page = [popupItem('继续翻卡领更多金币', 300, 800), flip, close]; + context.findFlipButton = items => items.includes(flip) ? flip : null; + context.flipEntryOpened = true; + assert.equal(context.needsCommonHandling(page), true); + let closed = false; + context.snapshot = () => closed ? [] : page; + context.sleep = () => {}; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +test('有翻字和右上角关闭时仍先等真实倒计时结束', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const flip = popupItem('立即翻开十位数', 400, 1400); + const close = popupItem('X', 970, 150, 995, 180); + const timer = popupItem('1秒后关闭', 850, 150); + context.findFlipButton = items => items.includes(flip) ? flip : null; + context.flipEntryOpened = true; + const pages = [[flip, close, timer], [flip, close], [flip, close], []]; + let waited = 0, taps = 0; + context.snapshot = () => pages.shift() || []; + context.sleep = () => waited++; + context.tap = item => {assert.equal(item, close); assert.ok(waited >= 1); taps++;}; + context.handleVideos(/./); + assert.equal(taps, 1); +}); +test('广告恭喜获得文案没有领取按钮时,等待倒计时后执行右上关闭', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const heading = popupItem('恭喜获得', 417, 1142, 664, 1203); + const coins = popupItem('5182金币', 389, 1521, 682, 1585); + const timer = popupItem('广告1)39秒|27秒后可领奖励×', 89, 130, 976, 197); + const close = popupItem('领取成功×', 850, 130, 976, 197); + const pages = [[heading, coins, timer], [heading, coins, close], [heading, coins, close], []]; + let waited = 0, taps = 0; + context.snapshot = () => pages.shift() || []; + context.sleep = () => waited++; + context.tap = item => {assert.match(item.text, /^关闭/); assert.ok(waited >= 1); taps++;}; + context.handleVideos(/./); + assert.equal(taps, 1); +}); +test('只有奖励标题和金额,没有可执行控件时不反复进入通用规则', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const page = [popupItem('恭喜获得', 417, 1142), popupItem('5182金币', 389, 1521)]; + assert.equal(context.needsCommonHandling(page), false); + context.snapshot = () => page; + context.tap = () => {throw Error('没有领取或关闭控件不能盲点');}; + context.handleVideos(/./); +}); +test('没有右上角关闭时仍保留翻卡的中央操作弹窗', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const flip = popupItem('立即翻开十位数', 400, 1400); + const page = [popupItem('继续翻卡领更多金币', 300, 800), flip, popupItem('X', 520, 1750, 560)]; + context.findFlipButton = () => flip; + context.flipEntryOpened = true; + context.snapshot = () => page; + context.tap = () => {throw Error('中央翻卡弹窗不应关闭');}; + context.handleVideos(/./); +}); +test('前景121元现金邀请弹窗无金币领取按钮,忽略背景金币任务并关闭', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const close = popupItem('X', 526, 1724, 554, 1751); + const page = [popupItem('送你现金红包', 410, 765, 670, 807), + popupItem('121元', 414, 902, 670, 1005), popupItem('邀靖好友立得', 418, 1444, 662, 1481), close, + popupItem('天天领金币最高471', 92, 1673, 613, 1721), popupItem('去领取', 841, 1727, 938, 1758), + popupItem('立即参与', 826, 2152, 953, 2183)]; + assert.equal(context.findEmptyRewardPopupClose(page), close); + assert.equal(context.needsCommonHandling(page), true); + let closed = false; + context.snapshot = () => closed ? [] : page; + context.sleep = () => {}; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +test('普通页面上的X和现金金额不冒充现金邀请弹窗', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + assert.equal(context.findEmptyRewardPopupClose([popupItem('121元', 414, 902), popupItem('X', 526, 1724)]), null); +}); +test('正常结束前再扫描一轮,处理晚出现的通用弹窗', () => { + const {context} = load({}); + context.foregroundPackage = () => context.CONFIG.packageName; + let scans = 0, pauses = 0; + context.snapshot = () => {scans++;}; + context.sleep = () => {pauses++;}; + context.drainCommonBeforeExit(); + assert.equal(scans, 2); + assert.equal(pauses, 1); +}); +function loadReader(page) { + const {context} = load({}, page); + vm.runInContext(source.slice(source.indexOf('function isPublicationReader('), source.indexOf('function readingPageKey(')), context); + context.device = {width: 1080, height: 2400}; + context.foregroundPackage = () => context.CONFIG.packageName; + let now = 100000; + context.Date = class extends Date { static now() { return now; } }; + context.sleep = ms => {now += ms;}; + return context; +} +const readerPage = current => [popupItem('正文第' + current + '页', 100, 600), popupItem(current + '/3', 86, 2300)]; +test('真实阅读页倒计时交给翻页流程,广告倒计时仍执行通用等待', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const close = popupItem('X', 970, 150, 995, 180); + const context = loadReader(readerPage(1)); + const page = [...readerPage(1), timer, close]; + assert.equal(context.needsCommonHandling(page), false); + assert.equal(context.needsCommonHandling([...page, popupItem('广告1)', 60, 150)]), true); + const claim = popupItem('领2136金币', 600, 1400); + assert.equal(context.needsCommonHandling([...page, popupItem('签到奖励', 300, 700), claim, + popupItem('领100金币', 200, 1400)]), true, '前景领取弹窗仍优先'); +}); +test('左滑到书末仍有倒计时则持续右滑,到首页即结束,即使倒计时仍存在', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const context = loadReader(readerPage(1)); + let current = 1, saved = false; + const directions = []; + context.snapshot = () => [...readerPage(current), timer]; + context.swipe = (x1, y1, x2) => { + assert.equal(saved, false); + const direction = x2 > x1 ? 1 : -1; + directions.push(direction); + current += direction > 0 ? -1 : 1; + return true; + }; + context.savePublicationClaimState = (pending, evidence) => { + assert.equal(current, 1); + assert.equal(pending, true); + assert.equal(evidence, '3/3'); + saved = true; + }; + assert.equal(context.runPublicationPages(), true); + assert.deepEqual(directions, [-1, -1, 1, 1]); + assert.equal(saved, true); +}); +test('本轮左滑到书末且无倒计时则确认2秒,不额外右滑', () => { + const context = loadReader(readerPage(2)); + const start = context.Date.now(); + let current = 2, turns = 0; + context.snapshot = () => readerPage(current); + context.swipe = (x1, y1, x2) => {assert.ok(x2 < x1); current = 3; turns++; return true;}; + let saved = false; + context.savePublicationClaimState = () => { + assert.ok(context.Date.now() - start >= 2000 + context.CONFIG.readingPagePauseMs); + saved = true; + }; + assert.equal(context.runPublicationPages(), true); + assert.equal(turns, 1); + assert.equal(saved, true); +}); +test('书末倒计时短暂漏识别后重新出现,清空2秒窗口并继续右滑', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const page = (n, timed) => [popupItem('正文', 100, 600), popupItem(n + '/10', 86, 2300), ...(timed ? [timer] : [])]; + const context = loadReader(page(10, true)); + const pages = [page(10, true), page(9, false), page(8, true), page(7, false), page(6, false), page(5, false)]; + let turns = 0; + context.snapshot = () => pages.shift() || page(5, false); + context.swipe = (x1, y1, x2) => {assert.ok(x2 > x1); turns++; return true;}; + const initial = context.snapshot(); + context.finishPublicationCountdown(initial, context.Date.now() + 60000); + assert.equal(turns, 5); +}); +test('书末右滑失败不能记录待领奖完成状态', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const context = loadReader([...readerPage(3), timer]); + context.swipe = () => false; + context.savePublicationClaimState = () => {throw Error('失败不应保存完读');}; + assert.throws(() => context.runPublicationPages(), /右滑执行失败/); +}); +test('左滑两次页码不变且有倒计时则右滑到首页,不冒充全书读完', () => { + const timer = popupItem('01:58得1353金市>', 701, 176); + const context = loadReader(readerPage(2)); + let current = 2; + const directions = [], logs = []; + context.snapshot = () => [...readerPage(current), timer]; + context.swipe = (x1, y1, x2) => {directions.push(x2 > x1 ? '右' : '左'); if (x2 > x1) current--; return true;}; + context.savePublicationClaimState = () => {throw Error('卡页不应保存全书完状态');}; + context.writeRunLog = value => logs.push(value); + assert.equal(context.runPublicationPages(), true); + assert.deepEqual(directions, ['左', '左', '右']); + assert.equal(current, 1); + assert.ok(logs.some(value => value.startsWith('READ STALLED:'))); + assert.equal(logs.some(value => value.startsWith('READ FINISHED:')), false); +}); +test('阅读倒计时支持分秒合框与OPPO原生逐字控件,排除底部时钟和无效秒数', () => { + const context = loadReader([]); + for (const label of ['01:58', '1:02', '01:58得1353金市>', '00:09得1353金币']) { + const item = popupItem(label, 701, 176); + assert.equal(context.publicationCountdown([item]), item); + } + const split = ['0', '1', ':', '5', '8'].map((text, i) => + ({...popupItem(text, 712 + i * 18, 174, 730 + i * 18, 209), node: {}})); + assert.equal(context.publicationCountdown(split).text, '01:58'); + assert.equal(context.publicationCountdown([popupItem('17:23', 806, 2290)]), null); + assert.equal(context.publicationCountdown([popupItem('01:88', 701, 176)]), null); +}); +test('无页码正文不变也触发右滑,倒计时消失连续2秒后退出', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const context = loadReader([]); + let rightTurns = 0, noTimerAt = null; + const directions = []; + const body = [popupItem('相同正文', 100, 600), popupItem('目录', 100, 2200), popupItem('设置', 600, 2200)]; + context.snapshot = () => { + if (rightTurns && noTimerAt === null) noTimerAt = context.Date.now(); + return [...body, ...(rightTurns ? [] : [timer])]; + }; + context.swipe = (x1, y1, x2) => { + directions.push(x2 > x1 ? '右' : '左'); + if (x2 > x1) rightTurns++; + return true; + }; + context.savePublicationClaimState = () => {throw Error('没有书末证据不保存完读');}; + assert.equal(context.runPublicationPages(), true); + assert.deepEqual(directions, ['左', '左', '右', '右', '右']); + assert.ok(context.Date.now() - noTimerAt >= context.CONFIG.readingCountdownClearMs); +}); +test('左滑连续无变化但没有倒计时仍继续左滑,直到明确书末', () => { + const context = loadReader(readerPage(2)); + let lefts = 0; + context.snapshot = () => readerPage(lefts >= 3 ? 3 : 2); + context.swipe = (x1, y1, x2) => {assert.ok(x2 < x1); lefts++; return true;}; + context.savePublicationClaimState = () => {}; + assert.equal(context.runPublicationPages(), true); + assert.equal(lefts, 3); +}); +test('一次左滑未推进后恢复翻页时不提前切右滑', () => { + const timer = popupItem('30秒后可领奖励', 850, 150); + const context = loadReader(readerPage(1)); + let lefts = 0; + context.snapshot = () => [...readerPage(Math.max(1, Math.min(3, lefts))), ...(lefts < 3 ? [timer] : [])]; + context.swipe = (x1, y1, x2) => {assert.ok(x2 < x1); lefts++; return true;}; + context.savePublicationClaimState = () => {}; + assert.equal(context.runPublicationPages(), true); + assert.equal(lefts, 3); +}); +test('历史待领奖状态不能跳过当前阅读现场的书末倒计时处理', () => { + const {context} = load({pendingClaim: true}); + vm.runInContext(source.slice(source.indexOf('function runNextPublication('), source.indexOf('function runDaily()')), context); + const calls = []; + context.runStep = name => {calls.push(name); return {ok: false};}; + context.runNextPublication(true); + assert.deepEqual(calls, ['读出版物赚金币:持续左滑阅读']); +}); +test('补贴常驻最高可领说明不当作追加奖励弹窗', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const page = [popupItem('饭点领金而补贴', 100, 150), popupItem('看视频最高可领50金币', 291, 1340)]; + assert.equal(context.offerAmount(page), null); + assert.equal(context.needsCommonHandling(page), false); +}); +const cappedTreasurePage = JSON.parse(fs.readFileSync(path.join(__dirname, + '../debug/2026-10-21/oppo-stopped-popup.json'), 'utf8')); +const flipRewardPage = JSON.parse(fs.readFileSync(path.join(__dirname, + '../debug/2026-10-21/oppo-monitor80-flip-reward.json'), 'utf8')); +test('真实翻卡奖励层优先关闭,不被背景明日签到和其他任务立即领取抢占', () => { + const context = loadReader(flipRewardPage); + context.device.height = 2374; + context.flipEntryOpened = true; + assert.equal(context.rewardReceiptHeading(flipRewardPage).text, '|恭喜获得翻卡奖励'); + assert.equal(context.needsCommonHandling(flipRewardPage), true); + const close = context.findRewardReceiptClose(flipRewardPage); + assert.equal(close.text, 'X'); + let closed = false; + context.snapshot = () => closed ? [] : flipRewardPage; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(context.flipSettlementDone, true); + assert.equal(context.flipActionDone, true); +}); +test('翻卡奖励标题即使低于屏幕中部也不能当翻卡操作按钮', () => { + const context = loadReader([]); + vm.runInContext(source.slice(source.indexOf('function isFlipButton('), source.indexOf('function flipCardStep(')), context); + context.flipEntryOpened = true; + const page = [popupItem('|恭喜获得翻卡奖励', 324, 1100), popupItem('翻卡奖励已到账', 324, 1200)]; + assert.equal(context.findFlipButton(page), null); + assert.equal(context.flipPopupHasAction(page), false); + assert.equal(context.findFlipButton([popupItem('立即翻开十位数', 350, 1400)]).text, '立即翻开十位数'); +}); +test('翻卡奖励层缺关闭时不搜索背景、不标记翻卡已处理', () => { + const context = loadReader([]); + context.device.height = 2374; + const missing = flipRewardPage.filter(item => item.text !== 'X'); + context.readPage = () => missing; + context.tap = () => {throw Error('不应点击背景领取');}; + restoreSnapshot(context); + assert.throws(() => context.snapshot(), /翻卡奖励弹窗仍在前台.*不搜索背景任务/); + assert.equal(context.flipSettlementDone, false); +}); +test('OPPO翻卡现场带竖线的标题不抢占真正的翻百位卡按钮', () => { + const page = JSON.parse(fs.readFileSync(path.join(__dirname, + '../debug/2026-10-21/oppo-monitor82-flip-title.json'), 'utf8')); + const context = loadReader(page); + context.device.height = 2374; + vm.runInContext(source.slice(source.indexOf('function isFlipButton('), source.indexOf('function flipCardStep(')), context); + assert.equal(context.findFlipButton(page).text, '看1个视频翻百位卡'); + for (const text of ['|已翻出个位数,继续翻卡赚更多金币', '|继续翻卡领更多金币', '|翻卡赢金币最高99999', '看继续翻卡领更多金币']) { + assert.equal(context.findFlipButton([popupItem(text, 92, 1100)]), null); + } +}); +test('翻卡奖励确认关闭失败不标记为处理完成', () => { + const context = loadReader(flipRewardPage); + context.device.height = 2374; + context.tap = () => {throw Error('点击失败');}; + assert.throws(() => context.handleVideos(/./), /点击失败/); + assert.equal(context.flipSettlementDone, false); +}); +test('已进入翻卡入口但没有操作按钮时继续阅读,真实错误仍保留现场', () => { + for (const ok of [true, false]) { + const {context} = load({}); + context.runStep = name => { + if (name === '翻卡赢金币') {context.flipEntryOpened = true; return {ok, skipped: true};} + return {ok: true}; + }; + let next = 0; + context.runNextPublication = () => next++; + context.toastLog = () => {}; + context.runDaily(); + assert.equal(next, ok ? 1 : 0); + } +}); +test('翻卡奖励弹窗被启动通用处理关闭后直接继续出版物,不重跑签到翻卡', () => { + const {context, calls} = load({}); + context.snapshot = () => {context.flipSettlementDone = true; context.flipActionDone = true; return [];}; + context.runDaily(); + assert.deepEqual(calls.slice(2), ['阅读与领奖']); +}); +test('翻卡按钮连续两次缺失直接跳过,不再额外重复三轮空检查', () => { + const context = loadReader([]); + context.flipEntryOpened = true; + let waits = 0; + context.waitFor = () => {waits++; return null;}; + assert.throws(() => context.flipCardStep(), /没有翻卡按钮/); + assert.equal(waits, 2); +}); +test('OPPO真实最高再领150宝箱弹窗优先关闭,不等待冷却、不点击背景去阅读', () => { + const context = loadReader(cappedTreasurePage); + context.device.height = 2374; + assert.equal(context.needsCommonHandling(cappedTreasurePage), true); + const close = context.cappedRewardPopup(cappedTreasurePage).close; + assert.equal(close.text, 'X'); + let closed = false; + context.snapshot = () => closed ? [] : cappedTreasurePage; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +function restoreSnapshot(context) { + vm.runInContext(source.slice(source.indexOf('function snapshot()'), source.indexOf('// 小号X')), context); +} +test('宝箱最高再领文案和金额拆开、关闭晚一帧出现时,清理前不返回背景页面', () => { + const context = loadReader([]); + context.device.height = 2374; + const split = cappedTreasurePage.filter(item => item.text !== '看视频最高再领150金币'); + const missing = split.filter(item => item.text !== 'X'); + assert.ok(context.cappedRewardPopup(missing)); + assert.equal(context.needsCommonHandling(missing), true); + let reads = 0, closed = false; + context.readPage = () => closed ? [] : ++reads < 3 ? missing : split; + context.tap = item => {assert.equal(item.text, 'X'); closed = true;}; + restoreSnapshot(context); + assert.equal(context.snapshot().length, 0); + assert.equal(closed, true); + assert.ok(reads >= 3); +}); +test('已确认宝箱前景但一直没有关闭控件时有界报错,不把背景当作任务缺失', () => { + const missing = cappedTreasurePage.filter(item => item.text !== 'X'); + const context = loadReader(missing); + context.device.height = 2374; + context.readPage = () => missing; + context.tap = () => {throw Error('不应点任何背景按钮');}; + restoreSnapshot(context); + assert.throws(() => context.snapshot(), /不搜索背景任务/); +}); +test('最高再领即使标高金额仍按上限关闭;无前景证据的普通文字不触发', () => { + const context = loadReader([]); + const heading = popupItem('看视频最高再领8000金币', 288, 1344, 793, 1397); + assert.equal(context.cappedRewardPopup([heading]), null); + const close = popupItem('X', 531, 1649, 554, 1675); + const page = [heading, close]; + let closed = false; + context.snapshot = () => closed ? [] : page; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +test('宝箱最高再领关闭漏识别时仅在手机本地裁剪其下方区域找X', () => { + const context = loadReader([]); + context.device.height = 2374; + const page = cappedTreasurePage.filter(item => item.text !== 'X'); + let recycled = 0; + context.images = { + clip: () => ({recycle: () => recycled++}), resize: () => ({recycle: () => recycled++}) + }; + context.$ocr = {detect: () => [{text: 'X', bounds: {left: 460, top: 756, right: 530, bottom: 834}}]}; + context.readReceiptCloseRegion({}, page); + assert.equal(context.cappedRewardPopup(page).close.text, 'X'); + assert.equal(recycled, 2); +}); +test('OPPO宝箱X与背景文字合框时只点击最后关闭字形,不点击整行背景', () => { + const page = JSON.parse(fs.readFileSync(path.join(__dirname, + '../debug/2026-10-21/oppo-monitor81-treasure-close-miss.json'), 'utf8')); + const context = loadReader(page); + context.device.height = 2374; + const close = context.cappedRewardPopup(page).close; + assert.ok(close.rect.left > 510); + assert.equal(close.rect.right, 554); + assert.equal(close.rect.top, 1632); + let closed = false; + context.snapshot = () => closed ? [] : page; + context.tap = item => {assert.deepEqual(item.rect, close.rect); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +test('宝箱合框关闭只接受前景标题下方中央的末尾X', () => { + const context = loadReader([]); + const heading = popupItem('看视频最高再领150金币', 288, 1344, 793, 1397); + for (const item of [popupItem('背景X', 840, 1632, 1000, 1677), + popupItem('背景X', 400, 500, 554, 550), popupItem('X背景', 400, 1632, 554, 1677)]) { + assert.equal(context.cappedRewardPopup([heading, item]), null); + } +}); +test('宝箱同一关闭按钮三次未响应后保留现场,不无限点击', () => { + const context = loadReader(cappedTreasurePage); + context.device.height = 2374; + let clicks = 0; + context.tap = () => clicks++; + assert.throws(() => context.handleVideos(/./), /同一关闭按钮连续三次未响应/); + assert.equal(clicks, 3); +}); +test('补贴领取确认层下方小X通过本机局部OCR找回并关闭', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const page = [popupItem('饭点领金而补贴', 100, 150), popupItem('恭喜获得', 475, 794, 603, 826), + popupItem('看视频最高可领50金币', 291, 1340, 785, 1384)]; + let recycled = 0; + context.images = { + clip: (frame, x, y, w, h) => {assert.deepEqual([x, y, w, h], [378, 1384, 324, 824]); return {recycle: () => recycled++};}, + resize: () => ({recycle: () => recycled++}) + }; + context.$ocr = {detect: () => [{text: '×', bounds: {left: 420, top: 150, right: 510, bottom: 240}}]}; + context.readReceiptCloseRegion({}, page); + const close = context.findRewardReceiptClose(page); + assert.equal(close.text, 'X'); + assert.equal(close.rect.left, 518); + assert.equal(close.rect.top, 1434); + assert.equal(recycled, 2); + let closed = false; + context.snapshot = () => closed ? [] : page; + context.tap = item => {assert.equal(item, close); closed = true;}; + context.handleVideos(/./); + assert.equal(closed, true); +}); +test('阅读先收起工具栏再左滑,直到末页才记录完读', () => { + const toolbar = [...readerPage(1), popupItem('上一章', 86, 1974), popupItem('目录', 182, 2276)]; + const context = loadReader(toolbar); + let page = toolbar, turns = 0, pressed = 0, finished = false; + context.snapshot = () => page; + context.press = () => {pressed++; page = readerPage(1); return true;}; + context.swipe = () => { + assert.equal(context.publicationToolbarVisible(page), false); + page = readerPage(++turns + 1); + return true; + }; + context.savePublicationClaimState = pending => {finished = pending;}; + assert.equal(context.runPublicationPages(), true); + assert.equal(pressed, 1); + assert.equal(turns, 2); + assert.equal(finished, true); +}); +test('五次卡页后仍继续左滑,页码不变时OCR噪声不算进度', () => { + const context = loadReader(readerPage(1)); + let turns = 0, finished = false; + const swipeYs = []; + context.snapshot = () => readerPage(turns < 6 ? 1 : turns < 7 ? 2 : 3); + context.swipe = (x1, y) => { + assert.ok(++turns <= 7, '应在真实末页结束'); + swipeYs.push(y); + return true; + }; + context.savePublicationClaimState = () => {finished = true;}; + context.runPublicationPages(); + assert.equal(turns, 7); + assert.notEqual(swipeYs[5], swipeYs[0], '卡页后更换左滑位置'); + assert.equal(finished, true); +}); +test('阅读未完返回福利中心后重新点对应去阅读,继续到末页', () => { + const context = loadReader(readerPage(1)); + let page = readerPage(1), turns = 0, reentered = 0; + context.snapshot = () => page; + context.searchPublicationEntry = () => popupItem('去阅读', 841, 403); + context.tap = () => {reentered++; page = readerPage(2);}; + context.swipe = () => {page = ++turns === 1 ? [popupItem('福利中心', 72, 129)] : readerPage(3); return true;}; + context.savePublicationClaimState = () => {}; + context.runPublicationPages(); + assert.equal(reentered, 1); + assert.equal(turns, 2); +}); +test('繁忙提示在通用处理期间迟到时也执行有限重试,提示消失后不禁用按钮', () => { + const button = popupItem('领午饭补贴303金币', 300, 1000); + const {context} = load({}, [popupItem('饭点领金币补贴', 200, 200), button]); + context.device = {width: 1080, height: 2400}; + context.sleep = () => {}; + let taps = 0; + context.tap = () => {taps++; context.mealBusyFeedback = null;}; + context.handleVideos = () => { + if (taps === 1) context.receiveMealToast({getPackageName: () => context.CONFIG.packageName, getText: () => '活动繁忙,请稍后再试'}); + }; + context.claimMealButton(button); + assert.equal(taps, 2); + assert.equal(context.mealClaimAvailable(button), true); +}); +for (const [left, right, expected] of [[100, 400, 100], [499, 500, 500], [600, 900, 900], [500, 500, 500]]) { + test(`双按钮金币 ${left}/${right} 选${expected}`, () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const page = [popupItem('签到奖励', 200, 600), popupItem(`领${left}金币`, 160, 1200), popupItem(`领${right}金币`, 600, 1200)]; + assert.equal(Number(context.findHigherCoinClaim(page).text.replace(/\D/g, '')), expected); + }); +} +for (const [amount, dark, take] of [[499, true, false], [500, true, true], [501, false, false]]) { + test(`单按钮正文${amount}金币 深色=${dark} 领取=${take}`, () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const button = {...popupItem('开心收下', 400, 1400), darkButton: dark}; + const close = popupItem('X', 520, 1750, 560); + const page = [popupItem('恭喜获得', 300, 700), popupItem(`${amount}金币`, 300, 900), button, close]; + const decision = context.singleButtonPopupDecision(page); + assert.equal(decision.take, take); + assert.equal(decision.button, take ? button : close); + }); +} +test('正文只有奖励上限不能当确定金币,关闭单按钮弹窗', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const close = popupItem('X', 520, 1750, 560); + const page = [popupItem('恭喜获得', 300, 700), popupItem('最高1000金币', 300, 900), + {...popupItem('立即领取', 400, 1400), darkButton: true}, close]; + assert.equal(context.singleButtonPopupDecision(page).button, close); +}); +test('深色判定取当前手机像素:深背景通过,白背景不通过', () => { + const {context} = load({}); + let level = 40; + context.images = {pixel: () => level}; + context.colors = {red: c => c, green: c => c, blue: c => c}; + assert.equal(context.isDarkButton({}, popupItem('领取奖励', 400, 1400)), true); + level = 255; + assert.equal(context.isDarkButton({}, popupItem('领取奖励', 400, 1400)), false); +}); +test('广告过渡帧仍属于通用处理,不能把后续任务全部判缺失', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const ad = popupItem('广告|1)', 70, 150); + assert.equal(context.isAdvertisementPage([ad]), true); + assert.equal(context.needsCommonHandling([ad]), true); + assert.equal(context.isAdvertisementPage([popupItem('广告', 70, 1800)]), false); +}); +test('奖励弹窗两按钮都不足500时优先小额,不走旧的直接关闭分支', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const small = popupItem('直接领取100金币', 160, 1400); + const page = [popupItem('恭喜获得', 300, 700), small, popupItem('看视频得400金币', 600, 1400), popupItem('X', 520, 1750, 560)]; + let tapped; + context.snapshot = () => tapped ? [] : page; + context.tap = item => {tapped = item;}; + context.handleVideos(/./); + assert.equal(tapped, small); +}); +test('无恭喜标题的单按钮弹窗也依据正文金币与深色判断', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const button = {...popupItem('领更多金币', 400, 1400), darkButton: true}; + const close = popupItem('X', 520, 1750, 560); + const page = [popupItem('500金币', 300, 900), button, close]; + assert.equal(context.singleButtonPopupDecision(page).button, button); + button.darkButton = false; + assert.equal(context.singleButtonPopupDecision(page).button, close); +}); +test('四段广告同位置X不会累计为连续三次未响应', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + context.sleep = () => {}; + const timer = popupItem('1秒后关闭', 850, 150); + const close = popupItem('X', 970, 150, 995, 180); + const pages = []; + for (let i = 0; i < 4; i++) pages.push([timer], [close], [close]); + pages.push([]); + context.snapshot = () => pages.shift() || []; + let taps = 0; + context.tap = () => taps++; + context.handleVideos(/./); + assert.equal(taps, 4); +}); +test('同一个X持续存在且无页面进展时仍在三次点击后保护退出', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + context.sleep = () => {}; + const close = popupItem('X', 970, 150, 995, 180); + context.snapshot = () => [close]; + let taps = 0; + context.tap = () => taps++; + assert.throws(() => context.handleVideos(/./), /同一关闭按钮连续三次未响应/); + assert.equal(taps, 3); +}); +test('赚钱页签到无需日常福利标题,按钮带竖线仍匹配', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const sign = popupItem('|去签到', 854, 237, 949, 267); + const page = [popupItem('签到领金币', 80, 206, 293, 246), sign, + popupItem('去领取', 854, 845, 951, 875)]; + context.snapshot = () => page; + context.swipe = () => {throw Error('入口已可见,不应滚动');}; + assert.equal(context.searchEarningTask(/^[||]?(?:签到|每日签到)(?:领金币.*)?$/, /^[||]?(?:去签到|立即签到|签到)$/, '签到'), sign); +}); +test('vivo领吃饭补贴991直接匹配本行去领取,不需要日常福利', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const meal = popupItem('去领取', 854, 845, 951, 875); + const page = [popupItem('领吃饭补贴991', 79, 811, 438, 857), meal, + popupItem('预约领金币', 80, 1008), popupItem('去领取', 854, 1037)]; + context.snapshot = () => page; + context.swipe = () => {throw Error('入口已可见,不应滚动');}; + assert.equal(context.findMealEntry(), meal); +}); +for (const caption of ['7天签到必得18万金币', '今日签到领100金币', '签到奖励']) { + test('单按钮签到弹窗'+caption+'直接点击唯一深色按钮', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const button = {...popupItem('立即领取', 400, 1400), darkButton: true}; + const page = [popupItem(caption, 250, 600), button, popupItem('X', 520, 1750, 560)]; + assert.equal(context.singleButtonPopupDecision(page).button, button); + assert.equal(context.singleButtonPopupDecision(page).signIn, true); + }); +} +test('普通签到任务行不当作签到弹窗,也不能越过双按钮金额规则', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + assert.equal(context.findSingleSignPopupClaim([popupItem('签到领金币', 80, 600), {...popupItem('去签到', 850, 600), darkButton: true}]), null); + const page = [popupItem('今日签到', 250, 600), {...popupItem('领100金币', 160, 1400), darkButton: true}, + {...popupItem('领400金币', 600, 1400), darkButton: true}, popupItem('X', 520, 1750, 560)]; + assert.equal(context.findSingleSignPopupClaim(page), null); + assert.equal(context.findHigherCoinClaim(page).text, '领100金币'); +}); +test('vivo弹窗无障碍closebutton明确按关闭识别', () => { + const {context} = load({}); + assert.equal(context.compact('closebutton'), '关闭'); + assert.equal(context.compact('close_button'), '关闭'); +}); +test('真实32216金币听读弹窗排除听读操作,直接关闭', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const button = {...popupItem('立即听读', 426, 1505, 654, 1573), darkButton: true}; + const page = [popupItem('连续7天听读赚金币', 266, 883, 814, 973), + popupItem('每天听读15分钟赚大额金币奖励', 188, 1002, 893, 1061), + popupItem('32216', 224, 1129, 640, 1345), popupItem('金币', 654, 1179, 754, 1251), + popupItem('common-info-modalbackground', 36, 858, 1044, 1650), button, + popupItem('关闭', 468, 1848, 612, 1992)]; + assert.equal(context.isPopupAction(button), false); + assert.equal(context.findListeningPopupClose(page), page[page.length - 1]); + assert.equal(context.singleButtonPopupDecision(page), null); +}); +test('补贴标签可见但右侧按钮漏识别时直接点标签,不滚动', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const label = popupItem('领吃饭补贴991', 79, 811, 438, 857); + context.snapshot = () => [label]; + context.swipe = () => {throw Error('标签已存在,不应继续滚动');}; + assert.equal(context.findMealEntry(), label); +}); +test('中央立即参与提示无领取入口时关闭遮挡层,不进入参与任务', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const close = popupItem('X', 515, 1731, 563, 1779); + const page = [popupItem('立即参与', 455, 1529, 624, 1570), close]; + assert.equal(context.findEmptyRewardPopupClose(page), close); +}); +test('vivo独立签到页没有X也领取;无障碍大按钮与OCR文字框合并为一个', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const native = {...popupItem('立即领取', 183, 1839, 896, 1972), darkButton: false}; + const ocr = {...popupItem('立即领取', 450, 1882, 630, 1925), darkButton: true}; + const page = [popupItem('已签0/7今日签到,额外奖励立即到账+7125', 82, 1674, 997, 1789), + popupItem('活动时间:10月20日-11月18日', 262, 356, 817, 406), popupItem('back', 64, 194, 86, 230), native, ocr]; + assert.equal(context.findSingleSignPopupClaim(page), native); + assert.equal(context.singleButtonPopupDecision(page).signIn, true); +}); +test('首次奖励弹窗明确看视频领1198金币按金额规则处理,不漏过通用规则', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2400}; + const button = popupItem('看视频领1198金币', 277, 1770, 803, 1846); + const page = [popupItem('首次完成额外送金币', 0, 447, 1080, 598), button, + popupItem('关闭', 468, 1976, 612, 2120)]; + assert.equal(context.offerAmount(page).amount, 1198); + assert.equal(context.needsCommonHandling(page), true); +}); + +function loadPublicationFlow(state, targets = []) { + const {context} = load(state); + vm.runInContext(source.slice(source.indexOf('function runNextPublication('), source.indexOf('function runDaily()')), context); + context.device = {width: 1080, height: 2374}; + context.snapshot = () => [popupItem('福利中心', 60, 142), popupItem('赚钱', 486, 2224)]; + const calls = []; + context.runStep = (name, action) => { + try { return {ok: true, value: action()}; } + catch (error) { return {ok: !!error.noMatch, skipped: true}; } + }; + context.searchPublicationTask = () => {calls.push('复查'); return targets.shift() || null;}; + context.publicationReadingStep = () => {calls.push('阅读');}; + context.publicationClaimStep = button => {calls.push(button.text); return {};}; + context.runNextReadingChallenge = () => {calls.push('挑战赛'); return {ok: true};}; + context.sleep = () => {}; + return {context, calls}; +} +const publicationRead = () => ({action: 'read', button: popupItem('去阅读', 842, 1433)}); +const publicationClaim = () => ({action: 'claim', button: popupItem('去领取', 842, 1433)}); +const publicationUnavailable = () => ({action: 'none', label: popupItem('读出版物赚金币', 93, 1400)}); +test('旧待领奖状态不限制当前按钮,连续阅读后领取,再复查两次无匹配才进入下一任务', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: true}, + [publicationRead(), publicationRead(), publicationClaim(), publicationUnavailable(), publicationUnavailable()]); + context.runNextPublication(); + assert.deepEqual(calls, ['复查', '阅读', '复查', '阅读', '复查', '去领取', '复查', '复查', '挑战赛']); +}); +test('没有待领奖记录也执行去领取,领取后仍有同按钮继续,不直接去下一任务', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: false}, + [publicationClaim(), publicationClaim(), publicationRead(), publicationUnavailable(), publicationUnavailable()]); + context.runNextPublication(); + assert.deepEqual(calls.filter(value => value !== '复查'), ['去领取', '去领取', '阅读', '挑战赛']); +}); +test('读完回页仍有去阅读就一直执行,不按本书已读完或重复次数退出', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: true}, + [...Array.from({length: 5}, publicationRead), publicationUnavailable(), publicationUnavailable()]); + context.runNextPublication(); + assert.equal(calls.filter(value => value === '阅读').length, 5); + assert.equal(calls.at(-1), '挑战赛'); +}); +test('出版物标签连续两次不存在才退出,保留未确认的待领奖记录', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: true}, [null, null]); + context.files.write = () => {throw Error('标签消失不等于奖励到账,不能清状态');}; + context.runNextPublication(); + assert.deepEqual(calls, ['复查', '复查', '挑战赛']); +}); +test('一次没有匹配后去阅读重现,重置无匹配计数并继续执行', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: false}, + [publicationUnavailable(), publicationRead(), publicationUnavailable(), publicationUnavailable()]); + context.runNextPublication(); + assert.deepEqual(calls, ['复查', '复查', '阅读', '复查', '复查', '挑战赛']); +}); +test('当前阅读现场先恢复,返回仍有去阅读时再次执行', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: true}, + [publicationRead(), publicationUnavailable(), publicationUnavailable()]); + context.runNextPublication(true); + assert.deepEqual(calls, ['阅读', '复查', '阅读', '复查', '复查', '挑战赛']); +}); +test('阅读真实异常保留现场,不冒充无匹配或完读', () => { + const {context, calls} = loadPublicationFlow({pendingClaim: false}, [publicationRead()]); + context.publicationReadingStep = () => {calls.push('阅读异常'); throw Error('翻页失败');}; + context.runNextPublication(); + assert.deepEqual(calls, ['复查', '阅读异常']); +}); +test('真实出版物去阅读可点击,上方其他任务的立即领取不可误领', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const reading = popupItem('去阅读', 842, 1433, 937, 1464); + const page = [popupItem('读出版物赚金币', 93, 1400, 392, 1446), + popupItem('继续阅读《王阳明心学》,攒满领奖', 92, 1464, 616, 1496), + popupItem('立即领取', 826, 1222, 955, 1253), reading]; + assert.equal(context.findPublicationClaim(page), null); + assert.equal(context.findPublicationEntry(page), reading); +}); +test('出版物同任务行优先去领取,兼容OCR长标题,不点击其他任务去领取', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const claim = popupItem('去领取', 842, 1433, 937, 1464); + const page = [popupItem('去领取', 842, 1222, 937, 1253), popupItem('读出版物賺全币最高5805', 93, 1400, 950, 1446), + popupItem('去阅读', 842, 1433, 937, 1464), claim]; + assert.equal(context.findPublicationEntry(page), claim); + assert.equal(context.findPublicationClaim(page), claim); +}); +const earningTreasurePage = amount => [popupItem('福利中心', 60, 142), popupItem('赚钱', 486, 2224), + popupItem('点击颌' + amount, 810, 2071, 989, 2102)]; +for (const [amount, take] of [[999, false], [1000, false], [1001, true], [2205, true]]) { + test(`右下宝箱金币${amount} 严格大于1000才领取=${take}`, () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const page = earningTreasurePage(amount); + assert.equal(!!context.findEarningTreasureClaim(page), take); + assert.equal(context.needsCommonHandling(page), take); + }); +} +test('宝箱规则只匹配赚钱页右下角,不误点任务列表、普通金币或其他页面', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + assert.equal(context.findEarningTreasureClaim(earningTreasurePage(2205).slice(1)), null); + assert.equal(context.findEarningTreasureClaim(earningTreasurePage(2205).slice(0, 1)), null); + const nav = earningTreasurePage(2205).slice(0, 2); + assert.equal(context.findEarningTreasureClaim([...nav, popupItem('领2205', 300, 2071)]), null); + assert.equal(context.findEarningTreasureClaim([...nav, popupItem('去领取', 810, 2071)]), null); + assert.equal(context.findEarningTreasureClaim([...nav, popupItem('2205金币', 810, 2071)]), null); +}); +test('宝箱金币与下方领金币分开显示时绑定同一宝箱,不使用远处余额', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const button = popupItem('领金币', 810, 2071, 989, 2102); + const page = [...earningTreasurePage(2205).slice(0, 2), popupItem('宝箱', 810, 1900), + popupItem('2205金币', 810, 1980), button]; + assert.equal(context.findEarningTreasureClaim(page).button, button); + assert.equal(context.findEarningTreasureClaim(page.filter(item => item.text !== '宝箱')), null); +}); +test('前景弹窗优先于背景宝箱,点宝箱后执行通用流程,同金额不连点阻塞', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const earning = earningTreasurePage(2205); + const close = popupItem('X', 526, 1724, 554, 1751); + const popup = [popupItem('送你现金红包', 410, 765), popupItem('121元', 414, 902), + popupItem('邀靖好友立得', 418, 1444), close]; + const exit = popupItem('坚持退出', 458, 1424, 618, 1462); + let stage = 0; + const taps = []; + context.snapshot = () => stage === 0 ? [...earning, ...popup] : stage === 1 ? earning : stage === 2 ? + [popupItem('再看一个视频最高可领800金币', 252, 922, 816, 976), exit] : earning; + context.sleep = () => {}; + context.tap = item => {taps.push(item.text); stage++;}; + context.handleVideos(/./); + assert.deepEqual(taps, ['X', '点击颌2205', '坚持退出']); + assert.equal(context.findEarningTreasureClaim(earning), null); + assert.equal(context.needsCommonHandling(earning), false); +}); +test('完整可见出版物行只有去阅读时直接选中,不滚动寻找其他任务立即领取', () => { + const {context} = load({pendingClaim: true, claimTapped: false}); + context.device = {width: 1080, height: 2374}; + const button = popupItem('去阅读', 842, 1433, 937, 1464); + const page = [popupItem('福利中心', 60, 142), popupItem('读出版物赚金币', 93, 1400, 392, 1446), + button, popupItem('立即领取', 826, 1222, 955, 1253)]; + context.snapshot = () => page; + context.swipe = () => {throw Error('任务行完整可见,无需滚动');}; + const target = context.searchPublicationTask(); + assert.equal(target.action, 'read'); + assert.equal(target.button, button); +}); +test('现场己使出版物廉金币OCR仍绑定出版物任务入口', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const claim = popupItem('|去领取', 842, 1433, 937, 1464); + const page = [popupItem('己使出版物廉金币最高5805', 93, 1400, 678, 1446), claim]; + assert.equal(context.findPublicationEntry(page), claim); + assert.equal(context.findPublicationClaim(page), claim); +}); +test('出版物行在底部但按钮完整可见时直接阅读,不先滚动把标题滑出屏幕', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const button = popupItem('去阅读', 842, 2030, 937, 2061); + context.snapshot = () => [popupItem('福利中心', 60, 142), + popupItem('|读出版物賺金币', 93, 1996, 392, 2042), button]; + context.swipe = () => {throw Error('完整可见按钮不应强制对齐');}; + const target = context.searchPublicationTask(); + assert.equal(target.button, button); + assert.equal(target.action, 'read'); +}); +test('出版物按钮被底部导航遮挡时小幅慢滑,重新识别当前按钮', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const heading = popupItem('福利中心', 60, 142); + let page = [heading, popupItem('读出版物赚金币', 93, 2180, 392, 2226)]; + const button = popupItem('去阅读', 842, 1830, 937, 1861); + context.snapshot = () => page; + context.sleep = () => {}; + let swipes = 0; + context.swipe = (x1, y1, x2, y2, ms) => { + assert.equal(x1, x2); + assert.ok(y1 - y2 < 300); + assert.equal(ms, 800); + swipes++; + page = [heading, popupItem('读出版物赚金币', 93, 1800, 392, 1846), button]; + return true; + }; + assert.equal(context.searchPublicationTask().button, button); + assert.equal(swipes, 1); +}); +test('真实宝箱选204/选2204双金额弹窗优先2204,不被背景视频任务干扰', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const page = JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-20/oppo-monitor72-treasure-popup.json'), 'utf8')); + page.forEach(item => {item.text = context.compact(item.text);}); + assert.equal(context.findHigherCoinClaim(page).text, '选2204金币'); + let tapped; + context.snapshot = () => tapped ? [] : page; + context.tap = item => {tapped = item;}; + context.handleVideos(/./); + assert.equal(tapped.text, '选2204金币'); +}); +test('宝箱双按钮都不足500仍选较小,原生关闭按钮文字归一', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const page = [popupItem('请选择宝箱奖励', 195, 726), popupItem('选204金币', 193, 1404), popupItem('选404金币', 646, 1405)]; + assert.equal(context.findHigherCoinClaim(page).text, '选204金币'); + assert.equal(context.compact('关闭按钮'), '关闭'); +}); +test('去领取按钮在没有旧状态文件时也先点击再执行通用规则,不捏造读完', () => { + const {context} = load({pendingClaim: false}); + context.device = {width: 1080, height: 2374}; + context.files.exists = () => false; + const actions = []; + const button = popupItem('去领取', 842, 1433, 937, 1464); + context.tap = item => {assert.equal(item, button); actions.push('点击');}; + context.savePublicationClaimState = (pending, evidence, tapped) => { + assert.equal(pending, true); + assert.equal(tapped, true); + assert.doesNotMatch(evidence, /全书完/); + actions.push('记录实际点击'); + }; + context.handleVideos = () => actions.push('通用'); + context.snapshot = () => []; + context.publicationClaimStep(button); + assert.deepEqual(actions, ['点击', '记录实际点击', '通用']); +}); +test('出版物标签存在但按钮不符合时返回无动作;其他任务的按钮不能续出版物循环', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const page = [popupItem('福利中心', 60, 142), popupItem('读出版物赚金币', 93, 1400, 392, 1446), + popupItem('已完成', 842, 1433, 937, 1464), popupItem('去阅读', 842, 1813, 937, 1847)]; + assert.equal(context.publicationTaskTarget(page).action, 'none'); + assert.equal(context.publicationTaskTarget(page).button, null); +}); +test('进入阅读前按钮变成去领取时交回循环,不点击后原地等待正文', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + context.searchPublicationEntry = () => popupItem('去领取', 842, 1433); + context.tap = () => {throw Error('该按钮应交给领取分支');}; + assert.throws(() => context.enterPublicationReader([popupItem('福利中心', 60, 142)]), /交回循环执行领取/); +}); +test('进入即全书完且无倒计时也先右滑一次,再开始2秒判断,不记成本轮重新完读', () => { + const ending = [popupItem('全书完', 400, 1200)]; + const context = loadReader(ending); + let page = ending, rights = 0, saved = false, firstRightAt; + const logs = []; + context.snapshot = () => page; + context.writeRunLog = value => logs.push(value); + context.swipe = (x1, y1, x2) => { + assert.ok(x2 > x1); + assert.equal(rights, 0); + assert.equal(saved, false); + firstRightAt = context.Date.now(); + rights++; + page = readerPage(2); + return true; + }; + context.countdown = () => {assert.equal(rights, 1, '必须先右滑,后判断倒计时'); return null;}; + context.savePublicationClaimState = () => { + assert.ok(context.Date.now() - firstRightAt >= context.CONFIG.readingPagePauseMs + 2000); + saved = true; + }; + assert.equal(context.runPublicationPages(), true); + assert.equal(rights, 1); + assert.equal(saved, true); + assert.equal(logs.some(value => value.startsWith('READ FINISHED:')), false); + assert.equal(logs.some(value => value.startsWith('READ END HANDLED:')), true); +}); +test('进入即书末的首次右滑失败时不开始后续倒计时判断,不保存完成状态', () => { + const context = loadReader([popupItem('全书完', 400, 1200)]); + context.swipe = () => false; + context.countdown = () => {throw Error('右滑失败前不能执行后续判断');}; + context.savePublicationClaimState = () => {throw Error('失败不应保存完成');}; + assert.throws(() => context.runPublicationPages(), /右滑执行失败/); +}); +test('入口仅识别全书完而无页码或工具栏,也确认已进入阅读页', () => { + const ending = [popupItem('全书完', 400, 1200)]; + const context = loadReader(ending); + const button = popupItem('去阅读', 842, 1433); + let taps = 0; + context.searchPublicationEntry = () => button; + context.tap = item => {assert.equal(item, button); taps++;}; + assert.equal(context.isPublicationReader(ending), false); + assert.equal(context.enterPublicationReader([popupItem('福利中心', 60, 142)]), ending); + assert.equal(taps, 1); +}); + +function navigationPage(selected, welfare = false) { + const tab = (text, left) => ({...popupItem(text, left, 2230, left + 100, 2290), node: {selected: () => selected === text}}); + return [...(welfare ? [popupItem('福利中心', 60, 142)] : []), tab('书城', 79), tab('赚钱', 486)]; +} +test('阅读结束先返回带导航页面,再点击首页并确认,最后点底部赚钱', () => { + const context = loadReader(readerPage(2)); + let page = readerPage(2); + const actions = []; + context.snapshot = () => page; + context.back = () => {actions.push('返回'); page = navigationPage('赚钱', true); return true;}; + context.tap = item => {actions.push(item.text); page = navigationPage(item.text, item.text === '赚钱');}; + context.returnHomeAndOpenEarning(); + assert.deepEqual(actions, ['返回', '书城', '赚钱']); +}); +test('首页点击后推荐页面打断,缺赚钱导航时继续返回,恢复首页再点击赚钱', () => { + const context = loadReader(readerPage(2)); + let page = navigationPage('赚钱', true); + const actions = []; + context.snapshot = () => page; + context.tap = item => { + actions.push(item.text); + page = item.text === '书城' ? readerPage(1) : navigationPage('赚钱', true); + }; + context.back = () => {actions.push('返回'); page = navigationPage('书城'); return true;}; + context.returnHomeAndOpenEarning(); + assert.deepEqual(actions, ['书城', '返回', '赚钱']); +}); +test('已经在首页时直接点击底部赚钱,等待福利中心加载后才确认成功', () => { + const context = loadReader(readerPage(2)); + let page = navigationPage('书城'), tapped = 0, loading = 0; + context.snapshot = () => { + if (tapped && ++loading >= 3) page = navigationPage('赚钱', true); + return page; + }; + context.tap = item => {assert.equal(item.text, '赚钱'); tapped++; page = navigationPage('赚钱');}; + context.back = () => {throw Error('加载中不应随意返回');}; + context.returnHomeAndOpenEarning(); + assert.equal(tapped, 1); + assert.ok(loading >= 3); +}); +test('点击首页仍停在赚钱页时重新确认首页,不把点击成功当作首页已到达', () => { + const context = loadReader(readerPage(2)); + let page = navigationPage('赚钱', true), homeTaps = 0; + const actions = []; + context.snapshot = () => page; + context.tap = item => { + actions.push(item.text); + if (item.text === '书城') {if (++homeTaps >= 2) page = navigationPage('书城');} + else page = navigationPage('赚钱', true); + }; + context.returnHomeAndOpenEarning(); + assert.deepEqual(actions, ['书城', '书城', '赚钱']); +}); +test('返回按钮失败或应用切走时保留现场,不能记录回到赚钱页', () => { + const context = loadReader(readerPage(2)); + context.back = () => false; + assert.throws(() => context.returnHomeAndOpenEarning(), /返回键执行失败/); + context.foregroundPackage = () => 'other.app'; + assert.throws(() => context.returnHomeAndOpenEarning(), /已离开番茄/); +}); +test('首页右侧真实原生Close Button优先于图片局部OCR的可疑X', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const native = {...popupItem(context.compact('Close Button'), 954, 1243, 1080, 1387), node: {}}; + const falseX = popupItem('X', 987, 548, 994, 558); + const page = [...navigationPage('书城'), falseX, native]; + assert.equal(context.findTopRightClose(page), native); + assert.equal(context.findTopRightClose([...page, popupItem('广告1)', 75, 147)]), falseX, + '广告页仍保留原先的顶部关闭规则'); +}); +test('首页书封的微小OCR X不当作关闭,正常大小X及原生关闭仍响应', () => { + const {context} = load({}); + context.device = {width: 1080, height: 2374}; + const tiny = popupItem('X', 987, 548, 994, 558); + assert.equal(context.findTopRightClose([...navigationPage('书城'), tiny]), null); + const normal = popupItem('X', 970, 530, 1002, 562); + assert.equal(context.findTopRightClose([...navigationPage('书城'), normal]), normal); + const native = {...tiny, node: {}}; + assert.equal(context.findTopRightClose([...navigationPage('书城'), native]), native); + assert.equal(context.findTopRightClose([tiny]), tiny, '非主导航页保持既有关闭匹配'); +}); diff --git a/hongguo_auto/README.md b/hongguo_auto/README.md new file mode 100644 index 0000000..fa6407d --- /dev/null +++ b/hongguo_auto/README.md @@ -0,0 +1,76 @@ +# 红果免费短剧脚本 + +脚本:[hongguo-daily.auto.js](hongguo-daily.auto.js)。流程为福利 → 签到领金币(去签到)→ 吃饭补贴 → 翻卡赢金币 → 看视频赚海量金币,不执行阅读。手机本地无障碍与 OCR 识别,不上传截图。 + +## 2026-10-21:hongguo-9 + +基于 OPPO PLJ110(3B15A700QEL00000)正在运行的 hongguo-8 修复。旧版前三处手机副本哈希相同,日志显示前两轮广告正常,从第 3 轮起一直点击 `900,1899`,至少重复到第 32 轮,没有启动广告。UI XML 同时显示右下悬浮容器覆盖 `[720,1650][1080,1905]`,包含原点击点;不能仅据 press 返回 true 确认广告或奖励成功。 + +- 海量金币领取前小幅慢滑,将按钮移到屏幕 15%—68% 的安全区域,避开右下宝箱及导航;每次使用新页面重新识别按钮,不沿用旧坐标。 +- 点击后等待广告启动并执行通用规则。通用流程没有后续操作、领取按钮仍在时记为无进展,不累计完成轮数;重新移动任务行后重试。连续 3 次无进展时明确跳过本轮任务,避免无限空点;真正广告流程正常时继续循环,不按总轮次数截断。 +- `textMatches` / `descMatches` 改用字符串参数,修复 AutoJs6 报参数为 NativeRegExp 的兼容错误;补充“看规频”OCR 文案识别。 +- 原前景弹窗、倒计时及直播处理规则保留;真正操作异常仍记录错误,不冒充标签消失或奖励到账。 + +检查:`node --check hongguo_auto/hongguo-daily.auto.js`;`node --test hongguo_auto/tests/mass-video.test.js`,9 项行为检查通过,包括原生节点读取、真实页面避让、点击无进展、正常多轮继续、恢复后重试计数清零、按钮变化和广告异常。 + +已同步 OPPO:`/sdcard/Download/hongguo-daily.auto.js`、`/sdcard/脚本/hongguo-daily.auto.js`、`/sdcard/脚本/红果/hongguo-daily.auto.js`。三处与本机 SHA256 均为 `4dba96170bc88eab204eb75df438debe505ad0b8cfde056d1bea6815c275587a`。北京时间 11:35:28 启动正式版本,截屏已授权整个屏幕,后续真机结果另记。 + +现场文字证据保存在 `debug/2026-10-21/oppo-hongguo8-stalled.log`、`.json`、`.xml`。 + +## 真机恢复验证 + +OPPO 正式 hongguo-9:11:36:52 完成补贴检查,继续翻卡;翻卡广告倒计时结束后自动关闭,处理“我知道了”提示,11:39:24 点击正文 2598 金币对应“开心收下”,11:40:04 完成翻卡并进入视频循环。 + +11:40:19 点击中部 `901,921` 的立即领取,确实打开广告并等待倒计时,11:40:53 自动关闭;11:41:00 第二轮仍在中部点击并成功打开广告,11:41:36 关闭,11:41:38 按原规则退出追加 450 金币;11:41:45 第三轮点击 `900,919`,11:41:49 再次识别真实倒计时。原第 3 轮起固定 `900,1899` 空点的问题未复现,脚本继续运行。启动后的系统日志未再见选择器 NativeRegExp 参数类型错误。 + +本轮实际验证了连续三轮广告启动,以及前两轮倒计时结束关闭、回页复查;避让函数及连续 3 次无进展后跳过分支由真实文字样本与行为测试覆盖,本次未强行制造手机广告失败。点击和广告流程正常不等于确认金币到账。运行文字证据见 `debug/2026-10-21/oppo-hongguo9-recovered.log`、`.json`;没有上传截图。 + +## 2026-10-21:hongguo-10 + +后续停止日志确认 hongguo-9 已正常执行 7 轮广告,第 8 轮 11:45:03 在 `tap` 点击前复查时,因文字或位置变化抛出“通用处理后目标标签已改变”。该保护本应只取消旧坐标点击,但调用层把 `ok=true, skipped=true` 当成广告异常,导致整个视频循环结束。最后页面仍有海量金币标签与立即领取,不能视为正常无匹配。文字现场:`debug/2026-10-21/oppo-hongguo9-target-changed.log`、`.json`。 + +领取点击前改为从最新一帧中按海量金币任务标签、同排立即领取语义、安全区域重新绑定按钮,兼容“领取/颌取”等已认可的 OCR 变体及位置变化。缺少可信新按钮时继续取消旧点击,并将 `targetChanged` 原因传回任务循环,重新搜索和调整;连续 3 次目标不稳定才跳过本轮,不能因一次刷新结束整段流程。真实广告处理错误仍保留原保护。连续点击无进展的 3 次上限保持。 + +语法检查及 13 项行为检查通过,新增最新帧语义绑定、真实停止页面、其他任务和遮挡区排除、第 8 轮刷新后继续至第 9 轮、持续变化有限恢复等检查。已同步 OPPO 三处正式副本,与本机 SHA256 一致:`a671493a11b5388592fd0b3a05d035d48275b3086ea007c53e87cd537f4b77d5`。已重新启动正式脚本,真机结果另记。 + +### hongguo-10 真机结果 + +11:51:08 启动正式版;11:52:31 补贴检查完成,11:53:10 未找到翻卡入口后继续视频任务。11:53:25 点击当前立即领取@901,927,11:53:28 确认真实广告倒计时,11:54:00 自动关闭,11:54:03 完成该轮。随后两次全列表搜索均未找到海量金币标签,11:55:18 正常结束,没有“目标标签已改变”异常退出。 + +为避免把搜索跳过任务行误报为正常结束,额外执行只读取文字的本机 OCR 小幅慢滑核对:福利列表顶部及日常福利区域已不再显示海量金币任务,首项为天天领金币,保留签到、补贴和收益日报等其他任务;没有把其他立即领取按钮误当海量金币任务。诊断结束已停止临时检查脚本,正式脚本当前已正常结束,不声称仍在运行。未上传截图。 + +本次真机确认一轮广告启动、倒计时关闭与无匹配正常退出。由于任务标签随后消失,未实际再次运行至第 8 轮;第 8 轮目标变化后恢复至第 9 轮由行为检查覆盖,不宣称此分支已真机触发。证据:`debug/2026-10-21/oppo-hongguo10-finished.log`、`oppo-hongguo10-slow-inspect.jsonl` 及对应慢滑文字日志。 + + +## 2026-10-21:hongguo-11 签到优先 + +参考番茄小说脚本,在普通启动进入福利后,先匹配“签到领金币”对应行的“去签到”,处理签到领取,再开始吃饭补贴。撤销旧的“签到弹窗一律关闭”规则:签到只有一个深色领取按钮时点击该按钮;双金额继续使用通用规则,有金额达到 500 时选较大,否则选较小。独立签到活动页完成领取后返回福利继续补贴;当前已经处于翻卡现场时保留恢复流程。 + +签到入口不依赖“日常福利”标题,并兼容 OPPO 真实 OCR 样本中“签到顿金币8828”的误识别。未找到入口或没有可执行领取时继续下一步骤,不一直等待该标签。无金币及听读等其他弹窗仍交给既有通用规则。 + +验证:`node --check hongguo_auto/hongguo-daily.auto.js` 与 `node --test hongguo_auto/tests/*.test.js`(23 项)通过,覆盖真实签到任务文字、单深色按钮、双金额、独立签到页返回,以及签到先于补贴和无入口继续。 + + +真机首轮已点击“去签到”,按双金额选择“领9835金币”,等待广告倒计时并关闭。后续核对发现签到完成浮层仍被背景“领63347金币”阻止关闭,修正空奖励判断:关闭按钮下方的任务文字不算该浮层内的可领取按钮;浮层内仍有领取按钮时继续保留领取优先。该真实页面文字已加入回归测试,见 `debug/2026-10-21/oppo-hongguo11-after-signin.json`;首轮日志见 `oppo-hongguo11-signin.log`,不将首轮的补贴点击误报为已经进入补贴页。 + + +第二轮确认签到完成浮层的 X 已成功关闭,但应用随后追加“添加赚钱助手到桌面/立即添加领专属奖励”推广。增加仅在这两个明确标签同时存在时关闭推广的通用处理。真机确认返回键无效、顶部原生拖动条下拉可关闭,因此优先识别原生拖动条下拉;没有拖动条才尝试返回,连续三次未关闭则保留错误。不点击添加按钮,也不在浮层下寻找补贴;真实文字样本与行为测试见 `oppo-hongguo11-shortcut-prompt.json` 和 `tests/sign-in.test.js`。 + + +最终 OPPO 复跑:12:10:56 开始签到入口复查,12:11:42 当前无签到入口后进入吃饭补贴;12:11:54 识别“吃饭补贴220”并点击本行去领取,12:11:56 已进入饭点补贴页并执行 MEAL LOOP。连续两轮所有已配置领取标签无可执行项后,12:12:15 执行返回福利。此次确认了实际进入补贴页面,未把首轮被遮挡的点击当作成功。签到领奖广告由首轮实测覆盖,最终复跑因当日已签到没有再次制造领奖。最终文字日志见 `debug/2026-10-21/oppo-hongguo11-final.log`,无截图上传。 + +最终源码与 OPPO 的 Download、脚本、脚本/红果 三处文件 SHA256 均为 `7294df60329b6dbbeacf66b491e57c04f4550e8c048c2a5285dcd8c4a40d4f68`。 + + +## 2026-10-21:hongguo-12 补贴金额按钮漏识别 + +用户反馈看不到吃饭补贴执行。12:33 启动的手机日志实际在 12:34:46 点击补贴入口并进入补贴页,但随后两轮均判定领取标签为空后退出,不能将“进入页面”视作完成领取。定向检查捕获连续 5 帧本机 OCR 文字,标题为“饭点领金币孙贴”,领取按钮稳定为“领午饭补补贴90金币”。标题已被旧规则接受,金额按钮的正则只允许一个“补”,导致漏识别;本次未观察到服务器报错作为该漏识别的原因。 + +金额领取及无金额时段按钮规则兼容重复“补”字,仍要求在已确认的补贴主区域内;繁忙去重键同时归一重复字,不能通过 OCR 文案变化绕过有限重试。没有放宽已领取说明或其他任务页面的领取判断。 + +验证:语法检查通过,`node --test hongguo_auto/tests/*.test.js` 共 26 项通过。新增测试用实际连续 5 帧页面确认走领取分支,覆盖正常文字、重复字、已领取与区域排除,以及繁忙去重。证据见 `debug/2026-10-21/oppo-hongguo11-meal-reported.log`、`oppo-hongguo11-meal-inspect.log`、`oppo-hongguo11-meal-inspect.jsonl`,无截图上传。 + +已同步 OPPO 的 Download、脚本、脚本/红果 三份脚本并校验一致,SHA256:`5b00952f8455b8200b5709baa32f64004c363185bf4d82d56a8cded1a2ee10d4`。 + + +OPPO 真机 hongguo-12:12:41:16 命中“领午饭补补贴90金币”,12:41:27 点击坐标 `540,1779`,12:41:29 按通用规则关闭领取后的 X,12:41:31 进入补贴第 2 轮扫描。此次验证到金额按钮实际点击及后续通用处理,未仅凭进入页面断言完成;未独立核验金币到账。恢复日志和页面文字见 `debug/2026-10-21/oppo-hongguo12-meal-recovered.log`、`.json`。临时诊断脚本已在写入 DONE 后结束,并从手机删除入口,正式脚本继续处理后续流程。 diff --git a/hongguo_auto/hongguo-daily.auto.js b/hongguo_auto/hongguo-daily.auto.js new file mode 100644 index 0000000..44b31ab --- /dev/null +++ b/hongguo_auto/hongguo-daily.auto.js @@ -0,0 +1,1622 @@ +"auto"; + +// Auto.js / AutoX.js / AutoJs6:启动后打开红果免费短剧,并识别可恢复的当前页面。 +// 页面识别:无障碍文字 + 可选的本地 $ocr.detect;图片不上传、不写入日志。 +// 福利 → 签到领金币(去签到)→ 吃饭补贴 → 翻卡赢金币 → 看视频赚海量金币;不执行阅读。 +var CONFIG = { + version: "2026-10-21-hongguo-12", + packageName: "com.phoenix.read", + rewardThreshold: 500, + pollMs: 1200, + pageTimeoutMs: 5000, + videoTimeoutMs: 180000, + maxVideos: 15, + maxScrolls: 1, + taskSearchScrolls: 16, + massVideoNoProgressLimit: 3, + stepTimeoutMs: 240000, + mealSessionTimeoutMs: 1800000, + mealBusyRetries: 2, + mealBusyRetryMs: 5000, + flipSessionTimeoutMs: 1800000, + recognitionTimeoutMs: 15000, + captureRecoveryLimit: 2, + capturePermissionTimeoutMs: 60000, + useLocalOcr: true, + logPath: "/sdcard/Download/hongguo-daily-run.log", + pageTextPath: "/sdcard/Download/hongguo-daily-page.json" +}; +var localOcrEnabled = false; +var commonHandling = false; +var actionSerial = 0; +var mealPageDone = false; +var mealUnavailableClaims = {}; +var mealBusyFeedback = null; +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 STREAK_SECTION = /连续(?:(?:5|五)(?:天|日)|[领颌]{1,2}吃饭补贴第\d+天)/; +var SIGN_ENTRY = /^[||]?(?:签到|每日签到)(?:[领颌顿頓]金币.*)?$/; +var MASS_VIDEO_LABEL = /^[||「『]?看[视规規][频頻][赚賺嫌]海量金[币市]/; + +function writeRunLog(message) { + var line = new Date().toISOString() + " " + message; + log(line); + files.append(CONFIG.logPath, line + "\n"); +} + +function stopWith(message) { + throw new Error(message.replace(/已停止/g, "本步骤跳过")); +} + +// 任务和识别分别限时;结束旧线程后才允许后续任务使用屏幕。 +function boundedCall(name, timeoutMs, action) { + var result; + var failure; + var worker = threads.start(function () { + try { result = action(); } catch (error) { failure = error; } + }); + var deadline = Date.now() + timeoutMs; + try { + while (worker.isAlive() && Date.now() < deadline) sleep(100); + if (worker.isAlive()) { + worker.interrupt(); + worker.join(1500); + var timeout = new Error(name + "超时(" + timeoutMs + "ms)"); + if (worker.isAlive()) timeout.unsafeWorker = true; + throw timeout; + } + if (failure) throw failure; + return result; + } finally { + if (worker.isAlive()) { + worker.interrupt(); + worker.join(1500); + if (worker.isAlive()) { + var unsafe = new Error(name + "的线程无法终止,不能让旧任务与下一任务同时点击"); + unsafe.unsafeWorker = true; + throw unsafe; + } + } + } +} + +function runStep(name, action, timeoutMs) { + writeRunLog("STEP START: " + name); + try { + var value = boundedCall(name, timeoutMs || CONFIG.stepTimeoutMs, action); + writeRunLog("STEP DONE: " + name); + return {ok: true, value: value}; + } catch (error) { + if (error.unsafeWorker || error.captureFatal) throw error; + writeRunLog("STEP SKIP: " + name + ";原因=" + error + ";继续下一步骤"); + return {ok: !!error.noMatch, skipped: true, targetChanged: !!error.targetChanged}; + } +} + +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 (!requestScreenCapture(false)) stopWith("未获得本机截屏权限;无需上传图片。"); + localOcrEnabled = true; + }); +} + +function isProjectionFailure(error) { + return /MediaProjection|VirtualDisplay|resultData|projection instance|Failed to capture screen|截图通道不可用/.test(String(error)); +} + +function readPage(name) { + try { + return captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot); + } catch (error) { + if (error.unsafeWorker || !isProjectionFailure(error)) throw error; + if (captureRecoveries >= CONFIG.captureRecoveryLimit) { + error.captureFatal = true; + writeRunLog("截图通道连续失效,结束本次运行;不能将识别故障当作类目缺失。"); + throw error; + } + captureRecoveries++; + writeRunLog("CAPTURE RECOVER: " + captureRecoveries + "/" + CONFIG.captureRecoveryLimit + ";释放失效投影并重新申请本机截屏。"); + try { + captureCall("恢复截图授权", CONFIG.capturePermissionTimeoutMs, function () { + images.stopScreenCapture(); + if (!requestScreenCapture(false)) throw new Error("恢复截图授权未获允许"); + sleep(500); + }); + var page = captureCall("恢复后重新识别", CONFIG.recognitionTimeoutMs, readSnapshot); + writeRunLog("CAPTURE RECOVERED: 本机页面识别已恢复。"); + return page; + } catch (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 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 ((isAdvertisementPage(items) || countdown(items)) && !popupFrame && !close) return null; + // 必须有前景弹窗证据,避免取背景任务行的立即领取。 + if (!close && !rewardReceiptHeading(items) && !findFlipSettlementHeading(items)) return null; + var buttons = matches(items, {test: function () { return true; }}, function (item) { + return isPopupAction(item) && item.rect.top >= heading.rect.bottom && + item.rect.top < heading.rect.bottom + device.height * 0.5; + }); + if (buttons.length !== 1) return null; + if (first(items, /^[||]?(?:坚持退出|退出|取消|暂不使用)$/, isCenteredPopupItem)) return null; + var button = buttons[0]; + // 若还存在带金额的操作选项,则不是单按钮弹窗。 + if (first(items, /^[||]?(?:领|看视频(?:再得|再领|领))\d+(?:,\d{3})*金币$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + })) return null; + var amounts = []; + items.forEach(function (item) { + if (item.rect.top < heading.rect.top || item.rect.bottom > button.rect.top || + !isCenteredPopupItem(item) || /最高|量高|最多|上限|余额|累计|7天签到必得/.test(item.text)) return; + var re = /(\d+(?:,\d{3})*)金币/g; + var match; + while ((match = re.exec(item.text)) !== null) { + var amount = Number(match[1].replace(/,/g, "")); + if (amounts.indexOf(amount) < 0) amounts.push(amount); + } + if (/^\d+(?:,\d{3})*$/.test(item.text) && first(items, /^金币$/, function (unit) { + return isCenteredPopupItem(unit) && Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08; + })) { + var split = Number(item.text.replace(/,/g, "")); + if (amounts.indexOf(split) < 0) amounts.push(split); + } + }); + var take = amounts.length === 1 && amounts[0] >= CONFIG.rewardThreshold && button.darkButton === true; + return {button: take ? button : close, amount: amounts.length === 1 ? amounts[0] : null, + take: take, settlement: !!findFlipSettlementHeading(items)}; +} + +function findListeningPopupClose(items) { + var heading = first(items, /听读/, isCenteredPopupItem); + if (!heading) return null; + var listening = first(items, /^(?:立即听读|去听读|继续听读)$/, isCenteredPopupItem); + if (!listening) return null; + return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= listening.rect.bottom; + }); +} + +function findPlaybackPopupDismiss(items) { + if (!first(items, /悬浮窗播放功能|退出直播间后也能继续观看/, isCenteredPopupItem)) return null; + return first(items, /^暂不使用(?:按钮)?$/, isCenteredPopupItem); +} + +function liveExitAction(items) { + var dismiss = findPlaybackPopupDismiss(items); + if (dismiss) return {button: dismiss, reason: "不使用直播悬浮窗"}; + var confirmation = first(items, /(?:确定|确认|是否|即将).*?(?:退出|离开).*?直播|退出直播间后|离开直播间后/); + var exit = first(items, /^(?:退出直播间|离开直播间|退出直播|确认退出|确定退出|立即退出|退出|离开)$/, + isCenteredPopupItem); + if (exit && (confirmation || first(items, /^(?:继续观看|继续看直播|留在直播间)$/))) { + return {button: exit, reason: "确认退出直播间"}; + } + // 用直播间自身控件判定,不能仅因任务列表或广告文案提及“直播”就返回。 + var room = first(items, /本场点赞|在线观众/, function (item) { + return item.rect.top < device.height * 0.2; + }) || first(items, /^(?:[·「|]?更多直播[>〉]?|[·]?左滑查看更多直播)$/); + var chat = first(items, /^说点什么$/) && first(items, /^(?:礼物|连线|商品列表|粉丝团)$/); + if (room || chat) return {back: true, reason: "已进入直播页面,立即返回"}; + return null; +} + +function isAdvertisementPage(items) { + return !!first(items, /^(?:广告(?:[|!!1ご))((].*)?|.*直播间)$/, function (item) { + return item.rect.top < device.height * 0.15; + }); +} + +function findVideoSurveyDismiss(items) { + if (!first(items, /刚才的视频你觉得如何|评价有助于我们做得更好/)) return null; + return first(items, /^我知道了$/, isCenteredPopupItem); +} + +function isShortcutPrompt(items) { + // 签到浮层关闭后可能追加桌面助手推广,它不是签到或补贴任务。 + return !!(first(items, /添加[赚賺][钱线]助手到桌|^[赚賺][钱线]助手$/) && first(items, /^立即添加领专属奖励$/)); +} + +function findShortcutDragHandle() { + var nodes = className("android.view.ViewGroup").find(); + for (var i = 0; i < nodes.size(); i++) { + var node = nodes.get(i); + var rect = rectOf(node.bounds()); + if (!rect || !node.visibleToUser()) continue; + var center = (rect.left + rect.right) / 2; + if (Math.abs(center - device.width / 2) < device.width * 0.03 && + rect.right - rect.left >= device.width * 0.06 && rect.right - rect.left <= device.width * 0.15 && + rect.bottom - rect.top < device.height * 0.012 && + rect.top > device.height * 0.4 && rect.bottom < device.height * 0.65) return rect; + } + return null; +} + +function needsCommonHandling(items) { + if (isShortcutPrompt(items) || findVideoSurveyDismiss(items) || liveExitAction(items)) return true; + if (findListeningPopupClose(items) || findPlaybackPopupDismiss(items) || singleButtonPopupDecision(items) || isAdvertisementPage(items)) return true; + if (flipPopupHasAction(items)) { + // 翻卡弹窗保留中央操作;不能阻止用户最新要求的右上角倒计时/关闭规则。 + var flipOffer = offerAmount(items); + return !!(countdown(items) || findTopRightClose(items) || findCoinChoiceClaim(items) || findEmptyRewardPopupClose(items) || + (rewardReceiptHeading(items) && findReceiptEligibleClaim(items)) || + (flipOffer && flipOffer.amount >= CONFIG.rewardThreshold)); + } + var popupClose = findEmptyRewardPopupClose(items); + return !!(findFlipSettlementHeading(items) || findMoreCoinsButton(items) || findReceiptEligibleClaim(items) || findRewardReceiptClose(items) || (first(items, /^继续领金币$/) && first(items, /^[||]?坚持退出$/)) || (countdown(items) || findTopRightClose(items)) || findCoinChoiceClaim(items) || popupClose || offerAmount(items)); +} + +function snapshot() { + var page = readPage("页面识别"); + var deadline = Date.now() + CONFIG.stepTimeoutMs; + while (!commonHandling && needsCommonHandling(page)) { + if (Date.now() >= deadline) stopWith("通用页面处理超时,保留当前页面"); + writeRunLog("通用规则优先:暂停当前任务,先处理倒计时、关闭或额外奖励。"); + handleVideos(/./); + page = readPage("通用处理后重新识别"); + // 广告切换或弹窗动画中关闭按钮可能晚一帧出现;重新执行通用规则,不能全局退出。 + } + return page; +} + +// 小号X常被整屏OCR漏掉;只在手机内存裁剪放大右上区域再识别。 +function readCloseRegion(frame, items, region) { + var left = region ? region.left : Math.floor(device.width * 0.55); + var top = region ? region.top : Math.floor(device.height * 0.045); + var width = region ? region.width : device.width - left; + var height = region ? region.height : Math.floor(device.height * 0.22); + var crop = null; + var enlarged = null; + try { + crop = images.clip(frame, left, top, width, height); + enlarged = images.resize(crop, [width * 3, height * 3]); + var results = $ocr.detect(enlarged); + if (!Array.isArray(results)) return; + for (var i = 0; i < results.length; i++) { + var raw = results[i].bounds; + if (!raw) continue; + function at(key) { return Number(typeof raw[key] === "function" ? raw[key]() : raw[key]); } + var rect = rectOf({left: left + at("left") / 3, top: top + at("top") / 3, + right: left + at("right") / 3, bottom: top + at("bottom") / 3}); + var value = compact(results[i].text); + if (rect && /^(?:关闭|关闭广告|[xX×✕✖✗✘]|(?:领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕])$/.test(value)) { + items.push({text: /^[xX×✕✖✗✘]$/.test(value) ? "X" : value, rect: rect, node: null}); + writeRunLog("局部放大识别关闭:" + value + " @" + Math.round(rect.left) + "," + Math.round(rect.top)); + } + } + } finally { + if (enlarged) enlarged.recycle(); + if (crop) crop.recycle(); + } +} + +function readReceiptCloseRegion(frame, items) { + var heading = rewardReceiptHeading(items); + if (!heading || flipPopupHasAction(items) || findRewardReceiptClose(items)) return; + var action = first(items, /^看视频.*最高(?:可)?领\d+金[币市而]$/, 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 readSnapshot() { + 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 = []; + // AutoJs6 的选择器桥接参数要求字符串,传 RegExp 会报 NativeRegExp 类型错误。 + var selectors = [textMatches(".+"), descMatches(".+")]; + for (var s = 0; s < selectors.length; s++) { + var nodes = selectors[s].find(); + for (var i = 0; i < nodes.size(); i++) { + var node = nodes.get(i); + var rect = rectOf(node.bounds()); + var value = compact(s === 0 ? node.text() : node.desc()); + if (value && rect && node.visibleToUser()) items.push({text: value, rect: rect, node: node}); + } + } + // 直播间动态画面可能拖住截屏/OCR;原生控件已确认直播时直接交给退出规则。 + if (localOcrEnabled && !liveExitAction(items)) { + var frame = null; + try { + // captureScreen 返回的原图由 AutoJs 管理,仅回收自己复制的 OCR 图。 + frame = images.copy(captureScreen()); + // 此适配器要求 detect 返回 [{text, bounds:{left,top,right,bottom}}]。 + // 不兼容的 OCR 返回格式会停止,不能把整段文字当作可点击坐标。 + var results = $ocr.detect(frame); + if (!Array.isArray(results)) stopWith("本地 OCR 返回格式不兼容,请适配 snapshot();无需上传图片。"); + for (var j = 0; j < results.length; j++) { + var box = rectOf(results[j].bounds); + var textValue = compact(results[j].text); + if (textValue && !box) { + writeRunLog("OCR 跳过边界无效的文字:" + textValue); + continue; + } + if (textValue && box) items.push({text: textValue, rect: box, node: null}); + } + if (!findTopRightClose(items)) readCloseRegion(frame, items); + 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(); + } + } + // 同一按钮可能同时被无障碍和 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, resolveFresh) { + if (!item) skipStep("没有目标标签,执行下一步骤"); + if (!commonHandling) { + var freshPage = snapshot(); + var original = item; + item = resolveFresh ? resolveFresh(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; + }); + if (!item) { + var changed = new Error("通用处理后目标标签已改变,跳过旧坐标点击"); + changed.noMatch = true; + changed.targetChanged = true; + throw changed; + } + } + if (foregroundPackage() !== CONFIG.packageName) stopWith("点击前页面已离开红果免费短剧,已停止。"); + var tapX = Math.round((item.rect.left + item.rect.right) / 2); + var tapY = Math.round((item.rect.top + item.rect.bottom) / 2); + writeRunLog("点击:" + item.text + " @" + tapX + "," + tapY); + var ok = false; + if (item.node) { + // 不向上寻找大范围可点击容器,以免触发相邻任务。 + try { if (item.node.clickable()) ok = item.node.click(); } catch (e) { ok = false; } + } + if (!ok) ok = press(tapX, tapY, 80); + writeRunLog("点击结果:" + ok); + if (!ok) stopWith("点击失败:" + item.text); + actionSerial++; + sleep(CONFIG.pollMs); +} + +function waitFor(pattern, timeout, predicate) { + var deadline = Date.now() + (timeout || CONFIG.pageTimeoutMs); + while (Date.now() < deadline) { + var found = first(snapshot(), pattern, predicate); + if (found) return found; + sleep(CONFIG.pollMs); + } + return null; +} + +function isTopRight(item) { + // 倒计时长文字会向左延伸,按文字中心判断,不能只检查左边界。 + return (item.rect.left + item.rect.right) / 2 >= device.width * 0.55 && + item.rect.top < device.height * 0.30; +} + +function 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) { + return first(items, /^恭喜(?:你)?(?:已)?(?:累计)?获得(?:奖励)?$/, isCenteredPopupItem); +} + +function findReceiptEligibleClaim(items) { + var heading = rewardReceiptHeading(items); + if (!heading) return null; + return first(items, /^(?:领|看视频(?:再得|再领|领))\d+金币$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom && + Number(item.text.replace(/[^\d]/g, "")) >= CONFIG.rewardThreshold; + }); +} + +function findRewardReceiptClose(items) { + if (flipPopupHasAction(items)) return null; + if (findFlipSettlementHeading(items) || findMoreCoinsButton(items)) return null; + var heading = rewardReceiptHeading(items); + if (!heading) return null; + if (findReceiptEligibleClaim(items)) return null; + var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + }); + if (close) return close; + // 透明弹窗下方的 X 可能与背景文字合框,只提取末尾字形,不点整段文字。 + var merged = first(items, /[xX×✕]$/, function (item) { + var glyphWidth = (item.rect.right - item.rect.left) / item.text.length; + var glyphCenter = item.rect.right - glyphWidth / 2; + return item.rect.top >= heading.rect.bottom && item.rect.top > device.height * 0.45 && + item.rect.top < device.height * 0.92 && glyphCenter > device.width * 0.35 && glyphCenter < device.width * 0.65; + }); + if (!merged) return null; + var width = (merged.rect.right - merged.rect.left) / merged.text.length; + return {text: "关闭奖励弹窗(" + merged.text + ")", node: null, rect: { + left: merged.rect.right - width, right: merged.rect.right, + top: merged.rect.top, bottom: merged.rect.bottom + }}; +} + +function findEmptyRewardPopupClose(items, ignoreCoinClaim) { + // 前景现金邀请提示不属于金币领取;背景任务行的金币不能阻止关闭。 + var cashHeading = first(items, /^送你现金红包$/, isCenteredPopupItem); + if (cashHeading && (first(items, /^邀[请靖]好友立得$/, isCenteredPopupItem) || + first(items, /^\d+(?:\.\d+)?元$/, isCenteredPopupItem))) { + var cashClose = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + var center = (item.rect.left + item.rect.right) / 2; + return center >= device.width * 0.35 && center <= device.width * 0.65 && + item.rect.top >= cashHeading.rect.bottom && item.rect.bottom <= device.height * 0.92; + }); + if (cashClose) return cashClose; + } + // 中央活动提示没有金币领取入口,只关闭遮挡层,不执行邀请或参与。 + var participation = first(items, /^立即参与$/, isCenteredPopupItem); + if (participation) { + var participationClose = first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= participation.rect.bottom; + }); + if (participationClose) return participationClose; + } + // 翻卡操作弹窗不是空奖励弹窗;背景“完成阅读任务…奖励”等说明不能触发关闭。 + if (flipPopupHasAction(items)) return null; + // 非右上角的 X 需要弹窗文字作依据,不能把普通页面上的 X 当作奖励弹窗。 + var heading = first(items, /弹窗|温馨提示|签到|领取成功|恭喜|奖励|再看.*视频|暂无金币|暂无奖励|明日再来|今日已领/); + if (!heading) return null; + // 7天签到累计总额不是本次立即领取金额;关闭遮挡任务列表的无明确金币领取弹窗。 + var weekly = first(items, /^7天签到必得[\d.万亿]+金币$/, isCenteredPopupItem); + if (weekly && !first(items, /^(?:领\d+金币|看视频领\d+金币)$/)) { + var weeklyClaim = first(items, /^立即[领颌]取$/, isCenteredPopupItem); + var weeklyClose = weeklyClaim && first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top > weeklyClaim.rect.bottom; + }); + if (weeklyClose) return weeklyClose; + } + var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return item.rect.top >= heading.rect.top && item.rect.top < device.height * 0.92; + }); + // 签到完成浮层下方仍能识别背景任务的“领63347金币”,不能因此阻止关闭浮层。 + var claim = first(items, /^(?:立即[领颌]取|领更多金币|领取奖励|看视频领取|领\d+金币|看视频(?:再得|再领|领)\d+金币)$/, + function (item) { return item.rect.top >= heading.rect.top && (!close || item.rect.bottom <= close.rect.top); }); + if (claim && !ignoreCoinClaim) return null; + return close; +} + +function findCoinChoiceClaim(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 (isWelfarePage(items) && !rewardReceiptHeading(items) && !findMoreCoinsButton(items) && + !first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false; + // 广告右上角“再看19秒后得300金币X”是倒计时状态,不是前景追加奖励弹窗。 + if (isTopRight(item) && /\d+(?:\.\d+)?(?:s|S|秒)/.test(item.text)) return false; + // 补贴页常驻“看视频最高可领”说明不是独立弹窗。 + if (first(items, MEAL_PAGE) && /看视频.*最高可领/.test(item.text) && !rewardReceiptHeading(items) && + !first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false; + return true; + }); + if (!heading) { + var claimAction = first(items, /^(?:继续领金币|领取奖励)$/, isCenteredPopupItem); + var exitAction = claimAction && first(items, /^[||]?坚持退出$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= claimAction.rect.bottom && + item.rect.top - claimAction.rect.bottom < device.height * 0.2; + }); + // 标题OCR缺失时,用同一前景层的领取/坚持退出组合确认挽留弹窗,金额不猜测。 + if (exitAction) return {amount: null, heading: claimAction}; + } + var moreButton = findMoreCoinsButton(items); + if (!heading && moreButton) { + var values = []; + var region = items.filter(function (item) { + return isCenteredPopupItem(item) && item.rect.top >= moreButton.rect.top - device.height * 0.4 && + item.rect.bottom <= moreButton.rect.bottom && + !/最高|最多|至多|上限|已获得|已领取|本次得|一共|余额|补贴|预约|签到/.test(item.text); + }); + region.forEach(function (item) { + var coins = /(\d+(?:,\d{3})*)金币/.exec(item.text); + var split = /^(\d+(?:,\d{3})*)[.。]?$/.exec(item.text); + if (!coins && split && !first(region, /^金币$/, function (unit) { + return Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08; + })) split = null; + var match = coins || split; + if (match) { + var value = Number(match[1].replace(/,/g, "")); + if (values.indexOf(value) < 0) values.push(value); + } + }); + var top = Math.max(device.height * 0.2, moreButton.rect.top - device.height * 0.4); + return {amount: values.length === 1 ? values[0] : null, heading: { + text: "领更多金币弹窗", rect: {left: moreButton.rect.left, right: moreButton.rect.right, top: top, bottom: moreButton.rect.bottom} + }}; + } + if (!heading) return null; + // 明确写在额外奖励按钮里的金额优先,不能混入弹窗背后“已攒0金币”等文字。 + var explicit = /^看视频(?:再得|再领|领)(\d+)金币$/.exec(heading.text); + if (explicit) return {amount: Number(explicit[1]), heading: heading}; + if (/最高|量高|最多|至多|上限/.test(heading.text)) return {amount: null, heading: heading}; + // 只解析该提示附近的明确金额;“最高可领”是上限,不是已确认奖励。 + var nearby = items.filter(function (item) { + return item.rect.top >= heading.rect.top - 30 && + item.rect.top < heading.rect.bottom + device.height * 0.25; + }); + var amounts = []; + for (var i = 0; i < nearby.length; i++) { + if (/最高|最多|至多|上限|补贴|已获得|已领取|领取成功|恭喜/.test(nearby[i].text)) continue; + var amountPattern = /(?:^|[^\d.,])([\d]+(?:,[\d]{3})*)(?:个)?金币/g; + var match; + while ((match = amountPattern.exec(nearby[i].text)) !== null) { + var amount = Number(match[1].replace(/,/g, "")); + if (amounts.indexOf(amount) < 0) amounts.push(amount); + } + } + if (amounts.length !== 1) return {amount: null, heading: heading}; + return {amount: amounts[0], heading: heading}; +} + +function handleVideos(returnPattern, launchGraceMs) { + var previous = commonHandling; + commonHandling = true; + try { return handleVideosLoop(returnPattern, launchGraceMs); } + finally { commonHandling = previous; } +} + +function handleVideosLoop(returnPattern, launchGraceMs) { + var launchDeadline = Date.now() + (launchGraceMs || 0); + var deadline = Date.now() + CONFIG.videoTimeoutMs; + var accepted = 0; + var stableReturn = 0; + var actions = 0; + var sawCountdown = false; + var lastWaitLog = 0; + var lastCloseKey = ""; + var repeatedClose = 0; + var liveExitAttempts = 0; + var shortcutAttempts = 0; + while (Date.now() < deadline) { + var items = snapshot(); + if (isShortcutPrompt(items)) { + if (++shortcutAttempts > 3) stopWith("桌面助手推广连续三次关闭未响应"); + var handle = findShortcutDragHandle(); + writeRunLog("关闭签到后的桌面助手推广:" + (handle ? "下拉原生拖动条" : "返回关闭") + ",随后重新识别福利页。"); + if (handle) { + var handleX = Math.round((handle.left + handle.right) / 2); + if (swipe(handleX, Math.round((handle.top + handle.bottom) / 2), handleX, + Math.round(device.height * 0.95), 600) === false) stopWith("桌面助手推广下拉关闭失败"); + } else if (back() === false) stopWith("桌面助手推广返回关闭失败"); + actionSerial++; + sleep(CONFIG.pollMs); + continue; + } + shortcutAttempts = 0; + var surveyDismiss = findVideoSurveyDismiss(items); + if (surveyDismiss) { + if (++actions > CONFIG.maxVideos * 4) stopWith("视频反馈提示关闭未响应"); + writeRunLog("视频反馈提示:点击我知道了关闭提示,继续当前任务。"); + tap(surveyDismiss); + continue; + } + var liveExit = liveExitAction(items); + if (liveExit) { + if (++liveExitAttempts > 6) stopWith("连续六次退出直播仍未离开,跳过本步骤并保留现场"); + writeRunLog("直播退出优先:" + liveExit.reason + ";不等待直播倒计时,不领取直播奖励。"); + if (liveExit.button) tap(liveExit.button); + else { + if (back() === false) stopWith("退出直播的返回键执行失败"); + actionSerial++; + sleep(CONFIG.pollMs); + } + continue; + } + liveExitAttempts = 0; + // 重试保护只计算按钮持续存在时的连续失败;新倒计时或按钮消失说明页面已推进。 + // 不可把不同广告在同一坐标的X累计为同一按钮未响应。 + var observedClose = findTopRightClose(items) || findEmptyRewardPopupClose(items); + if (countdown(items) || !observedClose) { + lastCloseKey = ""; + repeatedClose = 0; + } + var listeningClose = findListeningPopupClose(items); + if (listeningClose) { + if (++actions > CONFIG.maxVideos * 4) stopWith("听读弹窗关闭未响应"); + writeRunLog("听读选项已取消:直接关闭听读弹窗,不点击听读按钮。"); + tap(listeningClose); + continue; + } + var signClaim = findCoinChoiceClaim(items); + if (signClaim) { + if (++actions > CONFIG.maxVideos * 4) stopWith("金币选项多次点击无响应,跳过本步骤"); + writeRunLog("通用双金额规则:有>=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 && (!flipPopupHasAction(items) || offer.amount >= CONFIG.rewardThreshold)) { + stableReturn = 0; + if (++actions > CONFIG.maxVideos * 4) stopWith("弹窗处理次数达到上限,页面可能没有响应,已停止。"); + var take = offer.amount !== null && offer.amount >= CONFIG.rewardThreshold; + var button = first(items, take ? /^(领取奖励|领更多金币|颌更多金币|确认|继续领金币|看视频领取|看视频领\d+金币|看视频(?:再得|再领|领)\d+金币)$/ : /^[||]?(坚持退出|退出|[xX×✕])$/, + function (item) { return item.rect.top >= offer.heading.rect.top && + item.rect.top < offer.heading.rect.bottom + device.height * 0.30; }); + if (!button && !take) button = findEmptyRewardPopupClose(items, true); + if (!button) stopWith("未识别到额外奖励的" + (take ? "确认" : "退出") + "按钮,已停止。"); + if (take && accepted >= CONFIG.maxVideos) stopWith("已达到本次视频数量上限,停止继续领取。"); + writeRunLog("额外奖励 " + (offer.amount === null ? "金额不明确" : offer.amount + " 金币") + ":" + (take ? "继续观看" : "退出")); + tap(button); + if (take) { accepted++; sawCountdown = false; } + deadline = Date.now() + CONFIG.videoTimeoutMs; + continue; + } + var popupClose = findEmptyRewardPopupClose(items); + var foregroundClose = popupClose && !isTopRight(popupClose) ? popupClose : null; + // 前景弹窗的动作先处理,背景倒计时和背景右上X不能抢占。 + var timer = foregroundClose ? null : countdown(items); + if (timer) { + if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) { + writeRunLog("通用规则等待倒计时:" + timer.text); + lastWaitLog = Date.now(); + } + sawCountdown = true; + stableReturn = 0; + sleep(CONFIG.pollMs); + continue; + } + if (flipPopupHasAction(items) && !findTopRightClose(items) && !foregroundClose) { + writeRunLog("翻卡优先:仍有带翻字的按钮,不执行通用弹窗关闭,继续翻卡。"); + return; + } + var close = foregroundClose || findTopRightClose(items) || popupClose; + if (close) { + if (++actions > CONFIG.maxVideos * 4) stopWith("关闭次数达到上限,页面可能没有响应,已停止。"); + stableReturn = 0; + // 再取一次本机页面,避免倒计时刚刷新时点到关闭。 + sleep(CONFIG.pollMs); + var fresh = snapshot(); + if (liveExitAction(fresh)) continue; + if (flipPopupHasAction(fresh) && !findTopRightClose(fresh) && !findEmptyRewardPopupClose(fresh)) continue; + if (findRewardReceiptClose(fresh) || offerAmount(fresh) || findCoinChoiceClaim(fresh)) continue; + var freshPopupClose = findEmptyRewardPopupClose(fresh); + var freshForegroundClose = freshPopupClose && !isTopRight(freshPopupClose) ? freshPopupClose : null; + if (!freshForegroundClose && countdown(fresh)) { sawCountdown = true; continue; } + close = freshForegroundClose || findTopRightClose(fresh) || freshPopupClose; + if (close) { + var closeKey = close.text + ":" + Math.round(close.rect.left / 20) + ":" + Math.round(close.rect.top / 20); + repeatedClose = closeKey === lastCloseKey ? repeatedClose + 1 : 1; + lastCloseKey = closeKey; + if (repeatedClose > 3) stopWith("同一关闭按钮连续三次未响应,跳过本步骤"); + tap(close); + } + continue; + } + if (isAdvertisementPage(items)) { + if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) { + writeRunLog("广告仍在前台,等待倒计时/关闭控件刷新,不把背景任务判为缺失。"); + lastWaitLog = Date.now(); + } + sleep(CONFIG.pollMs); + continue; + } + // 广告可能在点击领取数秒后才出现;启动宽限期内继续识别,避免提前结束。 + if (Date.now() < launchDeadline) { sleep(CONFIG.pollMs); continue; } + // 无倒计时、无关闭、无额外奖励就交还调度,不等待旧的返回页标签。 + writeRunLog("通用规则:当前无可执行条件,继续下一步骤。"); + return; + } + stopWith("等待视频结束或目标页面超时,已停止;未用返回键跳过倒计时。"); +} + +function 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 searchTaskAction(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, "金币").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 (!/^活动繁忙[,,]?请稍后再试[。!!]?$/.test(message)) return; + mealBusyFeedback = {time: Date.now(), message: message}; + writeRunLog("饭点应用提示:" + message); +} + +function claimMealButton(claim, returnPattern) { + var key = mealClaimKey(claim); + for (var retry = 0; retry <= CONFIG.mealBusyRetries; retry++) { + var started = Date.now(); + tap(claim); + handleVideos(returnPattern || MEAL_PAGE); + // 提示可能晚于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; + // 饭点页的整段金额按钮也可领取,不要求固定的“领早餐/午餐补贴”文案。 + // 只查主补贴区;余额、已领取说明和连续奖励档位不作为金额按钮。 + // OPPO 实际把“领午饭补贴90金币”连续多帧读成“领午饭补补贴90金币”。 + 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() { + // 监听绑定主线程,避免带事件循环的任务线程结束动作后仍存活,阻塞runStep。 + try { + events.observeToast(); + events.onToast(receiveMealToast); + return runStep("吃饭补贴", mealStep, CONFIG.mealSessionTimeoutMs + 30000); + } finally { + events.removeListener("toast", receiveMealToast); + } +} + +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 (!waitForWelfare()) stopWith("已尝试退出补贴页,但尚未确认回到福利中心"); + mealPageDone = true; + return; + } + sleep(CONFIG.pollMs); + } + stopWith("补贴页循环达到30分钟异常保护上限;未确认全部无匹配,保留页面,不自动退出"); +} + +function ensureTaskPage() { + var page = snapshot(); + if (countdown(page) || first(page, /再看(?:一个|1个|一段|1段)?视频|再[看香]\d+秒|看视频(?:再得|再领|领)\d+金币|视频广告|广告剩余/)) { + stopWith("上一步仍停留在广告或额外奖励页,不跳过倒计时、不在广告上查找下一任务"); + } + if (!isWelfarePage(page) && !first(page, MEAL_PAGE) && !first(page, STREAK_SECTION)) { + skipStep("没有当前任务对应的福利或饭点标签,执行下一步骤"); + } + return page; +} + +function returnFromSignPage() { + var page = snapshot(); + if (isWelfarePage(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); + if (!waitForWelfare()) skipStep("签到页已返回,但暂未识别到福利页,交由下一步骤重新识别"); + } +} + +function signInStep() { + returnFromSignPage(); + var page = ensureTaskPage(); + if (first(page, MEAL_PAGE)) { + writeRunLog("跳过签到:当前位于饭点补贴页,继续处理饭点任务。"); + return; + } + var sign = searchEarningTask(SIGN_ENTRY, /^[||]?(?:去签到|立即签到|签到)$/, "签到"); + 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, /^翻卡[赢贏嘉羸]金币/); + return first(items, /^立即翻卡$/, function (button) { + return labels.some(function (label) { + return 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 searchFlipEntry() { + return searchTaskAction(findFlipEntry, "翻卡赢金币", /翻卡|翻牌/, "FLIP SEARCH"); +} + +function isFlipButton(item) { + if (!isCenteredPopupItem(item) || item.rect.top <= device.height * 0.4) return false; + // 按钮文字允许任意“翻”字,但标题、状态及背景介绍不是操作按钮。 + return !/^(?:已翻.*|继续翻卡领更多.*|翻卡[赢贏嘉羸].*|点击翻卡.*(?:最高|金[币市]).*|翻多少得多少.*)$/.test(item.text); +} + +function findFlipButton(items) { + return first(items, FLIP_BUTTON, isFlipButton); +} + +function flipCardStep() { + if (flipActionDone || flipSettlementDone) return; + if (!flipEntryOpened) { + var page = snapshot(); + // 可从已经打开的翻卡弹窗继续,不再点击弹窗背后的入口。 + if (findFlipButton(page)) flipEntryOpened = true; + else { + if (!isWelfarePage(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 transientRetries = 0; + var missingEntrySearched = false; + while (Date.now() < deadline) { + try { + if (flipSettlementDone) return; + var flip = waitFor(FLIP_BUTTON, CONFIG.pageTimeoutMs, isFlipButton); + if (flipSettlementDone) return; + if (!flip) { + var returnedPage = snapshot(); + var popupTitle = first(returnedPage, /^继续翻卡/, isCenteredPopupItem); + var nextEntry = !missingEntrySearched && !popupTitle && isWelfarePage(returnedPage) ? searchFlipEntry() : null; + if (!popupTitle && !nextEntry) missingEntrySearched = true; + if (nextEntry) { + if (++clicks > 20) stopWith("翻卡达到20次异常保护上限,未确认全部完成,保留页面"); + writeRunLog("FLIP RETURN: 返回福利页仍有立即翻卡,继续进入下一张卡。"); + tap(nextEntry); + missingEntrySearched = false; + emptyPasses = 0; + continue; + } + emptyPasses++; + writeRunLog("FLIP EMPTY: 没有翻卡按钮 " + emptyPasses + "/2"); + if (emptyPasses >= 2) { + if (!flipActionDone) skipStep("已进入翻卡页但没有翻卡按钮,跳过该操作"); + writeRunLog("完成:翻卡按钮已处理,连续两次未找到后续翻卡按钮。"); + return; + } + sleep(CONFIG.pollMs); + continue; + } + if (++clicks > 20) stopWith("翻卡达到20次异常保护上限,未确认全部完成,保留页面"); + emptyPasses = 0; + missingEntrySearched = false; + writeRunLog("FLIP ACTION: 第" + clicks + "次,点击 " + flip.text); + tap(flip); + flipActionDone = true; + handleVideos(/翻卡/); + sleep(CONFIG.pollMs); + snapshot(); + transientRetries = 0; + } catch (error) { + if (error.captureFatal || error.unsafeWorker || (error.noMatch && emptyPasses >= 2 && !flipActionDone)) throw error; + var retryable = error.noMatch || /未识别到额外奖励的.*按钮|通用页面仍未处理完成|通用处理后目标标签已改变|未识别到翻卡结算的开心收下按钮/.test(String(error)); + if (!retryable || ++transientRetries > 3) throw error; + emptyPasses = 0; + writeRunLog("FLIP RETRY: 通用处理或页面刷新后重新识别,第" + transientRetries + "次;" + error); + sleep(CONFIG.pollMs); + } + } + stopWith("翻卡达到30分钟异常保护上限,未确认全部完成,保留页面"); +} + +function searchTaskAction(finder, actionName, relatedPattern, logPrefix) { + var entry = finder(snapshot()); + if (entry) return entry; + for (var direction = 0; direction < 2; direction++) { + var lastKey = ""; + var stationary = 0; + for (var i = 0; i < CONFIG.taskSearchScrolls; i++) { + var moved = swipe(Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.8 : 0.35)), + Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.35 : 0.8)), 450); + sleep(CONFIG.pollMs); + var page = snapshot(); + writeRunLog((logPrefix || "TASK SEARCH") + ": " + actionName + ";" + (direction ? "向下" : "向上") + (i + 1) + ";滑动=" + moved + ";相关文字=" + + matches(page, relatedPattern || /补贴|翻卡|海量|立即领取/).map(function (item) { return item.text; }).join("、")); + entry = finder(page); + if (entry) return entry; + var 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 bottomNavigation(items, pattern) { + return first(items, pattern, function (item) { return item.rect.top > device.height * 0.9; }); +} + + +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: 结束前已复查通用条件,当前无可执行弹窗或广告规则。"); +} +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 isWelfarePage(items) { + if (first(items, /^(?:福利中心|日常福利)$/)) return true; + var welfare = bottomNavigation(items, /^福利$/); + try { if (welfare && welfare.node && welfare.node.selected()) return true; } catch (error) {} + return !!(welfare && first(items, /签到领金币|吃饭补贴|翻卡[赢贏嘉羸]|看视频[赚賺嫌]海量金币/)); +} + +function waitForWelfare() { + var deadline = Date.now() + CONFIG.pageTimeoutMs; + while (Date.now() < deadline) { + if (isWelfarePage(snapshot())) return true; + sleep(CONFIG.pollMs); + } + return false; +} + +function enterWelfareStep() { + var page = snapshot(); + if (first(page, MEAL_PAGE) || first(page, STREAK_SECTION) || findFlipButton(page)) return; + var welfare = bottomNavigation(page, /^福利$/); + if (!welfare) skipStep("没有底部福利导航,跳过进入福利步骤"); + tap(welfare); + if (!waitForWelfare()) skipStep("点击福利后尚未识别福利页,继续下一步骤"); +} + +function findMassVideoClaim(items) { + var labels = matches(items, MASS_VIDEO_LABEL); + return first(items, /^[||]?立即[领颌颁頒]取$/, function (button) { + return labels.some(function (label) { + return button.rect.left > label.rect.left && button.rect.left > device.width * 0.6 && + Math.abs((button.rect.top + button.rect.bottom - label.rect.top - label.rect.bottom) / 2) < device.height * 0.045; + }); + }); +} + +function searchMassVideoTask() { + var labelFound = false; + var button = searchTaskAction(function (items) { + if (first(items, MASS_VIDEO_LABEL)) labelFound = true; + return findMassVideoClaim(items); + }, "看视频赚海量金币立即领取", /海量|看视频|立即[领颌颁頒]取/, "MASS VIDEO SEARCH"); + return {labelFound: labelFound, button: button}; +} + +function findSafeMassVideoClaim(items) { + if (!isWelfarePage(items)) return null; + var button = findMassVideoClaim(items); + return button && button.rect.top >= device.height * 0.15 && button.rect.bottom < device.height * 0.68 ? button : null; +} + +function prepareMassVideoClaim(forceMove) { + for (var attempt = 0; attempt < 4; attempt++) { + var button = findMassVideoClaim(snapshot()); + if (!button) return null; // 页面变化后交回任务搜索,不使用旧坐标。 + var safe = button.rect.top >= device.height * 0.15 && button.rect.bottom < device.height * 0.68; + if (safe && !forceMove) return button; + var moveUp = (button.rect.top + button.rect.bottom) / 2 > device.height * 0.4; + writeRunLog("MASS VIDEO ALIGN: 小幅慢滑,将领取按钮移出右下宝箱和导航遮挡区,再识别当前按钮。"); + if (swipe(Math.round(device.width * 0.45), Math.round(device.height * (moveUp ? 0.65 : 0.3)), + Math.round(device.width * 0.45), Math.round(device.height * (moveUp ? 0.53 : 0.42)), 800) === false) + stopWith("海量金币任务行调整位置失败,保留现场"); + forceMove = false; + sleep(CONFIG.pollMs); + } + var finalButton = findMassVideoClaim(snapshot()); + if (!finalButton) return null; + if (finalButton.rect.top >= device.height * 0.15 && finalButton.rect.bottom < device.height * 0.68) return finalButton; + stopWith("海量金币按钮仍位于遮挡区,不重复点击旧位置"); +} + +function massVideoStep() { + var rounds = 0; + var emptyPasses = 0; + var noProgress = 0; + var targetRefreshes = 0; + writeRunLog("MASS VIDEO LOOP: 每次领取和通用处理后重新查找标签及对应立即领取,连续两次无匹配才结束。"); + while (true) { + // 每次查找、每次视频分别限时,整段循环不受单步骤四分钟上限截断。 + var found = runStep("复查海量金币标签及按钮", function () { + ensureTaskPage(); + return searchMassVideoTask(); + }); + if (!found.ok || found.skipped) { + writeRunLog("MASS VIDEO ERROR: 未能确认福利任务页面,保留现场,不视为标签已消失。"); + return {ok: false, rounds: rounds}; + } + var target = found.value; + if (!target || !target.button) { + emptyPasses++; + writeRunLog("MASS VIDEO EMPTY: " + (target && target.labelFound ? "标签存在但没有对应立即领取" : "没有找到看视频赚海量金币标签") + ";复查" + emptyPasses + "/2。"); + if (emptyPasses < 2) { sleep(CONFIG.pollMs); continue; } + writeRunLog("MASS VIDEO LOOP DONE: 连续两次没有符合条件的入口;共执行" + rounds + "轮。"); + return {ok: true, skipped: rounds === 0, rounds: rounds}; + } + emptyPasses = 0; + var nextRound = rounds + 1; + var claimed = runStep("海量金币第" + nextRound + "轮领取及通用处理", function () { + var button = prepareMassVideoClaim(noProgress > 0); + if (!button) return {changed: true}; + writeRunLog("MASS VIDEO CLAIM: 第" + nextRound + "轮,点击同一标签对应的立即领取。"); + // 同一任务行的按钮可有OCR同义字或布局变化,按当前帧语义重新绑定并复查安全区域。 + tap(button, findSafeMassVideoClaim); + var afterTapSerial = actionSerial; + handleVideos(/福利中心|日常福利|福利/, 10000); + var page = snapshot(); + // press=true 只代表触摸已发送。没有任何后续通用操作且领取入口仍在,不能记作完成。 + return {progressed: actionSerial > afterTapSerial || !findMassVideoClaim(page)}; + }); + if (claimed.targetChanged || (claimed.value && claimed.value.changed)) { + targetRefreshes++; + writeRunLog("MASS VIDEO TARGET REFRESH: 点击前目标变化,重新识别当前任务 " + targetRefreshes + "/" + CONFIG.massVideoNoProgressLimit + ";不点击旧坐标,不计为完成轮次。"); + if (targetRefreshes >= CONFIG.massVideoNoProgressLimit) { + writeRunLog("MASS VIDEO UNAVAILABLE: 领取入口连续变化,有限重试后跳过本轮任务,不冒充广告处理异常或正常无匹配。"); + return {ok: true, unavailable: true, rounds: rounds}; + } + sleep(CONFIG.pollMs); + continue; + } + if (!claimed.ok || claimed.skipped) { + writeRunLog("MASS VIDEO ERROR: 本轮广告或弹窗处理异常,保留现场,不记录为无匹配。"); + return {ok: false, rounds: rounds}; + } + targetRefreshes = 0; + if (!claimed.value || !claimed.value.progressed) { + noProgress++; + writeRunLog("MASS VIDEO NO PROGRESS: 点击后未触发广告或弹窗,领取入口仍在;重新定位重试 " + noProgress + "/" + CONFIG.massVideoNoProgressLimit + ",不计为完成轮次。"); + if (noProgress >= CONFIG.massVideoNoProgressLimit) { + writeRunLog("MASS VIDEO UNAVAILABLE: 连续无进展,跳过本轮海量金币任务,避免无限空点;不视为标签消失或奖励已到账。"); + return {ok: true, unavailable: true, rounds: rounds}; + } + sleep(CONFIG.mealBusyRetryMs); + continue; + } + noProgress = 0; + rounds++; + writeRunLog("MASS VIDEO RECHECK: 第" + rounds + "轮处理结束,继续重新查找标签和对应按钮。"); + } +} + +function runDaily() { + files.write(CONFIG.logPath, ""); + writeRunLog("START: version=" + CONFIG.version + ";红果免费短剧;仅手机本地识别。"); + var currentEngine = engines.myEngine(); + var stopped = false; + writeRunLog("SOURCE: " + currentEngine.getSource()); + engines.all().forEach(function (engine) { + if (engine.id !== currentEngine.id && /(?:fanqie-(?:daily|publication-live)|hongguo-daily)\.auto\.js$/.test(String(engine.getSource()))) { + engine.forceStop(); + stopped = true; + } + }); + if (stopped) sleep(500); + runStep("初始化本地OCR", initLocalOcr, CONFIG.capturePermissionTimeoutMs + 5000); + if (CONFIG.useLocalOcr && !localOcrEnabled) { writeRunLog("END: 本地OCR未就绪,保留页面。"); return; } + var startup = runStep("启动红果免费短剧", function () { + auto.waitFor(); + if (foregroundPackage() !== CONFIG.packageName && !app.launchPackage(CONFIG.packageName)) stopWith("无法打开红果免费短剧"); + var deadline = Date.now() + CONFIG.pageTimeoutMs; + while (foregroundPackage() !== CONFIG.packageName && Date.now() < deadline) sleep(300); + if (foregroundPackage() !== CONFIG.packageName) stopWith("等待红果进入前台超时"); + sleep(CONFIG.pollMs); + }, 25000); + if (!startup.ok) return; + writeRunLog("FLOW: 福利 -> 签到领金币(去签到) -> 吃饭补贴 -> 翻卡赢金币 -> 看视频赚海量金币立即领取。"); + var page = snapshot(); + if (!findFlipButton(page) && !flipSettlementDone) { + runStep("进入底部福利", enterWelfareStep, 30000); + runStep("签到领金币(去签到)", signInStep); + var mealResult = runMealStep(); + writeRunLog("补贴步骤结束:继续检查翻卡赢金币。"); + } else writeRunLog("RESUME: 当前为翻卡现场,继续翻卡后进入视频流程。"); + var flipResult = runStep("翻卡赢金币", flipCardStep, CONFIG.flipSessionTimeoutMs + 30000); + if (!flipResult.ok && flipEntryOpened) { + writeRunLog("END: 翻卡流程异常未处理完成,保留页面,避免在广告中查找下一任务。"); + return; + } + var videoResult = massVideoStep(); + if (videoResult.unavailable) return "END: 海量金币领取连续无进展,已有限重试并跳过本轮任务;未确认广告启动或奖励到账。"; + return videoResult.ok ? (videoResult.skipped ? "END: 视频标签或对应领取按钮无匹配,已跳过;本次流程结束。" : "END: 红果每日金币已配置流程执行结束。") : "END: 视频流程遇到异常,保留页面与文字日志。"; +} + + +try { + var endMessage = runDaily(); + drainCommonBeforeExit(); + if (endMessage) writeRunLog(endMessage); +} catch (error) { + writeRunLog("ERROR: " + error + "\n" + error.stack); + toastLog("本次运行异常结束:" + error); + throw error; +} + +finally { + // 授权超时后可能迟到返回;失败路径也必须释放截图会话。 + try { images.stopScreenCapture(); } catch (releaseError) { log(String(releaseError)); } + if (captureWorker && captureWorker.isAlive()) captureWorker.interrupt(); +} diff --git a/hongguo_auto/tests/mass-video.test.js b/hongguo_auto/tests/mass-video.test.js new file mode 100644 index 0000000..30df24f --- /dev/null +++ b/hongguo_auto/tests/mass-video.test.js @@ -0,0 +1,225 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = fs.readFileSync(path.join(__dirname, '../hongguo-daily.auto.js'), 'utf8'); +function load() { + const context = vm.createContext({console, Date, Math, JSON, Error, isFinite}); + vm.runInContext(source.slice(0, source.lastIndexOf('\ntry {\n var endMessage')), context); + context.device = {width: 1080, height: 2374}; + context.sleep = () => {}; + context.files = {write() {}}; + context.logs = []; + context.writeRunLog = text => context.logs.push(text); + return context; +} +const item = (text, top, bottom = top + 40, left = 826, right = 974) => ({text, rect: {left, right, top, bottom}}); +const taskPage = top => [item('日常福利', 350, 390, 60, 260), + item('看视频赚海量金币210', top - 30, top + 10, 187, 702), item('立即颌取', top)]; + +test('无障碍选择器使用AutoJs6支持的字符串参数,并保留原生文字节点', () => { + const c = load(); + c.foregroundPackage = () => c.CONFIG.packageName; + const node = {bounds: () => ({left: 696, top: 2217, right: 798, bottom: 2285}), + text: () => '福利', visibleToUser: () => true}; + c.textMatches = pattern => { + assert.equal(typeof pattern, 'string'); + return {find: () => ({size: () => 1, get: () => node})}; + }; + c.descMatches = pattern => { + assert.equal(typeof pattern, 'string'); + return {find: () => ({size: () => 0})}; + }; + const page = c.readSnapshot(); + assert.equal(page[0].text, '福利'); + assert.equal(page[0].node, node); +}); + +test('真实OPPO领取按钮位于宝箱区域时先慢滑避让,仅返回新帧按钮', () => { + const c = load(); + let page = JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo8-stalled.json'), 'utf8')); + const oldButton = c.findMassVideoClaim(page); + assert.equal(oldButton.rect.top, 1880); + c.snapshot = () => page; + let swipes = 0; + c.swipe = (x1, y1, x2, y2, duration) => { + assert.equal(x1, x2); + assert.ok(y1 > y2); + assert.ok(y1 - y2 < 300); + assert.equal(duration, 800); + swipes++; + page = taskPage(1880 - swipes * 285); + return true; + }; + const button = c.prepareMassVideoClaim(false); + assert.equal(swipes, 2); + assert.notEqual(button, oldButton); + assert.ok(button.rect.bottom < 2374 * 0.68); +}); + +test('安全区域按钮直接返回,无进展重试时至少移动一次并重新识别', () => { + const c = load(); + let page = taskPage(1200); + c.snapshot = () => page; + let swipes = 0; + c.swipe = () => {swipes++; page = taskPage(950); return true;}; + assert.equal(c.prepareMassVideoClaim(false), page[2]); + assert.equal(swipes, 0); + assert.equal(c.prepareMassVideoClaim(true), page[2]); + assert.equal(swipes, 1); +}); + +test('滑动失败或始终无法离开遮挡区时不点击旧位置', () => { + for (const moved of [false, true]) { + const c = load(); + c.snapshot = () => taskPage(1880); + c.swipe = () => moved; + assert.throws(() => c.prepareMassVideoClaim(false), /调整位置失败|仍位于遮挡区/); + } +}); + +function massFlow() { + const c = load(); + const button = taskPage(1200)[2]; + c.snapshot = () => taskPage(1200); + c.ensureTaskPage = () => {}; + c.searchMassVideoTask = () => ({labelFound: true, button}); + c.moves = []; + c.prepareMassVideoClaim = force => {c.moves.push(force); return button;}; + c.taps = 0; + c.tap = () => {c.taps++; c.actionSerial++;}; + c.handleVideos = (_pattern, grace) => assert.equal(grace, 10000); + c.runStep = (_name, action) => { + try {return {ok: true, value: action()};} + catch (error) {return {ok: !!error.noMatch, skipped: true, targetChanged: !!error.targetChanged};} + }; + return c; +} + +test('press成功但广告未启动不能算完成,三次无进展后跳过而非无限空点', () => { + const c = massFlow(); + const result = c.massVideoStep(); + assert.equal(c.taps, 3); + assert.equal(result.unavailable, true); + assert.equal(result.rounds, 0); + assert.deepEqual(c.moves, [false, true, true]); + assert.ok(c.logs.some(text => text.includes('不计为完成轮次'))); + assert.ok(!c.logs.some(text => text.includes('MASS VIDEO RECHECK'))); +}); + +test('真实广告通用操作有进展时继续同一按钮,不用总轮次截断正常循环', () => { + const c = massFlow(); + c.handleVideos = () => {c.actionSerial++;}; + let searches = 0; + c.searchMassVideoTask = () => ++searches <= 5 ? {button: taskPage(1200)[2]} : {labelFound: false}; + const result = c.massVideoStep(); + assert.equal(result.rounds, 5); + assert.equal(c.taps, 5); + assert.equal(searches, 7); + assert.equal(result.unavailable, undefined); +}); + +test('广告恢复成功清除连续无进展次数,新一轮故障仍有完整重试机会', () => { + const c = massFlow(); + c.handleVideos = () => {if (c.taps === 3) c.actionSerial++;}; + const result = c.massVideoStep(); + assert.equal(result.rounds, 1); + assert.equal(result.unavailable, true); + assert.equal(c.taps, 6); + assert.deepEqual(c.moves, [false, true, true, false, true, true]); +}); + +test('调整位置后按钮消失先复查,不点旧按钮也不记录完成', () => { + const c = massFlow(); + let searches = 0; + c.searchMassVideoTask = () => ++searches === 1 ? {button: taskPage(1200)[2]} : {labelFound: false}; + c.prepareMassVideoClaim = () => null; + const result = c.massVideoStep(); + assert.equal(c.taps, 0); + assert.equal(result.rounds, 0); + assert.equal(searches, 3); +}); + +test('真实广告处理异常保留错误,不冒充正常无匹配或完成', () => { + const c = massFlow(); + c.handleVideos = () => {throw Error('广告关闭未响应');}; + const result = c.massVideoStep(); + assert.equal(result.ok, false); + assert.equal(result.rounds, 0); + assert.equal(c.taps, 1); +}); + +test('点击前OCR领取同义字及位置发生变化,重新绑定当前任务按钮,不点旧坐标', () => { + const c = load(); + const old = item('立即领取', 900); + const fresh = taskPage(1000); + c.snapshot = () => fresh; + c.foregroundPackage = () => c.CONFIG.packageName; + const presses = []; + c.press = (x, y) => {presses.push([x, y]); return true;}; + c.tap(old, c.findSafeMassVideoClaim); + assert.deepEqual(presses, [[900, 1020]]); +}); + +test('真实停止页面仍可绑定海量金币按钮,其他任务领取和遮挡位置不能替代', () => { + const c = load(); + const page = JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo9-target-changed.json'), 'utf8')); + assert.equal(c.findSafeMassVideoClaim(page).rect.top, 901); + for (const fresh of [page.filter(row => !c.MASS_VIDEO_LABEL.test(row.text)), taskPage(1880)]) { + c.snapshot = () => fresh; + c.press = () => {throw Error('不能点击其他任务或被遮挡的入口');}; + assert.throws(() => c.tap(item('立即领取', 900), c.findSafeMassVideoClaim), error => error.targetChanged === true); + } +}); + +test('第8轮点击前目标变化时复查并恢复,保留前7轮完成结果', () => { + const c = massFlow(); + // 使用真实runStep错误分类,模拟AutoJs线程执行的结果。 + c.boundedCall = (_name, _timeout, action) => action(); + vm.runInContext(source.slice(source.indexOf('function runStep('), source.indexOf('function foregroundPackage(')), c); + let attempts = 0; + c.tap = () => { + attempts++; + if (attempts === 8) { + const error = Error('通用处理后目标标签已改变,跳过旧坐标点击'); + error.noMatch = true; + error.targetChanged = true; + throw error; + } + c.taps++; + c.actionSerial++; + }; + c.handleVideos = () => {c.actionSerial++;}; + c.searchMassVideoTask = () => c.taps < 9 ? {button: taskPage(1200)[2]} : {labelFound: false}; + const result = c.massVideoStep(); + assert.equal(result.ok, true); + assert.equal(result.rounds, 9); + assert.equal(c.taps, 9); + assert.equal(attempts, 10); + assert.ok(c.logs.some(text => text.includes('MASS VIDEO TARGET REFRESH'))); + assert.ok(!c.logs.some(text => text.includes('MASS VIDEO ERROR'))); +}); + +test('入口持续变化时有限复查,不无限重试也不误报广告异常', () => { + for (const changedDuringTap of [false, true]) { + const c = massFlow(); + let attempts = 0; + c.prepareMassVideoClaim = () => { + attempts++; + if (!changedDuringTap) return null; + return taskPage(1200)[2]; + }; + c.tap = () => { + const error = Error('目标变化'); + error.noMatch = true; + error.targetChanged = true; + throw error; + }; + const result = c.massVideoStep(); + assert.equal(attempts, 3); + assert.equal(result.unavailable, true); + assert.equal(result.rounds, 0); + assert.ok(!c.logs.some(text => text.includes('MASS VIDEO ERROR'))); + } +}); diff --git a/hongguo_auto/tests/meal.test.js b/hongguo_auto/tests/meal.test.js new file mode 100644 index 0000000..4a3e100 --- /dev/null +++ b/hongguo_auto/tests/meal.test.js @@ -0,0 +1,59 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = fs.readFileSync(path.join(__dirname, '../hongguo-daily.auto.js'), 'utf8'); +function load() { + const c = vm.createContext({Date, Math, JSON, Error, isFinite}); + vm.runInContext(source.slice(0, source.lastIndexOf('\ntry {\n var endMessage')), c); + c.device = {width: 1080, height: 2374}; + c.writeRunLog = () => {}; + return c; +} +function mealPage() { + return JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo11-meal-inspect.jsonl'), 'utf8').split('\n')[0]); +} + +test('OPPO连续五帧补补贴误识别仍执行真实午饭领取,不判定为空页', () => { + const frames = fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo11-meal-inspect.jsonl'), 'utf8').trim().split('\n').map(JSON.parse); + assert.equal(frames.length, 5); + for (const page of frames) { + const c = load(); + const button = page.find(i => i.text === '领午饭补补贴90金币'); + assert.ok(button); + assert.equal(c.findMealCoinClaim(page), button); + c.snapshot = () => page; + let claims = 0; + c.claimMealButton = target => {assert.equal(target, button); claims++; return true;}; + assert.equal(c.finishMealPage(true), true); + assert.equal(claims, 1); + } +}); + +test('重复补字兼容保留正常按钮识别与已领取说明、区域约束', () => { + for (const text of ['领午饭补贴90金币', '领午饭补补贴90金币', '|领午饭补补贴90金市']) { + const c = load(); + const page = mealPage(); + const button = page.find(i => i.text === '领午饭补补贴90金币'); + button.text = text; + assert.equal(c.findMealCoinClaim(page), button); + button.text = '已领取午饭补补贴90金币'; + assert.equal(c.findMealCoinClaim(page), null); + button.text = text; + button.rect.top = 100; button.rect.bottom = 145; + assert.equal(c.findMealCoinClaim(page), null); + } +}); + +test('补贴繁忙去重兼容OCR重复补字变化,不能绕过有限重试', () => { + const c = load(); + const page = mealPage(); + const button = page.find(i => i.text === '领午饭补补贴90金币'); + const key = c.mealClaimKey(button); + c.mealUnavailableClaims[key] = true; + assert.equal(c.findMealCoinClaim(page), null); + button.text = '领午饭补贴90金币'; + assert.equal(c.mealClaimKey(button), key); + assert.equal(c.findMealCoinClaim(page), null); +}); diff --git a/hongguo_auto/tests/sign-in.test.js b/hongguo_auto/tests/sign-in.test.js new file mode 100644 index 0000000..232ac80 --- /dev/null +++ b/hongguo_auto/tests/sign-in.test.js @@ -0,0 +1,147 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = fs.readFileSync(path.join(__dirname, '../hongguo-daily.auto.js'), 'utf8'); +function load() { + const c = vm.createContext({Date, Math, JSON, Error, isFinite}); + vm.runInContext(source.slice(0, source.lastIndexOf('\ntry {\n var endMessage')), c); + c.device = {width: 1080, height: 2374}; + c.logs = []; + c.writeRunLog = text => c.logs.push(text); + c.sleep = () => {}; + return c; +} +const item = (text, left, top, right = left + 180, bottom = top + 45) => ({text, rect: {left, top, right, bottom}}); +const singlePopup = () => [item('今日签到领100金币', 250, 600), + {...item('立即领取', 400, 1400), darkButton: true}, item('X', 520, 1750, 560)]; + +test('实际OPPO福利文字样本按签到标签匹配本行去签到,不依赖日常福利标题', () => { + const c = load(); + const frames = fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo10-slow-inspect.jsonl'), 'utf8') + .trim().split('\n').map(line => JSON.parse(line)); + const page = frames.find(frame => frame.some(i => i.text === '去签到')); + assert.ok(page); + c.snapshot = () => page.filter(i => i.text !== '日常福利'); + c.swipe = () => {throw Error('可见入口不应继续滑动');}; + assert.equal(c.searchEarningTask(c.SIGN_ENTRY, /^[||]?(?:去签到|立即签到|签到)$/, '签到').text, '去签到'); +}); + +test('单按钮签到按番茄规则领取唯一深色按钮,通用处理不能先关闭它', () => { + const c = load(); + const popup = singlePopup(); + assert.equal(c.needsCommonHandling(popup), true); + assert.equal(c.singleButtonPopupDecision(popup).signIn, true); + let taps = []; + c.snapshot = () => taps.length ? [item('日常福利', 80, 400)] : popup; + c.tap = button => {taps.push(button.text); c.actionSerial++;}; + c.handleVideosLoop(null, 0); + assert.deepEqual(taps, ['立即领取']); +}); + +for (const [left, right, expected] of [[2868, 4868, 4868], [100, 400, 100]]) { + test(`签到双金额 ${left}/${right} 按通用阈值选择 ${expected}`, () => { + const c = load(); + const popup = [item('今日签到', 250, 600), + {...item(`领${left}金币`, 160, 1400), darkButton: true}, + {...item(`领${right}金币`, 600, 1400), darkButton: true}, item('X', 520, 1750, 560)]; + assert.equal(c.findSingleSignPopupClaim(popup), null); + assert.equal(c.findCoinChoiceClaim(popup).text, `领${expected}金币`); + }); +} + +test('签到任务背景及无深色按钮证据不能触发单按钮签到领取', () => { + const c = load(); + assert.equal(c.findSingleSignPopupClaim([item('签到领金币8828', 203, 900), item('去签到', 828, 920)]), null); + const popup = singlePopup(); + popup[1].darkButton = false; + assert.equal(c.findSingleSignPopupClaim(popup), null); +}); + +test('独立签到活动页无X时仍识别深色领取,合并原生与OCR按钮', () => { + const c = load(); + const native = {...item('立即领取', 183, 1839, 896, 1972), darkButton: false}; + const ocr = {...item('立即领取', 450, 1882, 630, 1925), darkButton: true}; + const page = [item('已签0/7今日签到,额外奖励立即到账+7125', 82, 1674, 997, 1789), + item('活动时间:10月20日-11月18日', 262, 356), item('back', 64, 194, 86, 230), native, ocr]; + assert.equal(c.singleButtonPopupDecision(page).button, native); + assert.equal(c.singleButtonPopupDecision(page).signIn, true); +}); + +test('独立签到页处理后返回福利,再交给吃饭补贴', () => { + const c = load(); + const backButton = item('back', 64, 194, 86, 230); + c.snapshot = () => [backButton, item('今日签到', 250, 600), item('活动时间', 250, 356)]; + let returned = false; + c.tap = button => {assert.equal(button, backButton); returned = true;}; + c.waitForWelfare = () => returned; + c.returnFromSignPage(); + assert.equal(returned, true); +}); + +test('真实签到完成浮层忽略X下方背景任务金币,关闭后才能进入吃饭补贴', () => { + const c = load(); + const page = JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo11-after-signin.json'), 'utf8')); + const close = page.find(i => i.text === 'X'); + assert.ok(page.some(i => i.text === '领63347金币' && i.rect.top > close.rect.bottom)); + assert.equal(c.findEmptyRewardPopupClose(page), close); + assert.equal(c.needsCommonHandling(page), true); + // 浮层内部如果仍有合法金币领取按钮,应保留领取优先。 + assert.equal(c.findEmptyRewardPopupClose([...page, item('领900金币', 400, 1500)]), null); +}); + +test('签到后追加的桌面助手推广下拉原生拖动条关闭,不在遮挡层下查找补贴', () => { + const c = load(); + const page = JSON.parse(fs.readFileSync(path.join(__dirname, '../debug/2026-10-21/oppo-hongguo11-shortcut-prompt.json'), 'utf8')); + assert.equal(c.isShortcutPrompt(page), true); + assert.equal(c.needsCommonHandling(page), true); + let returned = 0; + c.snapshot = () => returned ? [item('日常福利', 80, 400)] : page; + c.className = name => { + assert.equal(name, 'android.view.ViewGroup'); + return {find: () => ({size: () => 1, get: () => ({visibleToUser: () => true, + bounds: () => ({left: 490, top: 1268, right: 590, bottom: 1279})})})}; + }; + c.swipe = (x1, y1, x2, y2, duration) => { + assert.equal(x1, 540); assert.equal(y1, 1274); + assert.equal(x2, 540); assert.ok(y2 > 2200); assert.equal(duration, 600); + returned++; return true; + }; + c.back = () => {throw Error('真机此推广不响应返回,应下拉拖动条');}; + c.tap = () => {throw Error('不应点击添加桌面助手或背景领取');}; + c.handleVideosLoop(null, 0); + assert.equal(returned, 1); + assert.equal(c.actionSerial, 1); + assert.equal(c.isShortcutPrompt([item('添加赚钱助手到桌面领金币', 200, 600)]), false); + assert.equal(c.isShortcutPrompt([item('添加賺钱助手到桌面领6666金币', 200, 600), item('立即添加领专属奖励', 300, 1400)]), true); +}); + +test('主流程先完成签到再启动补贴;无签到入口也继续后续任务', () => { + for (const available of [true, false]) { + const c = load(); + const order = []; + c.files = {write() {}}; + const engine = {id: 1, getSource: () => 'hongguo-daily.auto.js'}; + c.engines = {myEngine: () => engine, all: () => [engine]}; + c.initLocalOcr = () => {c.localOcrEnabled = true;}; + c.auto = {waitFor() {}}; + c.foregroundPackage = () => c.CONFIG.packageName; + const page = [item('日常福利', 80, 400)]; + c.snapshot = () => page; + c.enterWelfareStep = () => order.push('福利'); + c.ensureTaskPage = () => page; + c.returnFromSignPage = () => {}; + c.searchEarningTask = () => available ? item('去签到', 828, 920) : null; + c.tap = () => { + order.push('去签到'); + c.snapshot = () => {c.actionSerial++; order.push('通用领取'); return page;}; + }; + c.runMealStep = () => {order.push('补贴'); return {ok: true};}; + c.flipCardStep = () => order.push('翻卡'); + c.massVideoStep = () => {order.push('海量'); return {ok: true};}; + c.runStep = (_name, action) => ({ok: true, value: action()}); + c.runDaily(); + assert.deepEqual(order, available ? ['福利', '去签到', '通用领取', '补贴', '翻卡', '海量'] : ['福利', '补贴', '翻卡', '海量']); + } +}); diff --git a/qimao_auto/README.md b/qimao_auto/README.md new file mode 100644 index 0000000..d183fff --- /dev/null +++ b/qimao_auto/README.md @@ -0,0 +1,19 @@ +# 七猫免费小说脚本 + +入口:`qimao-daily.auto.js`,运行于 AutoJs6。手机路径:`/sdcard/脚本/七猫/qimao-daily.auto.js`。 + +流程:福利中心 → 吃饭补贴 → 逛街赚金币 → 商城红包 → 复查逛街剩余入口。沿用原脚本的奖励弹窗规则,只使用手机内存中的本地 OCR,不导出或上传图片。 + +2026-10-21 qimao-12 修复: + +- 午饭领取后任务按钮变成“去补领”,旧版本漏识别;现在识别去领取、去补领、领金币,并在滚动搜索过程中识别顶部补贴图标。 +- 点击补贴入口后等待页面完成加载,兼容“看视频补领一次补贴”页面文案,避免单帧空白导致整个流程提前结束。 +- 运行时保持亮屏并定期续期,正常退出后释放,避免等待广告时自动锁屏中断。 +- 系统界面短暂遮挡时先等待恢复;逛街搜索/执行被持续系统浮层中断时,最多重新识别两次,避免沿用旧坐标或无限重试。 +- 商城红包结束后复查逛街入口,继续尚未完成的逛街。异常/按钮无响应不再标记整组已完成。 + +排查证据位于 `debug/2026-10-21/`:旧源码、旧日志、当时的控件树。旧日志在 13:52:01 记录系统浮层导致逛街第 20 轮跳过,在 14:03:05 商城完成后直接结束;控件树显示逛街仍为 10/20 次,补贴入口为去补领。 + +验证:`node --test qimao_auto/tests/recovery.test.js`(在仓库根目录运行),11 项行为测试。`node --check qimao_auto/qimao-daily.auto.js` 检查语法。真机运行记录:`/sdcard/Download/qimao-daily-run.log`;当前文字识别:`/sdcard/Download/qimao-daily-page.json`。 + +OPPO 真机验证:qimao-11 已识别并点击去补领、看视频补领一次补贴;随后设备熄屏锁定。qimao-12 加入亮屏处理,14:22:30 完成逛街倒计时后关闭,14:22:39 点击直接领取,14:22:43 进入下一轮。`dumpsys power` 确认 AutoJs6 的 SCREEN_BRIGHT_WAKE_LOCK 生效。未等待本日所有任务全部结束,商城结束后的复查由离线行为测试覆盖。手机脚本目录和 Download 两份均已同步并校验。 diff --git a/qimao_auto/qimao-daily.auto.js b/qimao_auto/qimao-daily.auto.js new file mode 100644 index 0000000..54b04b4 --- /dev/null +++ b/qimao_auto/qimao-daily.auto.js @@ -0,0 +1,1323 @@ +"auto"; +// 七猫免费小说:福利中心 → 吃饭补贴 → 逛街赚金币 → 逛商城赚金币。 +// 无障碍 + 手机内存中的本地OCR,不上传或导出图片。 +var CONFIG = { + version:"2026-10-21-qimao-12", packageName:"com.kmxs.reader", rewardThreshold:500, + pollMs:1200, pageTimeoutMs:8000, videoTimeoutMs:180000, maxVideos:15, + stepTimeoutMs:240000, taskSearchScrolls:16, recognitionTimeoutMs:15000, + captureRecoveryLimit:2, capturePermissionTimeoutMs:60000, useLocalOcr:true, + mealSessionTimeoutMs:1800000, browseCycleTimeoutMs:240000, + logPath:"/sdcard/Download/qimao-daily-run.log", pageTextPath:"/sdcard/Download/qimao-daily-page.json" +}; +var localOcrEnabled=false, commonHandling=false, actionSerial=0; +var captureQueue=null, captureWorker=null, captureRecoveries=0; +var flipSettlementDone=false, flipActionDone=false; +var nextScreenKeepAliveAt=0; +var MEAL_PAGE=/吃饭补贴|饭点.*补贴/; +var STREET_LABEL=/^逛[街衛衔][赚賺嫌]金[币市]/; +var MALL_LABEL=/^逛商城[赚賺嫌]金[币市]/; +function writeRunLog(message) { + var line = new Date().toISOString() + " " + message; + log(line); + files.append(CONFIG.logPath, line + "\n"); +} +function keepScreenAwake() { + if(typeof device.keepScreenOn!=="function" || Date.now() 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 (!requestScreenCapture(false)) stopWith("未获得本机截屏权限;无需上传图片。"); + localOcrEnabled = true; + }); +} + +function isProjectionFailure(error) { + return /MediaProjection|VirtualDisplay|resultData|projection instance|Failed to capture screen|截图通道不可用/.test(String(error)); +} + +function readPage(name) { + try { + return captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot); + } catch (error) { + if (error.unsafeWorker || !isProjectionFailure(error)) throw error; + if (captureRecoveries >= CONFIG.captureRecoveryLimit) { + error.captureFatal = true; + writeRunLog("截图通道连续失效,结束本次运行;不能将识别故障当作类目缺失。"); + throw error; + } + captureRecoveries++; + writeRunLog("CAPTURE RECOVER: " + captureRecoveries + "/" + CONFIG.captureRecoveryLimit + ";释放失效投影并重新申请本机截屏。"); + try { + captureCall("恢复截图授权", CONFIG.capturePermissionTimeoutMs, function () { + images.stopScreenCapture(); + if (!requestScreenCapture(false)) throw new Error("恢复截图授权未获允许"); + sleep(500); + }); + var page = captureCall("恢复后重新识别", CONFIG.recognitionTimeoutMs, readSnapshot); + writeRunLog("CAPTURE RECOVERED: 本机页面识别已恢复。"); + return page; + } catch (recoveryError) { + recoveryError.captureFatal = true; + throw recoveryError; + } + } +} + +function flipPopupHasAction(items) { return false; } + +function isPopupAction(item) { + return isCenteredPopupItem(item) && /^[||]?(?:立即[领颌颁頒]取|领取奖励|开心收下|确认|继续领金币|[领颌]更多金币|看视频领取|立即阅读|领\d+金币吃饭补贴)$/.test(item.text); +} + +// 只在手机当前帧采样按钮文字周边背景,不上传像素或图片。 +function isDarkButton(frame, item) { + var rect = item.rect; + var values = []; + for (var x = 0; x < 5; x++) { + for (var y = 0; y < 2; y++) { + var px = Math.round(rect.left + (rect.right - rect.left) * (x + 0.5) / 5); + var py = Math.round(y ? rect.bottom - 2 : rect.top + 2); + var color = images.pixel(frame, px, py); + values.push(0.2126 * colors.red(color) + 0.7152 * colors.green(color) + 0.0722 * colors.blue(color)); + } + } + values.sort(function (a, b) { return a - b; }); + return values[Math.floor(values.length / 2)] < 190; +} + +function singleButtonPopupDecision(items) { + if (flipPopupHasAction(items)) return null; + if (first(items, /签到/, isCenteredPopupItem)) return null; + var heading = first(items, /^(?:[.,,。||]*恭喜|[.,,。||]*一共[赢贏]取|今日签到|签到奖励|额外奖励|领取成功|奖励已到账|再看.*(?:视频|秒)|获得奖励)/, isCenteredPopupItem); + var popupFrame = first(items, /^(?:common-info-modalbackground|common-info-modal-background)$/); + if (!heading && popupFrame) heading = first(items, /金币|奖励|签到/, function (item) { + return item.rect.top >= popupFrame.rect.top && item.rect.bottom <= popupFrame.rect.bottom; + }); + if (!heading) heading = first(items, /^\d+(?:,\d{3})*(?:金币)?$/, isCenteredPopupItem); + if (!heading) return null; + var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + var center = (item.rect.left + item.rect.right) / 2; + return center >= device.width * 0.2 && center <= device.width * 0.8 && + item.rect.top >= heading.rect.bottom && item.rect.bottom <= device.height * 0.92; + }); + // 广告创意会绘制仿奖励弹窗;无真实弹窗边框或中央关闭时,不能用正文打断广告倒计时。 + if ((isAdvertisementPage(items) || countdown(items)) && !popupFrame && !close) return null; + // 必须有前景弹窗证据,避免取背景任务行的立即领取。 + if (!close && !rewardReceiptHeading(items) && !findFlipSettlementHeading(items)) return null; + var buttons = matches(items, {test: function () { return true; }}, function (item) { + return isPopupAction(item) && item.rect.top >= heading.rect.bottom && + item.rect.top < heading.rect.bottom + device.height * 0.5; + }); + if (buttons.length !== 1) return null; + if (first(items, /^[||]?(?:坚持退出|退出|取消|暂不使用)$/, isCenteredPopupItem)) return null; + var button = buttons[0]; + // 若还存在带金额的操作选项,则不是单按钮弹窗。 + if (first(items, /^[||]?(?:领|看视频(?:再得|再领|领))\d+(?:,\d{3})*金币$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + })) return null; + var amounts = []; + items.forEach(function (item) { + if (item.rect.top < heading.rect.top || item.rect.bottom > button.rect.top || + !isCenteredPopupItem(item) || /最高|量高|最多|上限|余额|累计|7天签到必得/.test(item.text)) return; + var re = /(\d+(?:,\d{3})*)金币/g; + var match; + while ((match = re.exec(item.text)) !== null) { + var amount = Number(match[1].replace(/,/g, "")); + if (amounts.indexOf(amount) < 0) amounts.push(amount); + } + if (/^\d+(?:,\d{3})*$/.test(item.text) && first(items, /^金币$/, function (unit) { + return isCenteredPopupItem(unit) && Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08; + })) { + var split = Number(item.text.replace(/,/g, "")); + if (amounts.indexOf(split) < 0) amounts.push(split); + } + }); + var take = amounts.length === 1 && amounts[0] >= CONFIG.rewardThreshold && button.darkButton === true; + return {button: take ? button : close, amount: amounts.length === 1 ? amounts[0] : null, + take: take, settlement: !!findFlipSettlementHeading(items)}; +} + +function findListeningPopupClose(items) { + var heading = first(items, /听读/, isCenteredPopupItem); + if (!heading) return null; + var listening = first(items, /^(?:立即听读|去听读|继续听读)$/, isCenteredPopupItem); + if (!listening) return null; + return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= listening.rect.bottom; + }); +} + +function findPlaybackPopupDismiss(items) { + if (!first(items, /悬浮窗播放功能|退出直播间后也能继续观看/, isCenteredPopupItem)) return null; + return first(items, /^暂不使用(?:按钮)?$/, isCenteredPopupItem); +} + +function liveExitAction(items) { + var dismiss = findPlaybackPopupDismiss(items); + if (dismiss) return {button: dismiss, reason: "不使用直播悬浮窗"}; + var confirmation = first(items, /(?:确定|确认|是否|即将).*?(?:退出|离开).*?直播|退出直播间后|离开直播间后/); + var exit = first(items, /^(?:退出直播间|离开直播间|退出直播|确认退出|确定退出|立即退出|退出|离开)$/, + isCenteredPopupItem); + if (exit && (confirmation || first(items, /^(?:继续观看|继续看直播|留在直播间)$/))) { + return {button: exit, reason: "确认退出直播间"}; + } + // 用直播间自身控件判定,不能仅因任务列表或广告文案提及“直播”就返回。 + var room = first(items, /本场点赞|在线观众/, function (item) { + return item.rect.top < device.height * 0.2; + }) || first(items, /^(?:[·「|]?更多直播[>〉]?|[·]?左滑查看更多直播)$/); + var chat = first(items, /^说点什么$/) && first(items, /^(?:礼物|连线|商品列表|粉丝团)$/); + if (room || chat) return {back: true, reason: "已进入直播页面,立即返回"}; + return null; +} + +function isAdvertisementPage(items) { + return !!first(items, /^(?:广告(?:[|!!1ご))((].*)?|.*直播间)$/, function (item) { + return item.rect.top < device.height * 0.15; + }); +} + +function findVideoSurveyDismiss(items) { + if (!first(items, /刚才的视频你觉得如何|评价有助于我们做得更好/)) return null; + return first(items, /^我知道了$/, isCenteredPopupItem); +} + +function needsCommonHandling(items) { + if (findQimaoDirectClaim(items)) return true; + if (isMallPage(items)) return false; // 商品文案和红包由商城循环处理。 + if (isWelfarePage(items) || isMealPage(items)) { + return !!(findSignInPopupClose(items) || findVideoSurveyDismiss(items) || findQimaoPopupClose(items) || rewardReceiptHeading(items)); + } + return !!(isStreetScrollAd(items) || liveExitAction(items) || countdown(items) || isAdvertisementPage(items) || findTopRightClose(items) || findVideoSurveyDismiss(items) || singleButtonPopupDecision(items) || findRewardReceiptClose(items) || findMoreCoinsButton(items) || offerAmount(items)); +} + +function snapshot() { + var page = readPage("页面识别"); + var deadline = Date.now() + CONFIG.stepTimeoutMs; + while (!commonHandling && needsCommonHandling(page)) { + if (Date.now() >= deadline) stopWith("通用页面处理超时,保留当前页面"); + writeRunLog("通用规则优先:暂停当前任务,先处理倒计时、关闭或额外奖励。"); + handleVideos(/./); + page = readPage("通用处理后重新识别"); + // 广告切换或弹窗动画中关闭按钮可能晚一帧出现;重新执行通用规则,不能全局退出。 + } + return page; +} + +// 小号X常被整屏OCR漏掉;只在手机内存裁剪放大右上区域再识别。 +function readCloseRegion(frame, items, region) { + var left = region ? region.left : Math.floor(device.width * 0.55); + var top = region ? region.top : Math.floor(device.height * 0.045); + var width = region ? region.width : device.width - left; + var height = region ? region.height : Math.floor(device.height * 0.22); + var crop = null; + var enlarged = null; + try { + crop = images.clip(frame, left, top, width, height); + enlarged = images.resize(crop, [width * 3, height * 3]); + var results = $ocr.detect(enlarged); + if (!Array.isArray(results)) return; + for (var i = 0; i < results.length; i++) { + var raw = results[i].bounds; + if (!raw) continue; + function at(key) { return Number(typeof raw[key] === "function" ? raw[key]() : raw[key]); } + var rect = rectOf({left: left + at("left") / 3, top: top + at("top") / 3, + right: left + at("right") / 3, bottom: top + at("bottom") / 3}); + var value = compact(results[i].text); + if (rect && /^(?:关闭|关闭广告|[xX×✕✖✗✘]|(?:领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕])$/.test(value)) { + items.push({text: /^[xX×✕✖✗✘]$/.test(value) ? "X" : value, rect: rect, node: null}); + writeRunLog("局部放大识别关闭:" + value + " @" + Math.round(rect.left) + "," + Math.round(rect.top)); + } + } + } finally { + if (enlarged) enlarged.recycle(); + if (crop) crop.recycle(); + } +} + +function readReceiptCloseRegion(frame, items) { + var heading=rewardReceiptHeading(items); + if(!heading || findQimaoDirectClaim(items) || findQimaoPopupClose(items))return; + // 七猫的关闭X在领取层右上方,可能高于标题;仅对已确认的奖励层局部放大。 + var upper=Math.max(Math.floor(device.height*0.18),Math.floor(heading.rect.top-device.height*0.18)); + readCloseRegion(frame,items,{left:Math.floor(device.width*0.72),top:upper, + width:Math.floor(device.width*0.21),height:Math.floor(heading.rect.bottom+device.height*0.04)-upper}); + if(findQimaoPopupClose(items))return; + var action=first(items,/^看(?:小)?视频.*最高(?:可)?(?:再)?领(?:\d+金[币市而])?$/,isCenteredPopupItem); + if(!action)return; + var top=Math.floor(action.rect.bottom),bottom=Math.floor(device.height*0.92); + if(top= device.width * 0.55 && + item.rect.top < device.height * 0.30; +} + +function originalAdCountdown(items) { + return first(items, /(?:\d+(?:\.\d+)?(?:s|S|秒)|倒计时\d*|\d+后(?:关闭|可关闭|领取|可领取))/, function (item) { + if (!isTopRight(item)) return false; + // 广告侧栏“60秒/已完成/点击领取”是完成的时长档位,不是待关闭倒计时。 + var completedMilestone = /^\d+(?:s|S|秒)$/.test(item.text.replace(/[^\dA-Za-z\u4e00-\u9fff]/g, "")) && first(items, /^已完成$/, function (label) { + return label.rect.top >= item.rect.bottom && + label.rect.top - item.rect.bottom < device.height * 0.06 && + Math.abs(label.rect.left - item.rect.left) < device.width * 0.08; + }); + return !completedMilestone; + }); +} + +function findTopRightClose(items) { + var mainNavigation = bottomNavigation(items, /^(?:首页|书城)$/) && bottomNavigation(items, /^赚钱$/); + var advertisement = isAdvertisementPage(items); + // 首页浮层的无障碍Close Button是真实控件,优先于图片内局部OCR疑似X。 + // 现场该关闭在右侧中部,不能只因不在顶端而忽略,随后误点书籍内容。 + if (!advertisement && mainNavigation) { + var nativeClose = first(items, /^(?:关闭|关闭广告|关闭窗口|关闭弹窗)$/, function (item) { + return !!item.node && (item.rect.left + item.rect.right) / 2 > device.width * 0.85 && + item.rect.top < device.height * 0.7 && item.rect.right - item.rect.left < device.width * 0.2 && + item.rect.bottom - item.rect.top < device.height * 0.12; + }); + if (nativeClose) return nativeClose; + } + var close = first(items, /^(关闭|关闭广告|[xX×✕])$/, function (item) { + if (!isTopRight(item)) return false; + // OPPO首页书封被局部放大OCR识别成7×10像素的X,点击实际会打开书。 + // 仅排除主导航页中尺寸不足的OCR单字形;原生关闭、明确关闭文案和广告规则保留。 + return !(mainNavigation && !advertisement && !item.node && /^[xX×✕]$/.test(item.text) && + (item.rect.right - item.rect.left < device.width * 0.012 || + item.rect.bottom - item.rect.top < device.height * 0.008)); + }); + if (close) return close; + var merged = first(items, /^(领取成功|奖励已到账|已获得奖励|已获得\d+金币)[xX×✕]$/, isTopRight); + if (!merged) return null; + // OCR 将状态和 X 合框时,只取末尾关闭字形所在区域,不点击状态文字中心。 + var rect = merged.rect; + var glyphWidth = (rect.right - rect.left) / merged.text.length; + return {text: "关闭(" + merged.text + ")", node: null, rect: { + left: rect.right - glyphWidth, right: rect.right, top: rect.top, bottom: rect.bottom + }}; +} + +// 奖励到账确认是前景弹窗,不能被背景任务、倒计时或领取入口抢占。 +function isCenteredPopupItem(item) { + var center = (item.rect.left + item.rect.right) / 2; + return center >= device.width * 0.2 && center <= device.width * 0.8 && + item.rect.top >= device.height * 0.20 && item.rect.top < device.height * 0.82; +} + +function findFlipSettlementHeading(items) { return null; } + +function findFlipSettlementButton(items) { return null; } + +function findMoreCoinsButton(items) { + return first(items, /^[领颌]更多金币$/, isCenteredPopupItem); +} + +function rewardReceiptHeading(items) { + return first(items,/^(?:恭喜(?:你)?(?:已)?(?:累计)?获得(?:奖励)?|恭喜你|获得(?:早餐|早饭|午饭|午餐|晚饭|晚餐|夜宵)补贴)$/,isCenteredPopupItem); +} + +function findReceiptEligibleClaim(items) { + var heading = rewardReceiptHeading(items); + if (!heading) return null; + return first(items, /^(?:领|看视频(?:再得|再领|领))\d+金币$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom && + Number(item.text.replace(/[^\d]/g, "")) >= CONFIG.rewardThreshold; + }); +} + +function findRewardReceiptClose(items) { + if (flipPopupHasAction(items)) return null; + if (findFlipSettlementHeading(items) || findMoreCoinsButton(items)) return null; + var heading = rewardReceiptHeading(items); + if (!heading) return null; + if (findReceiptEligibleClaim(items)) return null; + var close = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + }); + if (close) return close; + // 透明弹窗下方的 X 可能与背景文字合框,只提取末尾字形,不点整段文字。 + var merged = first(items, /[xX×✕]$/, function (item) { + var glyphWidth = (item.rect.right - item.rect.left) / item.text.length; + var glyphCenter = item.rect.right - glyphWidth / 2; + return item.rect.top >= heading.rect.bottom && item.rect.top > device.height * 0.45 && + item.rect.top < device.height * 0.92 && glyphCenter > device.width * 0.35 && glyphCenter < device.width * 0.65; + }); + if (!merged) return null; + var width = (merged.rect.right - merged.rect.left) / merged.text.length; + return {text: "关闭奖励弹窗(" + merged.text + ")", node: null, rect: { + left: merged.rect.right - width, right: merged.rect.right, + top: merged.rect.top, bottom: merged.rect.bottom + }}; +} + +function findEmptyRewardPopupClose(items, ignoreCoinClaim) { + // 前景现金邀请提示不属于金币领取;背景任务行的金币不能阻止关闭。 + var cashHeading = first(items, /^送你现金红包$/, isCenteredPopupItem); + if (cashHeading && (first(items, /^邀[请靖]好友立得$/, isCenteredPopupItem) || + first(items, /^\d+(?:\.\d+)?元$/, isCenteredPopupItem))) { + var cashClose = first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + var center = (item.rect.left + item.rect.right) / 2; + return center >= device.width * 0.35 && center <= device.width * 0.65 && + item.rect.top >= cashHeading.rect.bottom && item.rect.bottom <= device.height * 0.92; + }); + if (cashClose) return cashClose; + } + // 中央活动提示没有金币领取入口,只关闭遮挡层,不执行邀请或参与。 + var participation = first(items, /^立即参与$/, isCenteredPopupItem); + if (participation) { + var participationClose = first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= participation.rect.bottom; + }); + if (participationClose) return participationClose; + } + // 翻卡操作弹窗不是空奖励弹窗;背景“完成阅读任务…奖励”等说明不能触发关闭。 + if (flipPopupHasAction(items)) return null; + // 非右上角的 X 需要弹窗文字作依据,不能把普通页面上的 X 当作奖励弹窗。 + var heading = first(items, /弹窗|温馨提示|签到|领取成功|恭喜|奖励|再看.*视频|暂无金币|暂无奖励|明日再来|今日已领/); + if (!heading) return null; + // 7天签到累计总额不是本次立即领取金额;关闭遮挡任务列表的无明确金币领取弹窗。 + var weekly = first(items, /^7天签到必得[\d.万亿]+金币$/, isCenteredPopupItem); + if (weekly && !first(items, /^(?:领\d+金币|看视频领\d+金币)$/)) { + var weeklyClaim = first(items, /^立即[领颌]取$/, isCenteredPopupItem); + var weeklyClose = weeklyClaim && first(items, /^(?:关闭|关闭弹窗|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top > weeklyClaim.rect.bottom; + }); + if (weeklyClose) return weeklyClose; + } + var claim = first(items, /^(?:立即[领颌]取|领更多金币|领取奖励|看视频领取|领\d+金币|看视频(?:再得|再领|领)\d+金币)$/, + function (item) { return item.rect.top >= heading.rect.top; }); + if (claim && !ignoreCoinClaim) return null; + return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return item.rect.top >= heading.rect.top && item.rect.top < device.height * 0.92; + }); +} + +function findCoinChoiceClaim(items) { + if (first(items, /签到/, isCenteredPopupItem)) return null; + var heading = first(items, /请选择宝箱奖励|开宝箱奖励|再看.*(?:视频|秒)|额外奖励|领取奖励|恭喜|一共.*金币/); + if (!heading) return null; + var marker = first(items, /^[||]?看视[频頻]奖励$/); + var candidates = matches(items, /^[||]?(?:选|领(?:取)?|直接领(?:取)?|看视频(?:再得|再领|领|得))(\d+(?:,\d{3})*)金币$/, function (item) { + return item.rect.top >= heading.rect.bottom && + item.rect.top < heading.rect.bottom + device.height * 0.55; + }); + if (!candidates.length) return null; + // 仅比较同一行的领取选项,不混入余额、标题金额或其他任务行。 + candidates.sort(function (a, b) { return a.rect.top - b.rect.top; }); + for (var i = 0; i < candidates.length; i++) { + var anchor = candidates[i]; + var row = candidates.filter(function (item) { + return Math.abs(item.rect.top - anchor.rect.top) < device.height * 0.04; + }); + if (row.length < 2) continue; + row.sort(function (a, b) { + var amountA = Number(a.text.replace(/[^\d]/g, "")); + var amountB = Number(b.text.replace(/[^\d]/g, "")); + return amountB - amountA || a.rect.left - b.rect.left; + }); + if (Number(row[0].text.replace(/[^\d]/g, "")) < CONFIG.rewardThreshold) row.reverse(); + return row[0]; + } + // 单选视频入口仍可使用明确的“看视频奖励”标签,不对多选位置作假设。 + if (marker) return first(candidates, /^[||]?领\d+(?:,\d{3})*金币$/, function (item) { + return Math.abs(item.rect.top - marker.rect.bottom) < device.height * 0.10; + }); + return null; +} + +function offerAmount(items) { + var heading = first(items, /再看(?:一个|1个|一段|1段)?视频|再[看香]\d+秒|看视频(?:再得|再领|领)\d+金币|看视频.*(?:最高可领|额外|奖励)|^(?:最高可领|最多可领)/, + function (item) { + // 福利列表的收益日报等说明含“看视频/奖励”,须有前景弹窗控件才作为追加奖励。 + if (isWelfarePage(items) && !rewardReceiptHeading(items) && !findMoreCoinsButton(items) && + !first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false; + // 广告右上角“再看19秒后得300金币X”是倒计时状态,不是前景追加奖励弹窗。 + if (isTopRight(item) && /\d+(?:\.\d+)?(?:s|S|秒)/.test(item.text)) return false; + // 补贴页常驻“看视频最高可领”说明不是独立弹窗。 + if (first(items, MEAL_PAGE) && /看视频.*最高可领/.test(item.text) && !rewardReceiptHeading(items) && + !first(items, /^[||]?(?:坚持退出|退出|取消)$/, isCenteredPopupItem)) return false; + return true; + }); + if (!heading) { + var claimAction = first(items, /^(?:继续领金币|领取奖励)$/, isCenteredPopupItem); + var exitAction = claimAction && first(items, /^[||]?坚持退出$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= claimAction.rect.bottom && + item.rect.top - claimAction.rect.bottom < device.height * 0.2; + }); + // 标题OCR缺失时,用同一前景层的领取/坚持退出组合确认挽留弹窗,金额不猜测。 + if (exitAction) return {amount: null, heading: claimAction}; + } + var moreButton = findMoreCoinsButton(items); + if (!heading && moreButton) { + var values = []; + var region = items.filter(function (item) { + return isCenteredPopupItem(item) && item.rect.top >= moreButton.rect.top - device.height * 0.4 && + item.rect.bottom <= moreButton.rect.bottom && + !/最高|最多|至多|上限|已获得|已领取|本次得|一共|余额|补贴|预约|签到/.test(item.text); + }); + region.forEach(function (item) { + var coins = /(\d+(?:,\d{3})*)金币/.exec(item.text); + var split = /^(\d+(?:,\d{3})*)[.。]?$/.exec(item.text); + if (!coins && split && !first(region, /^金币$/, function (unit) { + return Math.abs(unit.rect.top - item.rect.top) < device.height * 0.08; + })) split = null; + var match = coins || split; + if (match) { + var value = Number(match[1].replace(/,/g, "")); + if (values.indexOf(value) < 0) values.push(value); + } + }); + var top = Math.max(device.height * 0.2, moreButton.rect.top - device.height * 0.4); + return {amount: values.length === 1 ? values[0] : null, heading: { + text: "领更多金币弹窗", rect: {left: moreButton.rect.left, right: moreButton.rect.right, top: top, bottom: moreButton.rect.bottom} + }}; + } + if (!heading) return null; + // 明确写在额外奖励按钮里的金额优先,不能混入弹窗背后“已攒0金币”等文字。 + var explicit = /^看视频(?:再得|再领|领)(\d+)金币$/.exec(heading.text); + if (explicit) return {amount: Number(explicit[1]), heading: heading}; + if (/最高|量高|最多|至多|上限/.test(heading.text)) return {amount: null, heading: heading}; + // 只解析该提示附近的明确金额;“最高可领”是上限,不是已确认奖励。 + var nearby = items.filter(function (item) { + return item.rect.top >= heading.rect.top - 30 && + item.rect.top < heading.rect.bottom + device.height * 0.25; + }); + var amounts = []; + for (var i = 0; i < nearby.length; i++) { + if (/最高|最多|至多|上限|补贴|已获得|已领取|领取成功|恭喜/.test(nearby[i].text)) continue; + var amountPattern = /(?:^|[^\d.,])([\d]+(?:,[\d]{3})*)(?:个)?金币/g; + var match; + while ((match = amountPattern.exec(nearby[i].text)) !== null) { + var amount = Number(match[1].replace(/,/g, "")); + if (amounts.indexOf(amount) < 0) amounts.push(amount); + } + } + if (amounts.length !== 1) return {amount: null, heading: heading}; + return {amount: amounts[0], heading: heading}; +} + +function handleVideos(returnPattern, launchGraceMs) { + var previous = commonHandling; + commonHandling = true; + try { return handleVideosLoop(returnPattern, launchGraceMs); } + finally { commonHandling = previous; } +} + +function handleVideosLoop(returnPattern, launchGraceMs) { + var launchDeadline = Date.now() + (launchGraceMs || 0); + var deadline = Date.now() + CONFIG.videoTimeoutMs; + var accepted = 0; + var stableReturn = 0; + var actions = 0; + var sawCountdown = false; + var lastWaitLog = 0; + var lastCloseKey = ""; + var repeatedClose = 0; + var liveExitAttempts = 0; + var qimaoMissingClose = 0; + while (Date.now() < deadline) { + var items = snapshot(); + var qimaoDirect = findQimaoDirectClaim(items); + if (qimaoDirect) { + if (++actions > CONFIG.maxVideos * 4) stopWith("七猫直接领取弹窗多次未响应"); + writeRunLog("七猫奖励确认:点击直接领取,不选择最高金额的视频推广选项。"); + tap(qimaoDirect); + continue; + } + if (isMallPage(items)) return; + if(isStreetScrollAd(items)){writeRunLog("STREET RESUME: 处理右下角计时的下滑浏览广告。");finishStreetVisit();continue;} + if (isWelfarePage(items) || isMealPage(items)) { + var qimaoClose=findQimaoPopupClose(items) || findSignInPopupClose(items); + if(qimaoClose) { if(++actions>20) stopWith("七猫弹窗关闭多次未响应"); tap(qimaoClose); continue; } + if(rewardReceiptHeading(items)) { + var earnedClaim=findReceiptEligibleClaim(items); + if(earnedClaim){if(++actions>20)stopWith("七猫奖励按钮未响应");tap(earnedClaim);continue;} + if(++qimaoMissingClose<2){sleep(CONFIG.pollMs);continue;} + if(++actions>20)stopWith("七猫奖励弹窗返回关闭未响应"); + writeRunLog("QIMAO RECEIPT BACK: 已确认任务到账弹窗,无符合领取按钮,关闭图标未识别,返回关闭后复查。"); + back();actionSerial++;sleep(CONFIG.pollMs);qimaoMissingClose=0;continue; + } + if(Date.now() CONFIG.maxVideos * 4) stopWith("视频反馈提示关闭未响应"); + writeRunLog("视频反馈提示:点击我知道了关闭提示,继续当前任务。"); + tap(surveyDismiss); + continue; + } + var signClose = findSignInPopupClose(items); + if (signClose) { + if (++actions > CONFIG.maxVideos * 4) stopWith("签到遮挡弹窗关闭未响应"); + writeRunLog("签到流程已移除:关闭签到弹窗,继续当前流程。"); + tap(signClose); + continue; + } + var liveExit = liveExitAction(items); + if (liveExit) { + if (++liveExitAttempts > 6) stopWith("连续六次退出直播仍未离开,跳过本步骤并保留现场"); + writeRunLog("直播退出优先:" + liveExit.reason + ";不等待直播倒计时,不领取直播奖励。"); + if (liveExit.button) tap(liveExit.button); + else { + if (back() === false) stopWith("退出直播的返回键执行失败"); + actionSerial++; + sleep(CONFIG.pollMs); + } + continue; + } + liveExitAttempts = 0; + // 重试保护只计算按钮持续存在时的连续失败;新倒计时或按钮消失说明页面已推进。 + // 不可把不同广告在同一坐标的X累计为同一按钮未响应。 + var observedClose = findTopRightClose(items) || findEmptyRewardPopupClose(items); + if (countdown(items) || !observedClose) { + lastCloseKey = ""; + repeatedClose = 0; + } + var listeningClose = findListeningPopupClose(items); + if (listeningClose) { + if (++actions > CONFIG.maxVideos * 4) stopWith("听读弹窗关闭未响应"); + writeRunLog("听读选项已取消:直接关闭听读弹窗,不点击听读按钮。"); + tap(listeningClose); + continue; + } + var signClaim = findCoinChoiceClaim(items); + if (signClaim) { + if (++actions > CONFIG.maxVideos * 4) stopWith("金币选项多次点击无响应,跳过本步骤"); + writeRunLog("通用双金额规则:有>=500选较大,否则选最小;本次 " + signClaim.text); + tap(signClaim); + continue; + } + var singleDecision = singleButtonPopupDecision(items); + if (singleDecision) { + if (!singleDecision.button) stopWith("单按钮弹窗不符合领取条件,但尚未识别到关闭按钮,保留页面重查"); + if (++actions > CONFIG.maxVideos * 4) stopWith("单按钮弹窗处理达到上限"); + writeRunLog("通用单按钮规则:正文金币=" + singleDecision.amount + ";" + (singleDecision.take ? "点击深色按钮" : "关闭弹窗")); + tap(singleDecision.button); + if (singleDecision.settlement) { flipSettlementDone = true; flipActionDone = true; } + continue; + } + var settlement = findFlipSettlementButton(items); + if (settlement) { + if (++actions > CONFIG.maxVideos * 4) stopWith("翻卡结算按钮多次未响应"); + writeRunLog("翻卡结算:点击开心收下,完成翻卡流程。"); + tap(settlement); + flipSettlementDone = true; + flipActionDone = true; + continue; + } + if (findFlipSettlementHeading(items)) stopWith("未识别到翻卡结算的开心收下按钮,等待重新识别"); + var receipt = findRewardReceiptClose(items); + if (receipt) { + if (++actions > CONFIG.maxVideos * 4) stopWith("奖励确认多次点击未响应"); + writeRunLog("通用规则:奖励弹窗没有金币领取按钮,点击关闭"); + tap(receipt); + continue; + } + var eligibleClaim = findReceiptEligibleClaim(items); + // 广告正文也会显示“恭喜获得/金币”;只有实际领取入口才进入领取分支。 + // 缺少入口时继续判断倒计时和右上关闭,不能让背景文案中断通用处理。 + if (eligibleClaim && !findMoreCoinsButton(items)) { + if (++actions > CONFIG.maxVideos * 4 || accepted >= CONFIG.maxVideos) stopWith("奖励弹窗处理达到上限"); + writeRunLog("通用规则:奖励按钮金额大于500金币,点击领取"); + tap(eligibleClaim); + accepted++; + continue; + } + var offer = offerAmount(items); + if (offer && (!flipPopupHasAction(items) || offer.amount >= CONFIG.rewardThreshold)) { + stableReturn = 0; + if (++actions > CONFIG.maxVideos * 4) stopWith("弹窗处理次数达到上限,页面可能没有响应,已停止。"); + var take = offer.amount !== null && offer.amount >= CONFIG.rewardThreshold; + var button = first(items, take ? /^(领取奖励|领更多金币|颌更多金币|确认|继续领金币|看视频领取|看视频领\d+金币|看视频(?:再得|再领|领)\d+金币)$/ : /^[||]?(坚持退出|退出|[xX×✕])$/, + function (item) { return item.rect.top >= offer.heading.rect.top && + item.rect.top < offer.heading.rect.bottom + device.height * 0.30; }); + if (!button && !take) button = findEmptyRewardPopupClose(items, true); + if (!button) stopWith("未识别到额外奖励的" + (take ? "确认" : "退出") + "按钮,已停止。"); + if (take && accepted >= CONFIG.maxVideos) stopWith("已达到本次视频数量上限,停止继续领取。"); + writeRunLog("额外奖励 " + (offer.amount === null ? "金额不明确" : offer.amount + " 金币") + ":" + (take ? "继续观看" : "退出")); + tap(button); + if (take) { accepted++; sawCountdown = false; } + deadline = Date.now() + CONFIG.videoTimeoutMs; + continue; + } + var popupClose = findEmptyRewardPopupClose(items); + var foregroundClose = popupClose && !isTopRight(popupClose) ? popupClose : null; + // 前景弹窗的动作先处理,背景倒计时和背景右上X不能抢占。 + var timer = foregroundClose ? null : countdown(items); + if (timer) { + if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) { + writeRunLog("通用规则等待倒计时:" + timer.text); + lastWaitLog = Date.now(); + } + sawCountdown = true; + stableReturn = 0; + sleep(CONFIG.pollMs); + continue; + } + if (flipPopupHasAction(items) && !findTopRightClose(items) && !foregroundClose) { + writeRunLog("翻卡优先:仍有带翻字的按钮,不执行通用弹窗关闭,继续翻卡。"); + return; + } + var close = foregroundClose || findTopRightClose(items) || popupClose; + if (close) { + if (++actions > CONFIG.maxVideos * 4) stopWith("关闭次数达到上限,页面可能没有响应,已停止。"); + stableReturn = 0; + // 再取一次本机页面,避免倒计时刚刷新时点到关闭。 + sleep(CONFIG.pollMs); + var fresh = snapshot(); + if (liveExitAction(fresh)) continue; + if (flipPopupHasAction(fresh) && !findTopRightClose(fresh) && !findEmptyRewardPopupClose(fresh)) continue; + if (findRewardReceiptClose(fresh) || offerAmount(fresh) || findCoinChoiceClaim(fresh)) continue; + var freshPopupClose = findEmptyRewardPopupClose(fresh); + var freshForegroundClose = freshPopupClose && !isTopRight(freshPopupClose) ? freshPopupClose : null; + if (!freshForegroundClose && countdown(fresh)) { sawCountdown = true; continue; } + close = freshForegroundClose || findTopRightClose(fresh) || freshPopupClose; + if (close) { + var closeKey = close.text + ":" + Math.round(close.rect.left / 20) + ":" + Math.round(close.rect.top / 20); + repeatedClose = closeKey === lastCloseKey ? repeatedClose + 1 : 1; + lastCloseKey = closeKey; + if (repeatedClose > 3) stopWith("同一关闭按钮连续三次未响应,跳过本步骤"); + tap(close); + } + continue; + } + if (isAdvertisementPage(items)) { + if (!lastWaitLog || Date.now() - lastWaitLog >= 15000) { + writeRunLog("广告仍在前台,等待倒计时/关闭控件刷新,不把背景任务判为缺失。"); + lastWaitLog = Date.now(); + } + sleep(CONFIG.pollMs); + continue; + } + // 广告可能在点击领取数秒后才出现;启动宽限期内继续识别,避免提前结束。 + if (Date.now() < launchDeadline) { sleep(CONFIG.pollMs); continue; } + // 无倒计时、无关闭、无额外奖励就交还调度,不等待旧的返回页标签。 + writeRunLog("通用规则:当前无可执行条件,继续下一步骤。"); + return; + } + stopWith("等待视频结束或目标页面超时,已停止;未用返回键跳过倒计时。"); +} + +function bottomNavigation(items, pattern) { + return first(items, pattern, function (item) { return item.rect.top > device.height * 0.9; }); +} + + +function findSignInPopupClose(items) { + if (flipPopupHasAction(items)) return null; + var heading = first(items, /签到/, isCenteredPopupItem); + if (!heading) return null; + return first(items, /^(?:关闭|关闭弹窗|关闭窗口|[xX×✕])$/, function (item) { + return isCenteredPopupItem(item) && item.rect.top >= heading.rect.bottom; + }); +} + +function searchTaskAction(finder, actionName, relatedPattern, logPrefix) { + var entry = finder(snapshot()); + if (entry) return entry; + for (var direction = 0; direction < 2; direction++) { + var lastKey = ""; + var stationary = 0; + for (var i = 0; i < CONFIG.taskSearchScrolls; i++) { + var moved = swipe(Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.8 : 0.35)), + Math.round(device.width * 0.5), Math.round(device.height * (direction ? 0.35 : 0.8)), 450); + sleep(CONFIG.pollMs); + var page = snapshot(); + writeRunLog((logPrefix || "TASK SEARCH") + ": " + actionName + ";" + (direction ? "向下" : "向上") + (i + 1) + ";滑动=" + moved + ";相关文字=" + + matches(page, relatedPattern || /补贴|翻卡|海量|立即领取/).map(function (item) { return item.text; }).join("、")); + entry = finder(page); + if (entry) return entry; + var nativePage=page.filter(function(item){return !!item.node && item.text.length<60 && !/^[A-Za-z0-9_=+\/]{12,}$/.test(item.text);}); + var key = (nativePage.length ? nativePage : page).map(function (item) { + return item.text.replace(/\d+/g, "#") + ":" + Math.round(item.rect.top / 80); + }).sort().join("|"); + stationary = key === lastKey ? stationary + 1 : 0; + lastKey = key; + if (stationary >= 2) break; + } + } + return null; +} + + +function rawPage() { return readPage("七猫任务识别"); } +function tapKnown(item) { + var previous=commonHandling; commonHandling=true; + try { tap(item); } finally { commonHandling=previous; } +} +function topTab(items, name) { + return first(items, {test:function(t){return t===name;}}, function(i){return i.rect.top8) + return mall.rect.bottom-mall.rect.top>center.rect.bottom-center.rect.top; + return !!first(items,/^签到浏览商品可领|^成功浏览商城|^抖音商城推荐$/); +} + +function isWelfarePage(items) { + var center=topTab(items,"福利中心"), mall=topTab(items,"福利商城"); + if (!center || !bottomNavigation(items,/^福利$/) || isMallPage(items)) return false; + return !!(!mall || center.rect.bottom-center.rect.top>(mall.rect.bottom-mall.rect.top)*1.12 || + first(items,/^日常福利$|^吃饭补贴|^逛[街衛衔商城]+[赚賺嫌]金[币市]/)); +} +function isMealPage(items) { + if (bottomNavigation(items,/^福利$/)) return false; + return !!(first(items,/^领取(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)补贴/) || + (first(items,/^(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)$/) && first(items,/^看视频补领(?:一次补贴)?$|可领.*补贴|^吃饭补贴$/))); +} +function findQimaoDirectClaim(items) { + if (streetCountdown(items) || isAdvertisementPage(items)) return null; + var heading=first(items,/^(?:获得.*奖励|恭喜(?:你)?获得)/,isCenteredPopupItem); + if (!heading) return null; + var buttons=matches(items,/^直[接援]领取$/,function(i){return isCenteredPopupItem(i)&&i.rect.top>heading.rect.bottom;}); + buttons.sort(function(a,b){return b.rect.top-a.rect.top;}); + return buttons.length ? buttons[0] : null; +} +function findQimaoPopupClose(items) { + var heading=first(items,/^(?:恭喜|获得.*奖励|温馨提示|今日签到|签到奖励)/,isCenteredPopupItem); + if (!heading || findQimaoDirectClaim(items)) return null; + return first(items,/^(?:关闭|关闭弹窗|[xX×✕])$/,function(i){ + return i.rect.top>=heading.rect.top-device.height*0.18 && i.rect.topdevice.width*0.15 && i.rect.rightdevice.width*0.75&&i.rect.top>device.height*0.65&&i.rect.bottomdevice.width*0.75&&i.rect.top>device.height*0.65&&i.rect.bottomdevice.width*0.78 && i.rect.top>device.height*0.55 && i.rect.bottomdevice.width*0.78 && i.rect.top>device.height*0.55 && i.rect.bottomheading.rect.bottom&&i.rect.topdevice.height*0.10&&i.rect.bottomdevice.height*0.72 || button.rect.topdevice.height*0.72; + writeRunLog("TASK CENTER: "+name+"入口靠近屏幕边缘,滑到中部后重新识别,避开浮动宝箱。"); + swipe(Math.round(device.width*0.45),Math.round(device.height*(low?0.78:0.32)),Math.round(device.width*0.45),Math.round(device.height*(low?0.48:0.56)),450); + sleep(CONFIG.pollMs); + button=taskRowButton(snapshot(),labelPattern,actionPattern); + } + return {labelFound:seen,button:button}; +} +function mealClaimKey(item) { var name=item.text.replace(/^[||]/, "").replace(/\d+金[币市]$/, ""); return name+(/^领取/.test(name)?":main":":"+Math.round((item.rect.left+item.rect.right)/160)); } +function findQimaoMealClaim(items, unavailable) { + if(!isMealPage(items))return null; + function available(i){return !unavailable[mealClaimKey(i)];} + return first(items,/领一次补贴$/,available) || + first(items,/^领取(?:早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵)补贴(?:\d+金[币市])?$/,available) || + first(items,/^[||]?看视频补领$/,available); +} +function findMealEntry(items) { + return first(items,/^吃饭补贴$/,function(i){return i.rect.top>device.height*0.10 && i.rect.top=3){unavailable[key]=true;writeRunLog("MEAL UNAVAILABLE: 同一补贴按钮三次未消失,本轮跳过并查其他补贴。");continue;} + repeats[key]=(repeats[key]||0)+1; + writeRunLog("MEAL CLAIM: "+claim.text+";本位置第"+repeats[key]+"次"); + var beforeClaim=actionSerial; + tapKnown(claim); + handleVideos(MEAL_PAGE,10000); + if(actionSerial>beforeClaim+1)repeats[key]=0; // 广告关闭或奖励处理说明已推进,不累计为未响应重试。 + } + stopWith("吃饭补贴达到异常保护时限,保留现场"); +} +function finishStreetVisit() { + var until=Date.now()+CONFIG.browseCycleTimeoutMs,lastLog=0; + while(Date.now()15000){writeRunLog("STREET WAIT: "+timer.text+(isStreetScrollAd(page)?";下滑浏览推进计时":""));lastLog=Date.now();} + if(isStreetScrollAd(page))swipe(Math.round(device.width*0.45),Math.round(device.height*0.78),Math.round(device.width*0.45),Math.round(device.height*0.40),450); + sleep(CONFIG.pollMs);continue; + } + var done=streetFinished(page); + if(done) { + // X在倒计时期间也存在,必须先识别完成文案再允许关闭。 + var close=findStreetClose(page); + if(close){writeRunLog("STREET CLOSE: 完成标记="+done.text);tapKnown(close);} + else {writeRunLog("STREET BACK: 已确认获得奖励,关闭未识别,返回任务页。");back();sleep(CONFIG.pollMs);} + var returned=snapshot(); + if(isWelfarePage(returned))return true; + continue; + } + if(isWelfarePage(page)){snapshot();return true;} + sleep(CONFIG.pollMs); + } + stopWith("逛街倒计时或关闭超时,未用返回键跳过计时"); +} +function mallCycle() { + var until=Date.now()+CONFIG.browseCycleTimeoutMs,empty=0,claimedAt=0,lastLog=0,up=true; + while(Date.now()15000){writeRunLog("MALL WAIT: 右下角红包="+timer.text+";交替上下滑动。");lastLog=Date.now();} + swipe(Math.round(device.width*0.45),Math.round(device.height*(up?0.78:0.42)),Math.round(device.width*0.45),Math.round(device.height*(up?0.42:0.78)),450); + up=!up;sleep(CONFIG.pollMs);continue; + } + if(claimedAt && Date.now()-claimedAt<10000){sleep(CONFIG.pollMs);continue;} + empty++;writeRunLog("MALL EMPTY: 没有红包倒计时、领金币或继续逛商城,复查"+empty+"/2"); + if(empty>=2) { + var close=findQimaoPopupClose(page);if(close)tapKnown(close); + openWelfareCenter(false); + return {done:true}; + } + sleep(5000); + } + stopWith("商城单轮红包等待超时,保留现场,不继续点击商品"); +} +function runMallLoop() { + var rounds=0; + while(true) { + var result=runStep("商城红包第"+(rounds+1)+"轮",mallCycle,CONFIG.browseCycleTimeoutMs+5000); + if(!result.ok||result.skipped)return {ok:false}; + rounds++; + writeRunLog("MALL ROUND: 第"+rounds+"轮处理结束。"); + if(result.value.done){writeRunLog("MALL DONE: 没有下一步符合条件的红包或继续入口,已退出商城。");return {ok:true,rounds:rounds};} + } +} +function shoppingAction(mode, button) { + var before=rawPage(); + tapKnown(button); + var until=Date.now()+15000,responded=false; + while(Date.now()=2){writeRunLog("TASK UNAVAILABLE: 两次点击后没有页面或按钮变化,跳过当前任务以继续后续流程。");return {ok:false,skipped:true};} + writeRunLog("TASK RECHECK: "+name+"第"+rounds+"轮结束,重新查找同一任务标签和按钮。"); + } +} +function runDaily() { + files.write(CONFIG.logPath,""); + writeRunLog("START: version="+CONFIG.version+";七猫;仅手机本地识别。"); + var me=engines.myEngine();writeRunLog("SOURCE: "+me.getSource()); + engines.all().forEach(function(e){if(e.id!==me.id && /(?:fanqie-daily|hongguo-daily|qimao-(?:daily|inspect))\.auto\.js$/.test(String(e.getSource())))e.forceStop();}); + keepScreenAwake(); + var init=runStep("初始化本地OCR",initLocalOcr,CONFIG.capturePermissionTimeoutMs+5000); + if(!init.ok||!localOcrEnabled)stopWith("本地OCR未就绪"); + auto.waitFor(); + if(foregroundPackage()!==CONFIG.packageName&&!app.launchPackage(CONFIG.packageName))stopWith("无法打开七猫免费小说"); + sleep(CONFIG.pollMs); + var entered=runStep("底部福利与顶部福利中心",function(){openWelfareCenter(true);}); + if(!entered.ok||entered.skipped){writeRunLog("END: 福利中心导航未完成,保留现场与文字日志。");return;} + writeRunLog("FLOW: 福利中心 -> 吃饭补贴 -> 逛街赚金币循环 -> 逛商城赚金币红包循环。"); + var meal=runStep("吃饭补贴",qimaoMealStep,CONFIG.mealSessionTimeoutMs+5000); + if(!meal.ok&&!isWelfarePage(rawPage())){writeRunLog("END INCOMPLETE: 吃饭补贴异常且尚未返回福利中心,保留现场。");return;} + var street=runShoppingTask("street"); + if(!street.ok&&!isWelfarePage(rawPage())){writeRunLog("END: 逛街流程异常未返回福利中心,保留现场与文字日志。");return;} + var mall=runShoppingTask("mall"); + // 商城没有红包只代表商城结束。此前逛街可能被系统浮层打断,必须再查同一标签。 + var recheck=runStep("结束前复查逛街剩余入口",function(){ + openWelfareCenter(false); + return searchQimaoTask(STREET_LABEL,/逛|^领金[币市]$/,"复查逛街赚金币"); + }); + if(recheck.ok && !recheck.skipped && recheck.value.button) { + writeRunLog("FLOW RESUME: 商城结束后仍有逛街入口,继续剩余逛街与领取流程。"); + street=runShoppingTask("street"); + } else if(recheck.ok && !recheck.skipped) street={ok:true}; + else street={ok:false}; + writeRunLog(mall.ok && street.ok ? "END: 已配置流程执行结束,逛街入口已复查。" : + "END INCOMPLETE: 仍有步骤异常或未响应,不能判定全部任务完成;查看最近的 STEP SKIP/TASK UNAVAILABLE。"); +} +try { runDaily(); } +catch(error){writeRunLog("ERROR: "+error+"\n"+error.stack);toastLog("七猫本轮结束:"+error);} +finally {try{images.stopScreenCapture();}catch(e){} if(captureWorker&&captureWorker.isAlive())captureWorker.interrupt();try{device.cancelKeepingAwake();}catch(e){}} diff --git a/qimao_auto/tests/recovery.test.js b/qimao_auto/tests/recovery.test.js new file mode 100644 index 0000000..c27aeda --- /dev/null +++ b/qimao_auto/tests/recovery.test.js @@ -0,0 +1,124 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const source = fs.readFileSync(path.join(__dirname, '../qimao-daily.auto.js'), 'utf8'); +function load() { + let now = 0; + const c = vm.createContext({Date: {now: () => now}, Math, JSON, Error, isFinite}); + vm.runInContext(source.slice(0, source.lastIndexOf('\ntry { runDaily(); }')), c); + c.device = {width: 1080, height: 2374}; + c.sleep = ms => {now += ms;}; + c.writeRunLog = () => {}; + return c; +} +function item(text, left, top, right, bottom) {return {text, rect: {left, top, right, bottom}};} +test('运行时保持亮屏并按分钟续期,不在每次页面识别重复申请', () => { + const c = load(); + const holds = []; + c.device.keepScreenOn = ms => holds.push(ms); + c.keepScreenAwake(); + c.keepScreenAwake(); + assert.deepEqual(holds, [3600000]); + c.sleep(60001); + c.keepScreenAwake(); + assert.deepEqual(holds, [3600000, 3600000]); +}); +test('饭点领取后入口变成去补领,仍匹配补贴行,排除其他任务按钮', () => { + const c = load(); + const claim = item('去补领', 792, 1080, 1011, 1167); + const page = [item('吃饭补贴130金币', 69, 1059, 783, 1125), claim, + item('去领取', 792, 700, 1011, 787)]; + assert.equal(c.findMealEntry(page), claim); + claim.text = '明日再来'; + assert.equal(c.findMealEntry(page), null); +}); +test('搜索滚动过程中出现顶部吃饭补贴图标,也能重新进入', () => { + const c = load(); + const tile = item('吃饭补贴', 450, 480, 610, 540); + c.searchTaskAction = finder => {assert.equal(finder([]), null); return finder([tile]);}; + assert.equal(c.searchMealEntry(), tile); +}); +test('去补领后的空白加载帧不会使补贴任务立即退出', () => { + const c = load(); + const meal = [item('早饭',126,1671,207,1725),item('看视频补领一次补贴',144,1944,936,2028)]; + let frames = 0; + c.snapshot = () => ++frames <= 3 ? [] : meal; + assert.equal(c.waitForMealPage(), meal); + assert.equal(frames, 4); +}); +test('补贴页始终空白时有限等待并明确报错', () => { + const c = load(); + let frames = 0; + c.snapshot = () => {frames++; return [];}; + assert.throws(() => c.waitForMealPage(), /加载超时/); + assert.ok(frames > 1 && frames < 10); +}); +test('系统浮层短暂遮挡后继续识别,不跳过当前步骤', () => { + const c = load(); + let calls = 0; + c.foregroundPackage = () => ++calls <= 14 ? 'com.android.systemui' : c.CONFIG.packageName; + const empty = {find: () => ({size: () => 0})}; + c.textMatches = c.descMatches = () => empty; + c.files = {write() {}}; + assert.equal(c.readSnapshot().length, 0); + assert.ok(calls > 14); +}); +test('持续系统遮挡和其他应用不会触发错误页面点击', () => { + for (const pkg of ['com.android.systemui', 'com.heytap.market']) { + const c = load(); + c.foregroundPackage = () => pkg; + assert.throws(() => c.readSnapshot(), error => { + assert.equal(error.foregroundTransient, pkg === 'com.android.systemui'); + return true; + }); + } +}); +test('逛街被系统遮挡后重新搜索入口,不沿用原按钮坐标', () => { + const c = load(); + let searches = 0, actions = 0; + c.runStep = name => { + if (name.startsWith('查找')) { + searches++; + return {ok: true, value: {button: searches <= 2 ? {} : null, labelFound: true}}; + } + actions++; + return actions === 1 ? {ok: false, skipped: true, retryable: true} : {ok: true, value: {responded: true}}; + }; + assert.equal(c.runShoppingTask('street').ok, true); + assert.equal(actions, 2); + assert.equal(searches, 4); +}); +test('系统浮层始终存在时限制恢复次数,不形成无限重试', () => { + const c = load(); + let attempts = 0; + c.runStep = () => {attempts++; return {ok: false, skipped: true, retryable: true};}; + assert.equal(c.runShoppingTask('street').ok, false); + assert.equal(attempts, 3); +}); +function daily(c, pending) { + const logs = [], modes = []; + c.files = {write() {}}; + c.writeRunLog = message => logs.push(message); + c.engines = {myEngine: () => ({id: 1, getSource: () => 'qimao-daily.auto.js'}), all: () => []}; + c.auto = {waitFor() {}}; + c.foregroundPackage = () => c.CONFIG.packageName; + c.localOcrEnabled = true; + c.isWelfarePage = () => true; + c.rawPage = () => []; + c.runStep = name => ({ok: true, value: name === '结束前复查逛街剩余入口' ? {button: pending ? {} : null} : undefined}); + c.runShoppingTask = mode => {modes.push(mode); return {ok: mode === 'mall' || modes.length > 2};}; + c.runDaily(); + return {logs, modes}; +} +test('商城结束不能直接结束整组,恢复仍有入口的逛街任务', () => { + const result = daily(load(), true); + assert.deepEqual(result.modes, ['street', 'mall', 'street']); + assert.ok(result.logs.some(s => s.startsWith('FLOW RESUME:'))); +}); +test('结束复查没有逛街入口则退出,不反复重新进入已结束的商城', () => { + const result = daily(load(), false); + assert.deepEqual(result.modes, ['street', 'mall']); + assert.ok(result.logs.some(s => s.includes('逛街入口已复查'))); +}); diff --git a/task_manager/README.md b/task_manager/README.md new file mode 100644 index 0000000..dcb615e --- /dev/null +++ b/task_manager/README.md @@ -0,0 +1,90 @@ +# AutoJs6 可视化任务管理器 + +这是在 AutoJs6 内运行的独立管理脚本,无需修改或重新安装 AutoJs6。管理器需持续运行,界面可以退到后台;它每 500 毫秒检查一次状态,同一时间只启动一个任务。AutoJs6 被彻底关闭后调度停止,不自动恢复上次任务。 + +入口:`task-manager.auto.js`。需要 AutoJs6 6.6.3 或更新版本。 + +## 放到 OPPO 上运行 + +把本目录的入口与 `lib` 子目录一起放到手机,结构如下: + +```text +/sdcard/脚本/任务管理器/ + task-manager.auto.js + lib/ + scheduler.js + autojs-adapter.js + examples/ # 后续真机调度测试样例,可选 +``` + +也可以在电脑执行 `bash task_manager/deploy-oppo.sh`,默认设备是此前的 OPPO `3B15A700QEL00000`,其他连接序列号可作为第一个参数传入。同步脚本不覆盖手机 `data` 目录,也不会自动启动任务。 + +1. 在 AutoJs6 的文件管理中打开并运行 `task-manager.auto.js`。 +2. 默认列出“番茄小说”和“红果免费短剧”。管理器依次查找各自子目录、`/sdcard/脚本`、`/sdcard/Download` 中的脚本;路径不对时点“编辑”。 +3. 用“添加脚本”选择其他 `.js`;用“上移/下移”排序,勾选启用任务,分别配置次数、超时、重试和失败策略。删除任务只移除列表,保留脚本文件。 +4. 设置整组循环次数,`0` 表示无限循环;任务间隔也应用于重复执行和失败重试。 +5. 点击“开始整组”。界面会退到后台,任务自行打开对应应用。开启悬浮状态时,需先允许 AutoJs6 的悬浮窗权限;也可关闭该开关再运行。 +6. 从悬浮窗点击“停止整组”,或从最近任务切回管理器点击停止。运行中的返回键只让管理器退到后台,不取消调度。 + +悬浮窗显示当前任务、组轮数和单个任务次数,按住文字区可以拖动。若它遮挡任务按钮,可移开或关闭悬浮开关后运行。截屏授权、无障碍授权由原任务脚本继续处理;本管理器不上传截图。 + +## 次数与失败策略 + +假设 A 设置 2 次、B 设置 1 次,整组循环 3 次,顺序是: + +```text +A → A → B → A → A → B → A → A → B +``` + +重试次数是失败后的额外次数,例如重试 1 次,最多执行本次尝试 2 次。重试成功后才推进正常次数;每个正常次数都有独立重试额度。 + +- “跳过此任务”:重试耗尽后,跳过这个任务在本轮的剩余次数,进入下一个任务;下一组循环仍会尝试该任务。 +- “停止整组”:重试耗尽后不再调度其他任务。 +- 超时:先请求停止当前引擎,再等它实际销毁,随后按失败策略重试或跳过。 +- 停止整组:停止当前引擎,确认销毁后结束队列,不执行重试。 +- 15 秒仍无法确认停止:进入“停止待确认”,禁止启动下一任务。可再次点停止,或在 AutoJs6 运行列表结束旧任务;即使它稍后退出,也不会自动继续队列。 + +开始前若发现其他脚本正在运行,管理器会提示先结束,避免页面操作互相干扰;重复打开管理器也不会强行结束原管理器。运行中禁止改任务配置。 + +默认番茄单次超时 480 分钟,以容纳长阅读;红果为 120 分钟。都是可修改的上限,不是固定等待时间,脚本提前结束就会推进。默认整组只运行 1 次,失败额外重试 0 次,失败跳过。 + +## 如何判断脚本结束和失败 + +管理器监听当前引擎的 `finish/error`,并继续等 `isDestroyed()` 返回真;单独收到 `finish` 不代表清理已结束。引擎异常、超时及未收到正常结束事件的退出均按失败处理。 + +现有番茄、红果脚本有些失败会写日志后正常返回,因此按文件名自动读取各自 `/sdcard/Download/*-daily-run.log` 的本轮最终 `END/ERROR`。没有本轮新日志、没有最终结果,或结果报告异常、未就绪、未完成等,均不算成功;正常的“没有对应任务标签,跳过”算脚本正常结束。这里的“成功”表示脚本正常执行完毕,不等于独立确认金币到账。 + +其他脚本以引擎是否正常结束为准。若自行吞掉异常或启动其他独立脚本,需要由该脚本自行报告失败、等待它创建的脚本结束;管理器只跟踪自己直接启动的引擎。普通脚本宜自然返回,异常用 `throw` 报告。管理器不是外部守护进程,AutoJs6 或管理器自身被系统杀死后不会继续调度。 + +API 对照:[官方引擎文档](https://github.com/SuperMonster003/AutoJs6/blob/master/app/src/main/assets-app/docs/engines.html)、[ScriptEngine](https://github.com/SuperMonster003/AutoJs6/blob/master/app/src/main/java/org/autojs/autojs/engine/ScriptEngine.java)、[引擎事件实现](https://github.com/SuperMonster003/AutoJs6/blob/master/app/src/main/java/org/autojs/autojs/engine/ScriptEngineService.java)。 + +## 配置和运行记录 + +都保存在管理器同级 `data` 目录,首次使用时创建: + +- `plan.json`:任务顺序、次数、开关和整组设置。 +- `manager.log`:各轮启动、完成、失败、重试和停止记录;超过 1 MB 时在下次打开时归档一份。 +- `status.json`:最近一次调度事件的状态,供排查使用,不作为重启续跑指令。 +- `smoke-events.jsonl`:仅在手动运行测试样例时创建。 + +配置通过临时文件替换保存;配置损坏时保留 `.broken-*` 副本后显示默认任务。番茄和红果原脚本没有为本管理器修改。 + +## 已做和待做的验证 + +电脑检查: + +```bash +node --check task_manager/task-manager.auto.js +node --check task_manager/lib/scheduler.js +node --check task_manager/lib/autojs-adapter.js +node --test task_manager/tests/*.test.js +bash -n task_manager/deploy-oppo.sh +``` + +当前 30 项离线测试通过。测试覆盖:顺序、单任务与整组次数、无限循环停止、间隔、重试与跳过、超时等待销毁、停止不响应、极速结束、启动期间取消、异常事件优先、业务日志判断,以及模拟控件的添加、排序、启用、保存和停止交互。 + +2026-10-21 在 OPPO 上修复启动提示找不到函数:AutoJs6 没有 `files.dirname()`,主程序启动、浏览上级目录和子脚本调度统一通过 Java File 获取父目录,测试样例直接用 `files.ensureDir(日志完整路径)` 创建父目录。离线测试不再模拟不存在的文件 API。 + +已同步并在 OPPO 打开管理器,控件树确认任务列表和按钮正常显示。用实际调度器和引擎适配器运行无页面点击的测试任务,验证 A→B→A→B 两轮,共成功 4 次;真实引擎事件及工作目录设置正常。验证记录保存在本地 `debug/2026-10-21/`,没有更改用户任务配置。 + +悬浮窗、长期后台保活和手机上的失败重试/超时/停止仍需验证;这些分支已有离线行为测试。后续可使用 `examples` 下的样例:正常样例等待 2 秒后返回;失败样例故意抛异常;等待样例保持运行。样例只写测试日志,不点击任务应用。 diff --git a/task_manager/deploy-oppo.sh b/task_manager/deploy-oppo.sh new file mode 100755 index 0000000..477938d --- /dev/null +++ b/task_manager/deploy-oppo.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +cd -- "$(dirname -- "$0")" +TASK_MANAGER_SERIAL="${1:-3B15A700QEL00000}" +TASK_MANAGER_PHONE_DIR='/sdcard/脚本/任务管理器' + +# 只同步程序和测试样例;保留手机的 data 配置、日志,不自动执行任何脚本。 +timeout 15s adb -s "$TASK_MANAGER_SERIAL" get-state +timeout 15s adb -s "$TASK_MANAGER_SERIAL" shell mkdir -p "$TASK_MANAGER_PHONE_DIR/lib" "$TASK_MANAGER_PHONE_DIR/examples" +for TASK_MANAGER_FILE in task-manager.auto.js lib/scheduler.js lib/autojs-adapter.js README.md examples/smoke-success.js examples/smoke-failure.js examples/smoke-wait.js; do + timeout 15s adb -s "$TASK_MANAGER_SERIAL" push "$TASK_MANAGER_FILE" "$TASK_MANAGER_PHONE_DIR/$TASK_MANAGER_FILE" +done +echo "已同步。请在 AutoJs6 打开 $TASK_MANAGER_PHONE_DIR/task-manager.auto.js。" diff --git a/task_manager/dist/任务管理器.zip b/task_manager/dist/任务管理器.zip new file mode 100644 index 0000000000000000000000000000000000000000..5776549e2ea8117a9ec64a92aca79a13e2dcfe76 GIT binary patch literal 16941 zcma)^W0WS*vZlYX?dq~^n_aeT+qP}nuIjRF+cvt(_Vl?k>z+I3o>_M?*Iv2uM?OCy za_`7@M?}g?fq+q6Fr+9pU4t^3j?7)bPm#so49`b|;5VcF!H`AMr%kK{f=cu#xYcCJ!w z5~C}TtKYd!bG@!S^v+eJu6LR$4*cUctz-kdFRi|YM&(+7n%a$*gO;{lA%o-Gm3^rO z!I%9$N+CU~3{{`4*kH3k*-Kdw+++pjn2w_!5#4+&fUwYC>yh}e57;L_Xcy*d z!vAd+b9JV>3dOT}Qj-NM2=eTbgSsxIwP z9ZylBf?9+Yj;qe@mfye~h_5H#sNLLS6D(c_*y;8P-1nb_G5;>OLI%vxR9dYD;~x)C znQhT>7@Ve$AWsKN7E;k@zv^rB`pb;ru~oP^fSG7fxc?*(m!1x$)79`o7`svPy;_Zx zKV*omQueRfa60sM`omS4%EG{YGoNvi&Ab+?Tr4~Y4!&+NJ!Xfxf%mYRUbEBZLg7!d zVBiZ^onwNuXdp+a+dqI}e;um^@oUJk_La`$*l>!>HQxOAxa5L>oeV7s75$v8j?6`g zzYWT|id6bc*S(Pv-Ma(k?F1e!6-e0938|a%*ijOl;3}hzCAnbub-bBn#E`#3|73d7btj*@`wBcEdw5O(IKkgmX)XUA&HM5 zSg+Hy$}V7_-U*$aa6#PQ?m#H#yN~^y0=M}VC2>L>J!@P_G^Tjcwfo#}@QacsuS!ln zniMNHUX*d4Y%HeLtB=B0wWbd(ZYr8KGZ+76YgXE<3SRFipaX2KNIP}(NyC}i2x$pN zi$TV`G6 z=u)Jw!g}TR>dAVfaly#}(;2Hek@s6t#~B zfL2Q+zK5zl@;QWC9}f~Fr(}Bo1z@gvs9FdagTt9iUs;;`0b#=u zOs8bOfORXW#r+AVCWzYUFqqv{UERGasS3^d{%F`6`L=7rHMYG!ohFD_1MY=6j4o0? z?)ABBuOd#QdJrD`rxnM#Rv-1sVlf)Z&0CqS4>*vrMg?uZ3gRJf5!V%*71nKp6#M+# z34je^p*v3*^WbaUj66aW1EHfg?n>UaMDCaM&d2QUwA~NANcR5>FK6-JF^ehL4?&OI z1*IARRn?m!E(ZJU39NKgKyioNtD&FAx7ih@G16)KZ)5(Ocs@MkXuiYe%$WPRZRWad9%FGp45KAz@NzA8))y^G znBhaN;B^~i=@slgceMN_L_ZoF0X1TS#kRjp)HR1I@pZ6#e7e8kG=jMF%d?CLQ`(IK

lgl&U1VD#wp$DE^HK{?618}Y z+JoNMFpv9+t%Z9&v+4L*@i|^@0S5Bq%>f^>~(IFvuP^ zz@CFd?hPttk3S^I;U~EMihsy$R@M%GtYV(aeH1_v2WS}PK8&*a{l|K9ry}0vRFj(d zGhUs;L6_ULYqQ1a9s6|oV(36xWUKsSK#GABHT;_Fe5t<7DG#{b=kyJh`;X^}o;JC^ z6Yd>svLG)P6~p3tun`8aTp(8<<4>*nv?judKjkW>`1@$)i zsY(?KjRd|cf*+Mu#gAv|V5VHlcmC(+*dtQb_lRQ;c(~jCppVd5S45& zWouN^?hfDd9}&aiPw@<3R-)RL*JvZq6Q?#MWUL&q=obfSh(-N)*SZ$dwjFsIQx7@| zd3dMMTUmnH2_#NZw93Z@)fe867=ZdixclO-b&iFBKv>JQ!bXUw$E@z)^!4(1iQ&F1<+ujw!pBRzu1?3GAa5 zK&4xvbxfk*5T&o+i~p&76bc43&z@j%wB-axFvUI#T&Gn6m> z>|!MUXLXH;G5s{H9Bz5G&ED(#huP-ede?@~k5n_AMN0B=EQ%VS#{0}Z$ zR9*%tSGw3+gX04(xItDPx`6cUAGwAb0*&|&TA?UddKWiw#v6@7_Y@qTXwz_+yIVzd zrWWeS)2xZuDmpi?!JNIXF}ju@j5_ibsgrGS+iKM42+sO8fdOihFW{$&euGx+mcSzM z)M$+c5dq;?6E{0h_H1bZCG193Ho{}|Y>JCpFPo^l03{~gs*}7)*PpSQ zFl&Z}0SQpH%3P$M*+}nZ%vA2}5HSk5OB!%O+ zLz(lfVwl~~3j(u-%l!;Z(yQ_Hsd_!4S@Y#EdE9b#a$w6G5c;^QWT`A4jUPl16*dMI z{~1pP!a%;}{pNJP%qb09SxM6glv&)Cl~aM5s4j!mskKtGoNih}n`1XcZx>Fl=|Qk? zLF%>?QRlbsri~9)*Wqh)YQMpRbL&-Z3`LL@U;K=h(M{ zJ1yp>*Mb0PS6{n=qD@|eB3O7@EbW+3ODM(tF-OysXs`NEM8)KjC^*6&i$u6MyI$Tg~0B%==>OVur)xnYI#8JABKy8JJv-puE5_>{HVfT6XGk z;rR(Qvz`p!B6=3zB9rK@Pvw6hf_CUKCP0)(;|;Z$R$gecyz$<^VH# zkGxt6btOyoZ|M|U31P8(uX3A;{^4P#h1|K_5U`DWPwG=Pf2r$M7CHX&593g-EniCb z!mzHLLkNq+X1t$ds)5k}c=fU1B(<4yyb}S1IuSf<&fidEf2Vo>#Jh1jIh0)(uTb~F zOJ+K8jJ2&Y|Ozr(j%>z`F{B zVUGPhGFJtPiBuOcc~O9AGksr1!d;7xOlC-3e&xVU-#Ecyl{BwkfH@c=XMOLAf_ltM z+=gixlyqFK#8@U%l8j`blc{uRjLSumdQLe-)JbJw$YEic)+Eqo$E{o70Ft;2Zs?Xt z-z5MeBqg?p@E%xV#LoFdfUTV!7`@TOIOQ3@{&v0M%23=lcDVp+Z@Led?zY8}s$l|I z*mpv;HtHjR2i~?_FE>Um>mxK>5lfyLD^wuApk|FxcYU}Rz+kzsS8weLI*701V(E-h zRkN`uy!FARH;^}YeJR)^VN40#*ZStSXZ^faT_O7xwU1#lb~wN8hLkUcx=RBq$3m(P30oU zgzSx}+M58`Jp-MItTe1x00LTcEheA&W>!Kq8Z?v%x8g#a)&P6;hyzh=6qxuX zX41hgEd*alsl=-Ir$*}AowLyw(nha>B(NZUs7>h+{z~|>qAdajU0~XhcL!z1Dhb%!vKb~$+)7#??E79Z;8GlDadB z{?Js-A;=2mj0fcW;>Dp`7As&!7T#3kHj>o9j$RpXD!oIv ztfxpS`AU7mkW?;($9lGtGelETPpltH(q#e6YA1AGo;Sk z!lwQ;($A#ZrUorZ3siT(=T&0ogI8^4Y$^N!PK@gH!JP7WhuL}oJOl*{9u zpnfP7!WcIs(2`A`K-LV>obwSZz@hO$1;z^*4Ya62$ygT_84i~=_@)ALby0cLpvX~E z#Kw_ZmpF$1B2TVQU=i2hwRImlh2AGf6da&R2$O6eK#Ml+AqnnB!~i!v*Vj*ti#Kv) z1PU$8$8C>~1hIXKEH4RsJ7*3Tp1Pne70)I(jqtq+O#oqRYkjMXrLGfhs-FM&150+)U~1d z`wO>gzy|eC%q4Ec2z`G`{r{D#4kJ23p&a;BQH6lv1g3}9uygI zcde}y654GO)_UY}&K8DKVIyaG3ggigHuy$aHt^s&x6{J>8GvA^-$44i1ahaUSa-RTz-`l!aX__B7$)+80F>5PjAnfcN4@h|*R2#) zA`{#yfN00#t{{$YrHx<5RM2RIpuv-5rg+;+*~?GmmSU^ z-vR}k_hf3vc$H@aX8kV>LnTS{>a#O>7?SZU0}QM55wXM+=0zs%>d!LkYMvsNA^M{W zqIO>b+NYYLZXK5=q9jcXiWULrgt(W-gfuv`DnwCG&J-6@-2?}~ECJXEc=7fGmqdwi z=+A@S>+Xdc5xj4cN6%b74Zyy%2qZtF@W`N`1mQm026^KU<7fp_ zZ<#1=S031^PWfxkzkr+T=2`0>K-&@sDI6W;eGNq(7lFxamcN)rU@?Pw8+}==Egc=- ze9&6t>(QbIELmuL-OS7A!V8STD|)G5NeV;W1?tBFmz8su?(eJZ5|!!cg2GkxtOPQr zSq>SA&ETIyC$@p~oCnyFq!QirJA_^3p^KOD_(^81iW=4f^HF=F{wjfxAbFC^#ZGXN zwEQ?h&Wj>(r2m~e7wWL5OK0ILkNf{qm9YwaL3BL&t0DUQja87355a^YQbn7EP4*j8Vi!YV}0ufIbKC%B3~D-q5CqV z7Ta#6dy}L4>g%Q6=^L;7@C3%x7-GISjKKoeizOn#18?zV5tp;e=9g;5$HaC$X=BjWCw2!3pC9as_IZk>LJ^f?d~43fE~0Pz`vk*KLlURzJr zz>?m-<9!DS0cU+SP#-rl4i_q@Gw+q>exJdCdV6sXr|Vs5s1{0oVWRn=55@{N*eGW? zsTM*{d%?bksVdhCJuADIM*3)1YDIryt{Qsruq(fBlE^NVS@}6f$`!5n-n-JcCcE1|m`^n{Nx<&jYbMM<|DraxM_dn=9OendZ z9*-Ns$Mf*fobQb|_6LG6o?a%#9ccUkTqM>08rG8NG{%6>003+5LJb$Xu0Z9nlcF|S zd3$$F&9WT`$r1v$Leiv$AyoNYXeG&47rIoOLOPzyvpyT959Qq$2F#-%S%wL9AO5|d zNAUT99F=)jmZgxu?IinyFeQ0L6@+Ps9&M62-tECkKMWc*!OxR7P;zes9E3O}p@?0G z$Sq-!nDYS|wFx3@vK)oL@`Sq|jsnfVu#w@Kofu`z;=4iWFucG_WDx}IKo+*-hbV&0 zfF}O~TQW3pY%54MI@G4OjEtL^W&7hOdke}ZbQbV*y6lyWM zk|m6PSadF_hn~{Olw7iG=zkmDxSZ zDffwSqUCkz)K}b@S2|KDvSpUnysDdK=VRqC*v5_mgD74E&rm5#Bl*t>`XvuSFy zNi!7{BOEt+VKeqvT8;<*G(%pa+rKfBdCci_yXM_Kwpr8OP>uKPnUP|p<;uEq&3beZ zBAxa}SvFNxgxIKCoJ+_zVz$Ffzix_bN;aoN$X{b>Ba3^kVt2jq&>?{jDTFkE|Mjtf z2wTpC*=`F9i_!SL#N!u{-jIn+-EQRMp^ekN^au(f0knpu26yACtmv0GYNp{nBK7AA zk{;qI_iDYXZe&%gIfm$6OtG$W%adydT&ajq8K6p3b!HqsvYefgcBIar|6t*wN9i>n>l<+1JmQBX&AalN`yp z*gu_}d05z(Bf>1V8O&!}73}P3IB=a*h55nrq~$^jeGh~3et^Tm?`ADyJDW^SwnnKo zQnb#zZ;Lvb_E?NE7dMVB_Le)S6A(-8duK)LJ^uZ#HLtgu(PY~47yWfV&po1Hk2_;!Se4IoGIYv>tOExB3GW2Yu{4MW0& z83_am+7{h+Q5a19GRX*%9=#yw`ulaa|0k%UA^E~>W=-Z(RmU_pVzRA`<4~Q^mmQY3 z)f+s^zc#_LH%e{#AR#3Oh1{dc9U-Aj3l4i;*t`=^#()|QWy}_zfW*&Gyf)SEZ5H2X<&EN zfXoMn*q2*d-QXiRePWwF0RKHYZi5Ed;C?m_xTLnW=NoBJtVUW(TY@@5NVp%0|o~dSctC+XCtb8za?tLlanW!^PKE7myyI8oc2YXH7NH1OyvrfFO)&U#PDoahz)ws`;KLT(rq)ey75|53 zPnTJD_FluA@8>YS?<;6ExEZjOq_OCQqzhS(nVogiPSRDvat?~5F28&NBG1;TS5Xh| zE?QYOi=dvw9r{JEdifyri~tve8eP#9y>Qh@BwZi}K}cBo4Y@jF)mM(Cj zZ7x5fN5yjGKg4K%Om-}XSBJ*YW`ZKS;IyY>7?)trB5#OW;$PeSn)h{)GYh1F(892g zj*B!MeCDs^RSv3%cp*q7D4ztOd+N|iU>q~rlZ8$VprWhXVbl#+XOF8i(8sVy=%Vhh zwqcN`Ji#>xuxBr0io3DXWQg2dIpsoUOhb)k9E2lk`XS(cON@T5P@cGgh$e(kbKObX zuKan#*3Z7r_2Ktdu5-AL1-gSmAuKq`B9gMFFv_6)qbcE>)D=)au_ZTGNLDfd6KevA zaOxyt0;C2HRDy$V2*}>hHdI$>cirPsINEur^Zb?Wkv^ycIjDGvU;$pnxtpL-T?zXO zxj>COwV_L%x3FtWhTU9LhD=4Zmnsf*_p2|j{ zLMg{3S^H@|iBab z1s&=e75n|n=mtfFNpM4D2rWS0@iF=hoi_9Z_hJtwxZIlbeCvL-I>8X$xx6hK488+Z z>S%rsryey_d}r5=9(f&1u}U00i<13!yEr8Zfi{$Q%4)?8m7FDpGV`Zv$Zq~w=5D-| zS7GbVmx7u7&bb(BEr4dYSt%KG$F;C?{tfdyD_?%Ymt2=of5doRS3(BmuJMb5KmsmU zHwBI(^*FYIU4#lwx9|` zS<_Q-KU;k>px8n!>r#EM#`=-R@C*2?Mjo*vjhq2xS*OUFWR2?%R#3zcHwcaE7eSNV z(3}ZNPDu_nW+mL6x(EtoOLR`Ld`$DoTr`H2(o|7uAT_PB_l^iWe>l=IXrzgnfv;wB z^JY=Y+;$`h4hSG#@Wd{2^CoRStWJ+AUn2e*OZV*QRMW=);hsi@=5;E+2#oG zK0Yw`Z>O4F!*n2I9$wU#Chaw_;PkL19B$D7;Nf-IRm>YoiO&{FasCG(s?C4sMo+KR{klpc=mU$%6rEJkM7v(6NI(LW#o5vFM6 z_xsxU>}Y)R5ag5KmraJ8-h`PT*`z>16hV2r?BbJDj3f&J31FJ-nu5|)GtMQmu_J-? z8Rb`x(cp^ zl^FS~6Jt_HDswc7g$lBnd3qe-rnf{q68iEXqWOk}Ygrl=lG<^fNal(01dl8Ynd5kQ zgc*Q)#E>W$jz3BC!=;n@K+&X|bEHYNkt@b$B~=j|Q!TM`(Vh+?S2MXpEw%9+zBEZD zj?e}43#Cn-DXdsg%75|LC@rd%kr!oTnNjheGj;9E-_D)6twPxMa&musUa}~4vB`cM z*5JcqKYn3`Pk2S@lU{reiS=3(WukeOeVJ>I#SkZv96p5`*y*Le<2G&^T{j>=Z7t{V z>=ogSNnl$(r|{2VICZpHu<$H9oFGBvUbIC7wBiJoy&|QNUMYz8cqVvOn{g&PBERz( zj9SUo%i3R!Tgt@rSy&e^rANY*34c4{7UM>Js%Dr2l8A;0SOvj}xwlfISlgZZ&Igm& zxuoD0UQk)#B+W4$@7i~Fz)sZ^T&#{(bgrk7u4}R^W6xn*klfCIno=u6;xp*B$$f|v z)hZQeJBMY!=o}^`l%wk-#*}X)AX$`4Y#>77$r|BT##%jo6UY?xJ^=;cTd2^VCDs9e zRFGc!WLfw?=CJ)j%m+2O!YZa7GGH{kU8Om%~Ul?RRI99F%rU1W>P9RJo@n0g*d_mzv1bg3E< zPtTwl#xqrgZ7Kgo_X%=!d~KZ1A#oZa!JI?1o?^9D0--LrB8MC!~UUJG3&2@031?nO3I0)3@lMmzG@S1d5Qu4)&nu3d$QcG z@rN_oDTxsH3_RK-Frfl#J3k@ROX>9)Dd?l zfz%trRro%#m2ZmAPA-#qi^)Vdc35g{TC+cb0r{L4^oX5Rggf>S6^vLU&{X$+QdreF zfKtIS*v_8`PQRoJU!43@%QjS;IX)H&amuNlj;ZjJOq(PF9~5jB-;FPzK9E;SsJ7^I zY>g!~`}6yi{-0{n!d^wk+r{j(1r`7ZBLx5m{*9WnwlJi3GBP(YcCr3j*=Ff9t*NE7 z^%LFqxz1d{(OrwgHmD%KsR(RD=G=NqpQyiNCMk$0I)4q?ah0!F4 zo`mDcbDGw{df;&s(;}4oYaq8rVtWBLqMKf--IS%~YO!qgm^-aS@d@_mwN~RMr3Hoj z&cpc^r_-#_RY=S^zFX&f3NIMo^NcV43^aB|9*| zH6mVoiqRcZfpDp^HcqHP=sWed7!32}4EiZc@WSjBzmeR#q+q@Va zGM+!L;M~JAH+^nAhb2wS`%xi|_WkNp%N%TN1exQaGpcg?RgOg&CbbEXr6nF9=HQjC@tR-0IC_E$#J&YoQ|%pMCEo>^cT)o%O4qo9A-k z)pNw?l-seF^SjofIpswu>sHF*WY1#Cd)c$XPO%s{HIp|v=`|Wmht`xIyfLj9z2v0U zRzpr>wr+{cR{m_gm)GPB#5F;UoOM42lZE{kX%{zE?+%ndTkxlOp-xHK#6cZVV}?tyhLY_- z-Niq>E8J;dRMlBXI{U2ZG4&~#S$P=6LjC1L$B*>g1x&PVgZ7@=h4QXk-z=@bS({sf zUQityym^t>IZ*1kQy9Py%9w@@`bdIGzCqdX2nd49e*~g|S1sy?H@8~#@3@HShh_KG zPYp0+2QXZ(>G=;#)C$V(J!X-T_Veb*wvpA%kKz+s%(+QQ;?@Qo$87vITTXdjZZ~Uy z2TckOk$R%GOf;S*+K1+E-CIFXZQ*)H0q8S~;ew~us z{L!*wgVhH@IPRMu{B)LTHkRb$)OXVaSviKxlqw3nEX?uP)xv_?qdDLoFIu*zNBuQf z48>{koo$i!*@1ePCcu@R0TS8Fe(2vV#+}rE1ShapltbClPo76I9+a=cESeT$7$_ox z8ceLK#aKsBF~-GGdPiats;;R68g-(IiET>4fr-VUjqo8en5`A7gq%)ND>33P%5Z$~ z^r(Mr^0Zt-C|X-pClr&NPyVBnT~B^!n} z3vSDh>r`|kPK)SsRqm$7Q+|A2ul<2E3?}TTjo`7>6Lx=Z;#*(uCODTt!S_vdikhK? zLZvtixJjvV%~qX7{cpn6jU~$)7kB11-wrNb zV6g2iy@=LR4!Z3^1XYy~*6`3CYfBZcKT@Yv~MAQ6YRq>Mecb z4~4qGUVV6eu5-V9+$r`c@m33W%{)2TV2=87HxAsa3A+yE2$DF8fpa1men7tu+SR1zTZ4MbYGFq}K1gsS`PeGY#b)%;l{a zPP2oz4Bl?$5%vdu-+Xbo(3A^TQY*>JG3@5*z}WWW*Y$M=Js#_Sz)b=1!=UGeQcohT z2OeXw*|@&xJ4J7R&~ZSLUoq^(nh#{J(y*&+(|cKx4KkMJzlZP@W2@I=^|a(pU@a^} zxVsQL^rP3((BYU6%sPY)0R-6!-;{qJNAzE9>sy9qaQ9>O<>-Ha(Ka)@D74FKY<)o) z139QnMHfZmY%1qGWY0vK9lKNI;7mNGqwfh5m5nSI{v-0=!<>3mJh&C83-q^>0qAq#POh+iJ(~m$g`jK(qACY=l*o#}%F-Mpwv|IKI{9?KAt4^Z zh>43sk1dTAag}1H^1?)IzpqR3M&^ar zx(#l`#m7y=`csv`<5cA#l7XrD!J}ZWMOhEV#32Y_0{=YCqf|P9SxBQ6XEiqp&=O?( z$*z9(96TNnxDrYrVNUfB(I$%k4(aXr(m++pe-KrdhTphE5AV(`Xxc8^rcF=V+?n&1 z*Ajr_GrZ=~*B~4@Op)FaOdFtP97&Sric+aB2%5)qWrO2HU}mIBun3#C5%`u+ftlqS zWAWvSDkCfwrdXobqg_PpouB~ML;!-3&?ZcO1#E2US-ztT;GnxGrc>V$8k)kAJAO!4 z5FiOs<0DFNBtT`9EkRupfWxni4CXqh)n>kCWb77qN0Huw zOeHserd$Ey*J8FvW}75W{>TUyzA|bN%b7@KNbfESzSX5sBCo9BExHQqtWo;rTl4A5 zG|K?B0gtD;L^ewl-bjmHAgDwB^Ho)M!3lwC;&Cd82f zH4RBZ?zwB}Pt2T2GG`xD9BHId99cZRL9Y`H*h(BHU`g>zO7rPGe|X-@aJZ6wIM8_C zNjn+~seyue>W-X?&)37P%vOh=j&?3;aPpAGJf9~r`i{z8VWZzzmq&m;V%o(bvlVm< z`CK@g;+7PRmNElliZ6%GmCFPL>#HF>u`dLf8&z;hRERBQrW@ycaT%|1gZI7EM(lbX zw$M)||4ytW4yWKoF;W;fG$|ek*t?u%*(PQWVB#Or(FjHyP2!`(1c{NVHlb_u$%bHS z_&zKWT;L9mVNnJJ|4Lo!!i@Y%z$WaW3Ho!y(hgTi?l&)Y9<%X9W4!pFOFOJ~cSUIP z9KS{GPUb>lrf%(a&*d-Vm$U{Y?$Nk374eQj>30CyaKu*bYLli*M{>cT4d&=a6tX92 z^Qrmkaj~<$s{gWiZv=J>=y}YelOekcVVUHD=6z!dDejID81HqzY#1-r$Q%TK8=$+*k>G*_^f5l!%(L6yi;IOu;=m9WE*;bD- zE9C?#4N^D$Tl6ER`qN9Kyo6MqCdyr=Xq*)ONPy+^g!-(mdhgD2oH=ryv<7o1UCAZi z=>@MBqWHWL7W=3cYA_6TA}NrBSZW06M{Z!?@lT4^SrD{LE(DG>SEmt^=;Ad)v0~je zveuEth{@|C6Zh1N3VW#PasI|znQU}^VDfLUe`=n8H1j~0iZfzD001E<0Ki|_^WU0z z{-JsP(ZgfuL~CGdVDJ1N!Y4;v%WhE|)%UtC{SAn8W3MG@k8quUP=N#yxyt0Z;v%S? zJch8jv1L${RB@vDK?vpnxJin#NuIX5@2WCccW=~sL?Z76#>;dht^QEH$=CcMgPHl% z`;5mvVL9L8U%E9qH`9QYDF*IDPH?27Gj!Fx0+kwhKG&dApX44O0G0x5?q*Nw02A z8{Fv!O7jstyY*bfthSP8wmxsqD>OK4>Zn^?byZ!{FSWXjEsw^~he&l*(T ze#m}KB4>Pv%TXx9F3-z=RG_QkcuOixz_%!>4%)B5oHb z&QBu({*xp38!Xw;Ho0EohCOkAZpIr=q6Zqe!vkg5n1;t(clgw0vmd<0@UF-8!67o$ z0}ks2`=Z3WjKs~Sy}o`ay+bUw29IVb(=HT5jFFzu&3Gl}do;&q*PUTNVgJV7pSMd4 z14x;2+NK;lG!+fz$BadO_(l2(T>sIUbkyx_ibIsuf<9yhicF%JyIvSdw<_`Y1{rDKXNs@j_)NXQ#+B zlDGO!?id#B0eJXW46w^WU3F6}v|O>VI0pB*c?$`mKHH!E5U`wSrw(!}jT_WDL(+ z&5?nuS*Rm~S-Px}#4&rijoiZofb^&k2Yy$S{~aDXUZF%MT(f{si2#~23#Iav6c4(J51YSOV z_ae_gbd)Ipg~W4&=E#2cC!TdxZPHMQA~1eI&Q`Z@rN~@NbbobMsSib|8t^iq%mxdZ z`yG_KYbfoan}g!e6Zz60hez9~Cg-xMO7G&!3r6ql^7HjPO#cHqmdAB%Z)nrjn$N*k z{g@YZW<5DOVH~?&H}Pa6M625PO~P`Zw@?|5p5ek zB^%$?&YCE-v_^yqll)34KFQf?jJ@9?rJ+>YW`mn6-9C3XihD_axrJ%a;jEmaI+9EJA7M3C-Tt7d_oW#K?&=<%r(Bh|xItu}Kf$dj zvQh{6_(XchO^Wi;^z*&}{|v1ne?zP17)BKf5CBmBcToPD&}!mtU}JA>;zaLcV`pVT z>*Qi&Wa8xXcVDq2Rz?a~5Oeg}H_||^)0kUItRzc^YpK90tsl!uan!_&g(UD7(^O%& z5GrZ3E{SI+=7pqBdNwZaD;hTY8({v@1Mlm5_c{PEdiUvgPnWeW=!D=*b+k_HqJbHg z?P$G-W;JLd=c9W3tJAY~EN)QYT9sE@I*hz%r-JJ7I00X|vV+6Ijl3qSu3NF#pJ$J# z9tu4Gh*OpbVenRv*qpCF;d=70#nYndzMWhUVk zS@bDyVty_sh~{m)Og$M&i(rPVag@})u_oJaFY8f9@cu6put}>bYBmhK<#y%yEhte& zeft0&0};VYCLXQ(agu#)eBU|7%Lrh>Mo&osLF?2_wi+FnDIlX9tT&8Y!XZ`+oYDF( zl9h;W^Io9;+w@p;9y&6A&F=sIXL?fu3u_lglfS0di5L89der|ky<1V1?tfUm0M|*; z%*0fYB(RBAFow&xm^M6-FhN6^gzCk>(QGwIuR!7V!g=?zpPz5sa~L9Mo!QRKyj#`+ z?!>I*T-_`C_G=rV)#*Ze;;~m9%fpDM9YcCt)uMvglQP^J*!4c`%h{A<+5|#S-Lt-8 zpl*Lkcgt?)qgBrJq9H{T<`_W&AWI-r*8XkZ_~$bn7W-1bY#f8 zrktVQ98nc}CxopQlADmj63|X4O1?w($qYU~EMLaS^Mp z%1dXWKpUO>4{*X6O__DxpXaE=Qw$j@COf~XFU4EW*>Tow#wDH5b^`A~{%@aneU7v1 z|MkcB-$C|2PX{*x3+KNM$%*Bc8xX)8apM~{6o{%Da`m*q|y4*I_HMuLDYx_SYRn)3wf9lI`A_5X20F z`Lj>mp_k0=kC#J-xho&GI21JV0AynbeOz%a)`mHzhqI>1Z8IMOXg#k2C%mmk7Z9fM z#lj4+s`5a{q76b;2|-D6$2R}+P)J%WiXd7K-SXl?TkCLBktar^SVJ3P)rLZYLvnB_ zQjutmqQIK%9Ge&>7#O`;veiQ|N&*FNTCxg)xCp`-s-b(U`7C5P?~A_v8Tv05= 6.6.3:全局 finish/error 事件 + ScriptEngine.isDestroyed() 双重检查。 +// finish 事件在引擎销毁前发出,不能把它本身作为启动下一脚本的信号。 +function createAdapter(runtime) { + var engines = runtime.engines; + var files = runtime.files; + if (typeof engines.on !== "function" || typeof engines.removeListener !== "function") { + throw new Error("此管理器需要 AutoJs6 6.6.3 或更新版本的脚本引擎事件功能"); + } + var parentDirectory = runtime.parentDirectory; + if (typeof parentDirectory !== "function") throw new Error("未提供脚本父目录解析函数"); + var records = {}; + var recordOrder = []; + var handles = []; + + function idOf(engine) { return String(engine.getId()); } + function record(engine) { + if (!engine) return null; + var id = idOf(engine); + if (!records[id]) { + records[id] = {finished: false, error: ""}; + recordOrder.push(id); + if (recordOrder.length > 200) delete records[recordOrder.shift()]; + } + return records[id]; + } + function onFinish(engine) { var r = record(engine); if (r) r.finished = true; } + function onError(engine, args) { + var r = record(engine); + if (!r) return; + // 当前 AutoJs6 的事件第二参数是 Java Object[];也兼容直接传异常。 + var cause = args; + try { if (args && args.length) cause = args[0]; } catch (ignore) {} + r.error = String(cause || "脚本引擎报告异常"); + } + engines.on("finish", onFinish); + engines.on("error", onError); + + function readLog(path) { + if (!path || !files.exists(path)) return ""; + return String(files.read(path)).slice(-32000); + } + function forcePending(handle) { + if (handle.stopRequested && handle.engine && !handle.stopIssued) { + handle.engine.forceStop(); + handle.stopIssued = true; + } + } + var adapter = { + launch: function (task, now) { + if (!files.exists(task.path) || files.isDir(task.path)) throw new Error("脚本不存在:" + task.path); + var before = readLog(task.resultLog); + // 由管理器逐次启动;不能用 loopTimes,否则异常和次数无法独立处理。 + var execution = engines.execScriptFile(task.path, {path: parentDirectory(task.path), delay: 0, loopTimes: 1}); + var handle = {execution: execution, id: String(execution.getId()), task: task, + startedAt: now, engine: null, stopRequested: false, stopIssued: false, + destroyedAt: null, before: before}; + handles.push(handle); + return handle; + }, + poll: function (handle, now) { + if (!handle.engine) handle.engine = handle.execution.getEngine(); + if (!handle.engine) { + if (now - handle.startedAt >= 15000) throw new Error("启动15秒后仍未取得脚本引擎,无法确认启动状态"); + return {done: false}; + } + forcePending(handle); + if (!handle.engine.isDestroyed()) return {done: false}; + if (handle.destroyedAt === null) handle.destroyedAt = now; + var r = records[handle.id] || {finished: false, error: ""}; + var uncaught = handle.engine.getUncaughtException(); + if (uncaught) r.error = String(uncaught); + if (r.error) return {done: true, ok: false, reason: r.error}; + if (!r.finished) { + if (now - handle.destroyedAt < 1000) return {done: false}; + return {done: true, ok: false, reason: "脚本已销毁但未收到正常结束事件,可能被外部停止"}; + } + if (handle.task.resultLog) { + var result; + try { result = resultFromLog(handle.before, readLog(handle.task.resultLog)); } + catch (error) { result = {ok: false, reason: "无法读取本轮结果日志:" + error}; } + return {done: true, ok: result.ok, reason: result.reason}; + } + return {done: true, ok: true}; + }, + stop: function (handle) { + handle.stopRequested = true; + handle.stopIssued = false; + if (!handle.engine) handle.engine = handle.execution.getEngine(); + forcePending(handle); + }, + release: function (handle) { + delete records[handle.id]; + handles = handles.filter(function (other) { return other !== handle; }); + }, + close: function () { + handles.forEach(function (handle) { try { adapter.stop(handle); } catch (ignore) {} }); + engines.removeListener("finish", onFinish); + engines.removeListener("error", onError); + } + }; + return adapter; +} + +module.exports = {createAdapter: createAdapter}; diff --git a/task_manager/lib/scheduler.js b/task_manager/lib/scheduler.js new file mode 100644 index 0000000..400a9c7 --- /dev/null +++ b/task_manager/lib/scheduler.js @@ -0,0 +1,217 @@ +"use strict"; + +// 不依赖 Android;时钟和脚本引擎由外层提供,便于验证顺序、停止和重试。 +function integer(value, name, min, max) { + if (!/^\d+$/.test(String(value)) || Number(value) < min || Number(value) > max) { + throw new Error(name + "须为 " + min + "~" + max + " 的整数"); + } + return Number(value); +} + +function knownResultLog(path) { + if (/\/fanqie-daily\.auto\.js$/i.test(path)) return "/sdcard/Download/fanqie-daily-run.log"; + if (/\/hongguo-daily\.auto\.js$/i.test(path)) return "/sdcard/Download/hongguo-daily-run.log"; + return ""; +} + +function normalizePlan(plan) { + if (!plan || !Array.isArray(plan.tasks)) throw new Error("任务配置格式无效"); + var tasks = plan.tasks.map(function (task, index) { + var path = String(task.path || "").trim(); + if (path.charAt(0) !== "/" || !/\.js$/i.test(path)) throw new Error("任务 " + (index + 1) + " 须填写 .js 脚本的完整路径"); + var policy = task.onFailure || "skip"; + if (policy !== "skip" && policy !== "stop") throw new Error("失败策略无效"); + return { + id: String(task.id || "task-" + index), name: String(task.name || "").trim() || path.split("/").pop(), path: path, + enabled: task.enabled !== false, + times: integer(task.times, "脚本执行次数", 1, 100000), + timeoutMinutes: integer(task.timeoutMinutes, "单次超时(分钟)", 1, 1440), + retries: integer(task.retries, "失败重试次数", 0, 10), onFailure: policy, + resultLog: knownResultLog(path) + }; + }); + return {version: 1, loops: integer(plan.loops, "整组循环次数(0 为无限)", 0, 1000000), + gapSeconds: integer(plan.gapSeconds, "执行间隔(秒)", 0, 3600), floating: plan.floating === true, tasks: tasks}; +} + +function resultFromLog(before, after) { + if (!after || after === before) return {ok: false, reason: "未生成本轮结果日志"}; + var lines = String(after).trim().split(/\r?\n/); + var ending = ""; + for (var i = lines.length - 1; i >= 0; i--) { + if (/\b(?:END|ERROR):/.test(lines[i])) { ending = lines[i]; break; } + } + if (!ending) return {ok: false, reason: "脚本已退出,但本轮日志没有 END 或 ERROR 结果"}; + var failed = /\bERROR:/.test(ending) || /异常|失败|未就绪|未完成|未能|尚未确认|连续无进展/.test(ending); + return {ok: !failed, reason: ending.replace(/^.*?\b(?:END|ERROR):\s*/, "")}; +} + +function Scheduler(adapter, onEvent, options) { + this.adapter = adapter; + this.onEvent = onEvent || function () {}; + this.stopGraceMs = (options && options.stopGraceMs) || 15000; + this.phase = "idle"; + this.message = "设置任务后点击开始"; + this.active = null; + this.cancelled = false; + this.wasBlocked = false; + this.lastObserverError = ""; + this.lastTask = ""; + this.successes = 0; + this.failures = 0; + this.skipped = 0; +} + +Scheduler.prototype.isBusy = function () { + return /^(?:waiting|running|stopping|blocked)$/.test(this.phase); +}; + +Scheduler.prototype.event = function (message) { + this.message = message; + // 日志或界面更新失败不等于脚本启动失败,尤其不能因此重复启动同一任务。 + try { this.onEvent(message, this.status()); } + catch (error) { this.lastObserverError = String(error); } +}; + +Scheduler.prototype.start = function (plan, now) { + if (this.isBusy()) throw new Error("当前任务尚未完全停止,不能启动另一组"); + var normalized = normalizePlan(plan); + normalized.tasks = normalized.tasks.filter(function (task) { return task.enabled; }); + if (!normalized.tasks.length) throw new Error("请至少启用一个任务"); + this.plan = normalized; + this.round = 1; + this.index = 0; + this.repetition = 1; + this.attempt = 0; + this.successes = 0; + this.failures = 0; + this.skipped = 0; + this.active = null; + this.cancelled = false; + this.wasBlocked = false; + this.lastObserverError = ""; + this.lastTask = ""; + this.phase = "waiting"; + this.readyAt = now; + this.event("整组开始:共 " + normalized.tasks.length + " 个任务"); +}; + +Scheduler.prototype.requestStop = function () { + if (!this.isBusy()) return; + this.cancelled = true; + // blocked 时依然允许重发停止请求,但绝不放行下一任务。 + if (this.phase === "blocked" && this.active) { + try { this.adapter.stop(this.active.handle); } catch (ignore) {} + } + this.event("已请求停止整组,等待当前脚本完全退出"); +}; + +Scheduler.prototype.finish = function (phase, message) { + this.phase = phase; + this.event(message); +}; + +Scheduler.prototype.beginStop = function (reason, now) { + this.active.stopReason = reason; + this.active.stopAt = now; + this.phase = "stopping"; + try { this.adapter.stop(this.active.handle); } + catch (error) { this.active.stopError = String(error); } + this.event(reason === "user" ? "正在停止当前脚本,停止后结束整组" : reason + ";等待旧脚本退出"); +}; + +Scheduler.prototype.advance = function (skipTask, now) { + if (skipTask || this.repetition >= this.plan.tasks[this.index].times) { + this.index++; + this.repetition = 1; + } else this.repetition++; + this.attempt = 0; + if (this.index >= this.plan.tasks.length) { + if (this.plan.loops !== 0 && this.round >= this.plan.loops) { + this.finish("completed", "整组执行结束:成功 " + this.successes + " 次,跳过 " + this.skipped + " 个任务"); + return; + } + this.round++; + this.index = 0; + } + this.phase = "waiting"; + this.readyAt = now + this.plan.gapSeconds * 1000; + this.event("下一项:" + this.plan.tasks[this.index].name + ";间隔 " + this.plan.gapSeconds + " 秒"); +}; + +Scheduler.prototype.failAttempt = function (reason, now) { + this.failures++; + var task = this.plan.tasks[this.index]; + if (this.attempt < task.retries) { + this.attempt++; + this.phase = "waiting"; + this.readyAt = now + this.plan.gapSeconds * 1000; + this.event(task.name + "失败:" + reason + ";准备重试 " + this.attempt + "/" + task.retries); + } else if (task.onFailure === "skip") { + this.skipped++; + this.event(task.name + "失败:" + reason + ";跳过该任务的剩余次数"); + this.advance(true, now); + } else this.finish("failed", task.name + "失败:" + reason + ";按设置停止整组"); +}; + +Scheduler.prototype.tick = function (now) { + if (!this.isBusy()) return; + if (!this.active) { + if (this.cancelled) { this.finish("stopped", "整组已停止"); return; } + if (now < this.readyAt) return; + var task = this.plan.tasks[this.index]; + this.lastTask = task.name; + try { + this.active = {handle: this.adapter.launch(task, now), startedAt: now}; + this.phase = "running"; + this.event("启动 " + task.name + ":第 " + this.repetition + "/" + task.times + " 次" + + (this.attempt ? ",重试 " + this.attempt + "/" + task.retries : "")); + } catch (error) { this.failAttempt(String(error), now); } + return; + } + var active = this.active; + var report; + try { report = this.adapter.poll(active.handle, now); } + catch (error) { + if (!active.stopReason) this.beginStop("引擎状态检查失败:" + error, now); + report = {done: false}; + } + if (report.done) { + this.active = null; + this.adapter.release(active.handle); + if (this.cancelled || this.wasBlocked || active.stopReason === "user") { + this.finish("stopped", "当前脚本已退出,整组已停止"); + } else if (active.stopReason) this.failAttempt(active.stopReason, now); + else if (!report.ok) this.failAttempt(report.reason || "脚本异常退出", now); + else { + this.successes++; + this.event(this.lastTask + "已结束" + (report.reason ? ":" + report.reason : "")); + this.advance(false, now); + } + return; + } + if (!active.stopReason) { + if (this.cancelled) this.beginStop("user", now); + else if (now - active.startedAt >= this.plan.tasks[this.index].timeoutMinutes * 60000) { + this.beginStop("单次运行超时", now); + } + } + if (active.stopReason && now - active.stopAt >= this.stopGraceMs && this.phase !== "blocked") { + this.wasBlocked = true; + this.finish("blocked", "未能确认旧脚本退出,已停止后续调度。可再次点停止,或在 AutoJs6 运行列表结束该脚本。"); + } +}; + +Scheduler.prototype.status = function (now) { + var task = this.plan && this.plan.tasks[this.index]; + return {phase: this.phase, message: this.message, taskName: task ? task.name : this.lastTask, + round: this.round || 0, loops: this.plan ? this.plan.loops : 0, + index: (this.index || 0) + 1, taskCount: this.plan ? this.plan.tasks.length : 0, + repetition: this.repetition || 0, times: task ? task.times : 0, attempt: this.attempt || 0, + successes: this.successes, failures: this.failures, skipped: this.skipped, + elapsedSeconds: this.active && now ? Math.floor((now - this.active.startedAt) / 1000) : 0, + observerError: this.lastObserverError || ""}; +}; + +module.exports = {normalizePlan: normalizePlan, knownResultLog: knownResultLog, + resultFromLog: resultFromLog, Scheduler: Scheduler}; diff --git a/task_manager/task-manager.auto.js b/task_manager/task-manager.auto.js new file mode 100644 index 0000000..75f0a29 --- /dev/null +++ b/task_manager/task-manager.auto.js @@ -0,0 +1,335 @@ +"ui"; + +// AutoJs6 可视化串行任务管理器。将本文件与 lib 目录放在同一个文件夹。 +var ENTRY = String(engines.myEngine().getSource()); +var BASE = parentDirectory(files.path(ENTRY)); +var DATA = files.join(BASE, "data"); +var PLAN_FILE = files.join(DATA, "plan.json"); +var LOG_FILE = files.join(DATA, "manager.log"); +var STATUS_FILE = files.join(DATA, "status.json"); +var core = require(files.join(BASE, "lib/scheduler.js")); +var createAdapter = require(files.join(BASE, "lib/autojs-adapter.js")).createAdapter; +var adapter = null; +var scheduler = null; +var floatingWindow = null; +var closing = false; +var recentLogs = []; +var rowControls = []; + +function canonical(path) { return String(new java.io.File(String(path)).getCanonicalPath()); } +// AutoJs6 的 files 模块没有 dirname;统一通过 Android 的 Java File 取父目录。 +function parentDirectory(path) { + var parent = new java.io.File(String(path)).getParent(); + return parent === null ? "/" : String(parent); +} +function guard(action) { + return function () { + try { return action.apply(null, arguments); } + catch (error) { toast(String(error.message || error)); log(String(error)); } + }; +} +function ensureIdle() { + if (scheduler && scheduler.isBusy()) throw new Error("请先停止整组,确认当前脚本退出后再修改任务"); +} +function chooseExisting(paths) { + for (var i = 0; i < paths.length; i++) if (files.exists(paths[i])) return paths[i]; + return paths[0]; +} +function defaultPlan() { + return {version: 1, loops: 1, gapSeconds: 3, floating: true, tasks: [ + {id: "fanqie", name: "番茄小说", enabled: true, times: 1, timeoutMinutes: 480, retries: 0, onFailure: "skip", + path: chooseExisting(["/sdcard/脚本/番茄/fanqie-daily.auto.js", "/sdcard/脚本/fanqie-daily.auto.js", "/sdcard/Download/fanqie-daily.auto.js"])}, + {id: "hongguo", name: "红果免费短剧", enabled: true, times: 1, timeoutMinutes: 120, retries: 0, onFailure: "skip", + path: chooseExisting(["/sdcard/脚本/红果/hongguo-daily.auto.js", "/sdcard/脚本/hongguo-daily.auto.js", "/sdcard/Download/hongguo-daily.auto.js"])} + ]}; +} +function loadPlan() { + if (!files.exists(PLAN_FILE)) return core.normalizePlan(defaultPlan()); + try { return core.normalizePlan(JSON.parse(files.read(PLAN_FILE))); } + catch (error) { + var backup = PLAN_FILE + ".broken-" + Date.now(); + if (!files.copy(PLAN_FILE, backup)) throw new Error("配置损坏且无法保留副本,请检查:" + PLAN_FILE); + toast("旧配置无法读取,已保留副本;当前使用默认任务"); + return core.normalizePlan(defaultPlan()); + } +} +function atomicWrite(path, text) { + files.ensureDir(DATA + "/"); + files.write(path + ".tmp", text); + if (!new java.io.File(path + ".tmp").renameTo(new java.io.File(path))) throw new Error("保存失败:" + path); +} +function appendLog(message, state) { + var line = new Date().toISOString() + " " + message; + recentLogs.push(line); + if (recentLogs.length > 6) recentLogs.shift(); + files.append(LOG_FILE, line + "\n"); + if (state) atomicWrite(STATUS_FILE, JSON.stringify({updatedAt: new Date().toISOString(), state: state}, null, 2)); + log(line); +} + +// 第二次打开时保留原管理器及它正在运行的任务,不强停旧实例。 +var duplicate = engines.all().some(function (engine) { + return engine.id !== engines.myEngine().id && /(?:^|\/)task-manager\.auto\.js$/.test(String(engine.getSource())); +}); +if (duplicate) { + toast("任务管理器已经运行,请从最近任务切回原界面"); + activity.finish(); + exit(); +} + +files.ensureDir(DATA + "/"); +if (files.exists(LOG_FILE) && new java.io.File(LOG_FILE).length() > 1024 * 1024) { + if (files.copy(LOG_FILE, LOG_FILE + ".previous")) files.write(LOG_FILE, ""); +} +var plan = loadPlan(); +ui.layout( + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '