diff --git a/kuaishou_auto/kuaishou-daily.auto.js b/kuaishou_auto/kuaishou-daily.auto.js index 2539577..7736e33 100644 --- a/kuaishou_auto/kuaishou-daily.auto.js +++ b/kuaishou_auto/kuaishou-daily.auto.js @@ -2,37 +2,29 @@ // 快手极速版:无障碍文字 + 手机本地 OCR;不保存或上传图片,不访问媒体音量。 var CONFIG = { - version: "2026-10-30-kuaishou-26-ten-second-cadence", + version: "2026-10-23-kuaishou-6", packageName: "com.kuaishou.nebula", pollMs: 1200, - recognitionTimeoutMs: 30000, + recognitionTimeoutMs: 15000, capturePermissionTimeoutMs: 60000, captureRecoveryLimit: 2, useLocalOcr: true, roundTimeoutMs: 300000, taskSearchScrolls: 24, noProgressLimit: 3, - videoCalibrationMs: 120000, - videoSwipeIntervalMs: 10000, - videoSwipeDurationMs: 350, - videoSettleMs: 250, - videoCoinsPerPacket: 1, - videoEstimateMargin: 1.10, logPath: "/sdcard/Download/kuaishou-daily-run.log", - pageTextPath: "/sdcard/Download/kuaishou-daily-page.json", - flipResultPath: "/sdcard/Download/kuaishou-flip-result.json" + pageTextPath: "/sdcard/Download/kuaishou-daily-page.json" }; var localOcrEnabled = false; var captureQueue = null, captureWorker = null, captureRecoveries = 0; -var rejection = null, rewardSerial = 0, currentRoundRewardCoins = null; -var flipFlowActive = false; -var continuousCardReading = false; +var rejection = null, rewardSerial = 0; var STAGES = [ - {name: "翻卡赢金币", title: /^翻卡赢金币$/, kind: "flip"}, - {name: "连续看视频阶段奖励", kind: "continuousVideo"}, {name: "看广告得金币", title: /^看广告[得赚]金币$/, kind: "ad", stopAtCoins: 20}, + {name: "到饭点领饭补", title: /^到饭点领饭补$/, kind: "meal"}, {name: "明日0点领金币", title: /^(?:明日0点领金币|预约领金币)$/, kind: "reserve"}, {name: "搜索看广告", title: /^搜索看广告$/, kind: "search"}, + {name: "逛街领金币", title: /^逛街[领赚]金币$/, kind: "street"}, + {name: "翻卡赢金币", title: /^翻卡赢金币$/, kind: "flip"}, {name: "逛快手商城赚金币", title: /^逛(?:快手|开售)商城[赚领]金币$/, kind: "mall", products: 6} ]; @@ -189,7 +181,7 @@ function captureCall(name, timeoutMs, action) { if (done === null) { captureWorker.interrupt(); captureWorker.join(1500); - var timeout = new Error(name + "超时,页面读取或截图通道不可用"); + var timeout = new Error(name + "超时,截图通道不可用"); timeout.unsafeWorker = true; throw timeout; } @@ -256,14 +248,6 @@ function first(page, pattern, predicate) { } return null; } -// 只取明确到账文案,不能把“最高1金币”、余额或任务说明当成本轮收益。 -function recordRewardCoins(value) { - var match = /^(?:已成功领取|成功领取|恭喜获得|已获得|获得|领取成功[::]?)(\d+(?:,\d{3})*)金币$/.exec(compact(value)); - if (!match) return; - var amount = Number(match[1].replace(/,/g, "")); - if (currentRoundRewardCoins !== 1) currentRoundRewardCoins = amount; -} - function checkRejection(page) { var item = first(page, /设备异常|账号异常|操作异常|存在风险|风险行为|领取失败|操作过于频繁|操作频繁|任务失败/); if (rejection || item) throw new Error("[NO_RETRY] 平台拒绝:" + (rejection || item.text)); @@ -277,28 +261,18 @@ function readSnapshot() { foreground = foregroundPackage(); } if (foreground !== CONFIG.packageName) throw new Error("页面离开快手极速版(" + foreground + "),停止本轮操作"); - // 一次读取目标应用节点,避免分别按文字、描述、ID重复扫描整棵窗口树。 - // vivo 上切页期间重复全窗口查询可能累积超过识别期限。 - var items = []; - var nodes = packageName(CONFIG.packageName).find(); - for (var i = 0; i < nodes.size(); i++) { - var node = nodes.get(i), box = rectOf(node.bounds()); - if (!box || !node.visibleToUser()) continue; - var resourceId = String(node.id() || ""), enabled = node.enabled(); - var values = [compact(node.text()), compact(node.desc())]; - if (!values[0] && /:id\/(?:video_countdown|video_countdown_end_icon|.*close.*|live_simple_play_content_view|live_simple_play_swipe_text)$/.test(resourceId)) { - values.push("@" + resourceId.split("/").pop()); - } - if (!values[0] && !values[1] && node.clickable() && enabled && - box.right-box.left>device.width*.12 && box.right-box.leftdevice.height*.018 && box.bottom-box.topdevice.height*.25 && box.bottom= item.rect.right && - bounds.top <= item.rect.top && bounds.bottom >= item.rect.bottom && - bounds.right - bounds.left < device.width * 0.5 && - bounds.bottom - bounds.top < device.height * 0.12) ok = parent.click(); - } - } catch (ignore) {} + try { if (item.node.clickable()) ok = item.node.click(); } catch (ignore) {} } if (!ok) ok = press(Math.round((item.rect.left + item.rect.right) / 2), Math.round((item.rect.top + item.rect.bottom) / 2), 80); @@ -393,7 +351,7 @@ function isAd(page) { !!first(page, /^广告$/, function (item) {return item.rect.top < device.height * 0.20;}); } function adReward(page) { - return !!first(page, /^(?:已成功领取(?:奖励|\d+(?:,\d{3})*金币)|奖励已到账|已获得奖励|奖励领取成功|已领取奖励)$/, + return !!first(page, /^(?:已成功领取奖励|奖励已到账|已获得奖励|奖励领取成功|已领取奖励)$/, function (item) {return item.rect.top < device.height * 0.25;}); } function adClose(page) { @@ -423,44 +381,9 @@ function modalClose(page) { }); } function isLiveRoom(page) { - if (isAd(page) || isTaskCenter(page) || bottomNavigation(page, /^首页$/)) return false; - // 真直播间的关闭图标没有文字;不能只依赖“说点什么/更多直播”的 OCR。 - if (liveRoomClose(page)) return true; + if (isAd(page) || isTaskCenter(page)) return false; return !!first(page, /说点什么|直播回放/) && !!first(page, /更多直播|\d+观看/); } -function liveRoomClose(page) { - return first(page, /./, function (item) { - return /:id\/live_close$/.test(item.id || "") && item.enabled !== false && - item.rect.left > device.width * 0.65 && item.rect.bottom < device.height * 0.25; - }); -} -function liveLeaveConfirmation(page) { - if (!first(page, /(?:退出|离开|继续观看).*直播|直播.*(?:退出|离开)/)) return null; - return first(page, /^(?:退出直播间?|离开直播间?|确认退出|确定退出|仍要退出|退出|离开|确定)$/); -} -function exitLiveRoom(page) { - if (!isLiveRoom(page)) return page; - writeRunLog("LIVE EXIT: 误入直播间,优先点击直播关闭按钮"); - for (var attempt = 0; attempt < 4; attempt++) { - // 广告和首页预览有自己的处理规则,退出后不继续追点旧关闭坐标。 - if (isAd(page) || isTaskCenter(page) || bottomNavigation(page, /^首页$/)) { - writeRunLog("LIVE EXIT OK: 已离开直播间,继续原任务"); - return page; - } - var confirm = liveLeaveConfirmation(page), close = liveRoomClose(page); - if (confirm) tapFresh(confirm, liveLeaveConfirmation); - else if (close) tapFresh(close, function (fresh) { - return isLiveRoom(fresh) ? liveRoomClose(fresh) : null; - }); - else {back(); sleep(CONFIG.pollMs);} - page = snapshot(); - } - if (isAd(page) || isTaskCenter(page) || bottomNavigation(page, /^首页$/)) { - writeRunLog("LIVE EXIT OK: 已离开直播间,继续原任务"); - return page; - } - throw new Error("误入直播间后4次退出仍未回到首页或任务页,保留现场"); -} function dismissModal(page) { var close = modalClose(page); if (!close) return false; @@ -477,7 +400,6 @@ function ensureTaskCenter() { continue; } if (isAd(page)) throw new Error("奖励广告仍在进行,不用返回键提前退出"); - if (isLiveRoom(page)) {exitLiveRoom(page); continue;} if (dismissModal(page)) continue; var leave = first(page, /^(?:仍要退出|确认退出|坚持退出)$/); if (leave && first(page, /今日还剩\d+次.*机会|继续赚金币|继续賺金币/)) { @@ -540,15 +462,6 @@ function rowsOnPage(page, pattern) { rows.push({title: title, label: label, action: action, detail: detail, quota: progress, unavailable: unavailable}); }); - // 未结算翻卡卡片的标题是图片,原生列表只暴露倒计时、已翻位数和“继续翻”。 - if(pattern.test("翻卡赢金币") && !rows.some(function(r){return r.title==="翻卡赢金币";}) && isTaskCenter(page)) { - var resume=first(page,/^继续翻$/,function(i){return i.enabled!==false && i.rect.left>device.width*.72 && - i.rect.top>device.height*.095 && i.rect.bottom previous.done) { @@ -774,81 +682,15 @@ function browseStreet() { throw new Error("逛街连续5分钟没有领取次数进展,尚未领完10次"); } function isFlipPage(page) { - return !!first(page, /^翻卡赢金币$/) && !!first(page, /看广告翻|个视频可翻|不翻了[,,]?直接领|点击翻|立即翻|重翻[千百十个]位|^[千百十个]位$/); -} -function flipPositions(page) { - var heading=first(page,/^翻卡赢金币$/),positions=[]; - if(!heading) return positions; - ["个位","十位","百位","千位"].forEach(function(name){ - var label=first(page,{test:function(text){return text===name || (name==="千位"&&/^[包锁]千位$/.test(text));}},function(i){ - return i.rect.top>heading.rect.bottom && i.rect.bottom=label.rect.top-device.height*.12 && - i.rect.topheading.rect.bottom && i.rect.bottom=next.label.rect.top && - i.rect.bottom<=next.label.rect.bottom+device.height*.075 && - Math.abs((i.rect.left+i.rect.right)/2-center)heading.rect.bottom && i.rect.bottomdevice.height*.35 && i.rect.bottom device.height * 0.35 && item.rect.bottom < device.height * 0.88;}); } function flipSettlement(page) { - var decision=first(page,/^翻出\d+金币$/)&&flipDecision(page); - return decision&&decision.kind==="collect"?decision.button:null; + return first(page, /^翻出\d+金币$/) && first(page, /^(?:立即收下|开心收下|收下金币|领取金币)$/, + function (item) {return item.enabled !== false && item.rect.top > device.height * 0.4 && item.rect.bottom < device.height * 0.88;}); } function isMallList(page) { return !!first(page, /^购物车$/) && !!first(page, /^(?:推荐|直播精选|我的订单)$/) && !isTaskCenter(page); @@ -920,49 +762,32 @@ function browseMallProducts(limit) { return {taskDone: true, productsClicked: clicked, reason: "商城商品浏览完成(按页面剩余数量补足,最多6个)"}; } function executeRound(row, kind, options) { - var previous=flipFlowActive; - if(kind==="flip") flipFlowActive=true; - try{ - var outcome=executeTaskRound(row,kind,options); - if(kind==="flip" && outcome.taskDone && outcome.flippedAll) saveFlipDone(outcome.reason); - return outcome; - } - finally{flipFlowActive=previous;} -} -function executeTaskRound(row, kind, options) { options = options || {}; - var flipBeforeBalance=kind==="flip"?coinBalance(snapshot()):null; - var resumeFlip=kind==="flip" && options.resumeCurrent; - var fresh = resumeFlip?row:prepareRow(row); + var fresh = prepareRow(row); if (!fresh || fresh.unavailable) return {changed: !fresh, unavailable: !!fresh}; - if (!resumeFlip && !fresh.action) { + if (!fresh.action) { if (kind === "meal") return {unavailable: true, reason: "饭补入口不可点击"}; throw new Error("发现任务标题但没有同一行可用按钮:" + row.title); } var toastStart = rewardSerial; - if(!resumeFlip) tapFresh(fresh.action); + tapFresh(fresh.action); var deadline = Date.now() + CONFIG.roundTimeoutMs, rewardSeen = false, adSeen = false; var adClosed = false, searchClicked = false, entered = false, claims = {}; - var firstPageAt = Date.now(), searchAttempts = 0, flipClaimRequested=false,flipProgress=""; - var finalUnlockExpected=false,finalUnlockClosed=false,flipBalanceDeadline=null; + var firstPageAt = Date.now(); while (Date.now() < deadline) { var page = snapshot(); rewardSeen = rewardSeen || rewardSerial > toastStart; if (adReward(page)) rewardSeen = true; if (kind === "flip" && flipSettlement(page)) { - if(tapFresh(flipSettlement(page), flipSettlement)) flipClaimRequested=true; - continue; + tapFresh(flipSettlement(page), flipSettlement); + return {rewardSeen: true}; } if (kind === "street" && (streetProgress(page) || streetBadge(page) || streetComplete(page))) return browseStreet(); if (!(kind === "flip" && isFlipPage(page)) && dismissModal(page)) continue; if (isAd(page)) { adSeen = true; var close = adClose(page); - if (close) {tapFresh(close); adClosed = true; - if(kind==="flip") { - if(finalUnlockExpected) finalUnlockClosed=true; - writeRunLog("FLIP AD CLOSED: 已关闭奖励广告,回到当前卡片继续,不计翻卡已完成"); - }} + if (close) {tapFresh(close); adClosed = true;} else sleep(CONFIG.pollMs); continue; } @@ -970,33 +795,13 @@ function executeTaskRound(row, kind, options) { return {unavailable: true, rewardSeen: rewardSeen}; } if (kind === "flip" && isFlipPage(page)) { - var signature=flipPositions(page).map(function(p){return p.name+":"+p.digit;}).join("|"); - var unlockProgress=flipUnlockProgress(page); - if(unlockProgress) signature+="|解锁视频:"+unlockProgress.done+"/"+unlockProgress.total; - if(signature!==flipProgress){flipProgress=signature;deadline=Date.now()+CONFIG.roundTimeoutMs; - writeRunLog("FLIP PROGRESS: "+signature);} - var decision=flipDecision(page); - if(!decision){sleep(CONFIG.pollMs);continue;} - if(tapFresh(decision.button,function(p){var latest=flipDecision(p);return latest && latest.kind===decision.kind && - latest.position===decision.position?latest.button:null;})) { - writeRunLog("FLIP ACTION: "+decision.kind+";"+(decision.position||decision.button.text)); - if(decision.kind==="collect") flipClaimRequested=true; - if(decision.kind==="unlock") finalUnlockExpected=!!(unlockProgress && unlockProgress.done+1>=unlockProgress.total); - } - adClosed = false; - if(!flipClaimRequested) rewardSeen = false; + var flip = flipAction(page); + if (!flip) throw new Error("翻卡页未识别到可用翻卡或领取按钮"); + tapFresh(flip); + adClosed = false; rewardSeen = false; continue; } if (isTaskCenter(page)) { - if(kind==="flip" && flipClaimRequested) return {rewardSeen:true,taskDone:true,flippedAll:true,reason:"全部位数翻完,领取后已返回任务中心"}; - if(kind==="flip" && finalUnlockClosed && flipBeforeBalance!==null) { - var flipAfterBalance=coinBalance(page); - if(flipAfterBalance!==null && flipAfterBalance>flipBeforeBalance) return {rewardSeen:true,taskDone:true,flippedAll:true, - reason:"千位解锁次数完成并自动结算,余额增加"+(flipAfterBalance-flipBeforeBalance)+"金币"}; - if(flipBalanceDeadline===null) flipBalanceDeadline=Date.now()+15000; - if(Date.now() 8000) return {rewardSeen: rewardSeen}; sleep(CONFIG.pollMs); continue; @@ -1004,11 +809,10 @@ function executeTaskRound(row, kind, options) { entered = true; if (isLiveRoom(page)) { writeRunLog("ROUND LIVE REDIRECT: 进入直播推广页,返回任务中心;不计为完成"); - exitLiveRoom(page); return {rewardSeen: rewardSeen}; } // 续看弹窗关闭后本轮结束,由主循环重找任务,防止跨任务串行。 - if (adClosed && kind!=="flip") return {rewardSeen: rewardSeen}; + if (adClosed) return {rewardSeen: rewardSeen}; if (kind === "mall" && isMallList(page)) return browseMallProducts(options.products || 6); if (kind === "reserve") { if (first(page, /预约成功|已预约/)) return {taskDone: true, reason: "明日0点领金币已预约"}; @@ -1031,27 +835,18 @@ function executeTaskRound(row, kind, options) { } if (kind === "search" && !searchClicked) { var search = prescribedSearch(page); - if (search) { - if (++searchAttempts > 3) throw new Error("搜词按钮连续3次未进入搜索结果,保留异常,不空等5分钟"); - tapFresh(search); sleep(1500); - var searchAfter = snapshot(); - searchClicked = !prescribedSearch(searchAfter); - writeRunLog("SEARCH TRANSITION: 第" + searchAttempts + "次;" + - (searchClicked ? "已离开选词列表" : "仍在选词列表,重新识别按钮后重试")); - continue; - } + if (search) {tapFresh(search); searchClicked = true; sleep(1500); continue;} } var completion = first(page, /^(?:任务完成|浏览完成|恭喜获得\d+金币|已获得\d+金币|金币已到账|领取成功|奖励已到账)$/); if (completion) rewardSeen = true; var claim = first(page, /^(?:领取\d+金币|领取金币|领取奖励|点击领取|开心收下|收下金币)$/, function (item) {return item.rect.top > device.height * 0.3 && item.rect.bottom < device.height * 0.93;}); // 仅在任务/结算页面领取,广告推广的同名字样不触发。 - if (claim && !isAd(page) && (kind!=="flip" || flipClaimRequested) && (completion || first(page, /浏览.*(?:完成|金币)|搜索.*(?:完成|金币)|恭喜|任务奖励/))) { + if (claim && !isAd(page) && (completion || first(page, /浏览.*(?:完成|金币)|搜索.*(?:完成|金币)|恭喜|任务奖励/))) { var key = claim.text + ":" + Math.round(claim.rect.top / 50); if (!claims[key]) {claims[key] = true; tapFresh(claim); continue;} } - if (rewardSeen && (kind!=="flip" || flipClaimRequested)) return kind==="flip"? - {rewardSeen:true,taskDone:true,flippedAll:true,reason:"全部位数翻完并确认领取"}:{rewardSeen:true}; + if (rewardSeen) return {rewardSeen: true}; if ((kind === "street" || kind === "search") && timedBrowse(page)) { // 浏览计时期间交替上下滑,直到页面实际完成;不把“15秒”说明当作已结束。 var x = device.width * 0.42, down = Math.floor((Date.now() - firstPageAt) / 12000) % 2 === 0; @@ -1070,12 +865,11 @@ function drainTask(initial, kind, options) { var row = locateTask(pattern); if (!row) return {title: title, rounds: rounds, reason: "入口连续两次完整扫描未找到"}; if (row.unavailable) return {title: title, rounds: rounds, reason: "任务已完成或次数用完"}; - var beforeBalance = coinBalance(snapshot()); - currentRoundRewardCoins = null; + var beforeBalance = options.stopAtCoins !== undefined ? coinBalance(snapshot()) : null; var outcome; try { - // 翻卡可能要多次广告解锁下一位;按位数进展重置超时,不让外层固定5分钟截断。 - outcome = kind === "street" || kind === "flip" ? executeRound(row, kind, options) : + // 逛街在同页连续领取10次,按领取进展重置超时,不套用整项5分钟上限。 + outcome = kind === "street" ? executeRound(row, kind, options) : boundedCall(title + "单轮", CONFIG.roundTimeoutMs + 20000, function () {return executeRound(row, kind, options);}); } catch (error) { if (error.unsafeWorker || error.captureFatal || /\[NO_RETRY\]/.test(String(error))) throw error; @@ -1083,16 +877,12 @@ function drainTask(initial, kind, options) { outcome = {error: String(error)}; } ensureTaskCenter(); - if (currentRoundRewardCoins === 1) { - writeRunLog("ONE COIN STOP: " + title + ";单次实际收益1金币,退出当前流程,继续下一流程"); - return {title: title, rounds: rounds + 1, lastRewardCoins: 1, reason: "单次实际收益1金币,结束当前流程"}; - } if (outcome.taskDone) return {title: title, rounds: rounds, productsClicked: outcome.productsClicked, reason: outcome.reason}; var after = locateTask(pattern); if (resultAdvanced(row, after, outcome.rewardSeen)) { rounds++; noProgress = 0; writeRunLog("ROUND CONFIRMED: " + title + ";已确认=" + rounds); - { + if (options.stopAtCoins !== undefined) { var afterBalance = coinBalance(snapshot()), balanceDeadline = Date.now() + 6000; while (beforeBalance !== null && (afterBalance === null || afterBalance === beforeBalance) && Date.now() < balanceDeadline) { sleep(CONFIG.pollMs); @@ -1100,10 +890,9 @@ function drainTask(initial, kind, options) { } var earned = beforeBalance !== null && afterBalance !== null && afterBalance > beforeBalance ? afterBalance - beforeBalance : null; writeRunLog("ROUND COINS: " + title + ";本轮实际金币=" + earned); - if (earned === null && options.stopAtCoins !== undefined) return {title: title, rounds: rounds, incomplete: true, reason: "未确认本轮实际金币,暂停该项以免越过奖励阈值"}; - var stopAt = options.stopAtCoins !== undefined ? options.stopAtCoins : 1; - if (earned !== null && earned <= stopAt) return {title: title, rounds: rounds, lastRewardCoins: earned, - reason: "本轮实际金币≤" + stopAt + ",结束当前流程"}; + if (earned === null) return {title: title, rounds: rounds, incomplete: true, reason: "未确认本轮实际金币,暂停该项以免越过奖励阈值"}; + if (earned <= options.stopAtCoins) return {title: title, rounds: rounds, lastRewardCoins: earned, + reason: "本轮实际金币≤" + options.stopAtCoins + ",结束当前流程"}; } } else if (!outcome.changed && !outcome.unavailable && after && !after.unavailable) { noProgress++; @@ -1117,191 +906,10 @@ function drainTask(initial, kind, options) { incomplete: true, reason: "连续3轮未确认进展,保留异常,不冒充任务已完成"}; } } -function continuousVideoCard(page) { - var heading = first(page, /^连续看视频\d+天/, function(item) { - return item.rect.left < device.width * 0.3 && item.rect.top < device.height * 0.55; - }); - if (!heading) return null; - var region = page.filter(function(item) { - return item.rect.top >= heading.rect.bottom && item.rect.bottom < heading.rect.bottom + device.height * 0.24; - }); - var claim = first(region, /^(?:领金币|一键领取)$/); - var watch = first(region, /^(?:去看视频|看视频|继续看视频)$/); - // OPPO实际文案为“已攒6112/7886金币,继续看视频可开启”,不是单独的页码式数字。 - var progressItem = first(region, /^(?:已攒|已累计|已获得|已赚|已完成)?\d+(?:,\d{3})*\/\d+(?:,\d{3})*(?:金币|$)/); - var progress = progressItem && quota(progressItem.text.replace(/,/g, "")); - if (progress && (!progress.total || progress.done > progress.total)) progress = null; - var status = first(region, /(?:\d+金币待领取|已领\d+金币)/); - var done = !claim && !!first(region, /今日(?:奖励|金币|任务)?已(?:全部)?(?:领完|领取完|完成)|今日奖励已全部领取|明日再来|明天再来/); - return {claim:claim, watch:watch, progress:progress, done:done, - remainingCoins:progress ? progress.total - progress.done : null, - signature:(progress ? progress.done + "/" + progress.total : "") + "|" + (status ? status.text : "")}; -} -function locateContinuousVideoCard() { - var previous=continuousCardReading;continuousCardReading=true; - try{return readContinuousVideoCard();}finally{continuousCardReading=previous;} -} -function readContinuousVideoCard() { - ensureTaskCenter(); - for (var i=0;i<=CONFIG.taskSearchScrolls;i++) { - var page=snapshot(); - if (dismissModal(page)) continue; - var card=continuousVideoCard(page); - if (card) return card; - if(i CONFIG.roundTimeoutMs) - throw new Error("连续5分钟未确认正常视频观看,保留现场,不当作任务完成"); - if (isAd(page)) {pendingWatchMs = 0; finishExistingAd(); continue;} - if (isLiveRoom(page)) { - exitLiveRoom(page); - pendingWatchMs = 0; - continue; - } - if (dismissModal(page)) {pendingWatchMs = 0; continue;} - if (skippableContinuousFeedCard(page)) { - pendingWatchMs = 0; - writeRunLog("CONTINUOUS VIDEO: 上滑跳过兴趣选择、直播预览或图文卡片,继续观看"); - } else { - if (!isContinuousVideoFeed(page)) throw new Error("连续看视频未进入已识别的视频播放页,保留现场"); - lastVideoAt = Date.now(); - if (pendingWatchMs) { - // 只有等待前后都确认是普通视频才累计观看,直播/广告/预览不抵扣计划时长。 - watchedMs += Math.min(durationMs - watchedMs, Date.now() - pendingWatchSince); - pendingWatchMs = 0; - if (watchedMs >= durationMs) { - writeRunLog("CONTINUOUS VIDEO BATCH END: 已连续观看" + Math.round(watchedMs / 1000) + "秒,返回任务页领奖"); - return {watchedMs:watchedMs, reason:"duration"}; - } - } else { - pendingWatchMs = Math.min(CONFIG.videoSwipeIntervalMs, durationMs - watchedMs); - pendingWatchSince = readStartedAt; - writeRunLog("CONTINUOUS VIDEO WATCH: 普通视频,已看" + Math.round(watchedMs / 1000) + - "/" + Math.ceil(durationMs / 1000) + "秒;等待后重新识别页面"); - // 首读期间视频也在播放,并预留同量补读时间,让实际切换接近10秒。 - var remainingWait = pendingWatchMs - (Date.now() - pendingWatchSince) - pageReadMs; - if (remainingWait > 0) sleep(remainingWait); - keepScreenAwake(); - continue; - } - } - if (!swipe(device.width * 0.4, device.height * 0.74, device.width * 0.4, device.height * 0.3, CONFIG.videoSwipeDurationMs)) - throw new Error("连续看视频切换失败"); - writeRunLog("CONTINUOUS VIDEO SWIPE: 已切换下一视频"); - sleep(CONFIG.videoSettleMs); - } -} -function continuousVideoWatchPlan(card, msPerCoin) { - if (!card.progress || card.remainingCoins === null) throw new Error("未读到连续看视频剩余金币,不能估算观看时间"); - if (card.remainingCoins <= 0) throw new Error("视频进度已满但未出现领奖入口,不能继续盲刷"); - var durationMs = msPerCoin ? Math.max(1, Math.round(card.remainingCoins * msPerCoin * CONFIG.videoEstimateMargin)) : CONFIG.videoCalibrationMs; - if (!isFinite(durationMs) || durationMs <= 0) throw new Error("观看时间估算无效"); - return {durationMs:durationMs, remainingCoins:card.remainingCoins, - packets:Math.ceil(card.remainingCoins / CONFIG.videoCoinsPerPacket), calibration:!msPerCoin}; -} -function waitContinuousVideoReceipt() { - // vivo 弹窗动画期间原生树和截图可能仍是上一帧,不能单次读取就判定失败。 - var deadline=Date.now()+15000; - do { - var page=snapshot(); - if(first(page,/^任务完成奖励$/)) return page; - sleep(CONFIG.pollMs); - } while(Date.now() 0 && sample.watchedMs > 0) { - var measured = sample.watchedMs / gain; - msPerCoin = msPerCoin ? (msPerCoin + measured) / 2 : measured; - noProgress = 0; - writeRunLog("CONTINUOUS VIDEO RATE: 观看" + Math.round(sample.watchedMs / 1000) + "秒,任务增加" + gain + - "金币;按每红包约" + CONFIG.videoCoinsPerPacket + "金币折算,每红包约" + - (msPerCoin * CONFIG.videoCoinsPerPacket / 1000).toFixed(2) + "秒"); - } else if (!card.claim && !card.done && gain === 0) { - noProgress++; - // 进度未增加时重新测算,不沿用已经失效的收益速度。 - msPerCoin = null; - writeRunLog("CONTINUOUS VIDEO NO PROGRESS: " + noProgress + "/" + CONFIG.noProgressLimit); - } else noProgress = 0; - sample = null; - } - if(card.done) return {title:"连续看视频阶段奖励",rounds:claims,reason:"今日连续看视频奖励已全部领取"}; - if(noProgress>=CONFIG.noProgressLimit) return {title:"连续看视频阶段奖励",rounds:claims,incomplete:true, - reason:"连续3次观看未确认金币进度增加,保留异常,不当作全部领完"}; - if(card.claim) { - if (!tapFresh(card.claim,function(page){var current=continuousVideoCard(page);return current&¤t.claim;})) continue; - var receipt=waitContinuousVideoReceipt(); - claims++;writeRunLog("CONTINUOUS VIDEO CLAIM: 已确认领取第"+claims+"笔,不按1金币阈值退出"); - var close=modalClose(receipt); - if(close) tapFresh(close,modalClose); - else throw new Error("连续看视频领奖弹窗没有明确关闭入口"); - continue; - } - if(!card.watch) throw new Error("连续看视频尚未确认领完,且未找到观看入口"); - var plan = continuousVideoWatchPlan(card, msPerCoin); - writeRunLog("CONTINUOUS VIDEO PLAN: 当前奖励还差" + plan.remainingCoins + "金币,约" + plan.packets + "个红包;" + - (plan.calibration ? "先观看" : "预计连续观看") + Math.ceil(plan.durationMs / 1000) + "秒" + - (plan.calibration ? "测算速度,仅回查一次" : "(含10%余量),到时再回任务页领奖,中途不查收益")); - if (!tapFresh(card.watch,function(page){var current=continuousVideoCard(page);return current&¤t.watch;})) - throw new Error("开始连续观看前任务入口变化,未启动观看"); - var result = watchContinuousVideoSegment(plan.durationMs); - sample = {before:card.progress, watchedMs:result.watchedMs}; - } -} - -function runStages(startKind) { +function runStages() { var results = []; - var stages = STAGES; - if (startKind) { - var index = STAGES.map(function (stage) {return stage.kind;}).indexOf(String(startKind)); - if (index < 0) throw new Error("未知恢复流程:" + startKind); - stages = STAGES.slice(index); - writeRunLog("RESUME STAGE: " + stages[0].name); - } - stages.forEach(function (stage) { - if(stage.kind==="flip" && flipDoneToday()) { - results.push({title:stage.name,taskDone:true,reason:"今天翻卡已确认结算,直接进入下一流程"}); - writeRunLog("STAGE SKIP COMPLETED: "+stage.name+";今天已结算,直接进入下一流程"); - return; - } + STAGES.forEach(function (stage) { writeRunLog("STAGE START: " + stage.name); - if (stage.kind === "continuousVideo") { - var videoResult=continuousVideoStep();results.push(videoResult); - writeRunLog("TASK RESULT: "+JSON.stringify(videoResult)); - writeRunLog("STAGE END: "+stage.name);return; - } var row = locateTask(stage.title); if (row) { var result = drainTask(row, stage.kind, stage); @@ -1317,7 +925,6 @@ function installToastObserver() { events.onToast(function (event) { if (String(event.getPackageName()) !== CONFIG.packageName) return; var value = compact(event.getText()); - recordRewardCoins(value); if (/设备异常|账号异常|操作异常|领取失败|操作频繁|操作过于频繁|存在风险/.test(value)) rejection = value; if (/领取成功|已获得\d+金币|金币已到账|成功领取\d+金币/.test(value)) rewardSerial++; writeRunLog("APP TOAST: " + value); @@ -1330,10 +937,6 @@ function finishExistingAd() { var deadline = Date.now() + CONFIG.roundTimeoutMs; while (Date.now() < deadline) { page = snapshot(); - if(isFlipPage(page) || flipSettlement(page)) { - writeRunLog("STARTUP AD CLOSED: 已回到未完成翻卡,交回翻卡流程,不关闭卡片弹窗"); - return; - } if (dismissModal(page)) continue; if (!isAd(page)) { writeRunLog("STARTUP AD CLOSED: 当前广告已退出"); @@ -1364,14 +967,8 @@ function runDaily() { return "INSPECT DONE: 仅保存本机页面文字,未执行任务"; } finishExistingAd(); - var currentPage=snapshot(); - if((!mine.execArgv || !mine.execArgv.startStage || mine.execArgv.startStage==="flip") && - (isFlipPage(currentPage) || flipSettlement(currentPage))) { - writeRunLog("FLIP RESUME: 当前翻卡尚未结算,先完成现有卡片再回任务中心"); - executeRound({title:"翻卡赢金币"},"flip",{resumeCurrent:true}); - } ensureTaskCenter(); - var results = runStages(mine.execArgv && mine.execArgv.startStage); + var results = runStages(); if (results.some(function (result) {return result.incomplete;})) throw new Error("部分任务未确认完成,请查看 TASK RESULT 日志"); return "DONE: 快手极速版各类任务已依次执行至不可做或入口消失;" + JSON.stringify(results); } diff --git a/kuaishou_main_auto/README.md b/kuaishou_main_auto/README.md new file mode 100644 index 0000000..5d52a95 --- /dev/null +++ b/kuaishou_main_auto/README.md @@ -0,0 +1,27 @@ +# 快手 App 日常任务脚本 + +入口:[kuaishou-main-daily.auto.js](kuaishou-main-daily.auto.js),目标包名 `com.smile.gifmaker`,用于普通快手 App。快手极速版继续使用 `kuaishou_auto/kuaishou-daily.auto.js`,包名为 `com.kuaishou.nebula`。 + +当前流程:翻卡赢金币 → 看广告得金币 → 明日0点领金币/预约领金币 → 搜索看广告 → 逛快手商城赚金币。按用户最新要求不执行“看视频赚金币”和连续视频阶段。 + +- 通过底部赚钱导航或左上侧边栏“任务中心”进入任务页。只识别这两个入口,不点“玩游戏送超多金币”行的“去赚钱”。 +- 普通版列表滚动后会收起“任务中心”标题,使用顶部固定的金币/现金栏继续识别任务页;余额支持标签和数值分开显示。 +- 翻卡保留原有数位和解锁进度;其他任务按当前可执行入口循环,操作失败保留未完成。 +- 看广告得金币单轮实际收益≤20金币时结束该项;预约仅执行一次;商城最多补足6个商品。 +- 取消明确的“添加桌面微件”浮层。刚点击赚钱入口就被其他应用抢前台时,仅重新打开目标应用复查一次;广告和普通观看中离开应用仍停止。 +- “去分享视频可再得金币/确定要离开吗”挽留弹窗点“狠心离开”。任务中心“努力加载中”最多等待30秒,不滑动刷新或反复退出重进;持续加载记为异常,不当作任务消失。 +- 日志、最近页面文字和每日翻卡完成记录与极速版分别保存;不上传或保存图片,不改变媒体音量。 + +手机部署路径:`/sdcard/脚本/快手/kuaishou-main-daily.auto.js`。极速版独立放在`/sdcard/脚本/快手极速版/kuaishou-daily.auto.js`。 + +手机文字文件: + +- `/sdcard/Download/kuaishou-main-daily-run.log` +- `/sdcard/Download/kuaishou-main-daily-page.json` +- `/sdcard/Download/kuaishou-main-flip-result.json` + +部署前须在 AutoJs6 应用详情 → 耗电管理核对“允许后台高耗电”已开启。两款快手任务使用同一台手机时应依次运行,避免两个引擎同时操作页面。 + +2026-11-01:16项针对性检查与两份脚本语法检查通过。已核对AutoJs6设置页“完全允许后台行为”选中;普通版实机通过侧边栏任务中心进入“看广告得金币”,等待真实倒计时并关闭广告和续看浮层,余额1340→1341,按单轮≤20金币结束该项。此期间AutoJs6在后台,任务持续更新日志。 + +两款手机文件夹已经分开,任务管理器旧极速版路径已迁移,原启用状态及次数保持不变。连接恢复后已同步普通版5(不看普通视频,含加载等待修复),手机与电脑SHA256一致:`a92d0f166f0a124ae5fcda195a3cb3b176eca601fc7ae2cf2d70b7bbc2d333d2`。目前手机依次复测两款脚本,当前运行极速版,避免同时操作页面。实机记录见`../kuaishou_auto/verification/2026-11-01-oppo-stall/`,未声称当天全部任务已经完成。 diff --git a/kuaishou_main_auto/kuaishou-main-daily.auto.js b/kuaishou_main_auto/kuaishou-main-daily.auto.js new file mode 100644 index 0000000..8504f26 --- /dev/null +++ b/kuaishou_main_auto/kuaishou-main-daily.auto.js @@ -0,0 +1,1501 @@ +"auto"; + +// 快手:无障碍文字 + 手机本地 OCR;不保存或上传图片,不访问媒体音量。 +var CONFIG = { + version: "2026-11-01-kuaishou-main-5-no-video", + appName: "快手", + packageName: "com.smile.gifmaker", + taskCenterWithoutBottomNav: true, + homeNavigationPattern: /^(?:首页|精选)$/, + continuousVideoOptional: true, + pollMs: 1200, + recognitionTimeoutMs: 30000, + capturePermissionTimeoutMs: 60000, + captureRecoveryLimit: 2, + useLocalOcr: true, + roundTimeoutMs: 300000, + taskSearchScrolls: 24, + noProgressLimit: 3, + videoCalibrationMs: 120000, + videoSwipeIntervalMs: 10000, + videoSwipeDurationMs: 350, + videoSettleMs: 250, + videoCoinsPerPacket: 1, + videoEstimateMargin: 1.10, + logPath: "/sdcard/Download/kuaishou-main-daily-run.log", + pageTextPath: "/sdcard/Download/kuaishou-main-daily-page.json", + flipResultPath: "/sdcard/Download/kuaishou-main-flip-result.json" +}; +var localOcrEnabled = false; +var captureQueue = null, captureWorker = null, captureRecoveries = 0; +var rejection = null, rewardSerial = 0, currentRoundRewardCoins = null; +var flipFlowActive = false; +var continuousCardReading = false; +var STAGES = [ + {name: "翻卡赢金币", title: /^翻卡赢金币$/, kind: "flip"}, + {name: "看广告得金币", title: /^看广告[得赚]金币$/, kind: "ad", stopAtCoins: 20}, + {name: "明日0点领金币", title: /^(?:明日0点领金币|预约领金币)$/, kind: "reserve"}, + {name: "搜索看广告", title: /^搜索看广告$/, kind: "search"}, + {name: "逛快手商城赚金币", title: /^逛(?:快手|开售)商城[赚领]金币$/, kind: "mall", products: 6} +]; + +function writeRunLog(message) { + var line = new Date().toISOString() + " " + message; + log(line); + files.append(CONFIG.logPath, line + "\n"); +} + +// 各脚本保持可单独复制运行;共同启动行为由跨脚本回归测试验证。 +var nextScreenKeepAliveAt = 0; +function keepScreenAwake() { + if (typeof device === "undefined" || typeof device.keepScreenOn !== "function" || Date.now() < nextScreenKeepAliveAt) return; + device.keepScreenOn(3600000); + nextScreenKeepAliveAt = Date.now() + 60000; +} +function releaseScreenAwake() { + nextScreenKeepAliveAt = 0; + if (typeof device !== "undefined" && typeof device.cancelKeepingAwake === "function") device.cancelKeepingAwake(); +} +function waitStartupPackage(packageName, timeoutMs) { + var deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + keepScreenAwake(); + if (foregroundPackage() === packageName) return; + sleep(200); + } + throw new Error("等待应用进入前台超时:" + packageName); +} +function clickStartupNode(node) { + for (var depth = 0; node && depth < 4; depth++, node = node.parent()) { + if (!node.enabled()) return false; + if (node.clickable()) return node.click(); + } + return false; +} +function prepareCaptureForeground() { + keepScreenAwake(); + auto.waitFor(); + var staleTitle = textMatches(/.*AutoJs6.*(?:录制|投放|投射|截取|共享|分享|screen|capture).*/i).packageName("com.android.systemui").findOnce(); + var cancel = staleTitle && textMatches(/^(?:取消|Cancel)$/i).packageName("com.android.systemui").findOnce(); + if (cancel && clickStartupNode(cancel)) sleep(400); + var hostPackage = String(context.getPackageName()); + if (foregroundPackage() !== hostPackage && !app.launchPackage(hostPackage)) throw new Error("无法将 AutoJs6 切到前台申请截屏授权"); + waitStartupPackage(hostPackage, 8000); + sleep(400); +} +// 仅处理系统的 AutoJs6 录屏对话框,不处理应用里的“允许”等按钮。 +function approveCaptureDialog(state) { + var verified = false; + var deadline = Date.now() + CONFIG.capturePermissionTimeoutMs; + while (state.pending && Date.now() < deadline) { + if (foregroundPackage() === "com.android.systemui") { + var title = textMatches(/.*AutoJs6.*(?:录制|投放|投射|截取|共享|分享|screen|capture).*/i).packageName("com.android.systemui").findOnce(); + if (title) verified = true; + if (verified) { + var whole = textMatches(/^(?:整个屏幕|Entire screen|Full screen)$/i).packageName("com.android.systemui").findOnce(); + var single = textMatches(/^(?:单个应用|单个应用程序|A single app|Single app)$/i).packageName("com.android.systemui").findOnce(); + if (single && !whole) clickStartupNode(single); + else if (whole && !title) clickStartupNode(whole); // 展开的范围菜单 + else if (title && !single) { + var allow = textMatches(/^(?:开始|立即开始|允许|Start now|Start|Allow)$/i).packageName("com.android.systemui").findOnce(); + if (allow && clickStartupNode(allow)) writeRunLog("CAPTURE APPROVE: 已确认 AutoJs6 系统截屏授权。"); + } + } + } else verified = false; + sleep(200); + } +} +function requestLocalCapture() { + prepareCaptureForeground(); + var state = {pending: true}; + var approver = threads.start(function () { approveCaptureDialog(state); }); + try { + return requestScreenCapture(false); + } finally { + state.pending = false; + approver.interrupt(); + approver.join(1500); + if (approver.isAlive()) { + var error = new Error("截屏授权辅助线程未退出,不能继续操作页面"); + error.unsafeWorker = true; + throw error; + } + } +} +function 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 compact(value) { + var text = String(value || "").replace(/[\s\u200b-\u200d\uFEFF]+/g, "").replace(/領/g, "领").replace(/貼/g, "贴").replace(/朴贴/g, "补贴") + .replace(/視/g, "视").replace(/頻/g, "频").replace(/賺/g, "赚").replace(/贏/g, "赢").replace(/^[||「『]+|[||]+$/g, ""); + return /^(?:close[_-]?button|关闭按钮)$/i.test(text) ? "关闭" : text; +} + +function rectOf(bounds) { + if (!bounds) return null; + function numberAt(name) { + return Number(typeof bounds[name] === "function" ? bounds[name]() : bounds[name]); + } + var rect = {left: numberAt("left"), top: numberAt("top"), + right: numberAt("right"), bottom: numberAt("bottom")}; + if (!isFinite(rect.left) || !isFinite(rect.top) || !isFinite(rect.right) || + !isFinite(rect.bottom) || rect.right <= rect.left || rect.bottom <= rect.top) return null; + if (rect.left < 0 || rect.top < 0 || rect.right > device.width || rect.bottom > device.height) return null; + return rect; +} + +// 整次运行复用同一截图线程,避免每次识别创建新的投影显示。 +function captureCall(name, timeoutMs, action) { + if (!captureWorker || !captureWorker.isAlive()) { + captureQueue = new java.util.concurrent.LinkedBlockingQueue(); + captureWorker = threads.start(function () { + while (!java.lang.Thread.currentThread().isInterrupted()) { + var job = captureQueue.take(); + try { job.value.set({value: job.action()}); } + catch (error) { job.value.set({error: error}); } + } + }); + } + var result = new java.util.concurrent.atomic.AtomicReference(); + captureQueue.put({action: action, value: result}); + var deadline = Date.now() + timeoutMs; + while (result.get() === null && Date.now() < deadline) sleep(100); + var done = result.get(); + if (done === null) { + captureWorker.interrupt(); + captureWorker.join(1500); + var timeout = new Error(name + "超时,页面读取或截图通道不可用"); + timeout.unsafeWorker = true; + throw timeout; + } + if (done.error) throw done.error; + return done.value; +} + +function initLocalOcr() { + if (!CONFIG.useLocalOcr || typeof $ocr === "undefined" || typeof $ocr.detect !== "function") { + log("未检测到本地 $ocr.detect,仅使用无障碍文字;识别不到时停止,不按旧坐标点击。"); + return; + } + captureCall("申请截图", CONFIG.capturePermissionTimeoutMs, function () { + // Android 14+ 不允许复用同一个授权令牌创建第二个显示。 + // 本任务为竖屏,固定方向可避免 AUTO 模式在页面切换后重建显示。 + if (!requestLocalCapture()) stopWith("未获得本机截屏权限;无需上传图片。"); + localOcrEnabled = true; + }); +} + +function isProjectionFailure(error) { + return /MediaProjection|VirtualDisplay|resultData|projection instance|Failed to capture screen|截图通道不可用/.test(String(error)); +} + +function readPage(name) { + try { + return captureCall(name, CONFIG.recognitionTimeoutMs, readSnapshot); + } catch (error) { + if (error.unsafeWorker || !isProjectionFailure(error)) throw error; + if (captureRecoveries >= CONFIG.captureRecoveryLimit) { + error.captureFatal = true; + writeRunLog("截图通道连续失效,结束本次运行;不能将识别故障当作类目缺失。"); + throw error; + } + captureRecoveries++; + writeRunLog("CAPTURE RECOVER: " + captureRecoveries + "/" + CONFIG.captureRecoveryLimit + ";释放失效投影并重新申请本机截屏。"); + try { + captureCall("恢复截图授权", CONFIG.capturePermissionTimeoutMs, function () { + images.stopScreenCapture(); + if (!requestLocalCapture()) throw new Error("恢复截图授权未获允许"); + if (!app.launchPackage(CONFIG.packageName)) throw new Error("截图恢复后无法返回目标应用"); + waitStartupPackage(CONFIG.packageName, 10000); + sleep(500); + }); + var page = captureCall("恢复后重新识别", CONFIG.recognitionTimeoutMs, readSnapshot); + writeRunLog("CAPTURE RECOVERED: 本机页面识别已恢复。"); + return page; + } catch (recoveryError) { + recoveryError.captureFatal = true; + throw recoveryError; + } + } +} + + +function foregroundPackage() { + var root = auto.service ? auto.service.getRootInActiveWindow() : auto.rootInActiveWindow; + return root ? String(root.getPackageName()) : ""; +} +function stopWith(message) { throw new Error(message); } +function first(page, pattern, predicate) { + for (var i = 0; i < page.length; i++) { + if (pattern.test(page[i].text) && (!predicate || predicate(page[i]))) return page[i]; + } + return null; +} +// 只取明确到账文案,不能把“最高1金币”、余额或任务说明当成本轮收益。 +function recordRewardCoins(value) { + var match = /^(?:已成功领取|成功领取|恭喜获得|已获得|获得|领取成功[::]?)(\d+(?:,\d{3})*)金币$/.exec(compact(value)); + if (!match) return; + var amount = Number(match[1].replace(/,/g, "")); + if (currentRoundRewardCoins !== 1) currentRoundRewardCoins = amount; +} + +function checkRejection(page) { + var item = first(page, /设备异常|账号异常|操作异常|存在风险|风险行为|领取失败|操作过于频繁|操作频繁|任务失败/); + if (rejection || item) throw new Error("[NO_RETRY] 平台拒绝:" + (rejection || item.text)); +} +function desktopShortcutCancel(page) { + var heading = first(page, /^(?:添加至桌面|添加到桌面|添加到主屏幕|添加小组件)$/); + if (!heading || !first(page, /领钱助手|赚钱助手|微件|小组件/)) return null; + return first(page, /^取消$/, function (item) { + return item.enabled !== false && item.rect.top > heading.rect.bottom && + item.rect.left < device.width * 0.5; + }); +} +function dismissSystemShortcutPrompt(foreground) { + if (!/^(?:com\.android\.launcher|com\.oplus\.launcher|com\.coloros\.launcher|com\.android\.systemui|android)$/.test(foreground)) return false; + var heading = textMatches("^(?:添加至桌面|添加到桌面|添加到主屏幕|添加小组件)$").packageName(foreground).findOnce(); + var widget = textMatches(".*(?:领钱助手|赚钱助手|微件|小组件).*").packageName(foreground).findOnce(); + var cancel = textMatches("^取消$").packageName(foreground).findOnce(); + if (!heading || !widget || !cancel || !clickStartupNode(cancel)) return false; + writeRunLog("SHORTCUT DISMISS: 已取消系统添加桌面微件,返回" + CONFIG.appName); + sleep(CONFIG.pollMs); + return true; +} +function readSnapshot() { + keepScreenAwake(); + var foreground = foregroundPackage(), deadline = Date.now() + 1500; + if (foreground !== CONFIG.packageName && dismissSystemShortcutPrompt(foreground)) foreground = foregroundPackage(); + // 切页时无障碍窗口可能短暂为空,确认后再判断是否真的离开应用。 + while (foreground !== CONFIG.packageName && Date.now() < deadline) { + sleep(150); + foreground = foregroundPackage(); + } + if (foreground !== CONFIG.packageName) { + var foregroundError = new Error("页面离开" + CONFIG.appName + "(" + foreground + "),停止本轮操作"); + foregroundError.foregroundMismatch = true; + foregroundError.foreground = foreground; + throw foregroundError; + } + // 一次读取目标应用节点,避免分别按文字、描述、ID重复扫描整棵窗口树。 + // vivo 上切页期间重复全窗口查询可能累积超过识别期限。 + var items = []; + var nodes = packageName(CONFIG.packageName).find(); + for (var i = 0; i < nodes.size(); i++) { + var node = nodes.get(i), box = rectOf(node.bounds()); + if (!box || !node.visibleToUser()) continue; + var resourceId = String(node.id() || ""), enabled = node.enabled(); + var values = [compact(node.text()), compact(node.desc())]; + if (!values[0] && !values[1] && CONFIG.taskCenterWithoutBottomNav && + /:id\/(?:left_btn|left_button|sidebar_button)$/.test(resourceId) && + box.left < device.width * 0.20 && box.top < device.height * 0.20) values.push("@task_center_menu"); + if (!values[0] && /:id\/(?:video_countdown|video_countdown_end_icon|.*close.*|live_simple_play_content_view|live_simple_play_swipe_text)$/.test(resourceId)) { + values.push("@" + resourceId.split("/").pop()); + } + if (!values[0] && !values[1] && node.clickable() && enabled && + box.right-box.left>device.width*.12 && box.right-box.leftdevice.height*.018 && box.bottom-box.topdevice.height*.25 && box.bottom= item.rect.right && + bounds.top <= item.rect.top && bounds.bottom >= item.rect.bottom && + bounds.right - bounds.left < device.width * 0.5 && + bounds.bottom - bounds.top < device.height * 0.12) ok = parent.click(); + } + } catch (ignore) {} + } + if (!ok) ok = press(Math.round((item.rect.left + item.rect.right) / 2), + Math.round((item.rect.top + item.rect.bottom) / 2), 80); + if (!ok) throw new Error("点击未响应:" + item.text); + writeRunLog("CLICK: " + item.text); + sleep(CONFIG.pollMs); +} +function sameItem(page, old) { + return first(page, {test: function (value) { return value === old.text; }}, function (item) { + return Math.abs(item.rect.top - old.rect.top) < 45 && Math.abs(item.rect.left - old.rect.left) < 45; + }); +} +function tapFresh(item, resolveFresh) { + var page = snapshot(), fresh = resolveFresh ? resolveFresh(page) : sameItem(page, item); + // 弹窗自行消失时重新识别页面,不追点旧叉号。 + if (!fresh && resolveFresh) return false; + clickItem(fresh); + return true; +} +function bottomNavigation(page, pattern) { + return first(page, pattern, function (item) { + return item.rect.top > device.height * 0.90 && item.rect.bottom < device.height * 0.99; + }); +} +function homeNavigation(page) { + return bottomNavigation(page, CONFIG.homeNavigationPattern || /^首页$/); +} +function isTaskCenter(page) { + var heading = first(page, /^(?:任务中心|金币任务中心)$/); + if (!CONFIG.taskCenterWithoutBottomNav) return !!heading && !!bottomNavigation(page, /^去赚钱$/); + if (heading && first(page, /^(?:我的金币|我的金币[>〉]|金币收益|日常任务)$/)) return true; + // 普通版滚动后标题收起,顶部固定显示“金币: / 现金:”,不能误判离开任务中心。 + var coinHeader = first(page, /^(?:金币[::]\d*|我的金币[>〉]?)$/, function (item) { return item.rect.bottom < device.height * 0.25; }); + var cashHeader = first(page, /^(?:现金[::]\d*(?:\.\d+)?|我的现金)$/, function (item) { return item.rect.bottom < device.height * 0.25; }); + return !!(coinHeader && cashHeader); +} +function taskCenterEntry(page) { + var nav = bottomNavigation(page, /^(?:去赚钱|赚钱)$/); + if (nav || !CONFIG.taskCenterWithoutBottomNav) return nav; + // 任务列表里的游戏卡也叫“去赚钱”;只允许侧边栏中的明确任务中心入口。 + if (!first(page, /^(?:sideBarScroller|常用功能|工具服务)$/)) return null; + return first(page, /^任务中心$/, function (item) { + return item.enabled !== false && item.rect.top < device.height * 0.5; + }); +} +function taskCenterMenu(page) { + if (!CONFIG.taskCenterWithoutBottomNav || isAd(page) || isLiveRoom(page)) return null; + return first(page, /./, function (item) { + return item.enabled !== false && item.rect.left < device.width * 0.20 && item.rect.top < device.height * 0.20 && + (/^(?:菜单|打开菜单|侧边栏|侧边栏按钮|打开侧边栏|更多功能)$/.test(item.text) || /:id\/(?:left_btn|left_button|sidebar_button)$/.test(item.id || "")); + }); +} +function isAd(page) { + return !!first(page, /^(?:@video_countdown_end_icon|\d+(?:s|秒)后可领取奖励|已成功领取奖励)$/) || + page.some(function (item) {return /:id\/video_countdown$/.test(item.id || "");}) || + !!first(page, /^广告$/, function (item) {return item.rect.top < device.height * 0.20;}); +} +function adReward(page) { + return !!first(page, /^(?:已成功领取(?:奖励|\d+(?:,\d{3})*金币)|奖励已到账|已获得奖励|奖励领取成功|已领取奖励)$/, + function (item) {return item.rect.top < device.height * 0.25;}); +} +function adClose(page) { + if (!adReward(page)) return null; + // 实机关闭图标位于左上奖励倒计时旁;不是媒体音量控件。 + return first(page, /^@video_countdown_end_icon$/) || first(page, /^(?:关闭广告|关闭|[xX×✕])$/, + function (item) {return item.rect.top < device.height * 0.25;}); +} +function modalClose(page) { + var shortcutCancel = desktopShortcutCancel(page); + if (shortcutCancel) return shortcutCancel; + var sharing = first(page, /^去分享视频可再得金币$/); + var leaveHeading = sharing && first(page, /^确定要离开吗[??]?$/); + if (leaveHeading) { + var leaveSharing = first(page, /^狠心离开$/, function (item) { + return item.enabled !== false && item.rect.top > leaveHeading.rect.bottom && + item.rect.left < device.width * 0.5 && item.rect.bottom < device.height * 0.93; + }); + if (leaveSharing) return leaveSharing; + } + var close = first(page, /^(?:close_view|关闭弹窗|关闭幸运宝箱活动)$/); + if (close) return close; + var mallHeading = first(page, /^我的金币收益$/); + if (mallHeading && first(page, /^点击商品[((]\d+\/\d+[))]$/)) { + return first(page, /^(?:关闭|[xX×✕])$/, function (item) { + return item.rect.left > device.width * 0.90 && item.rect.bottom <= mallHeading.rect.top && + item.rect.top > mallHeading.rect.top - device.height * 0.10; + }); + } + // 实机邀请浮层只提供 OCR 的 X,位置在邀请标题上方的右侧。 + var invite = first(page, /限时邀.*好友.*(?:现金|现全)/); + if (!invite || !first(page, /^去微信邀请好友$/)) return null; + return first(page, /^(?:关闭|[xX×✕])$/, function (item) { + return item.rect.left > device.width * 0.82 && item.rect.bottom < invite.rect.top && + item.rect.top > Math.max(device.height * 0.10, invite.rect.top - device.height * 0.25) && + item.rect.right - item.rect.left < device.width * 0.12 && + item.rect.bottom - item.rect.top < device.height * 0.06; + }); +} +function isLiveRoom(page) { + if (isAd(page) || isTaskCenter(page) || homeNavigation(page)) return false; + // 真直播间的关闭图标没有文字;不能只依赖“说点什么/更多直播”的 OCR。 + if (liveRoomClose(page)) return true; + return !!first(page, /说点什么|直播回放/) && !!first(page, /更多直播|\d+观看/); +} +function liveRoomClose(page) { + return first(page, /./, function (item) { + return /:id\/live_close$/.test(item.id || "") && item.enabled !== false && + item.rect.left > device.width * 0.65 && item.rect.bottom < device.height * 0.25; + }); +} +function liveLeaveConfirmation(page) { + if (!first(page, /(?:退出|离开|继续观看).*直播|直播.*(?:退出|离开)/)) return null; + return first(page, /^(?:退出直播间?|离开直播间?|确认退出|确定退出|仍要退出|退出|离开|确定)$/); +} +function exitLiveRoom(page) { + if (!isLiveRoom(page)) return page; + writeRunLog("LIVE EXIT: 误入直播间,优先点击直播关闭按钮"); + for (var attempt = 0; attempt < 4; attempt++) { + // 广告和首页预览有自己的处理规则,退出后不继续追点旧关闭坐标。 + if (isAd(page) || isTaskCenter(page) || homeNavigation(page)) { + writeRunLog("LIVE EXIT OK: 已离开直播间,继续原任务"); + return page; + } + var confirm = liveLeaveConfirmation(page), close = liveRoomClose(page); + if (confirm) tapFresh(confirm, liveLeaveConfirmation); + else if (close) tapFresh(close, function (fresh) { + return isLiveRoom(fresh) ? liveRoomClose(fresh) : null; + }); + else {back(); sleep(CONFIG.pollMs);} + page = snapshot(); + } + if (isAd(page) || isTaskCenter(page) || homeNavigation(page)) { + writeRunLog("LIVE EXIT OK: 已离开直播间,继续原任务"); + return page; + } + throw new Error("误入直播间后4次退出仍未回到首页或任务页,保留现场"); +} +function dismissModal(page) { + var close = modalClose(page); + if (!close) return false; + // 只关闭明确标识的弹窗,不点广告推广区“立即领取”或“看详情”。 + tapFresh(close, modalClose); + return true; +} +function waitTaskCenterContent(page) { + var loading = /^(?:(?:努力|正在|页面)?加载中|Loading)[.。…]*$/i; + if (!first(page, loading) || isAd(page)) return page; + var deadline = Date.now() + 30000; + writeRunLog("TASK CONTENT WAIT: 任务中心正在加载,等待内容,不滑动刷新或反复重新进入"); + while (Date.now() < deadline) { + if (dismissModal(page)) { page = snapshot(); } + if (!first(page, loading) || isAd(page)) return page; + sleep(CONFIG.pollMs); + page = snapshot(); + } + if (!first(page, loading)) return page; + throw new Error("任务中心内容加载超时,保留页面,不把加载中当作任务消失"); +} +function ensureTaskCenter() { + var deadline = Date.now() + 45000; + var restoringAfterEntry = false, restoredAfterEntry = false, menuOpened = false; + for (var i = 0; i < 8 && Date.now() < deadline;) { + var page; + try { page = snapshot(); } + catch (error) { + // 只在刚点击任务中心入口后恢复一次;不在广告、领奖或普通观看中接管其他应用。 + if (!error.foregroundMismatch || !restoringAfterEntry || restoredAfterEntry) throw error; + restoredAfterEntry = true; + writeRunLog("TASK ENTRY RECOVER: 点击赚钱入口后前台被" + error.foreground + "占用,重新打开" + CONFIG.appName + "复查一次"); + if (!app.launchPackage(CONFIG.packageName)) throw error; + waitStartupPackage(CONFIG.packageName, 8000); + sleep(CONFIG.pollMs); + continue; + } + page = waitTaskCenterContent(page); + if (!page.length) { + sleep(CONFIG.pollMs); + continue; + } + if (isAd(page)) throw new Error("奖励广告仍在进行,不用返回键提前退出"); + if (isLiveRoom(page)) {exitLiveRoom(page); continue;} + if (dismissModal(page)) continue; + var leave = first(page, /^(?:仍要退出|确认退出|坚持退出)$/); + if (leave && first(page, /今日还剩\d+次.*机会|继续赚金币|继续賺金币/)) { + tapFresh(leave); + continue; + } + var abandon = first(page, /^放弃$/); + if (abandon && first(page, /^继续浏览可获得奖励$/)) { + // 只在明确要求回任务中心时退出;正常逛街计时不会走这里。 + tapFresh(abandon); + continue; + } + if (isTaskCenter(page)) return page; + var nav = taskCenterEntry(page); + if (nav) { restoringAfterEntry = true; tapFresh(nav); } + else if (!menuOpened && taskCenterMenu(page)) { + menuOpened = true; + tapFresh(taskCenterMenu(page), taskCenterMenu); + } + else {back(); sleep(CONFIG.pollMs);} + i++; + } + throw new Error("无法返回去赚钱任务中心"); +} +function taskTitle(item) { + return item.rect.left < device.width * 0.55 && item.rect.top > device.height * 0.095 && + item.rect.bottom < device.height * 0.91 && item.rect.right - item.rect.left > device.width * 0.1; +} +function quota(text) { + var match = String(text).match(/(?:已完成)?(\d+)\s*\/\s*(\d+)/); + return match ? {done: Number(match[1]), total: Number(match[2])} : null; +} +function canonicalTaskTitle(value) { + var title = compact(value).replace(/(?:全币|金市)/g, "金币"); + var fixed = title.match(/^(看广告[得赚]金币|到饭点领饭补|明日0点领金币|预约领金币|逛街[领赚]金币|翻卡[赢贏]金币|逛(?:快手|开售)商城[赚领]金币)(?:最高)?\d*$/); + if (fixed) return fixed[1]; + return /^搜/.test(title) ? title.replace(/最高\d+(?:金币)?$/, "") : title; +} +function rowsOnPage(page, pattern) { + var labels = page.filter(function (item) { + return pattern.test(canonicalTaskTitle(item.text)) && taskTitle(item) && + !/(?:已完成|单日|\d+\s*\/\s*\d+|\d+(?:秒|s))/i.test(item.text); + }); + var rows = []; + labels.forEach(function (label) { + var title = canonicalTaskTitle(label.text); + if (rows.some(function (row) {return row.title === title;})) return; + var lower = label.rect.top + device.height * 0.075; + labels.forEach(function (other) { + if (other.rect.top > label.rect.top + 30) lower = Math.min(lower, other.rect.top - 5); + }); + var nearby = page.filter(function (item) { + return item.rect.top >= label.rect.top - 12 && item.rect.top < lower && + item.rect.bottom < device.height * 0.915; + }); + var action = first(nearby, /^(?:领福利|去完成|去观看|去领取|去查看|去搜索|去浏览|立即领取|看广告|已完成|已领取|已预约|明日再来|去看看|去预约|立即预约|继续翻|去翻卡|去逛街|去逛逛|去逛商城|点击领\d+(?:金币)?)$/, + function (item) {return item.rect.left > device.width * 0.72;}); + var detail = nearby.filter(function (item) {return item.rect.left < device.width * 0.7;}) + .map(function (item) {return item.text;}).join(" "); + var progress = quota(detail); + var unavailable = !!(progress && progress.done >= progress.total) || + !!(action && (/^(?:已完成|已领取|已预约|明日再来)$/.test(action.text) || action.enabled === false)) || + /今日(?:任务)?已完成|明日再来|次数已用完|已达上限/.test(detail); + rows.push({title: title, label: label, action: action, detail: detail, + quota: progress, unavailable: unavailable}); + }); + // 未结算翻卡卡片的标题是图片,原生列表只暴露倒计时、已翻位数和“继续翻”。 + if(pattern.test("翻卡赢金币") && !rows.some(function(r){return r.title==="翻卡赢金币";}) && isTaskCenter(page)) { + var resume=first(page,/^继续翻$/,function(i){return i.enabled!==false && i.rect.left>device.width*.72 && + i.rect.top>device.height*.095 && i.rect.bottom= 2) break; + prior = signature; + if (i === CONFIG.taskSearchScrolls) throw new Error("列表超过扫描范围,不能判断任务已消失"); + scrollList(direction === 1); + } + } + return null; +} +function locateTask(pattern, excluded) { + var previous=flipFlowActive; + if(pattern.test("翻卡赢金币")) flipFlowActive=true; + try { + var row = scanTask(pattern, excluded); + return row || scanTask(pattern, excluded); + } finally {flipFlowActive=previous;} +} +function exactTitle(title) { return {test: function (value) {return value === title;}}; } +function prepareRow(row) { + for (var i = 0; i < 5; i++) { + var fresh = rowsOnPage(snapshot(), exactTitle(row.title))[0]; + if (!fresh) return null; + if (fresh.unavailable) return fresh; + if (fresh.action && fresh.action.rect.top > device.height * 0.18 && + fresh.action.rect.bottom < device.height * 0.70) return fresh; + // 避免右下悬浮宝箱遮挡;移动后必须重新识别同一行。 + var low = fresh.label.rect.top > device.height * 0.55; + var x = device.width * 0.37, start = device.height * (low ? 0.70 : 0.40); + swipe(x, start, x, start + device.height * (low ? -0.20 : 0.20), 800); + sleep(CONFIG.pollMs); + } + throw new Error("任务按钮无法移入安全区域:" + row.title); +} +function resultAdvanced(before, after, rewardSeen) { + return !!rewardSeen || !!(before && after && before.quota && after.quota && + after.quota.total === before.quota.total && after.quota.done > before.quota.done); +} +function coinBalance(page) { + var balance = first(page, /^金币[::]?\d+(?:瓜分百亿)?$/, function (item) { + return item.rect.top < device.height * 0.24; + }); + if (balance) return Number(balance.text.match(/\d+/)[0]); + var pinnedLabel = first(page, /^金币[::]$/, function (item) { return item.rect.top < device.height * 0.24; }); + var pinnedValue = pinnedLabel && first(page, /^\d+$/, function (item) { + return item.rect.left >= pinnedLabel.rect.right - device.width * 0.025 && + item.rect.left - pinnedLabel.rect.right < device.width * 0.18 && + Math.abs(item.rect.top - pinnedLabel.rect.top) < device.height * 0.025; + }); + if (pinnedValue) return Number(pinnedValue.text); + var label = first(page, /^我的金币[》>]?$/); + var value = label && first(page, /^\d+$/, function (item) { + return item.rect.top >= label.rect.bottom && item.rect.top - label.rect.bottom < device.height * 0.08 && + Math.abs(item.rect.left - label.rect.left) < device.width * 0.08; + }); + return value ? Number(value.text) : null; +} +function mealSubsidyAction(page) { + return first(page, /补贴/, function (item) { + return item.enabled !== false && item.rect.top > device.height * 0.35 && + item.rect.bottom < device.height * 0.88 && item.rect.right - item.rect.left > device.width * 0.25 && + /领.*补贴|补贴.*领/.test(item.text) && + !/倒计时|后领|已领|已完成|待补|补签|\d+[::]\d+|规则|说明|最高|可得/.test(item.text); + }); +} +function roundUnavailable(page, kind) { + if (kind === "meal" && mealSubsidyAction(page)) return false; + if (first(page, /今日(?:任务)?已完成|今日次数已用完|今日已达上限|明日再来|暂无广告|暂无可用广告|广告加载失败|当前暂无任务/)) return true; + return false; +} +function prescribedSearch(page) { + if (!first(page, /今日任务进行中|金币最高|搜索浏览.*(?:秒|s)|搜索.*得金币/)) return null; + return first(page, /^去搜索$/, function (item) { + return item.rect.left > device.width * 0.65 && item.rect.top > device.height * 0.30 && + item.rect.bottom < device.height * 0.87 && item.enabled !== false; + }); +} +function timedBrowse(page) { + return !!first(page, /(?:浏览|滑动|搜索|阅读).*(?:\d+(?:秒|s)|倒计时)|\d+(?:秒|s).*(?:金币|奖励|浏览|领取|完成)|浏览中|计时中|倒计时/i) || + (!!first(page, /逛街领奖励|浏览领取/) && !!first(page, /^\d+(?:秒|s)$/i, + function (item) {return item.rect.left > device.width * 0.75 && item.rect.top > device.height * 0.30;})) || + !!first(page, /^\d{1,2}[::]\d{2}$/, function (item) { + return item.rect.left > device.width * 0.6 && item.rect.top > device.height * 0.55; + }); +} +function streetProgress(page) { + var label = first(page, /逛街领奖励[,,]?已领\d+\/\d+次/); + return label ? quota(label.text) : null; +} +function streetBadge(page) { + return first(page, /.+/, function (item) {return /:id\/reward_merchant_text$/.test(item.id || "");}); +} +function streetComplete(page) { + return !!first(page, /^(?:今日)?金币已(?:全部)?领完/); +} +function streetEnded(page) { + if (streetCounting(page)) return false; + var badge = streetBadge(page); + return !!(badge && /^(?:0秒|0s|已领取|已领完|已完成)$/.test(badge.text)) || + !!first(page, /^(?:浏览完成|任务完成|倒计时结束)$/); +} +function streetClaim(page) { + return first(page, /^去领取$/, function (item) { + return item.rect.left > device.width * 0.75 && + (/:id\/reward_merchant_text$/.test(item.id || "") || item.rect.top > device.height * 0.65) && + item.rect.bottom < device.height * 0.95; + }); +} +function streetCounting(page) { + var clock = first(page, /^\d+(?:秒|s)$/i, function (item) { + return item.rect.left > device.width * 0.75 && item.rect.top > device.height * 0.30; + }); + if (clock) return Number(clock.text.match(/\d+/)[0]) > 0; + return timedBrowse(page) && !first(page, /^(?:浏览完成|任务完成|倒计时结束)$/); +} +function browseStreet() { + var previous = null, claims = {}, deadline = Date.now() + CONFIG.roundTimeoutMs; + var swipeDown = true, settlingAt = null, lastSeconds = null; + while (Date.now() < deadline) { + var page = snapshot(), progress = streetProgress(page); + if (currentRoundRewardCoins === 1) return {rewardSeen: true, reason: "单次收益仅1金币"}; + if (streetComplete(page)) return {taskDone: true, reason: "页面显示金币已领完"}; + if (progress) { + if (!previous || progress.done > previous.done) { + writeRunLog("STREET PROGRESS: 已领=" + progress.done + "/" + progress.total); + deadline = Date.now() + CONFIG.roundTimeoutMs; + previous = progress; + } + if (progress.done >= Math.min(10, progress.total)) return {taskDone: true, reason: "逛街浏览奖励已领完:" + progress.done + "/" + progress.total}; + } + if (isAd(page)) { + var close = adClose(page); + if (close) tapFresh(close); + else sleep(CONFIG.pollMs); + continue; + } + if (roundUnavailable(page, "street")) return {unavailable: true, reason: "逛街任务当前不可做"}; + if (isTaskCenter(page)) return {rewardSeen: !!(previous && previous.done > 0)}; + var rightClaim = streetClaim(page); + if (rightClaim && !streetCounting(page)) { + if (rightClaim.enabled === false) return {unavailable: true, reason: "逛街右下角去领取不可点击"}; + try {tapFresh(rightClaim, streetClaim);} + catch (error) { + if (/目标按钮不存在|点击未响应/.test(String(error))) return {unavailable: true, reason: "逛街右下角去领取不可点击"}; + throw error; + } + var afterClaim = snapshot(), afterProgress = streetProgress(afterClaim); + if (streetClaim(afterClaim) && (!afterProgress || !previous || afterProgress.done === previous.done) && !streetCounting(afterClaim)) { + return {unavailable: true, reason: "逛街右下角去领取点击后无响应"}; + } + continue; + } + var claim = first(page, /^(?:领取奖励|立即领取|点击领取|领取\d+金币|领取金币|开心收下|立即收下|再逛一会)$/, + function (item) {return item.enabled !== false && item.rect.top > device.height * 0.30 && item.rect.bottom < device.height * 0.88;}); + if (claim && (progress || first(page, /继续浏览可获得奖励|浏览完成|恭喜|浏览奖励|逛街/))) { + var key = (previous ? previous.done : "?") + ":" + claim.text; + if (!claims[key]) {claims[key] = true; tapFresh(claim); continue;} + } + if (dismissModal(page)) continue; + var badge = streetBadge(page); + var seconds = badge && /^\d+(?:秒|s)$/i.test(badge.text) ? Number(badge.text.match(/\d+/)[0]) : null; + // 顶部次数可能滑出屏幕;原生倒计时重新开始同样证明已进入下一轮。 + if (seconds !== null) { + if (seconds > 0 && ((lastSeconds !== null && lastSeconds <= 10 && seconds > lastSeconds + 10) || settlingAt !== null)) { + deadline = Date.now() + CONFIG.roundTimeoutMs; + writeRunLog("STREET NEXT TIMER: " + seconds + "秒"); + } + lastSeconds = seconds; + } + if (streetCounting(page)) settlingAt = null; + else if (streetEnded(page) || settlingAt !== null) { + if (settlingAt === null) settlingAt = Date.now(); + // 0秒、已领取是自动结算过渡,期间也持续滑动,等下一轮计时。 + if (Date.now() - settlingAt >= 20000) { + // 结算持续不变时先把顶部次数滑回来,避免漏掉最终10/10。 + for (var reveal = 0; reveal < 3; reveal++) { + if (!swipe(device.width * 0.42, device.height * 0.42, device.width * 0.42, device.height * 0.78, 1200)) throw new Error("逛街滑动失败"); + sleep(300); + } + var settled = snapshot(), settledProgress = streetProgress(settled); + if (streetComplete(settled)) return {taskDone: true, reason: "页面显示金币已领完"}; + if (settledProgress && settledProgress.done >= Math.min(10, settledProgress.total)) return {taskDone: true, reason: "逛街浏览奖励已领完:" + settledProgress.done + "/" + settledProgress.total}; + if (settledProgress && (!previous || settledProgress.done > previous.done)) { + previous = settledProgress; + deadline = Date.now() + CONFIG.roundTimeoutMs; + settlingAt = Date.now(); + writeRunLog("STREET PROGRESS: 已领=" + previous.done + "/" + previous.total); + continue; + } + if (streetCounting(settled) || streetClaim(settled)) continue; + if (streetEnded(settled) || !streetBadge(settled)) return {unavailable: true, reason: "逛街结算持续20秒且没有倒计时或右下角去领取"}; + } + } + var x = device.width * 0.42; + if (!swipe(x, device.height * (swipeDown ? 0.72 : 0.42), x, device.height * (swipeDown ? 0.42 : 0.72), 1200)) throw new Error("逛街滑动失败"); + writeRunLog("STREET SWIPE: " + (swipeDown ? "上滑" : "下滑") + ";状态=" + (badge ? badge.text : "继续浏览")); + swipeDown = !swipeDown; + sleep(300); + } + throw new Error("逛街连续5分钟没有领取次数进展,尚未领完10次"); +} +function isFlipPage(page) { + return !!first(page, /^翻卡赢金币$/) && !!first(page, /看广告翻|个视频可翻|不翻了[,,]?直接领|点击翻|立即翻|重翻[千百十个]位|^[千百十个]位$/); +} +function flipPositions(page) { + var heading=first(page,/^翻卡赢金币$/),positions=[]; + if(!heading) return positions; + ["个位","十位","百位","千位"].forEach(function(name){ + var label=first(page,{test:function(text){return text===name || (name==="千位"&&/^[包锁]千位$/.test(text));}},function(i){ + return i.rect.top>heading.rect.bottom && i.rect.bottom=label.rect.top-device.height*.12 && + i.rect.topheading.rect.bottom && i.rect.bottom=next.label.rect.top && + i.rect.bottom<=next.label.rect.bottom+device.height*.075 && + Math.abs((i.rect.left+i.rect.right)/2-center)heading.rect.bottom && i.rect.bottomdevice.height*.35 && i.rect.bottom device.height * 0.87) return; + var column = price.rect.left < device.width * 0.5 ? 0 : 1; + var titles = page.filter(function (item) { + return item.text.length >= 6 && !/^[¥¥]|已优惠|已售|低价特卖|消费券|去领取|立即|榜第|入选|price-|price_|推荐|购物车|订单/.test(item.text) && + item.rect.bottom <= price.rect.top && price.rect.top - item.rect.bottom < device.height * 0.13 && + item.rect.top > device.height * 0.32 && item.rect.bottom - item.rect.top < device.height * 0.09 && + item.rect.right - item.rect.left > device.width * 0.25 && + (item.rect.left < device.width * 0.5 ? 0 : 1) === column && + item.rect.right <= device.width * (column ? 1 : 0.51); + }); + titles.sort(function (a, b) {return Number(!!b.node) - Number(!!a.node) || b.rect.bottom - a.rect.bottom;}); + if (titles.length && !visited[compact(titles[0].text)] && !products.some(function (p) {return p.text === titles[0].text;})) products.push(titles[0]); + }); + return products; +} +function isProductDetail(page) { + return !isMallList(page) && !!first(page, /详情|商品/) && !!first(page, /评价|进店|加入购物车|立即购买|预计.*发货/); +} +function returnToMall() { + for (var i = 0; i < 5; i++) { + var page = snapshot(); + if (dismissModal(page)) continue; + if (isMallList(page)) return page; + if (isTaskCenter(page)) throw new Error("商品返回后已离开商城,未完成6个商品"); + back(); sleep(CONFIG.pollMs); + } + throw new Error("商品详情无法返回商城列表"); +} +function browseMallProducts(limit) { + var page = snapshot(), remaining = remainingProducts(page); + var target = remaining === null ? limit : Math.min(limit, remaining); + var visited = {}, clicked = 0, misses = 0; + while (clicked < target) { + page = snapshot(); + if (!isMallList(page)) page = returnToMall(); + var products = mallProducts(page, visited); + if (!products.length) { + if (++misses >= 6) throw new Error("商城连续6次未找到新商品,当前已打开=" + clicked); + scrollList(true); + continue; + } + var product = products[0]; + tapFresh(product); + var deadline = Date.now() + 15000, opened = false; + while (Date.now() < deadline) { + if (isProductDetail(snapshot())) {opened = true; break;} + sleep(CONFIG.pollMs); + } + if (!opened) throw new Error("点击后未确认商品详情,不计入6个商品"); + visited[compact(product.text)] = true; + clicked++; misses = 0; + writeRunLog("MALL PRODUCT: 本次打开=" + clicked + "/" + target + ";" + product.text); + sleep(CONFIG.pollMs); + page = returnToMall(); + if (remainingProducts(page) === 0) break; + } + return {taskDone: true, productsClicked: clicked, reason: "商城商品浏览完成(按页面剩余数量补足,最多6个)"}; +} +function executeRound(row, kind, options) { + var previous=flipFlowActive; + if(kind==="flip") flipFlowActive=true; + try{ + var outcome=executeTaskRound(row,kind,options); + if(kind==="flip" && outcome.taskDone && outcome.flippedAll) saveFlipDone(outcome.reason); + return outcome; + } + finally{flipFlowActive=previous;} +} +function executeTaskRound(row, kind, options) { + options = options || {}; + var flipBeforeBalance=kind==="flip"?coinBalance(snapshot()):null; + var resumeFlip=kind==="flip" && options.resumeCurrent; + var fresh = resumeFlip?row:prepareRow(row); + if (!fresh || fresh.unavailable) return {changed: !fresh, unavailable: !!fresh}; + if (!resumeFlip && !fresh.action) { + if (kind === "meal") return {unavailable: true, reason: "饭补入口不可点击"}; + throw new Error("发现任务标题但没有同一行可用按钮:" + row.title); + } + var toastStart = rewardSerial; + if(!resumeFlip) tapFresh(fresh.action); + var deadline = Date.now() + CONFIG.roundTimeoutMs, rewardSeen = false, adSeen = false; + var adClosed = false, searchClicked = false, entered = false, claims = {}; + var firstPageAt = Date.now(), searchAttempts = 0, flipClaimRequested=false,flipProgress=""; + var finalUnlockExpected=false,finalUnlockClosed=false,flipBalanceDeadline=null; + while (Date.now() < deadline) { + var page = snapshot(); + rewardSeen = rewardSeen || rewardSerial > toastStart; + if (adReward(page)) rewardSeen = true; + if (kind === "flip" && flipSettlement(page)) { + if(tapFresh(flipSettlement(page), flipSettlement)) flipClaimRequested=true; + continue; + } + if (kind === "street" && (streetProgress(page) || streetBadge(page) || streetComplete(page))) return browseStreet(); + if (!(kind === "flip" && isFlipPage(page)) && dismissModal(page)) continue; + if (isAd(page)) { + adSeen = true; + var close = adClose(page); + if (close) {tapFresh(close); adClosed = true; + if(kind==="flip") { + if(finalUnlockExpected) finalUnlockClosed=true; + writeRunLog("FLIP AD CLOSED: 已关闭奖励广告,回到当前卡片继续,不计翻卡已完成"); + }} + else sleep(CONFIG.pollMs); + continue; + } + if (roundUnavailable(page, kind)) { + return {unavailable: true, rewardSeen: rewardSeen}; + } + if (kind === "flip" && isFlipPage(page)) { + var signature=flipPositions(page).map(function(p){return p.name+":"+p.digit;}).join("|"); + var unlockProgress=flipUnlockProgress(page); + if(unlockProgress) signature+="|解锁视频:"+unlockProgress.done+"/"+unlockProgress.total; + if(signature!==flipProgress){flipProgress=signature;deadline=Date.now()+CONFIG.roundTimeoutMs; + writeRunLog("FLIP PROGRESS: "+signature);} + var decision=flipDecision(page); + if(!decision){sleep(CONFIG.pollMs);continue;} + if(tapFresh(decision.button,function(p){var latest=flipDecision(p);return latest && latest.kind===decision.kind && + latest.position===decision.position?latest.button:null;})) { + writeRunLog("FLIP ACTION: "+decision.kind+";"+(decision.position||decision.button.text)); + if(decision.kind==="collect") flipClaimRequested=true; + if(decision.kind==="unlock") finalUnlockExpected=!!(unlockProgress && unlockProgress.done+1>=unlockProgress.total); + } + adClosed = false; + if(!flipClaimRequested) rewardSeen = false; + continue; + } + if (isTaskCenter(page)) { + if(kind==="flip" && flipClaimRequested) return {rewardSeen:true,taskDone:true,flippedAll:true,reason:"全部位数翻完,领取后已返回任务中心"}; + if(kind==="flip" && finalUnlockClosed && flipBeforeBalance!==null) { + var flipAfterBalance=coinBalance(page); + if(flipAfterBalance!==null && flipAfterBalance>flipBeforeBalance) return {rewardSeen:true,taskDone:true,flippedAll:true, + reason:"千位解锁次数完成并自动结算,余额增加"+(flipAfterBalance-flipBeforeBalance)+"金币"}; + if(flipBalanceDeadline===null) flipBalanceDeadline=Date.now()+15000; + if(Date.now() 8000) return {rewardSeen: rewardSeen}; + sleep(CONFIG.pollMs); + continue; + } + entered = true; + if (isLiveRoom(page)) { + writeRunLog("ROUND LIVE REDIRECT: 进入直播推广页,返回任务中心;不计为完成"); + exitLiveRoom(page); + return {rewardSeen: rewardSeen}; + } + // 续看弹窗关闭后本轮结束,由主循环重找任务,防止跨任务串行。 + if (adClosed && kind!=="flip") return {rewardSeen: rewardSeen}; + if (kind === "mall" && isMallList(page)) return browseMallProducts(options.products || 6); + if (kind === "reserve") { + if (first(page, /预约成功|已预约/)) return {taskDone: true, reason: "明日0点领金币已预约"}; + var reserve = first(page, /^(?:立即预约|预约领取|预约领金币|确认预约)$/); + if (reserve) {tapFresh(reserve); continue;} + } + if (kind === "meal") { + if (!page.length) {sleep(CONFIG.pollMs); continue;} + var meal = mealSubsidyAction(page); + if (!meal) return {unavailable: true, reason: "没有可点击的补贴按钮"}; + try {tapFresh(meal);} + catch (error) { + if (/目标按钮不存在|点击未响应/.test(String(error))) return {unavailable: true, reason: "补贴按钮不可点击"}; + throw error; + } + sleep(1500); + var mealAfter = snapshot(); + if (!isAd(mealAfter) && sameItem(mealAfter, meal)) return {unavailable: true, reason: "补贴按钮点击后未进入任务"}; + continue; + } + if (kind === "search" && !searchClicked) { + var search = prescribedSearch(page); + if (search) { + if (++searchAttempts > 3) throw new Error("搜词按钮连续3次未进入搜索结果,保留异常,不空等5分钟"); + tapFresh(search); sleep(1500); + var searchAfter = snapshot(); + searchClicked = !prescribedSearch(searchAfter); + writeRunLog("SEARCH TRANSITION: 第" + searchAttempts + "次;" + + (searchClicked ? "已离开选词列表" : "仍在选词列表,重新识别按钮后重试")); + continue; + } + } + var completion = first(page, /^(?:任务完成|浏览完成|恭喜获得\d+金币|已获得\d+金币|金币已到账|领取成功|奖励已到账)$/); + if (completion) rewardSeen = true; + var claim = first(page, /^(?:领取\d+金币|领取金币|领取奖励|点击领取|开心收下|收下金币)$/, + function (item) {return item.rect.top > device.height * 0.3 && item.rect.bottom < device.height * 0.93;}); + // 仅在任务/结算页面领取,广告推广的同名字样不触发。 + if (claim && !isAd(page) && (kind!=="flip" || flipClaimRequested) && (completion || first(page, /浏览.*(?:完成|金币)|搜索.*(?:完成|金币)|恭喜|任务奖励/))) { + var key = claim.text + ":" + Math.round(claim.rect.top / 50); + if (!claims[key]) {claims[key] = true; tapFresh(claim); continue;} + } + if (rewardSeen && (kind!=="flip" || flipClaimRequested)) return kind==="flip"? + {rewardSeen:true,taskDone:true,flippedAll:true,reason:"全部位数翻完并确认领取"}:{rewardSeen:true}; + if ((kind === "street" || kind === "search") && timedBrowse(page)) { + // 浏览计时期间交替上下滑,直到页面实际完成;不把“15秒”说明当作已结束。 + var x = device.width * 0.42, down = Math.floor((Date.now() - firstPageAt) / 12000) % 2 === 0; + if (!swipe(x, device.height * (down ? 0.72 : 0.44), x, device.height * (down ? 0.42 : 0.69), 1200)) throw new Error("浏览滑动失败"); + sleep(300); + continue; + } + sleep(CONFIG.pollMs); + } + throw new Error("本轮超过5分钟,未确认完成:" + row.title); +} +function drainTask(initial, kind, options) { + options = options || {}; + var title = initial.title, pattern = exactTitle(title), rounds = 0, noProgress = 0; + while (true) { + var row = locateTask(pattern); + if (!row) return {title: title, rounds: rounds, reason: "入口连续两次完整扫描未找到"}; + if (row.unavailable) return {title: title, rounds: rounds, reason: "任务已完成或次数用完"}; + var beforeBalance = coinBalance(snapshot()); + currentRoundRewardCoins = null; + var outcome; + try { + // 翻卡可能要多次广告解锁下一位;按位数进展重置超时,不让外层固定5分钟截断。 + outcome = kind === "street" || kind === "flip" ? executeRound(row, kind, options) : + boundedCall(title + "单轮", CONFIG.roundTimeoutMs + 20000, function () {return executeRound(row, kind, options);}); + } catch (error) { + if (error.unsafeWorker || error.captureFatal || /\[NO_RETRY\]/.test(String(error))) throw error; + writeRunLog("ROUND ERROR: " + title + ";" + error); + outcome = {error: String(error)}; + } + ensureTaskCenter(); + if (currentRoundRewardCoins === 1) { + writeRunLog("ONE COIN STOP: " + title + ";单次实际收益1金币,退出当前流程,继续下一流程"); + return {title: title, rounds: rounds + 1, lastRewardCoins: 1, reason: "单次实际收益1金币,结束当前流程"}; + } + if (outcome.taskDone) return {title: title, rounds: rounds, productsClicked: outcome.productsClicked, reason: outcome.reason}; + var after = locateTask(pattern); + if (resultAdvanced(row, after, outcome.rewardSeen)) { + rounds++; noProgress = 0; + writeRunLog("ROUND CONFIRMED: " + title + ";已确认=" + rounds); + { + var afterBalance = coinBalance(snapshot()), balanceDeadline = Date.now() + 6000; + while (beforeBalance !== null && (afterBalance === null || afterBalance === beforeBalance) && Date.now() < balanceDeadline) { + sleep(CONFIG.pollMs); + afterBalance = coinBalance(snapshot()); + } + var earned = beforeBalance !== null && afterBalance !== null && afterBalance > beforeBalance ? afterBalance - beforeBalance : null; + writeRunLog("ROUND COINS: " + title + ";本轮实际金币=" + earned); + if (earned === null && options.stopAtCoins !== undefined) return {title: title, rounds: rounds, incomplete: true, reason: "未确认本轮实际金币,暂停该项以免越过奖励阈值"}; + var stopAt = options.stopAtCoins !== undefined ? options.stopAtCoins : 1; + if (earned !== null && earned <= stopAt) return {title: title, rounds: rounds, lastRewardCoins: earned, + reason: "本轮实际金币≤" + stopAt + ",结束当前流程"}; + } + } else if (!outcome.changed && !outcome.unavailable && after && !after.unavailable) { + noProgress++; + writeRunLog("ROUND UNCONFIRMED: " + title + ";连续无进展=" + noProgress); + } + if (outcome.unavailable || !after || after.unavailable) { + return {title: title, rounds: rounds, reason: outcome.reason || (outcome.unavailable ? "当前流程不可做" : "入口消失或配额完成")}; + } + if (outcome.changed) noProgress++; + if (noProgress >= CONFIG.noProgressLimit) return {title: title, rounds: rounds, + incomplete: true, reason: "连续3轮未确认进展,保留异常,不冒充任务已完成"}; + } +} +function continuousVideoCard(page) { + var heading = first(page, /^连续看视频\d+天/, function(item) { + return item.rect.left < device.width * 0.3 && item.rect.top < device.height * 0.55; + }); + if (!heading) return null; + var region = page.filter(function(item) { + return item.rect.top >= heading.rect.bottom && item.rect.bottom < heading.rect.bottom + device.height * 0.24; + }); + var claim = first(region, /^(?:领金币|一键领取)$/); + var watch = first(region, /^(?:去看视频|看视频|继续看视频)$/); + // OPPO实际文案为“已攒6112/7886金币,继续看视频可开启”,不是单独的页码式数字。 + var progressItem = first(region, /^(?:已攒|已累计|已获得|已赚|已完成)?\d+(?:,\d{3})*\/\d+(?:,\d{3})*(?:金币|$)/); + var progress = progressItem && quota(progressItem.text.replace(/,/g, "")); + if (progress && (!progress.total || progress.done > progress.total)) progress = null; + var status = first(region, /(?:\d+金币待领取|已领\d+金币)/); + var done = !claim && !!first(region, /今日(?:奖励|金币|任务)?已(?:全部)?(?:领完|领取完|完成)|今日奖励已全部领取|明日再来|明天再来/); + return {claim:claim, watch:watch, progress:progress, done:done, + remainingCoins:progress ? progress.total - progress.done : null, + signature:(progress ? progress.done + "/" + progress.total : "") + "|" + (status ? status.text : "")}; +} +function locateContinuousVideoCard() { + var previous=continuousCardReading;continuousCardReading=true; + try{return readContinuousVideoCard();}finally{continuousCardReading=previous;} +} +function readContinuousVideoCard() { + ensureTaskCenter(); + for (var i=0;i<=CONFIG.taskSearchScrolls;i++) { + var page=snapshot(); + if (dismissModal(page)) continue; + var card=continuousVideoCard(page); + if (card) return card; + if(i CONFIG.roundTimeoutMs) + throw new Error("连续5分钟未确认正常视频观看,保留现场,不当作任务完成"); + if (isAd(page)) {pendingWatchMs = 0; finishExistingAd(); continue;} + if (isLiveRoom(page)) { + exitLiveRoom(page); + pendingWatchMs = 0; + continue; + } + if (dismissModal(page)) {pendingWatchMs = 0; continue;} + if (skippableContinuousFeedCard(page)) { + pendingWatchMs = 0; + writeRunLog("CONTINUOUS VIDEO: 上滑跳过兴趣选择、直播预览或图文卡片,继续观看"); + } else { + if (!isContinuousVideoFeed(page)) throw new Error("连续看视频未进入已识别的视频播放页,保留现场"); + lastVideoAt = Date.now(); + if (pendingWatchMs) { + // 只有等待前后都确认是普通视频才累计观看,直播/广告/预览不抵扣计划时长。 + watchedMs += Math.min(durationMs - watchedMs, Date.now() - pendingWatchSince); + pendingWatchMs = 0; + if (watchedMs >= durationMs) { + writeRunLog("CONTINUOUS VIDEO BATCH END: 已连续观看" + Math.round(watchedMs / 1000) + "秒,返回任务页领奖"); + return {watchedMs:watchedMs, reason:"duration"}; + } + } else { + pendingWatchMs = Math.min(CONFIG.videoSwipeIntervalMs, durationMs - watchedMs); + pendingWatchSince = readStartedAt; + writeRunLog("CONTINUOUS VIDEO WATCH: 普通视频,已看" + Math.round(watchedMs / 1000) + + "/" + Math.ceil(durationMs / 1000) + "秒;等待后重新识别页面"); + // 首读期间视频也在播放,并预留同量补读时间,让实际切换接近10秒。 + var remainingWait = pendingWatchMs - (Date.now() - pendingWatchSince) - pageReadMs; + if (remainingWait > 0) sleep(remainingWait); + keepScreenAwake(); + continue; + } + } + if (!swipe(device.width * 0.4, device.height * 0.74, device.width * 0.4, device.height * 0.3, CONFIG.videoSwipeDurationMs)) + throw new Error("连续看视频切换失败"); + writeRunLog("CONTINUOUS VIDEO SWIPE: 已切换下一视频"); + sleep(CONFIG.videoSettleMs); + } +} +function continuousVideoWatchPlan(card, msPerCoin) { + if (!card.progress || card.remainingCoins === null) throw new Error("未读到连续看视频剩余金币,不能估算观看时间"); + if (card.remainingCoins <= 0) throw new Error("视频进度已满但未出现领奖入口,不能继续盲刷"); + var durationMs = msPerCoin ? Math.max(1, Math.round(card.remainingCoins * msPerCoin * CONFIG.videoEstimateMargin)) : CONFIG.videoCalibrationMs; + if (!isFinite(durationMs) || durationMs <= 0) throw new Error("观看时间估算无效"); + return {durationMs:durationMs, remainingCoins:card.remainingCoins, + packets:Math.ceil(card.remainingCoins / CONFIG.videoCoinsPerPacket), calibration:!msPerCoin}; +} +function waitContinuousVideoReceipt() { + // vivo 弹窗动画期间原生树和截图可能仍是上一帧,不能单次读取就判定失败。 + var deadline=Date.now()+15000; + do { + var page=snapshot(); + if(first(page,/^任务完成奖励$/)) return page; + sleep(CONFIG.pollMs); + } while(Date.now() 0 && sample.watchedMs > 0) { + var measured = sample.watchedMs / gain; + msPerCoin = msPerCoin ? (msPerCoin + measured) / 2 : measured; + noProgress = 0; + writeRunLog("CONTINUOUS VIDEO RATE: 观看" + Math.round(sample.watchedMs / 1000) + "秒,任务增加" + gain + + "金币;按每红包约" + CONFIG.videoCoinsPerPacket + "金币折算,每红包约" + + (msPerCoin * CONFIG.videoCoinsPerPacket / 1000).toFixed(2) + "秒"); + } else if (!card.claim && !card.done && gain === 0) { + noProgress++; + // 进度未增加时重新测算,不沿用已经失效的收益速度。 + msPerCoin = null; + writeRunLog("CONTINUOUS VIDEO NO PROGRESS: " + noProgress + "/" + CONFIG.noProgressLimit); + } else noProgress = 0; + sample = null; + } + if(card.done) return {title:"连续看视频阶段奖励",rounds:claims,reason:"今日连续看视频奖励已全部领取"}; + if(noProgress>=CONFIG.noProgressLimit) return {title:"连续看视频阶段奖励",rounds:claims,incomplete:true, + reason:"连续3次观看未确认金币进度增加,保留异常,不当作全部领完"}; + if(card.claim) { + if (!tapFresh(card.claim,function(page){var current=continuousVideoCard(page);return current&¤t.claim;})) continue; + var receipt=waitContinuousVideoReceipt(); + claims++;writeRunLog("CONTINUOUS VIDEO CLAIM: 已确认领取第"+claims+"笔,不按1金币阈值退出"); + var close=modalClose(receipt); + if(close) tapFresh(close,modalClose); + else throw new Error("连续看视频领奖弹窗没有明确关闭入口"); + continue; + } + if(!card.watch) throw new Error("连续看视频尚未确认领完,且未找到观看入口"); + var plan = continuousVideoWatchPlan(card, msPerCoin); + writeRunLog("CONTINUOUS VIDEO PLAN: 当前奖励还差" + plan.remainingCoins + "金币,约" + plan.packets + "个红包;" + + (plan.calibration ? "先观看" : "预计连续观看") + Math.ceil(plan.durationMs / 1000) + "秒" + + (plan.calibration ? "测算速度,仅回查一次" : "(含10%余量),到时再回任务页领奖,中途不查收益")); + if (!tapFresh(card.watch,function(page){var current=continuousVideoCard(page);return current&¤t.watch;})) + throw new Error("开始连续观看前任务入口变化,未启动观看"); + var result = watchContinuousVideoSegment(plan.durationMs); + sample = {before:card.progress, watchedMs:result.watchedMs}; + } +} + +function runStages(startKind) { + var results = []; + var stages = STAGES; + if (startKind) { + var index = STAGES.map(function (stage) {return stage.kind;}).indexOf(String(startKind)); + if (index < 0) throw new Error("未知恢复流程:" + startKind); + stages = STAGES.slice(index); + writeRunLog("RESUME STAGE: " + stages[0].name); + } + stages.forEach(function (stage) { + if(stage.kind==="flip" && flipDoneToday()) { + results.push({title:stage.name,taskDone:true,reason:"今天翻卡已确认结算,直接进入下一流程"}); + writeRunLog("STAGE SKIP COMPLETED: "+stage.name+";今天已结算,直接进入下一流程"); + return; + } + writeRunLog("STAGE START: " + stage.name); + if (stage.kind === "continuousVideo") { + var videoResult=continuousVideoStep();results.push(videoResult); + writeRunLog("TASK RESULT: "+JSON.stringify(videoResult)); + writeRunLog("STAGE END: "+stage.name);return; + } + var row = locateTask(stage.title); + if (row) { + var result = drainTask(row, stage.kind, stage); + results.push(result); + writeRunLog("TASK RESULT: " + JSON.stringify(result)); + } + writeRunLog("STAGE END: " + stage.name); + }); + return results; +} +function installToastObserver() { + events.observeToast(); + events.onToast(function (event) { + if (String(event.getPackageName()) !== CONFIG.packageName) return; + var value = compact(event.getText()); + recordRewardCoins(value); + if (/设备异常|账号异常|操作异常|领取失败|操作频繁|操作过于频繁|存在风险/.test(value)) rejection = value; + if (/领取成功|已获得\d+金币|金币已到账|成功领取\d+金币/.test(value)) rewardSerial++; + writeRunLog("APP TOAST: " + value); + }); +} +function finishExistingAd() { + var page = snapshot(); + if (!isAd(page)) return; + writeRunLog("STARTUP AD: 等待当前广告完成并关闭"); + var deadline = Date.now() + CONFIG.roundTimeoutMs; + while (Date.now() < deadline) { + page = snapshot(); + if(isFlipPage(page) || flipSettlement(page)) { + writeRunLog("STARTUP AD CLOSED: 已回到未完成翻卡,交回翻卡流程,不关闭卡片弹窗"); + return; + } + if (dismissModal(page)) continue; + if (!isAd(page)) { + writeRunLog("STARTUP AD CLOSED: 当前广告已退出"); + return; + } + var close = adClose(page); + if (close) tapFresh(close); + else sleep(CONFIG.pollMs); + } + throw new Error("当前广告未能正常结束或关闭"); +} +function runDaily() { + // 只阻止本脚本重复运行,不停止其他应用的脚本。 + var mine = engines.myEngine(), source = String(mine.getSource()); + engines.all().forEach(function (engine) { + if (engine.id !== mine.id && String(engine.getSource()) === source) throw new Error("已有相同快手脚本在运行"); + }); + files.write(CONFIG.logPath, ""); + writeRunLog("START: " + CONFIG.version); + auto.waitFor(); + initLocalOcr(); + if (!app.launchPackage(CONFIG.packageName)) throw new Error("未安装" + CONFIG.appName); + waitStartupPackage(CONFIG.packageName, 15000); + sleep(1500); + installToastObserver(); + if (mine.execArgv && mine.execArgv.inspectOnly) { + snapshot(); + return "INSPECT DONE: 仅保存本机页面文字,未执行任务"; + } + finishExistingAd(); + var currentPage=snapshot(); + if((!mine.execArgv || !mine.execArgv.startStage || mine.execArgv.startStage==="flip") && + (isFlipPage(currentPage) || flipSettlement(currentPage))) { + writeRunLog("FLIP RESUME: 当前翻卡尚未结算,先完成现有卡片再回任务中心"); + executeRound({title:"翻卡赢金币"},"flip",{resumeCurrent:true}); + } + ensureTaskCenter(); + var results = runStages(mine.execArgv && mine.execArgv.startStage); + if (results.some(function (result) {return result.incomplete;})) throw new Error("部分任务未确认完成,请查看 TASK RESULT 日志"); + return "DONE: " + CONFIG.appName + "各类任务已依次执行至不可做或入口消失;" + JSON.stringify(results); +} + +// MAIN:测试只加载函数,不执行手机操作。 +try { + var endMessage = runDaily(); + writeRunLog(endMessage); +} catch (error) { + writeRunLog("ERROR: " + error + "\n" + error.stack); + toastLog("快手任务结束:" + error); + throw error; +} finally { + try {events.removeAllListeners();} catch (ignore) {} + try {events.removeToastObserver();} catch (ignoreObserver) {} + try {images.stopScreenCapture();} catch (ignoreCapture) {} + if (captureWorker && captureWorker.isAlive()) {captureWorker.interrupt(); captureWorker.join(1500);} + releaseScreenAwake(); +}