编辑代码

/*---------- 全局配置 ----------*/
const APP_NAME = "猫眼";
const RETRY_DELAY = 100; // 操作重试间隔
const TIMEOUT = 5000;    // 元素查找超时时间

/*---------- 工具函数 ----------*/
/**
 * 获取服务器时间戳(需替换为猫眼实际接口)
 */
function getServerTimestamp() {
    try {
        const res = http.get("https://mtop.damai.cn/gw/mtop.common.getTimestamp/", {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Mobile'
            }
        });
        return JSON.parse(res.body.string()).data.t;
    } catch (e) {
        console.error("获取时间失败,使用本地时间", e);
        return Date.now();
    }
}

/**
 * 时间戳转北京时间
 */
function formatTimestamp(timestamp) {
    const date = new Date(Number(timestamp));
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,"0")} ` +
           `${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}`;
}

/**
 * 带重试的元素点击
 */
function safeClick(selector, timeout = TIMEOUT) {
    const endTime = Date.now() + timeout;
    while (Date.now() < endTime) {
        const target = selector.findOne();
        if (target) {
            return target.click();
        }
        sleep(RETRY_DELAY);
    }
    throw new Error("元素查找超时");
}

/*---------- 核心流程 ----------*/
function handlePayment() {
    // 立即支付处理逻辑
    while (true) {
        const payButton = className("android.widget.Button").findOne();
        if (payButton) {
            console.log("点击立即支付");
            payButton.click();
        } else if (textContains("人数太多").exists()) {
            console.log("检测到人数过多提示");
            safeClick(className("android.widget.Button").text("返回"));
            className("android.widget.Button").waitFor();
        }
        sleep(RETRY_DELAY);
    }
}

function selectTicket() {
    // 票务选择逻辑
    const buttons = [
        "立即预订", 
        "立即购票", 
        "特惠购票"
    ];

    buttons.forEach(btnText => {
        if (className("android.widget.TextView").text(btnText).exists()) {
            console.log("点击购票按钮:", btnText);
            safeClick(className("android.widget.TextView").text(btnText));
            return true;
        }
    });
    throw new Error("未找到有效购票按钮");
}

function waitTargetTime(targetTime) {
    console.log("等待开抢时间:", formatTimestamp(targetTime));
    while (true) {
        const current = getServerTimestamp();
        if (current >= targetTime) {
            console.log("到达目标时间!");
            return;
        }
        // 动态等待策略
        const diff = targetTime - current;
        if (diff > 1000) {
            sleep(Math.min(diff - 300, 1000)); // 提前300ms进入高频率检查
        } else {
            sleep(Math.max(diff - 50, 10));    // 最后50ms精度调整
        }
    }
}

/*---------- 主流程 ----------*/
function main() {
    // 初始化环境
    auto.waitFor();
    app.launch(APP_NAME);
    console.show();
    
    try {
        // 时间设置(示例:03-01 20:00)
        const inputTime = dialogs.rawInput("请输入抢票时间", "03-01 20:00")
            .match(/(\d{2})-(\d{2}) (\d{2}):(\d{2})/);
        
        const [, month, day, hour, minute] = inputTime;
        const targetDate = new Date();
        targetDate.setMonth(month-1, day);
        targetDate.setHours(hour, minute, 0, 0);
        
        // 进入抢票等待
        waitTargetTime(targetDate.getTime() - 50); // 提前50ms
        
        // 执行购票操作
        selectTicket();
        safeClick(className("android.widget.TextView").text("确认"));
        handlePayment();
        
    } catch (e) {
        console.error("执行出错:", e);
        alert("抢票失败: " + e.message);
    } finally {
        console.hide();
    }
}

// 启动主程序
main();