app_auto_all/ximalaya_auto/ximalaya-lite.auto.js
2026-11-17 12:27:32 +08:00

1170 lines
69 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

"auto";
// 喜马拉雅极速版:福利 → 签到 → 整点打卡 → 听书领奖 → 翻卡 → 视频红包 → 复查听书。
// 仅在手机内存进行OCR,不保存或上传截图。不执行饭点补贴;仅限时下载分区执行安装任务。
"use strict";
// BEGIN SHARED SCREEN AWAKE
// 独立亮屏锁 + 可恢复的系统超时租约;多引擎只在最后一个使用者退出时恢复原设置。
function createScreenAwake(runtime) {
var nextRefresh = 0, active = false, settingHeld = false, permissionLogged = false;
function report(message) { if (runtime.log) runtime.log("SCREEN AWAKE: " + message); }
function livingOwners(state) {
var alive = runtime.aliveOwners();
return (state.owners || []).filter(function (owner) { return alive.indexOf(owner) >= 0; });
}
function claimSetting() {
if (!runtime.canWrite()) {
if (!permissionLogged) { report("未获修改系统设置权限,仅使用独立亮屏锁。"); permissionLogged = true; }
return;
}
runtime.locked(function () {
var current = runtime.readTimeout(), state = runtime.readState();
if (!state) state = {originalTimeout: current, owners: []};
state.owners = livingOwners(state);
// 崩溃遗留的24小时值沿用日志中的原值,用户另行修改过则以当前值为准。
if (!state.owners.length && current !== runtime.timeoutMs) state.originalTimeout = current;
if (state.owners.indexOf(runtime.owner) < 0) state.owners.push(runtime.owner);
runtime.writeState(state); // 先保存原值,进程被杀后下一次运行仍可恢复。
if (current < runtime.timeoutMs && !runtime.writeTimeout(runtime.timeoutMs)) throw new Error("设置熄屏超时失败");
settingHeld = true;
});
}
return {
keep: function () {
if (active && runtime.now() < nextRefresh) return;
// 先建立每引擎独立的锁,不调用会被其他脚本cancelKeepingAwake释放的共享Device锁。
runtime.acquire();
active = true;
nextRefresh = runtime.now() + 60000;
if (!settingHeld) {
try { claimSetting(); }
catch (error) { report("超时兜底暂不可用:" + error); }
}
},
release: function () {
nextRefresh = 0;
try {
if (settingHeld) runtime.locked(function () {
var state = runtime.readState();
if (!state) return;
state.owners = livingOwners(state).filter(function (owner) { return owner !== runtime.owner; });
if (state.owners.length) runtime.writeState(state);
else {
// 运行中用户手动改了设置时不覆盖用户的新值。
if (runtime.readTimeout() === runtime.timeoutMs && !runtime.writeTimeout(state.originalTimeout))
throw new Error("恢复原熄屏超时失败");
runtime.clearState();
}
});
settingHeld = false;
} catch (error) { report("恢复超时设置失败,保留恢复记录:" + error); }
finally {
if (active) runtime.release();
active = false;
}
}
};
}
function createAndroidScreenAwake(options) {
var ctx = options.context, api = options.android, screenDevice = options.device;
// 兼容没有Android桥的单元测试或旧宿主;手机上始终使用下面的独立锁。
if (!ctx || !api) {
var next = 0, held = false;
return {keep: function () {
if (!screenDevice || typeof screenDevice.keepScreenOn !== "function" || (held && Date.now() < next)) return;
screenDevice.keepScreenOn(3600000); held = true; next = Date.now() + 60000;
}, release: function () {
if (screenDevice && typeof screenDevice.cancelKeepingAwake === "function") screenDevice.cancelKeepingAwake();
held = false; next = 0;
}};
}
var statePath = "/sdcard/Download/autojs-screen-awake-state.json";
var pid = String(api.os.Process.myPid()), owner = pid + ":" + options.engines.myEngine().id;
var pm = ctx.getSystemService(api.content.Context.POWER_SERVICE);
var wakeLock = pm.newWakeLock(api.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK | api.os.PowerManager.ON_AFTER_RELEASE,
"autojs6:screen-awake:" + owner);
wakeLock.setReferenceCounted(false);
var system = api.provider.Settings.System, resolver = ctx.getContentResolver();
var store = options.files;
var runtime = {
owner: owner, timeoutMs: 86400000, now: function () { return Date.now(); }, log: options.log,
acquire: function () { wakeLock.acquire(3600000); },
release: function () { if (wakeLock.isHeld()) wakeLock.release(); },
canWrite: function () { return api.os.Build.VERSION.SDK_INT < 23 || system.canWrite(ctx); },
readTimeout: function () { return Number(system.getInt(resolver, system.SCREEN_OFF_TIMEOUT, 30000)); },
writeTimeout: function (value) { return !!system.putInt(resolver, system.SCREEN_OFF_TIMEOUT, value); },
aliveOwners: function () {
return options.engines.all().map(function (engine) { return pid + ":" + engine.id; });
},
readState: function () { return store.exists(statePath) ? JSON.parse(String(store.read(statePath))) : null; },
writeState: function (state) { store.write(statePath + ".tmp", JSON.stringify(state));
if (!new java.io.File(statePath + ".tmp").renameTo(new java.io.File(statePath))) throw new Error("保存常亮恢复记录失败"); },
clearState: function () { store.remove(statePath); },
locked: function (action) {
var file = new java.io.RandomAccessFile(statePath + ".lock", "rw"), channel = file.getChannel(), lock = null;
try {
var deadline = Date.now() + 1500;
while (!lock && Date.now() < deadline) {
try { lock = channel.tryLock(); } catch (error) {
if (!/OverlappingFileLockException/.test(String(error))) throw error;
}
if (!lock) java.lang.Thread.sleep(20);
}
if (!lock) throw new Error("等待常亮设置锁超时");
return action();
} finally {
if (lock) lock.release();
channel.close(); file.close();
}
}
};
return createScreenAwake(runtime);
}
// END SHARED SCREEN AWAKE
var CONFIG = {
packageName: "com.ximalaya.ting.lite", rewardThreshold: 500,
scanLimit: 14, adTimeoutMs: 180000, noProgressMs: 90000,
floatingCoinCheckMs: 30000,
browserSkipPath: "/sdcard/Download/ximalaya-lite-browser-skips.json",
logPath: "/sdcard/Download/ximalaya-lite.log",
statePath: "/sdcard/Download/ximalaya-lite-state.json",
pagePath: "/sdcard/Download/ximalaya-lite-page.json"
};
var state = {status:"ready", stages:[], current:"准备"};
var keeper = null, keeperWorker = null, captureReady = false;
function startScreenAwake() {
keeper=createAndroidScreenAwake({context:context,android:android,device:device,engines:engines,files:files,log:record});
keeper.keep();
// 主线程长期同步识别、sleep或等待广告时,JS定时器可能无法及时调度。
keeperWorker=threads.start(function(){
while(true) {
sleep(30000);
try {keeper.keep();}
catch(e) {
if(/InterruptedException|ScriptInterruptedException/.test(String(e)))throw e;
record("常亮续保暂失败,下轮重试:"+e);
}
}
});
record("常亮保护已开启,等待广告和任务冷却期间持续生效");
}
function stopScreenAwake() {
if(keeperWorker) {
keeperWorker.interrupt();keeperWorker.join(1500);keeperWorker=null;
}
if(keeper){keeper.release();keeper=null;}
}
var debugTaskLimit = 0;
var activeLimitedDownload=null;
var activeDailyTask=null,dailyBrowserSkippedTitles={},nextFloatingCoinAt=0,floatingCoinActive=false;
var browserPackages={"com.microsoft.bing":true,"com.android.browser":true,"com.vivo.browser":true,
"com.android.chrome":true,"org.mozilla.firefox":true,"com.quark.browser":true,
"com.UCMobile":true,"com.tencent.mtt":true},browsersDiscovered=false;
function isBrowserPackage(packageName) {
if(browserPackages[packageName])return true;
if(!browsersDiscovered) {
browsersDiscovered=true;
try {
var intent=new android.content.Intent(android.content.Intent.ACTION_VIEW,android.net.Uri.parse("https://example.com/"));
intent.addCategory(android.content.Intent.CATEGORY_BROWSABLE);
var activities=context.getPackageManager().queryIntentActivities(intent,0);
for(var i=0;i<activities.size();i++)browserPackages[String(activities.get(i).activityInfo.packageName)]=true;
} catch(ignored) {}
}
return browserPackages[packageName]===true;
}
function dailyBrowserReturn(page) {
if(state.current!=="每日任务" || page.packageName===CONFIG.packageName)return null;
var chooser=/^(android|com.android.systemui|com.vivo.resolver)$/.test(page.packageName) &&
/打开方式|使用以下应用|选择.*浏览器/.test(corpus(page)) && /浏览器|Chrome|Bing|必应/.test(corpus(page));
if(!isBrowserPackage(page.packageName) && !chooser)return null;
var floating=floatingCoinActive;
if(activeDailyTask && !floating) {
activeDailyTask.browserSkipped=true;
if(activeDailyTask.title)dailyBrowserSkippedTitles[activeDailyTask.title]=true;
files.write(CONFIG.browserSkipPath,JSON.stringify(dailyBrowserSkippedTitles,null,2));
state.browserSkippedTasks=Object.keys(dailyBrowserSkippedTitles);persist();
}
record("每日任务打开浏览器,立即返回喜马拉雅并跳过:"+page.packageName);
back();sleep(300);
if(!foregroundWait(CONFIG.packageName,1200))app.launchPackage(CONFIG.packageName);
if(!foregroundWait(CONFIG.packageName,8000))throw new Error("跳过浏览器任务后未回到喜马拉雅");
floatingCoinActive=false;
return {packageName:CONFIG.packageName,items:[],browserSkipped:true,floatingCoin:floating};
}
function browseDwell(ms) {
if(state.current!=="每日任务"){sleep(ms);return null;}
var end=Date.now()+ms;
while(Date.now()<end) {
try {var skipped=dailyBrowserReturn(nativePage());if(skipped)return skipped;}
catch(e){if(!e.windowTransient)throw e;}
sleep(250);
}
return null;
}
function findFloatingCoin(page) {
if(!welfare(page))return null;
return find(page,/^(限时领金币|领金币)$/,function(i){
if(i.x<device.width*.72 || i.y<device.height*.65 || i.y>device.height*.90)return false;
if(i.text==="限时领金币")return true;
// 普通任务行也叫“领金币”;仅接受右下角方形悬浮容器中的同名文字。
try {
var n=i.node;
for(var depth=0;n && depth<4;depth++,n=n.getParent()) {
var b=new android.graphics.Rect();n.getBoundsInScreen(b);
var w=b.right-b.left,h=b.bottom-b.top;
if(b.left>device.width*.70 && b.right<=device.width && b.top>device.height*.60 &&
w>device.width*.12 && w<device.width*.30 && h>device.height*.07 && h<device.height*.18 && h/w>.65 && h/w<1.5)return true;
}
} catch(ignored) {}
return false;
});
}
function checkFloatingCoin(page) {
// 先完成明确选中的领奖/视频流程,避免浮标广告反复抢占任务入口。
if(/^(听书奖励领取|复查听书奖励|看视频开红包|翻卡|幸运红包|限时下载任务)$/.test(state.current))return false;
if(Date.now()<nextFloatingCoinAt)return false;
nextFloatingCoinAt=Date.now()+CONFIG.floatingCoinCheckMs;
var coin=findFloatingCoin(page);if(!coin)return false;
record("右下角领金币可领取,先领取再继续当前任务");
if(!tap(coin))return false;
floatingCoinActive=true;sleep(2500);
state.lastFloatingCoin={at:new Date().toISOString(),status:"clicked"};persist();
return true;
}
function record(message) {
var line = new Date().toISOString() + " [喜马拉雅][" + state.current + "] " + message;
console.log(line); files.append(CONFIG.logPath, line + "\n");
}
function persist() { files.write(CONFIG.statePath, JSON.stringify(state, null, 2)); }
function clean(value) { return String(value || "").replace(/\s+/g, "").replace(/賺/g,"赚").replace(/領/g,"领").replace(/裝/g,"装").replace(/幣/g,"币"); }
function rectOf(b) {
if (!b) return null;
function at(k) { return Number(typeof b[k] === "function" ? b[k]() : b[k]); }
var r = {left:at("left"),top:at("top"),right:at("right"),bottom:at("bottom")};
return isFinite(r.left+r.top+r.right+r.bottom) && r.right>r.left && r.bottom>r.top ? r : null;
}
function item(text, bounds, node, id) {
return {text:clean(text), bounds:bounds, x:(bounds.left+bounds.right)/2,
y:(bounds.top+bounds.bottom)/2, node:node || null, id:id || ""};
}
function bounded(name, timeout, action) {
var value, error;
var worker=threads.start(function(){try{value=action();}catch(e){error=e;}});
var end=Date.now()+timeout;
while(worker.isAlive() && Date.now()<end) sleep(100);
if(worker.isAlive()) {
worker.interrupt(); worker.join(1500);
var e=new Error(name+"超时"); e.fatal=worker.isAlive();
if(name === "截图识别") e.fatal=true;
throw e;
}
if(error) throw error;
return value;
}
function nativePage() {
var root=null, list=[], count=0, end=Date.now()+1800;
do {
root=auto.service?auto.service.getRootInActiveWindow():auto.rootInActiveWindow;
if(root)break;
sleep(150);
} while(Date.now()<end);
if(!root) {var unavailable=new Error("无障碍活动窗口暂时为空");unavailable.windowTransient=true;throw unavailable;}
try { root.refresh(); } catch(ignored) {}
function walk(n,depth) {
if(!n || depth>35 || ++count>1200) return;
try {
if(!n.isVisibleToUser())return;
var r=new android.graphics.Rect(); n.getBoundsInScreen(r); var b=rectOf(r);
if(n.isVisibleToUser() && b && b.top>=0 && b.left>=0 && b.bottom<=device.height && b.right<=device.width) {
var text=String(n.getText() || n.getContentDescription() || "");
var entry=item(text,b,n,String(n.getViewIdResourceName() || ""));
entry.scrollable=Boolean(n.isScrollable());list.push(entry);
}
for(var i=0;i<n.getChildCount();i++) walk(n.getChild(i),depth+1);
} catch(ignored) {}
}
walk(root,0);
return {packageName:String(root.getPackageName() || ""),items:list};
}
function find(page, re, predicate) {
return page.items.filter(function(i){return re.test(i.text) && (!predicate || predicate(i));})[0] || null;
}
function corpus(page) { return page.items.map(function(i){return i.text;}).join("|"); }
function tap(i,gestureOnly) {
if(!i) return false;
if(i.node) {
try {
if(!i.node.refresh()) return false;
var b=new android.graphics.Rect();i.node.getBoundsInScreen(b);
if(Math.abs((b.left+b.right)/2-i.x)>25 || Math.abs((b.top+b.bottom)/2-i.y)>25) return false;
var n=i.node;
for(var d=0;!gestureOnly && n && d<3;d++,n=n.getParent()) {
if(d>0) {
var parentBounds=new android.graphics.Rect();n.getBoundsInScreen(parentBounds);
if(parentBounds.right-parentBounds.left>device.width*.65 || parentBounds.bottom-parentBounds.top>device.height*.15)break;
}
if(n.isEnabled() && n.isClickable() && n.performAction(android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK)) {
record("点击:"+(i.text || i.id));sleep(1100);return true;
}
}
} catch(ignored) {}
}
if(i.x<=0 || i.y<=0 || i.x>=device.width || i.y>=device.height) return false;
record("点击真实文字位置:"+(i.text || i.id)+" @"+Math.round(i.x)+","+Math.round(i.y));
var ok=press(i.x,i.y,100)!==false;sleep(1100);return ok;
}
function readPage() {
return bounded("截图识别",15000,function(){
var p=nativePage(), frame=null;
// 福利列表与内嵌任务页原生文字完整时不等待静止屏幕产生新的截屏帧。
// 广告、小号关闭符号、奖励弹层仍补OCR和按钮颜色判断。
var needsOcr=(!welfare(p) && !embeddedPage(p)) || rewardPopup(p) ||
!!find(p,/^(立即领取|领\d+金币|领取\d+金币)$/);
if(captureReady && p.packageName===CONFIG.packageName && needsOcr) {
try {
frame=images.copy(captureScreen());
var result=typeof ocr!=="undefined" && ocr.detect ? ocr.detect(frame) : $ocr.detect(frame);
for(var j=0;j<result.length;j++) {
var b=rectOf(result[j].bounds), t=clean(result[j].text);
if(!b || !t) continue;
if(!p.items.some(function(i){return i.text===t && Math.abs(i.x-(b.left+b.right)/2)<40 && Math.abs(i.y-(b.top+b.bottom)/2)<40;}))
p.items.push(item(t,b));
}
if(!welfare(p)) readCornerClose(frame,p);
p.items.forEach(function(i){if(/^(立即领取|立即收下|开心收下|收下金币)$/.test(i.text))i.dark=darkButton(frame,i);});
} finally {if(frame)frame.recycle();}
}
files.write(CONFIG.pagePath,JSON.stringify({at:new Date().toISOString(),packageName:p.packageName,
items:p.items.map(function(i){return {text:i.text,bounds:i.bounds,id:i.id};})}));
return p;
});
}
function darkButton(frame,i) {
var b=i.bounds, points=[[i.x,b.top-8],[i.x,b.bottom+8],[b.left-8,i.y],[b.right+8,i.y]],dark=0,total=0;
points.forEach(function(p){
var x=Math.round(p[0]),y=Math.round(p[1]);if(x<0||y<0||x>=frame.getWidth()||y>=frame.getHeight())return;
var color=images.pixel(frame,x,y),r=(color>>>16)&255,g=(color>>>8)&255,blue=color&255;
total++;if((r+g+blue)/3<210)dark++;
});
return total>=3 && dark>=3;
}
function readCornerClose(frame,p) {
var crop=null,large=null, left=Math.round(device.width*.87),top=Math.round(device.height*.025);
try {
crop=images.clip(frame,left,top,device.width-left,Math.round(device.height*.15));
large=images.resize(crop,[crop.getWidth()*3,crop.getHeight()*3]);
var results=typeof ocr!=="undefined" && ocr.detect?ocr.detect(large):$ocr.detect(large);
for(var i=0;i<results.length;i++) {
var text=clean(results[i].text),b=rectOf(results[i].bounds);
if(b && /^(关闭|跳过|[xX×✕✖]|\d{1,3}(?:秒|[sS])?)$/.test(text))p.items.push(item(text,
{left:left+b.left/3,top:top+b.top/3,right:left+b.right/3,bottom:top+b.bottom/3}));
}
} finally {if(large)large.recycle();if(crop)crop.recycle();}
}
function requestCapture() {
app.launchPackage(String(context.getPackageName()));sleep(600);
var pending=true, worker=threads.start(function(){
var end=Date.now()+45000, verified=false;
while(pending && Date.now()<end) {
try {
var p=nativePage(), s=corpus(p);
if(p.packageName==="com.android.systemui" && /AutoJs6.*(?:录制|投放|截取|共享|screen|capture)/i.test(s)) verified=true;
if(p.packageName==="com.android.systemui" && verified) {
var single=find(p,/^(单个应用|单个应用程序)$/), whole=find(p,/^整个屏幕$/);
if(single && !whole) tap(single);
else if(whole && !/AutoJs6/.test(s)) tap(whole);
else if(!single) tap(find(p,/^(立即开始|开始|允许)$/));
}
} catch(ignored) {}
sleep(200);
}
});
try {captureReady=requestScreenCapture(false);}
finally {pending=false;worker.interrupt();worker.join(1500);if(worker.isAlive()){var e=new Error("截屏授权线程未退出");e.fatal=true;throw e;}}
if(!captureReady) throw new Error("未获得整个屏幕截屏授权");
}
function foregroundWait(pkg, timeout) {
var end=Date.now()+timeout;
while(Date.now()<end){try{if(nativePage().packageName===pkg)return true;}catch(ignored){}sleep(200);}return false;
}
function restartTarget() {
var name=String(app.getAppName(CONFIG.packageName)||"");
if(!name) throw new Error("未安装喜马拉雅极速版");
app.openAppSetting(CONFIG.packageName);
if(!foregroundWait("com.android.settings",8000)) throw new Error("未打开目标应用详情");
sleep(800);
var p=nativePage();
if(!find(p,new RegExp("^"+name+"$")))throw new Error("未确认目标应用,不点击强行停止");
var stop=find(p,/^(强行停止|强制停止|结束运行)$/);
if(!stop)throw new Error("未找到强行停止按钮");
if(stop.node.isEnabled()) {
tap(stop); var end=Date.now()+6000;
while(Date.now()<end) {
p=nativePage();var confirm=find(p,/^(确定|确认|停止|强行停止|强制停止)$/,function(i){return i.id==="android:id/button1";});
if(confirm)tap(confirm);
var info=context.getPackageManager().getApplicationInfo(CONFIG.packageName,0);
if((info.flags & android.content.pm.ApplicationInfo.FLAG_STOPPED)!==0)break;
sleep(200);
}
var stopped=context.getPackageManager().getApplicationInfo(CONFIG.packageName,0);
if((stopped.flags & android.content.pm.ApplicationInfo.FLAG_STOPPED)===0)throw new Error("尚未确认目标应用关闭");
}
app.launchPackage(CONFIG.packageName);
if(!foregroundWait(CONFIG.packageName,15000))throw new Error("喜马拉雅极速版启动超时");
sleep(1800);record("已关闭并重新打开应用,运行期间保持亮屏");
}
function embeddedPage(p) {return p.items.some(function(i){return /:id\/comp_actionbar_(?:close|title)$/.test(i.id);});}
function welfare(p) {
var fullAd=p.items.some(function(i){return /:id\/(tme_ad_container|host_reward_count_down)$/.test(i.id);});
return !fullAd && !embeddedPage(p) && !!find(p,/^福利$/,function(i){return /:id\/tab_welfare$/.test(i.id);});
}
function rewardPopup(p) {
return !!find(p,/恭喜(?:获得|领取)|签到成功|再看.*再领|奖励翻倍|放弃奖励|^我知道了$/) ||
p.items.some(function(i){return /:id\/main_inspire_ad_btn$/.test(i.id);});
}
function adRewardReceived(p) {
return /恭喜(?:已)?获得奖励|已完成浏览|已获得奖励|奖励已到账|奖励已发放/.test(corpus(p));
}
function closeButton(p, popup) {
var nativeClose=p.items.filter(function(i){return /(?:^|[_/])(?:close|dismiss|iv_close|btn_close)(?:$|_)/i.test(i.id) &&
(popup || i.y<device.height*.24) && i.bounds.right-i.bounds.left<device.width*.35;})[0];
if(nativeClose)return nativeClose;
if(popup) {
var dismiss=find(p,/^(我知道了|知道了|好的|放弃奖励|放弃领取|暂不领取|坚持退出|残忍离开|暂时放弃)$/,function(i){return i.y>device.height*.30;});
if(dismiss)return dismiss;
// 已确认的奖励广告弹层:关闭图标无文字、无ID,位于广告按钮下面的唯一小方框。
// 取真实可见节点bounds,不猜固定坐标,也不点击背景列表里的按钮。
var adButton=p.items.filter(function(i){return /:id\/main_inspire_ad_btn$/.test(i.id);})[0];
if(adButton) {
var icons=p.items.filter(function(i){
var w=i.bounds.right-i.bounds.left,h=i.bounds.bottom-i.bounds.top;
return !i.text && i.node && Math.abs(i.x-device.width*.5)<device.width*.08 &&
w>=device.width*.04 && w<=device.width*.12 && h/w>.7 && h/w<1.3 &&
i.bounds.top>adButton.bounds.bottom+device.height*.02 &&
i.y<Math.min(adButton.bounds.bottom+device.height*.18,device.height*.88);
}).filter(function(i,n,a){return !a.slice(0,n).some(function(j){return Math.abs(i.x-j.x)<5 && Math.abs(i.y-j.y)<5;});});
if(icons.length===1)return icons[0];
}
}
// OCR会把广告标识和叉合成“广告、|X”,只有已领奖励且位于右上才拆出末尾叉号。
if(adRewardReceived(p)) {
var merged=find(p,/^广告[、,,::||·•]*[xX×✕✖]$/,function(i){return i.bounds &&
i.bounds.left>device.width*.65 && i.bounds.right>device.width*.88 && i.bounds.right<=device.width &&
i.bounds.top>device.height*.04 && i.bounds.bottom<device.height*.20 &&
i.bounds.right-i.bounds.left<device.width*.35 && i.bounds.bottom-i.bounds.top<device.height*.045;});
if(merged) {
var b=merged.bounds,w=Math.min((b.bottom-b.top)*1.4,(b.right-b.left)*.25);
return item('X',{left:b.right-w,top:b.top,right:b.right,bottom:b.bottom});
}
}
return find(p,/^(关闭|关闭广告|跳过|[xX×✕✖])$/,function(i){
return popup ? i.y>device.height*.18 : i.y<device.height*.24 &&
(!/^[xX×✕✖]$/.test(i.text) || i.x>device.width*.72);
});
}
function coinAmount(text) {
var m=clean(text).match(/(?:领|得|奖励|翻倍)?\+?(\d+)金[币市]/);return m?Number(m[1]):null;
}
function popupChoice(buttons, textAmount) {
var withCoins=buttons.filter(function(b){return b.amount!==null;});
if(withCoins.length>=2) {
var high=withCoins.filter(function(b){return b.amount>=CONFIG.rewardThreshold;});
return (high.length?high.sort(function(a,b){return b.amount-a.amount;}):withCoins.sort(function(a,b){return a.amount-b.amount;}))[0];
}
if(withCoins.length===1) return withCoins[0].amount>=CONFIG.rewardThreshold ? withCoins[0] : null;
return buttons.length===1 && textAmount>=CONFIG.rewardThreshold && buttons[0].item.dark===true ? buttons[0] : null;
}
function handlePopup(p) {
if(!rewardPopup(p))return false;
var buttons=p.items.filter(function(i){return i.y>device.height*.32 && i.y<device.height*.82 &&
/^(?:立即领取|立即收下|开心收下|收下金币|看.*领.*金币|.*浏览.*领.*金币|领取\d+金币|领\d+金币)$/.test(i.text);
}).filter(function(i,n,a){return !a.slice(0,n).some(function(j){return Math.abs(j.x-i.x)<40 && Math.abs(j.y-i.y)<40;});});
var choices=buttons.map(function(i){return {item:i,amount:coinAmount(i.text)};});
var heading=find(p,/恭喜(?:获得|领取)|签到成功/,function(i){return i.y>device.height*.2 && i.y<device.height*.55;});
var bodyTop=heading?heading.bounds.top:device.height*.3;
var body=p.items.filter(function(i){return i.y>=bodyTop && i.y<device.height*.65 && i.x>device.width*.25 && i.x<device.width*.75;});
var amounts=body.map(function(i){
var direct=coinAmount(i.text);if(direct!==null)return direct;
// 奖励金额与“金币”常被分成两个原生节点,仅拼合同一行的相邻数字和单位。
if(/^\+?\d+$/.test(i.text) && body.some(function(j){return j.text==="金币" && j.x>i.x &&
j.bounds.left-i.bounds.right<device.width*.10 && Math.abs(j.y-i.y)<device.height*.04;}))return Number(i.text.replace('+',''));
return null;
}).filter(function(n){return n!==null;});
var choice=popupChoice(choices,amounts.length?Math.max.apply(Math,amounts):0);
var target=choice && choice.item;
if(!target)target=closeButton(p,true);
if(target){tap(target);return true;}
// 已确认奖励弹层且没有可领取条件,Android返回键交给弹层消费,不点背景任务。
record("奖励弹窗不符合领取条件,返回关闭");back();sleep(900);return true;
}
function fastRewardBrowseButton(p) {
if(p.packageName!==CONFIG.packageName || (welfare(p) && !rewardPopup(p)))return null;
var matches=p.items.filter(function(i){return i.text==="我要更快拿奖" && i.bounds &&
i.bounds.left>=0 && i.bounds.right<=device.width && i.bounds.top>=0 && i.bounds.bottom<=device.height;});
return matches.filter(function(i){return !!i.node;})[0] || matches[0] || null;
}
function browseRewardAndReturn(button,ms) {
if(!tap(button))return false;
record("已点击"+button.text+",浏览"+(ms/1000)+"秒后返回喜马拉雅");
var skipped=browseDwell(ms);if(skipped)return skipped;
// 内部详情页与广告同包名,单纯launchPackage不会退回广告,必须先返回。
back();sleep(800);
if(!foregroundWait(CONFIG.packageName,2000))app.launchPackage(CONFIG.packageName);
if(!foregroundWait(CONFIG.packageName,8000))throw new Error("浏览奖励后未返回喜马拉雅");
return true;
}
function fastRewardBrowseAndReturn(button) {return browseRewardAndReturn(button,15000);}
function retentionBrowseButton(p) {
var s=corpus(p);
if(!/现在退出|奖励还差/.test(s) || !/浏览(?:广告详情)?\d+秒|浏览\d+秒|继续(?:浏览|观看)/.test(s))return null;
return find(p,/^(?:点击)?去浏览$|^继续(?:浏览|观看)(?:领奖励)?$/,function(i){return i.bounds &&
i.bounds.top>=device.height*.25 && i.bounds.bottom<=device.height*.90;});
}
function common() {
var end=Date.now()+(activeLimitedDownload?360000:CONFIG.adTimeoutMs), browseClicked=false, previous="", repeated=0, popupAttempts=0, adStartedAt=0,floatingChecked=false,blankFloatingSince=0;
var retentionAttempts=0;
while(Date.now()<end) {
var p;
try {p=readPage();}
catch(error) {if(error.windowTransient){sleep(300);continue;}throw error;}
var s=corpus(p);
if(activeLimitedDownload) {
var step=limitedDownloadPlan(p,activeLimitedDownload);
if(step && step.kind==="blocked")return {downloadBlocked:true,reason:step.reason};
if(step && step.kind==="wait"){sleep(1200);continue;}
if(step && step.kind==="tap") {
var actionKey=p.packageName+":"+step.button.text;
activeLimitedDownload.repeats=actionKey===activeLimitedDownload.lastAction?activeLimitedDownload.repeats+1:1;
activeLimitedDownload.lastAction=actionKey;
if(activeLimitedDownload.repeats>3)return {downloadBlocked:true,reason:"安装或下载按钮连续操作未生效"};
record("限时任务目标"+activeLimitedDownload.name+":"+step.button.text);
tap(step.button,true);sleep(1800);continue;
}
if(step && step.kind==="browse") {
record("限时任务已打开目标应用,停留"+(activeLimitedDownload.dwellMs/1000)+"秒后返回");
browseDwell(activeLimitedDownload.dwellMs);activeLimitedDownload.browsed=true;
back();sleep(700);app.launchPackage(CONFIG.packageName);sleep(1000);
activeLimitedDownload=null;continue;
}
}
var browserSkipped=dailyBrowserReturn(p);if(browserSkipped)return browserSkipped;
if(p.packageName!==CONFIG.packageName) {
if(/packageinstaller|permissioncontroller/.test(p.packageName)) {
record("广告误入安装器,取消安装并返回");back();sleep(800);
} else {
var skipped=browseDwell(16000);if(skipped)return skipped;
app.launchPackage(CONFIG.packageName);sleep(1200);
}
continue;
}
var blankFloating=floatingCoinActive && p.items.some(function(i){return /:id\/tme_ad_container$/.test(i.id);}) &&
!p.items.some(function(i){return i.text && i.y>device.height*.05;});
if(blankFloating) {
if(!blankFloatingSince)blankFloatingSince=Date.now();
if(Date.now()-blankFloatingSince>=15000) {
record("右下角金币广告持续空白,返回并稍后再检查,不记为已领取");
back();sleep(1000);floatingCoinActive=false;nextFloatingCoinAt=Date.now()+60000;
state.lastFloatingCoin={at:new Date().toISOString(),status:"unconfirmed",reason:"广告持续空白"};persist();
continue;
}
} else blankFloatingSince=0;
if(/活动繁忙|服务繁忙|稍后再试/.test(s)){record("活动繁忙,跳过当前步骤");back();sleep(800);return {busy:true};}
if(/正在直播|进入直播间|直播已结束|直播间/.test(s) && !welfare(p)){record("退出误入直播页");back();sleep(1000);continue;}
var faster=fastRewardBrowseButton(p);
if(faster && !browseClicked) {
var fastResult=fastRewardBrowseAndReturn(faster);
if(fastResult && fastResult.browserSkipped)return fastResult;
if(fastResult)browseClicked=true;
continue;
}
var retention=retentionBrowseButton(p);
if(retention) {
if(++retentionAttempts>3)throw new Error("浏览挽留弹窗完成浏览后仍未消失,未继续点背景关闭");
record("前台是退出挽留弹窗,优先点击去浏览,不点击背景叉号");
var retentionResult=browseRewardAndReturn(retention,16000);
if(retentionResult && retentionResult.browserSkipped)return retentionResult;
if(retentionResult)browseClicked=true;
continue;
}
if(handlePopup(p)) {
if(++popupAttempts>5)throw new Error("弹窗多次操作未关闭,保留未完成状态");
continue;
}
popupAttempts=0;
// 有福利底栏时属于业务列表,列表中“观看15秒”等任务说明不能当作广告倒计时。
if(welfare(p)) {
floatingCoinActive=false;
if(!floatingChecked){floatingChecked=true;if(checkFloatingCoin(p))continue;}
return p;
}
var ad=adRewardReceived(p) || /奖励将于\d+秒|点击下载或打开第三方|观看完视频.*奖励|点击后[,,、]?看\d+秒/.test(s) ||
p.items.some(function(i){return /:id\/(tme_ad_container|host_reward_count_down)$/.test(i.id);}) ||
!embeddedPage(p) && /广告/.test(s) && !!closeButton(p,false);
if(!ad)return p;
if(!adStartedAt)adStartedAt=Date.now();
var browse=p.items.filter(function(i){return /^(我要更快拿奖|去浏览|立即浏览|查看详情|立即抢购|立即打开|打开应用|去看看|去逛逛|立即查看|了解详情|去了解)$/.test(i.text) &&
i.y>device.height*.55;}).sort(function(a,b){return b.y-a.y;})[0];
if(browse && !browseClicked && /浏览(?:广告详情)?\d+秒|更快拿奖|点击后[,,、]?看\d+秒/.test(s)) {
record("广告要求点击后浏览,打开详情并停留16秒后返回");
var skippedBrowse=browseRewardAndReturn(browse,16000);
if(skippedBrowse && skippedBrowse.browserSkipped)return skippedBrowse;
if(skippedBrowse)browseClicked=true;
continue;
}
var rewarded=adRewardReceived(p);
var timer=find(p,/(?:奖励将于|再看|还剩|剩余)\d+秒|\d+秒后(?:可|获|领)|^\d+[sS秒]$/,function(i){return i.y<device.height*.2;}) ||
find(p,/^\d{1,3}$/,function(i){return i.x>device.width*.65 && i.y>device.height*.04 && i.y<device.height*.18 && Number(i.text)<=120;});
var seconds=timer && timer.text.match(/\d+/);
if(timer && (!seconds || Number(seconds[0])>0) && !rewarded){sleep(1200);continue;}
// TME部分创意只显示“观看完视频,可获得奖励”,数字倒计时没有暴露给无障碍。
// 给视频播放留足时间,不能刚加载出关闭符号就立即退出并放弃奖励。
if(!rewarded && /观看完视频.*奖励/.test(s) && Date.now()-adStartedAt<35000){sleep(1200);continue;}
var close=closeButton(p,false);
if(close) {
var key=close.text+":"+Math.round(close.x)+","+Math.round(close.y);
repeated=key===previous?repeated+1:1;previous=key;
if(repeated>3)throw new Error("广告关闭连续3次未生效,保留现场");
tap(close);continue;
}
sleep(1200);
}
throw new Error("通用广告/弹窗处理超时,不能当作任务完成");
}
function enterWelfare() {
var end=Date.now()+18000,attempts=0;
while(Date.now()<end && attempts++<12) {
var before=Date.now(),p=common();
// 广告播放和浏览有独立超时,不消耗返回福利的导航预算。
end+=Date.now()-before;
if(p.busy || p.browserSkipped)continue;
if(embeddedPage(p)) {
var webClose=p.items.filter(function(i){return /:id\/comp_actionbar_close$/.test(i.id);})[0] ||
p.items.filter(function(i){return /:id\/comp_actionbar_up$/.test(i.id);})[0];
record("先退出内嵌任务页,再返回福利列表");
if(webClose)tap(webClose);else {back();sleep(800);}
continue;
}
var nav=find(p,/^福利$/,function(i){return /:id\/tab_welfare$/.test(i.id);});
if(nav){tap(nav);sleep(800);return common();}
if(p.packageName!==CONFIG.packageName)app.launchPackage(CONFIG.packageName);
else back();sleep(900);
}
throw new Error("未找到首页底部福利入口");
}
function scroll(direction, fraction) {
var h=device.height,w=device.width;
var list=nativePage().items.filter(function(i){return i.scrollable && i.bounds.bottom-i.bounds.top>h*.40;})
.sort(function(a,b){return (b.bounds.bottom-b.bounds.top)-(a.bounds.bottom-a.bounds.top);})[0];
if(!fraction && list && list.node.performAction(direction==="top"?android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD:
android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
record("列表滚动:"+direction+",使用原生滚动容器");sleep(1200);return;
}
var start=direction==="top"?.30:.78, end=fraction?start+(direction==="top"?fraction:-fraction):(direction==="top"?.78:.30);
// 限时任务附近有内嵌广告,沿列表左侧留白滑动,避免广告子页面吞掉滚动。
var x=w*(fraction?.07:.5);
var ok=swipe(x,h*start,x,h*end,650);
record("列表滚动:"+direction+",手势接受="+ok);sleep(1000);
}
function signature(p) {
var nativeItems=p.items.filter(function(i){return !!i.node && !!i.text;});
return (nativeItems.length?nativeItems:p.items).filter(function(i){return i.text && i.y>device.height*.12 && i.y<device.height*.88;})
.map(function(i){return i.text+":"+Math.round(i.y/30);}).sort().join("|");
}
function seek(label) {
enterWelfare();var last="",same=0;
var current=common();
if(current.busy)return null;
var visible=find(current,label,function(i){return i.y>device.height*.10 && i.y<device.height*.88;});
if(visible)return {page:current,anchor:visible};
// 回到列表顶部再从上向下查找,避免继承上一流程列表底部的位置。
for(var i=0;i<8;i++) {
var p=common();if(p.busy)return null;
var early=find(p,label,function(i){return i.y>device.height*.10 && i.y<device.height*.88;});
if(early)return {page:p,anchor:early};
var sig=signature(p);same=sig && sig===last?same+1:0;last=sig;
if(same>=2)break;scroll("top");
}
last="";same=0;
for(var j=0;j<CONFIG.scanLimit;j++) {
var page=common();if(page.busy)return null;
var anchor=find(page,label,function(i){return i.y>device.height*.10 && i.y<device.height*.88;});
if(anchor){record("找到任务:"+anchor.text);return {page:page,anchor:anchor};}
var key=signature(page);same=key && key===last?same+1:0;last=key;
if(same>=2)return null;scroll("down",.32);
}
return null;
}
function rowAction(found, labels) {
return find(found.page,labels,function(i){return i.x>device.width*.68 &&
Math.abs(i.y-found.anchor.y)<device.height*.055 && i.y<device.height*.90;});
}
function revealTaskSection(found, label) {
if(!found || !found.anchor || !found.anchor.bounds || found.anchor.y<=device.height*.45)return found;
// 保持标题在视野内,小幅上移,露出同一任务的按钮和奖励卡片。
var distance=Math.min(device.height*.45,found.anchor.y-device.height*.30);
swipe(device.width*.07,device.height*.78,device.width*.07,device.height*.78-distance,600);
sleep(900);
var page=common(),anchor=find(page,label,function(i){return i.y>device.height*.08 && i.y<device.height*.88;});
return anchor?{page:page,anchor:anchor}:seek(label);
}
function signClaimStage() {
var f=seek(/^(?:新人|新手|每日|福利)?签到(?:领金币)?$/);
if(!f)return {status:"skipped",reason:"没有签到入口"};
if(rowAction(f,/^(明日再来|已签到|已领取)$/))return {status:"success",reason:"今日已签到"};
var button=rowAction(f,/^(签到|立即签到|去签到|领取|去领取|立即领取)$/);
if(!button)return {status:"skipped",reason:"签到没有可领取按钮"};
tap(button);common();
f=seek(/^(?:新人|新手|每日|福利)?签到(?:领金币)?$/);
return f && rowAction(f,/^(明日再来|已签到|已领取)$/)?{status:"success"}:{status:"unresolved",reason:"点击签到后未确认已签到"};
}
function newbieSignAdState(found) {
var lower=device.height*.92;
found.page.items.forEach(function(i){
if(i.bounds.top>found.anchor.bounds.bottom &&
/^(看广告免费听VIP|每日听书赚金币|看视频开红包|免费领礼物|做任务赚金币|每日任务|整点打卡|翻卡)/.test(i.text))
lower=Math.min(lower,i.bounds.top);
});
var title=find(found.page,/(?:观看\d+秒广告|看广告).*(?:领取奖励|领.*金币)/,function(i){
return i.bounds.top>found.anchor.bounds.bottom && i.bounds.bottom<lower;
});
if(!title)return {missing:true};
var count=title.text.match(/[((](\d+)\/(\d+)[))]/);
return {title:title,progress:count?count[1]+"/"+count[2]:title.text,
done:!!count && Number(count[1])>=Number(count[2]),
action:find(found.page,/^去完成$/,function(i){return i.x>device.width*.68 &&
i.bounds.bottom<lower && Math.abs(i.y-title.y)<device.height*.055;})};
}
function newbieSignAdStage() {
var clicked=false,last="",unchanged=0;
for(var round=0;round<CONFIG.scanLimit;round++) {
var found=seek(/^(?:新人|新手)签到(?:领金币)?$/);
if(!found)return {status:clicked?"unresolved":"skipped",reason:"未找到新手签到区域"};
var ad=newbieSignAdState(found);
if(ad.missing && found.anchor.y>device.height*.55) {
// 把已识别的签到标题移到上方,露出本区域下面的广告,而不是点别的分区。
swipe(device.width*.5,found.anchor.y,device.width*.5,device.height*.30,650);sleep(1000);
var page=common(),anchor=!page.busy && find(page,/^(?:新人|新手)签到(?:领金币)?$/);
if(anchor)ad=newbieSignAdState({page:page,anchor:anchor});
}
if(ad.missing)return {status:clicked?"success":"skipped",reason:"新手签到区域没有可执行广告入口"};
if(ad.done)return {status:"success",reason:"新手签到广告次数已完成("+ad.progress+")"};
if(!ad.action)return {status:"unresolved",reason:"新手签到广告仍在,未找到本行去完成按钮"};
unchanged=ad.progress===last?unchanged+1:0;last=ad.progress;
if(unchanged>=3)return {status:"unresolved",reason:"新手签到广告次数连续未变化"};
record("新手签到区域广告:"+ad.progress);
if(!tap(ad.action))continue;
clicked=true;sleep(2500);
if(common().busy)return {status:"skipped",reason:"新手签到广告活动繁忙"};
}
return {status:"unresolved",reason:"新手签到广告尚未确认全部完成"};
}
function signStage() {
var claim;
try {claim=signClaimStage();}
catch(e) {
if(e.fatal || /InterruptedException|ScriptInterruptedException/.test(String(e)))throw e;
claim={status:"failed",reason:String(e)};record("签到领取未完成,继续检查同区域广告:"+e);
}
var ads=newbieSignAdStage();
var failed=/failed|unresolved/.test(claim.status) || /failed|unresolved/.test(ads.status);
return {status:failed?"unresolved":claim.status==="success" || ads.status==="success"?"success":"skipped",
sign:claim,newbieAds:ads,reason:"签到领取与同区域广告已分别检查"};
}
function hourlyRowState(found) {
var row=found.page.items.filter(function(i){return i.y>=found.anchor.bounds.top &&
i.y<=found.anchor.bounds.bottom+device.height*.035;});
var text=corpus({items:row});
var claim=rowAction(found,/^(领取|去领取|立即领取|立即领|打卡|去打卡)$/);
var waiting=/下一场|下次领取|后领|未到领取时间/.test(text) ||
!!rowAction(found,/^\d{1,2}:\d{2}(?::\d{2})?$/);
return {claim:claim,waiting:waiting,claimed:/已领取|已打卡|今日已完成/.test(text)};
}
function hourlyStage() {
var clicked=false;
for(var attempt=0;attempt<3;attempt++) {
var found=seek(/^整点打卡(?:[((]\d+\/\d+[))])?$/);
if(!found)return {status:clicked?"unresolved":"skipped",reason:clicked?"领取后未重新确认整点打卡状态":"没有整点打卡入口"};
var row=hourlyRowState(found);
if(row.waiting || row.claimed)return {status:clicked || row.claimed?"success":"skipped",
reason:clicked?"本场整点打卡已领取":row.claimed?"本场已打卡":"整点打卡尚未到领取时间,继续下一流程"};
if(!row.claim)return {status:"unresolved",reason:"整点打卡标签仍在,未识别到可领取或等待状态"};
if(!tap(row.claim))continue;
clicked=true;sleep(2500);
if(common().busy)return {status:"skipped",reason:"整点打卡活动繁忙"};
}
return {status:"unresolved",reason:"整点打卡点击后未确认领取成功"};
}
function findListeningClaim(found) {
var lower=device.height*.92;
found.page.items.forEach(function(i){
if(i.bounds.top>found.anchor.bounds.bottom &&
/^(看视频开红包|免费领礼物|做任务赚金币|每日任务|整点打卡|翻卡)/.test(i.text))lower=Math.min(lower,i.bounds.top);
});
var candidates=found.page.items.filter(function(i){
return i.bounds.top>=found.anchor.bounds.top && i.bounds.bottom<lower &&
/^(立即领|立即领取|去领取|领取|待领取|领\d+金币|领取\d+金币)$/.test(i.text);
});
var nativeCandidates=candidates.filter(function(i){return !!i.node;});
if(nativeCandidates.length)candidates=nativeCandidates;
else candidates=candidates.filter(function(i){return i.text!=="领取" ||
(i.x>device.width*.68 && Math.abs(i.y-found.anchor.y)<device.height*.055);});
return candidates.sort(function(a,b){
var pa=/^立即领/.test(a.text)?0:1,pb=/^立即领/.test(b.text)?0:1;
return pa-pb || a.y-b.y || a.x-b.x;
})[0] || null;
}
function listeningRewardStage() {
var claimed=0,last="",unchanged=0,emptyFrames=0;
for(var round=0;round<CONFIG.scanLimit;round++) {
var label=/^每日听书赚金币(?:[((].*[))])?$/;
var found=revealTaskSection(seek(label),label);
if(!found)return {status:claimed?"unresolved":"skipped",reason:"没有每日听书赚金币区域"};
var claim=findListeningClaim(found);
if(!claim) {
if(++emptyFrames>=2)return {status:claimed?"success":"skipped",reason:"连续确认听书奖励已无可领取按钮",claims:claimed};
sleep(800);continue;
}
emptyFrames=0;
var key=claim.text+":"+signature(found.page);
unchanged=key===last?unchanged+1:0;last=key;
if(unchanged>=3)return {status:"unresolved",reason:"听书奖励领取后页面未变化",claims:claimed};
record("领取已达标听书奖励:"+claim.text);
if(!tap(claim))continue;
claimed++;sleep(2500);
var page=common();
if(page.busy || page.browserSkipped)return {status:"skipped",reason:page.browserSkipped?"听书奖励打开浏览器,已返回":"听书奖励活动繁忙"};
}
return {status:"unresolved",reason:"听书奖励仍未确认领完",claims:claimed};
}
function repeatRowStage(label, actions, options) {
var last="",at=Date.now(),runs=0,sameRounds=0;
while(true) {
var f=seek(label);
if(options && options.reveal)f=revealTaskSection(f,label);
if(!f)return {status:runs?"success":"skipped",reason:runs?"返回福利页后入口已消失":"没有符合条件的入口"};
var progress=options && options.progress ? taskRowProgress(f) : null;
if(progress && progress.current>=progress.total)return {status:"success",
reason:"福利页确认次数已完成",progress:progress.current+"/"+progress.total};
var button=rowAction(f,actions);
if(!button) {
var done=rowAction(f,/^(明日再来|已领取|已完成|次数已用完|今日已完成)$/);
var cooldown=rowAction(f,/^\d{1,2}:\d{2}(?::\d{2})?$/);
if(cooldown) {
if(options && options.revisit) {
var parts=cooldown.text.split(":").map(Number),seconds=0;
parts.forEach(function(part){seconds=seconds*60+part;});
return {status:"deferred",reason:"翻卡冷却,先执行其他流程后返回继续",
retryAt:Date.now()+Math.max(1,seconds)*1000+1500};
}
return {status:"success",reason:"本轮奖励已领取,入口冷却中,继续下一流程"};
}
if(progress && progress.current<progress.total)return {status:"unresolved",
reason:"任务次数尚未完成,未识别到可执行按钮",progress:progress.current+"/"+progress.total};
return done?{status:"success",reason:"福利页已确认任务完成"}:
{status:"unresolved",reason:"任务标签仍在,但未识别到可执行或明确完成按钮"};
}
var key=progress?progress.current+"/"+progress.total:
corpus({items:f.page.items.filter(function(i){return Math.abs(i.y-f.anchor.y)<device.height*.09;})});
sameRounds=key===last?sameRounds+1:0;
if(key!==last){last=key;at=Date.now();}
if(options && options.reveal?sameRounds>=3:Date.now()-at>CONFIG.noProgressMs)return {status:"unresolved",reason:"同一任务反复执行但进度未变化"};
if(!tap(button,options && options.gesture))continue;
record("任务进度快照:"+key);
runs++;sleep(2500);var p=common();if(p.busy)return {status:"skipped",reason:"活动繁忙"};
if(debugTaskLimit && runs>=debugTaskLimit)return {status:"unresolved",reason:"调试执行一轮,未把剩余任务标记完成"};
}
}
function taskRowProgress(found) {
var text=found.anchor.text+"|"+corpus({items:found.page.items.filter(function(i){
return Math.abs(i.y-found.anchor.y)<device.height*.035;
})});
var match=text.match(/(?:已完成)?(\d+)\/(\d+)/);
return match && Number(match[2])>0?{current:Number(match[1]),total:Number(match[2])}:null;
}
function luckyRedPacketStage() {
return repeatRowStage(/^幸运红包(?:[((].*[))])?$/,
/^(去完成|去观看|看视频|去领取|领取|立即领取|继续观看)$/,{reveal:true,progress:true,gesture:true});
}
function limitedDownloadRow(found) {
var lower=device.height*.92;
found.page.items.forEach(function(i){if(i.bounds.top>found.anchor.bounds.bottom &&
/^(红包雨|喝水补贴|1元红包|幸运大转盘|免费领礼物|做任务赚金币|每日任务|每日听书|看视频开红包|幸运红包|整点打卡|翻卡)/.test(i.text))
lower=Math.min(lower,i.bounds.top);});
var items=found.page.items.filter(function(i){return i.bounds.top>=found.anchor.bounds.bottom && i.bounds.bottom<lower;});
var title=find({items:items},/^(?:下载并打开|下载并浏览|下载并体验|下载|安装|打开|浏览|体验).+/);
var button=find({items:items},/^(去安装|去下载|下载|安装|去打开|打开|去浏览|去完成|去领取|立即领取|领取)$/,
function(i){return i.x>device.width*.68 && (!title || Math.abs(i.y-title.y)<device.height*.055);});
return {title:title,button:button,waiting:!!find({items:items},/^\d{1,2}:\d{2}(?::\d{2})?后(?:打开|浏览)/),
done:!!find({items:items},/^(已领取|已完成|今日已完成|明日再来|暂无任务)$/)};
}
function limitedDownloadTarget(text) {
var name=clean(text).replace(/^(下载并打开|下载并浏览|下载并体验|下载|安装|打开|浏览|体验)/,"")
.replace(/\d+秒.*$/,"").replace(/[《》「」]/g,"");
var seconds=clean(text).match(/(\d+)秒/);
return {name:name,dwellMs:Math.max(16000,seconds?Number(seconds[1])*1000+1000:16000),browsed:false,repeats:0};
}
function limitedDownloadPlan(page,task) {
var s=corpus(page),installer=/packageinstaller|permissioncontroller/.test(page.packageName);
var target=task.name && s.indexOf(task.name)>=0;
if(installer) {
if(/permissioncontroller/.test(page.packageName) && /请求向您发送通知/.test(s) && target) {
var deny=find(page,/^(禁止|不允许|暂不允许)$/);
return deny?{kind:"tap",button:deny}:{kind:"blocked",reason:"未识别到通知权限拒绝按钮"};
}
if(/permissioncontroller/.test(page.packageName) && /请求|访问|权限/.test(s) && !/安装/.test(s))
return {kind:"blocked",reason:"目标应用的其他权限需要确认"};
if(/安装失败|未安装此应用|应用未安装|安装包损坏|解析.*错误/.test(s))return {kind:"blocked",reason:"目标应用安装失败"};
if(/输入.*密码|验证身份|指纹验证|人脸验证/.test(s))return {kind:"blocked",reason:"安装需要手动身份验证"};
if(target)task.installerConfirmed=true;
if(!task.installerConfirmed)return {kind:"blocked",reason:"安装器未确认目标应用名称,不点击安装"};
if(target && /喜马拉雅极速版.*(?:请求使用安装权限|正在发起安装)/.test(s)) {
var allow=find(page,/^允许$/,function(i){return i.id==="android:id/button1";});
return allow?{kind:"tap",button:allow}:{kind:"wait"};
}
if(/正在安装|安装中|正在验证|正在准备|正在检测|正在扫描/.test(s))return {kind:"wait"};
var open=find(page,/^(打开|立即打开)$/),finish=find(page,/^完成$/);
if(open || finish)return {kind:"tap",button:open || finish};
var install=find(page,/^(继续安装|安装|下一步)$/);
return install?{kind:"tap",button:install}:{kind:"wait"};
}
var store=/^(com\.bbk\.appstore|com\.heytap\.market|com\.oppo\.market|com\.tencent\.android\.qqdownloader)$/.test(page.packageName);
if(page.packageName==="com.bbk.appstore") {
var appTitle=find(page,new RegExp("^"+task.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$"),
function(i){return i.id==="com.bbk.appstore:id/package_detail_title";});
if(!appTitle) {
var otherTitle=page.items.some(function(i){return i.id==="com.bbk.appstore:id/package_detail_title" && i.text;});
var sameDetail=task.storeConfirmed && !otherTitle && page.items.some(function(i){
return i.id==="com.bbk.appstore:id/banner_main_title_left" &&
i.text.indexOf("安装了"+task.name+"的人还安装了")===0;
});
if(!sameDetail) {
if(task.storeConfirmed && !otherTitle)return {kind:"wait"};
return {kind:"blocked",reason:"vivo商店未确认目标详情标题"};
}
}
task.storeConfirmed=true;
var primary=find(page,/^(安装|立即安装|下载|立即下载|继续下载|打开|立即打开)$/,
function(i){return i.id==="com.bbk.appstore:id/download_progress_text";});
return primary?{kind:"tap",button:primary}:{kind:"wait"};
}
var detail=target && !welfare(page) && (store || /应用版本|开发者|权限详情|隐私协议/.test(s));
if(detail) {
var button=find(page,/^(立即下载|下载|继续下载|去安装|安装|立即安装|打开|立即打开)$/,
function(i){return i.y>device.height*.80 && i.bounds.right-i.bounds.left>device.width*.45;});
if(button)return {kind:"tap",button:button};
return {kind:"wait"};
}
if(page.packageName!==CONFIG.packageName && !store) {
var name=page.appName;
if(name===undefined)try{name=String(app.getAppName(page.packageName)||"");}catch(ignored){name="";}
if(name && (name.indexOf(task.name)>=0 || task.name.indexOf(name)>=0))return {kind:"browse"};
return {kind:"blocked",reason:"前台不是限时任务目标应用:"+page.packageName};
}
if(store)return {kind:"wait"};
return null;
}
function limitedDownloadStage() {
var completed=0,last="",same=0,creditBefore=null,runs=0;
try {
for(var round=0;round<CONFIG.scanLimit;round++) {
activeLimitedDownload=null;
var label=/^限时下载任务$/,found=revealTaskSection(seek(label),label);
if(!found)return {status:completed?"success":runs?"unresolved":"skipped",
reason:runs?"操作后未确认限时任务入口和奖励到账":"福利页没有限时下载任务入口",completed:completed};
var balance=welfareCoinBalance(found.page);
if(creditBefore!==null && balance!==null && balance>creditBefore) {
record("限时任务确认到账:"+(balance-creditBefore)+"金币");completed++;creditBefore=null;
}
var row=limitedDownloadRow(found);
if(row.done && !row.button)return {status:"success",reason:"限时下载任务已完成",completed:completed};
if(!row.title && row.waiting)return {status:completed?"success":"skipped",
reason:"当前没有可执行限时任务,其余任务尚未到领取时间",completed:completed,waiting:true};
if(!row.title || !row.button)return {status:"unresolved",reason:"限时下载区域仍在,未确认可执行或已完成状态",completed:completed};
var key=row.title.text+":"+row.button.text;same=key===last?same+1:0;last=key;
if(same>=3)return {status:"unresolved",reason:"限时下载任务重复执行但状态未更新",completed:completed};
var target=limitedDownloadTarget(row.title.text);
if(!target.name)return {status:"unresolved",reason:"没有识别到下载目标名称"};
activeLimitedDownload=/^(去领取|立即领取|领取)$/.test(row.button.text)?null:target;
if(creditBefore===null)creditBefore=balance;
record("限时下载任务:"+row.title.text+"/"+row.button.text);
if(!tap(row.button,true))continue;
runs++;
sleep(1800);
if(/浏览|打开/.test(row.button.text)) {
// 已安装任务直接浏览;下载任务则由公共安装器等到目标应用打开后计时。
var p=nativePage();
if(p.packageName===CONFIG.packageName && !welfare(p)) {
browseDwell(target.dwellMs);target.browsed=true;back();sleep(800);activeLimitedDownload=null;
}
}
var page=common();
if(page.downloadBlocked)return {status:"unresolved",reason:page.reason,completed:completed};
if(page.busy)return {status:"skipped",reason:"限时下载活动繁忙",completed:completed};
var afterBalance=welfareCoinBalance(page);
if(creditBefore!==null && afterBalance!==null && afterBalance>creditBefore) {
record("限时任务确认到账:"+(afterBalance-creditBefore)+"金币");completed++;creditBefore=null;
}
}
return {status:"unresolved",reason:"限时下载仍有待办,达到本轮检查上限",completed:completed};
} finally {activeLimitedDownload=null;}
}
function welfareCoinBalance(page) {
if(!welfare(page))return null;
var unit=find(page,/^金币$/,function(i){return i.x<device.width*.30 && i.y<device.height*.30;});
if(!unit)return null;
var value=find(page,/^\d+$/,function(i){return i.bounds.right<=unit.bounds.left &&
unit.bounds.left-i.bounds.right<device.width*.08 && Math.abs(i.y-unit.y)<device.height*.025;});
return value?Number(value.text):null;
}
function videoRedPacketStage() {
return repeatRowStage(/^看视频(?:开红包|赚金币|领金币)/,
/^(去领取|领取|去观看|看视频|立即领|立即领取|开红包|领红包|继续观看)$/,{reveal:true});
}
function workflowStages() {
return [{name:"签到",action:signStage},
{name:"整点打卡",action:hourlyStage},
{name:"听书奖励领取",action:listeningRewardStage},
{name:"翻卡",action:function(){return repeatRowStage(/翻卡.*金币/,/^(继续翻卡|去翻卡|翻卡|立即翻卡|去完成|领取)$/,{revisit:true});}},
{name:"看视频开红包",action:videoRedPacketStage},
{name:"限时下载任务",action:limitedDownloadStage},
{name:"幸运红包",action:luckyRedPacketStage},
{name:"复查听书奖励",action:listeningRewardStage}];
}
function dailyDetail() {
var last="",unchanged=0;
for(var step=0;step<8;step++) {
var p=common();if(p.busy)return false;
if(p.browserSkipped){if(p.floatingCoin)continue;return false;}
if(welfare(p))return true;
var s=corpus(p);
if(/确认支付|提交订单|绑定银行卡|开通会员|验证身份/.test(s)){record("每日任务需要额外操作,返回而不提交");back();sleep(900);return false;}
if(/今日已领取|今日已完成|任务已完成|领取次数已用完/.test(s)){back();sleep(800);return true;}
var button=p.items.filter(function(i){return i.y>device.height*.25 && i.y<device.height*.91 &&
/^(立即领取|领取奖励|领取金币|点击领金币|点一下领金币|立即领|领金币|去领取|领取|领取补贴|我喝水了|看视频领取|看广告领取|看视频翻倍|去点击|去浏览)$/.test(i.text);
}).sort(function(a,b){return b.y-a.y;})[0];
if(!button){record("每日任务详情暂未识别到可执行按钮,返回保留待办");back();sleep(900);return false;}
var key=button.text+":"+signature(p);unchanged=key===last?unchanged+1:0;last=key;
if(unchanged>=2){back();sleep(900);return false;}
tap(button);
}
return false;
}
function dailyStage() {
var f=seek(/^(每日任务|日常任务)$/) || seek(/^做任务赚金币$/);
if(!f)return {status:"skipped",reason:"未找到每日任务区域"};
var counts={},last="",same=0,unhandled=[],relocate=false;
for(var round=0;round<120;round++) {
var p=common();if(p.busy)return {status:"skipped",reason:"活动繁忙"};
if(p.browserSkipped || !welfare(p)){enterWelfare();relocate=true;continue;}
if(relocate) {
var restored=seek(/^(每日任务|日常任务)$/) || seek(/^做任务赚金币$/);
if(!restored)return {status:"unresolved",reason:"任务返回后未重新找到每日任务分区"};
p=restored.page;relocate=false;
}
var header=find(p,/^(每日任务|日常任务)$/) || find(p,/^做任务赚金币$/), top=header?header.bounds.bottom:device.height*.10;
var actions=p.items.filter(function(i){return i.y>top && i.y<device.height*.89 && i.x>device.width*.68 &&
/^(领取|领金币|立即领|去领取|去观看|看视频|去浏览|去完成|去答题|去收听|去听书)$/.test(i.text);});
var chosen=null,key="",taskTitle="";
for(var i=0;i<actions.length;i++) {
var a=actions[i];var nearby=p.items.filter(function(n){return n.text && n.x<device.width*.7 && Math.abs(n.y-a.y)<device.height*.045;});
var nativeNearby=nearby.filter(function(n){return !!n.node;});
if(nativeNearby.length)nearby=nativeNearby;
var description=nearby.map(function(n){return n.text;}).join("|");
var titleItem=nearby.filter(function(n){return !/^(最高|\+?\d)/.test(n.text);})[0];
var title=titleItem?titleItem.text:description;
if(dailyBrowserSkippedTitles[title])continue;
if(/饭点|吃饭|喝水补贴|拆红包领金币|红包雨|答题|点一下领金币|福利天天赚|下载|安装|开通|付费|支付|邀请|绑卡|翻卡/.test(description) || a.text==="去答题")continue;
if(/^(去收听|去听书)$/.test(a.text)) {unhandled.push(description+":"+a.text);continue;}
if(a.text==="去完成" && !/浏览|广告|视频/.test(description)) {unhandled.push(description);continue;}
key=description+":"+a.text;
if((counts[key]||0)>=3){unhandled.push(key);continue;}
chosen=a;taskTitle=title;break;
}
if(chosen) {
record("每日任务:"+key);
counts[key]=(counts[key]||0)+1;
activeDailyTask={key:key,title:taskTitle,browserSkipped:false};
try {
tap(chosen);sleep(2500);
var completed=dailyDetail();
if(activeDailyTask.browserSkipped)record("该任务已加入浏览器跳过列表:"+taskTitle);
else if(!completed)unhandled.push(key);
} finally {activeDailyTask=null;}
last="";same=0;relocate=true;continue;
}
var sig=signature(p);same=sig && sig===last?same+1:0;last=sig;
if(same>=3)return {status:unhandled.length?"unresolved":"success",reason:unhandled.length?"仍有无法确认完成的任务":"列表到底且无支持的可执行任务"};
scroll("down");
}
return {status:"unresolved",reason:"每日任务扫描达到上限"};
}
function run() {
state.status="running";state.startedAt=new Date().toISOString();persist();
events.on("exit",stopScreenAwake);
try {
startScreenAwake();
if(files.exists(CONFIG.browserSkipPath)) {
try {var saved=JSON.parse(String(files.read(CONFIG.browserSkipPath)));
Object.keys(saved).forEach(function(title){if(saved[title]===true)dailyBrowserSkippedTitles[title]=true;});
} catch(e){record("浏览器跳过记录读取失败,本轮重新识别:"+e);}
}
var end=Date.now()+10000;while(!auto.rootInActiveWindow && Date.now()<end)sleep(200);
if(!auto.rootInActiveWindow)throw new Error("请开启AutoJs6无障碍服务");
var args=engines.myEngine().execArgv || {};
debugTaskLimit=args.ximalayaDebugResume ? Number(args.ximalayaDebugTaskLimit || 0) : 0;
requestCapture();
if(args.ximalayaDebugResume) {
if(nativePage().packageName===String(context.getPackageName()))back();
if(!foregroundWait(CONFIG.packageName,3000))app.launchPackage(CONFIG.packageName);
foregroundWait(CONFIG.packageName,10000);record("调试恢复当前页面");
}
else restartTarget();
var stages=workflowStages();
var first=Number(args.ximalayaStartStage || 0);
if(!isFinite(first) || first<0 || first>=stages.length)throw new Error("无效的起始流程");
var queue=[];for(var initial=first;initial<stages.length;initial++)queue.push(initial);
while(queue.length) {
var i=queue.shift();
state.current=stages[i].name;persist();record("开始流程");
var result;
try {result=stages[i].action();}
catch(e) {
if(e.fatal || /InterruptedException|ScriptInterruptedException/.test(String(e)))throw e;
result={status:"failed",reason:String(e)};
record("本流程失败,返回福利后执行下一流程:"+e);
try {enterWelfare();}
catch(recoveryError) {
if(recoveryError.fatal || /InterruptedException|ScriptInterruptedException/.test(String(recoveryError)))throw recoveryError;
record("当前页面无法返回福利,重新打开应用后继续下一流程:"+recoveryError);
restartTarget();enterWelfare();
}
}
result.name=state.current;
var existing=-1;state.stages.forEach(function(s,index){if(s.name===result.name)existing=index;});
if(existing>=0)state.stages[existing]=result;else state.stages.push(result);
persist();record("流程结果:"+JSON.stringify(result));
if(!queue.length) {
var pending=state.stages.filter(function(s){return s.status==="deferred";})
.sort(function(a,b){return a.retryAt-b.retryAt;})[0];
if(pending) {
state.current="等待翻卡冷却";persist();record("其他流程已核对,等待翻卡冷却后继续");
while(Date.now()<pending.retryAt)sleep(Math.min(1000,pending.retryAt-Date.now()));
stages.forEach(function(stage,index){if(stage.name===pending.name)queue.push(index);});
}
}
}
state.status=state.stages.some(function(s){return /failed|unresolved/.test(s.status);})?"partial_failure":"success";
} catch(e) {state.status="interrupted";state.error=String(e);record("停止:"+e);}
finally {stopScreenAwake();state.finishedAt=new Date().toISOString();persist();}
}
// BEGIN XIMALAYA ENTRY
run();
exit();