1391 lines
75 KiB
JavaScript
1391 lines
75 KiB
JavaScript
"auto";
|
||
|
||
// 快手极速版:无障碍文字 + 手机本地 OCR;不保存或上传图片,不访问媒体音量。
|
||
var CONFIG = {
|
||
version: "2026-10-30-kuaishou-24-video-cadence",
|
||
packageName: "com.kuaishou.nebula",
|
||
pollMs: 1200,
|
||
recognitionTimeoutMs: 30000,
|
||
capturePermissionTimeoutMs: 60000,
|
||
captureRecoveryLimit: 2,
|
||
useLocalOcr: true,
|
||
roundTimeoutMs: 300000,
|
||
taskSearchScrolls: 24,
|
||
noProgressLimit: 3,
|
||
videoCalibrationMs: 120000,
|
||
videoSwipeIntervalMs: 8000,
|
||
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"
|
||
};
|
||
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: "连续看视频阶段奖励", kind: "continuousVideo"},
|
||
{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 readSnapshot() {
|
||
keepScreenAwake();
|
||
var foreground = foregroundPackage(), deadline = Date.now() + 1500;
|
||
// 切页时无障碍窗口可能短暂为空,确认后再判断是否真的离开应用。
|
||
while (foreground !== CONFIG.packageName && Date.now() < deadline) {
|
||
sleep(150);
|
||
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.left<device.width*.32 &&
|
||
box.bottom-box.top>device.height*.018 && box.bottom-box.top<device.height*.065 &&
|
||
box.top>device.height*.25 && box.bottom<device.height*.80) {
|
||
// 保留图片小按钮;仅在翻卡标题、位数标签及相对位置均匹配后才会使用。
|
||
values.push("@flip_card_button");
|
||
}
|
||
for (var v = 0; v < values.length; v++) {
|
||
if (values[v] && values[v].length < 120) {
|
||
items.push({text: values[v], rect: box, node: node, id: resourceId, enabled: enabled});
|
||
}
|
||
}
|
||
}
|
||
if (localOcrEnabled && needsLocalOcr(items)) {
|
||
var frame = null;
|
||
try {
|
||
frame = images.copy(captureScreen());
|
||
var results = $ocr.detect(frame);
|
||
if (!Array.isArray(results)) throw new Error("本地 OCR 格式不兼容");
|
||
results.forEach(function (result) {
|
||
var box = rectOf(result.bounds), value = compact(result.text);
|
||
if (box && value && value.length < 120) items.push({text: value, rect: box, node: null});
|
||
});
|
||
} finally { if (frame) frame.recycle(); }
|
||
}
|
||
var unique = [];
|
||
items.forEach(function (item) {
|
||
if (!unique.some(function (other) {
|
||
return other.text === item.text && Math.abs(other.rect.top - item.rect.top) < 35 &&
|
||
Math.abs(other.rect.left - item.rect.left) < 35;
|
||
})) unique.push(item);
|
||
});
|
||
files.write(CONFIG.pageTextPath, JSON.stringify(unique.map(function (item) {
|
||
return {text: item.text, rect: item.rect, id: item.id, enabled: item.enabled};
|
||
})));
|
||
unique.forEach(function (item) {recordRewardCoins(item.text);});
|
||
checkRejection(unique);
|
||
return unique;
|
||
}
|
||
function snapshot() { return readPage("识别快手页面"); }
|
||
function needsLocalOcr(page) {
|
||
if((flipFlowActive || continuousCardReading) && !isAd(page)) return true;
|
||
// 翻卡的百位/千位底部按钮是图片,原生树只有已翻数字及“重翻十位”。
|
||
// 不能因看到了翻卡标题就认定所有按钮已完整暴露。
|
||
if (isFlipPage(page) || flipSettlement(page)) return true;
|
||
// 这些实机页面已完整暴露任务文字,重复做全屏 OCR 会拖慢倒计时滑动。
|
||
if (streetProgress(page) || streetComplete(page) || isMallList(page) || isProductDetail(page)) return false;
|
||
if (page.some(function (item) {return /:id\/video_countdown$/.test(item.id || "");}) ||
|
||
page.some(function (item) {return /:id\/reward_merchant_text$/.test(item.id || "");}) ||
|
||
first(page, /^close_view$/)) return false;
|
||
// 邀请浮层的 X 只有 OCR 可见,必须保留补充识别。
|
||
if (isTaskCenter(page) && !first(page, /邀.*好友|去微信邀请好友/)) return false;
|
||
return true;
|
||
}
|
||
function clickItem(item) {
|
||
if (!item || item.enabled === false) throw new Error("目标按钮不存在或不可点击");
|
||
if (foregroundPackage() !== CONFIG.packageName) throw new Error("点击前已离开快手");
|
||
var ok = false;
|
||
if (item.node) {
|
||
try {
|
||
if (item.node.clickable()) ok = item.node.click();
|
||
else {
|
||
var parent = item.node.parent(), bounds = parent && rectOf(parent.bounds());
|
||
// 只向上一层点击紧贴文字的小按钮,不能点击整行任务或整页容器。
|
||
if (bounds && parent.enabled() && parent.clickable() &&
|
||
bounds.left <= item.rect.left && bounds.right >= 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 isTaskCenter(page) {
|
||
return !!first(page, /^任务中心$/) && !!bottomNavigation(page, /^去赚钱$/);
|
||
}
|
||
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 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) || bottomNavigation(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) || 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;
|
||
// 只关闭明确标识的弹窗,不点广告推广区“立即领取”或“看详情”。
|
||
tapFresh(close, modalClose);
|
||
return true;
|
||
}
|
||
function ensureTaskCenter() {
|
||
var deadline = Date.now() + 45000;
|
||
for (var i = 0; i < 8 && Date.now() < deadline;) {
|
||
var page = snapshot();
|
||
if (!page.length || first(page, /^(?:加载中\.?|正在加载\.?|页面加载中\.?|Loading\.?)$/i)) {
|
||
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 = bottomNavigation(page, /^去赚钱$/);
|
||
if (nav) tapFresh(nav);
|
||
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<device.height*.90;});
|
||
var expiry=resume && first(page,/^\d{1,2}[::]\d{2}[::]\d{2}[||]?倒计时结束后失效$/,function(i){
|
||
return i.rect.left<device.width*.70 && Math.abs(i.rect.top-resume.rect.top)<device.height*.05;
|
||
});
|
||
if(expiry) rows.push({title:"翻卡赢金币",label:expiry,action:resume,detail:expiry.text,quota:null,unavailable:false});
|
||
}
|
||
return rows;
|
||
}
|
||
function scrollList(down) {
|
||
if (foregroundPackage() !== CONFIG.packageName) throw new Error("滑动前已离开快手");
|
||
var x = Math.round(device.width * 0.37);
|
||
if (!swipe(x, device.height * (down ? 0.79 : 0.32), x,
|
||
device.height * (down ? 0.34 : 0.77), 800)) throw new Error("任务列表滑动失败");
|
||
sleep(CONFIG.pollMs);
|
||
}
|
||
function pageSignature(page) {
|
||
var nativeItems = page.filter(function (item) {return !!item.node;});
|
||
var stable = nativeItems.length ? nativeItems : page;
|
||
return stable.filter(function (item) {
|
||
return taskTitle(item) && !/^\d/.test(item.text) && !/\d+[::]\d+/.test(item.text);
|
||
}).map(function (item) {return item.text;}).sort().join("|");
|
||
}
|
||
function scanTask(pattern, excluded) {
|
||
ensureTaskCenter();
|
||
// 先向上扫描,再由顶部向下完整扫描;未找到的任务必须复查第二遍。
|
||
for (var direction = 0; direction < 2; direction++) {
|
||
var prior = "", stationary = 0;
|
||
for (var i = 0; i <= CONFIG.taskSearchScrolls; i++) {
|
||
var page = snapshot();
|
||
if (dismissModal(page)) {page = snapshot();}
|
||
if (!isTaskCenter(page)) {
|
||
writeRunLog("TASK PAGE RECHECK: 浮层或加载遮挡,重新确认任务中心");
|
||
page = ensureTaskCenter();
|
||
}
|
||
var rows = rowsOnPage(page, pattern).filter(function (row) {return !excluded || !excluded[row.title];});
|
||
if (rows.length) return rows[0];
|
||
var signature = pageSignature(page);
|
||
stationary = signature === prior ? stationary + 1 : 0;
|
||
if (stationary >= 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 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<Math.min(device.height*.75,heading.rect.bottom+device.height*.25);
|
||
});
|
||
if(!label) return;
|
||
var center=(label.rect.left+label.rect.right)/2;
|
||
var digit=first(page,/^\d$/,function(i){return i.rect.top>=label.rect.top-device.height*.12 &&
|
||
i.rect.top<label.rect.top && Math.abs((i.rect.left+i.rect.right)/2-center)<device.width*.08;});
|
||
positions.push({name:name,label:label,digit:digit&&digit.text});
|
||
});
|
||
return positions;
|
||
}
|
||
function flipUnlockProgress(page) {
|
||
if(!isFlipPage(page)) return null;
|
||
var counter=first(page,/^看[((]\d+\/\d+[))]个视频可翻$/);
|
||
return counter&"a(counter.text);
|
||
}
|
||
function flipTaskDay() {
|
||
var now=new Date();return now.getFullYear()+"-"+("0"+(now.getMonth()+1)).slice(-2)+"-"+("0"+now.getDate()).slice(-2);
|
||
}
|
||
function saveFlipDone(reason) {
|
||
var state={version:1,day:flipTaskDay(),done:true,reason:reason,updatedAt:new Date().toISOString()};
|
||
var temp=CONFIG.flipResultPath+".tmp";
|
||
files.write(temp,JSON.stringify(state,null,2));
|
||
if(!new java.io.File(temp).renameTo(new java.io.File(CONFIG.flipResultPath))) throw new Error("翻卡已领取,但无法保存完成记录");
|
||
}
|
||
function flipDoneToday() {
|
||
if(!files.exists(CONFIG.flipResultPath)) return false;
|
||
var state;
|
||
try{state=JSON.parse(files.read(CONFIG.flipResultPath));}catch(error){writeRunLog("FLIP STATE RECHECK: 完成记录损坏,重新确认入口");return false;}
|
||
return !!(state&&state.version===1&&state.day===flipTaskDay()&&state.done===true);
|
||
}
|
||
function flipDecision(page) {
|
||
if(isAd(page)) return null;
|
||
var heading=first(page,/^翻卡赢金币$/),positions=flipPositions(page);
|
||
var pending=positions.filter(function(p){return p.digit===null;});
|
||
// 明确的看视频解锁弹层先于其背后的卡片按钮。
|
||
var unlock=heading && first(page,/^(?:看广告翻[千百十个]位|(?:再)?看(?:完)?(?:\d+个?|\d+次|一个|一次)?(?:视频|广告)(?:[,,]?可)?(?:解锁|翻|翻开|开启)(?:卡|[千百十个]位)?|解锁[千百十个]位)(?:[((]\d+\/\d+[))])?$/,function(i){
|
||
return i.enabled!==false && i.rect.top>heading.rect.bottom && i.rect.bottom<device.height*.88;
|
||
});
|
||
if(unlock) return {kind:"unlock",button:unlock};
|
||
// 按个、十、百、千补足尚未翻开的位数,只点卡片底部按钮,不点标签或可选重翻。
|
||
if(heading && pending.length) {
|
||
var next=pending[0],center=(next.label.rect.left+next.label.rect.right)/2;
|
||
var bottom=first(page,/^(?:@flip_card_button|(?:点击|立即|免费)?翻(?:卡|[千百十个]位)?)$/,function(i){
|
||
return i.enabled!==false && i.rect.top>=next.label.rect.top &&
|
||
i.rect.bottom<=next.label.rect.bottom+device.height*.075 &&
|
||
Math.abs((i.rect.left+i.rect.right)/2-center)<device.width*.10 &&
|
||
i.rect.right-i.rect.left<device.width*.40;
|
||
});
|
||
if(bottom) return {kind:"flip",position:next.name,button:bottom};
|
||
}
|
||
if(pending.length) return null;
|
||
var legacy=heading && first(page,/^(?:点击|立即|免费)?翻(?:卡|[千百十个]位)$/,function(i){
|
||
return i.enabled!==false && i.rect.top>heading.rect.bottom && i.rect.bottom<device.height*.88;
|
||
});
|
||
if(legacy) return {kind:"flip",button:legacy};
|
||
// 未完整识别四位时,只接受明确“翻出N金币”的结算页,不能拿“不翻了”提前结算。
|
||
if(!(positions.length===4 && positions.every(function(p){return p.digit!==null;})) && !first(page,/^翻出\d+金币$/)) return null;
|
||
var collect=first(page,/^(?:不翻了[,,]?直接领|立即收下|开心收下|收下金币|领取\d+金币|领取金币)$/,function(i){
|
||
return i.enabled!==false && i.rect.top>device.height*.35 && i.rect.bottom<device.height*.88;
|
||
});
|
||
return collect?{kind:"collect",button:collect}:null;
|
||
}
|
||
function flipAction(page) {
|
||
var decision=flipDecision(page);return decision&&decision.button;
|
||
}
|
||
function flipSettlement(page) {
|
||
var decision=first(page,/^翻出\d+金币$/)&&flipDecision(page);
|
||
return decision&&decision.kind==="collect"?decision.button:null;
|
||
}
|
||
function isMallList(page) {
|
||
return !!first(page, /^购物车$/) && !!first(page, /^(?:推荐|直播精选|我的订单)$/) && !isTaskCenter(page);
|
||
}
|
||
function remainingProducts(page) {
|
||
var label = first(page, /^(?:再|还需|还差)?点(?:击)?\d+个商品$/);
|
||
return label ? Number(label.text.match(/\d+/)[0]) : null;
|
||
}
|
||
function mallProducts(page, visited) {
|
||
var products = [];
|
||
page.forEach(function (price) {
|
||
if (!/^[¥¥]\d+(?:\.\d+)?/.test(price.text) || price.rect.top < device.height * 0.35 ||
|
||
price.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()<flipBalanceDeadline){sleep(CONFIG.pollMs);continue;}
|
||
}
|
||
if(kind==="flip" && (adSeen || entered)) return {changed:true,reason:"翻卡未结算便返回任务中心,重新进入继续"};
|
||
if (entered || adSeen || Date.now() - firstPageAt > 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.taskSearchScrolls) scrollList(false);
|
||
}
|
||
throw new Error("连续看视频奖励卡片未找到,不能认定全部领取完成");
|
||
}
|
||
function skippableContinuousFeedCard(page) {
|
||
if (!bottomNavigation(page,/^首页$/)) return false;
|
||
return !!first(page,/^(?:上滑继续观看视频|点击进入直播间|查看图片详情|图文)$/) || page.some(function(item) {
|
||
// OPPO 直播预览的进入提示会随动画隐藏,保留稳定内容控件和底部标题作为证据。
|
||
return /:id\/(?:live_simple_play_swipe_text|live_simple_play_content_view|live_preview_bottom_caption|pic_text)$/.test(item.id || "");
|
||
});
|
||
}
|
||
function isContinuousVideoFeed(page) {
|
||
if (isAd(page) || isTaskCenter(page) || isLiveRoom(page) ||
|
||
!bottomNavigation(page, /^首页$/) || skippableContinuousFeedCard(page)) return false;
|
||
var nativeFeed = page.some(function (item) {return /:id\/like_button$/.test(item.id || "");}) &&
|
||
page.some(function (item) {return /:id\/user_name_text_view(?:_new)?$/.test(item.id || "");});
|
||
return !!first(page, /^(?:暂停视频|播放视频)$/) || nativeFeed;
|
||
}
|
||
function watchContinuousVideoSegment(durationMs) {
|
||
durationMs = durationMs === undefined ? CONFIG.videoCalibrationMs : durationMs;
|
||
if (!isFinite(durationMs) || durationMs <= 0) throw new Error("连续观看时长必须是有效正数");
|
||
var watchedMs = 0, pendingWatchMs = 0, pendingWatchSince = 0, lastVideoAt = Date.now();
|
||
while (true) {
|
||
var readStartedAt = Date.now();
|
||
var page = snapshot();
|
||
if (isTaskCenter(page)) return {watchedMs:watchedMs, reason:"taskCenter"};
|
||
if (Date.now() - lastVideoAt > 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) + "秒;等待后重新识别页面");
|
||
// 首次识别期间视频也在播放,只补足本条停留,避免叠加固定等待。
|
||
var remainingWait = pendingWatchMs - (Date.now() - pendingWatchSince);
|
||
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, 600))
|
||
throw new Error("连续看视频切换失败");
|
||
writeRunLog("CONTINUOUS VIDEO SWIPE: 已切换下一视频");
|
||
sleep(CONFIG.pollMs);
|
||
}
|
||
}
|
||
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()<deadline);
|
||
throw new Error("连续看视频领取后等待15秒仍未确认奖励到账弹窗,保留现场");
|
||
}
|
||
function continuousVideoStep() {
|
||
var lastSignature=null, claims=0, msPerCoin=null, sample=null, noProgress=0;
|
||
while(true) {
|
||
var card=locateContinuousVideoCard();
|
||
if(card.signature!==lastSignature) {lastSignature=card.signature;
|
||
writeRunLog("CONTINUOUS VIDEO PROGRESS: "+card.signature);}
|
||
if (sample) {
|
||
var gain = card.progress && card.progress.total === sample.before.total ? card.progress.done - sample.before.done : null;
|
||
if (gain > 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("未安装快手极速版");
|
||
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: 快手极速版各类任务已依次执行至不可做或入口消失;" + 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();
|
||
}
|