/*
哔哩哔哩每日任务(V1.1)

更新时间: 2024-04-06
脚本兼容: QuantumultX, Surge, Loon
脚本作者: MartinsKing（@ClydeTime）
软件功能: 登录/观看/分享/投币/直播签到/银瓜子转硬币/大会员积分签到/年度大会员每月B币券+等任务
注意事项:
    抓取cookie时注意保证账号登录状态;
    账号内须有一定数量的关注数，否则无法完成投币;
    当硬币不足5枚，提示硬币不足，停止投币;
    为保证投币任务成功, 脚本有重试机制(最多重试10次), 以确保任务完成, 前提需要您尽可能多的关注Up主;
    年度大会员每月B币券会在每月1号、15号尝试领取，确保应用正常运行, 以防漏领;
    年度大会员自动充电会在每次领劵之后进行, 默认为自己充电, B币多的用户可自行到boxjs设置，以防误充.
使用声明: ⚠️此脚本仅供学习与交流，请勿贩卖！⚠️
脚本参考: Nobyda、Wyatt1026、ABreadTree、chavyleung、SocialSisterYi
************************
QX, Surge, Loon说明：
************************
1.获取cookie
    ①后台退出手机B站客户端的情况下, 重新打开APP进入主页
    ②通过网址「https://www.bilibili.com」登录,登录后当前网页登录状态失效
如通知成功获取cookie, 则可以使用此签到脚本.
脚本将在每天上午7点30执行.
2.投币设置
定时任务脚本投币规则为: 随机获取关注列表Up主视频, 默认5视频5硬币, 不点赞.
用户如需要不投币的版本, 请使用boxjs订阅「https://raw.githubusercontent.com/ClydeTime/BiliBili/main/boxjs/BiliBili.boxjs.json」
将投币次数置为0, 并保存即可.
/***********************
Surge 脚本配置:
************************

# B站每日等级任务 「请在模块中添加」
https://raw.githubusercontent.com/ClydeTime/BiliBili/main/modules/BiliBiliDailyBonus.sgmodule

************************
Loon 远程脚本配置:
************************

# B站每日等级任务 「请在插件中添加」
https://raw.githubusercontent.com/ClydeTime/BiliBili/main/modules/BiliBiliDailyBonus.plugin

************************
QuantumultX 远程脚本配置:
************************

[rewrite local]
# > 哔哩哔哩cookie
^https?:\/\/app\.bilibili\.com\/x\/resource\/fingerprint\? url script-request-header https://git.vsprit.com/shawenguan/Quantumult-X/raw/master/Scripts/bilibili/bilibiliHelper.js
^https?:\/\/m.bilibili.com/$ url script-request-header https://git.vsprit.com/shawenguan/Quantumult-X/raw/master/Scripts/bilibili/bilibiliHelper.js

[MITM]

hostname = m.bilibili.com,app.bilibili.com

*/

const magicJS = MagicJS(`哔哩哔哩`, "INFO");

const formatNow = () => {
    return magicJS.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss');
}

const check = key =>
    !config.hasOwnProperty(key) ||
    !config[key].hasOwnProperty("time") ||
    !(config[key]["num"] > 0) ||
    formatNow() > config[key].time

const string2object = cookie => {
    let obj = {}
    let arr = cookie.split("; ")
    arr.forEach(function (val) {
        let array = val.split("=")
        obj[array[0]] = array[1]
    })
    return obj
}

const isFlag = exec_times => 
    config.user.num === 0 ||
    config.watch.num === 0 ||
    config.share.num === 0 ||
    (config.coins.num < exec_times * 10 && Math.floor(config.user.money) > 5)

const getTimestamp = (d=new Date())=>{
    return Math.floor(d.getTime()/1000);
}

const startTime = formatNow();
let cards = [];
let config = {
    cookie: {},
    cookieStr: "",
    key: "",
    user: {},
    watch: {},
    share: {},
    coins: {},
    score: {}
};
let real_times; //实际需要投币次数

async function Main() {
    if (magicJS.isRequest) {
        magicJS.logger.info("- 正在获取cookie, 请稍后");
        await checkHandleRequest();
    } else {
        await signBiliBili();
    }
    magicJS.notification.msg('');
    magicJS.done();
}

async function checkHandleRequest(){
    const request = magicJS.request;
    let cookieStr = request.headers.cookie || request.headers.Cookie;
    if(cookieStr){
        config.cookie = magicJS.parseCookies(cookieStr);
        const PStoreConfig = magicJS.data.read("bilibili_daily_bonus", {})
        if (PStoreConfig.cookie && PStoreConfig.cookie.bili_jct !== config.cookie.bili_jct) {
            if (PStoreConfig.Settings) config.Settings = PStoreConfig.Settings // 同步boxjs数据
            config.FirstInsert = false;
            magicJS.logger.info(magicJS.toStr(config));
            await persistentStore(config)
        } else if (PStoreConfig.cookie) {
            magicJS.logger.info("- cookie未失效,无需更新");
        } else {
            config.FirstInsert = true;
            await persistentStore(config);
        }
    }
}

async function persistentStore(config){
    if (config.cookie.DedeUserID) {
        const url = $request.url;
        config.key = url.match(/.*access_key=(.*?)&build/)?.[1];
        config.cookieStr = `DedeUserID=${config.cookie.DedeUserID}; DedeUserID__ckMd5=${config.cookie.DedeUserID__ckMd5}; SESSDATA=${config.cookie.SESSDATA}; bili_jct=${config.cookie.bili_jct}; sid=${config.cookie.sid}`;
        if (!config.key) { //网页方式登录
            let auth_code = "0", access_key = "0", login_confirm = false;
            auth_code = await getAuthCode();
            if (auth_code !== "0"){
                login_confirm = await loginConfirm(auth_code)
            }
            if (login_confirm){
                access_key = await getAccessKey(auth_code)
            }
            if (access_key !== "0") {
                config.key = access_key
            } else {
                magicJS.logger.info("- 获取用户access_key失败!");
                magicJS.notification.post(magicJS.scriptName, "🤒获取用户access_key失败!");
            }
        }
        const isFirstInsert = config.FirstInsert;
        delete config.FirstInsert;
        magicJS.logger.info(magicJS.toStr(config))
        const successMessage = magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
            ? "🎉cookie存储成功"
            : "🤒cookie存储失败"
        magicJS.notification.post(magicJS.scriptName, isFirstInsert ? "首次获取cookie" : "检测到cookie已更新", successMessage);
    } else {
        magicJS.notification.post(magicJS.scriptName, "- 尚未登录, 请登录后重新获取cookie");
    }
}

async function signBiliBili() {
    config = magicJS.data.read("bilibili_daily_bonus", {});
    if (config.cookie && await getUserInfo()) {
        await queryStatus();
        let exec_times = config.Settings?.exec;  //用户设置投币次数
        if (!Boolean(exec_times)) {
            exec_times = 5;
            real_times = 5 - (Number(config.coins.num) / 10);
        } else {
            exec_times = Number(exec_times);
            real_times = Math.max(0, exec_times - (Number(config.coins.num) / 10));
        }
        let flag = isFlag(exec_times);
        if (flag){
            await dynamic();
            if (cards.length) {
                let item = cards[Math.floor(Math.random() * cards.length)];
                let card = magicJS.toObj(item.card);
                short_link = encodeURIComponent(card?.short_link_v2.replace(/\\\//g, '/'));
                await watch(item.desc.rid, item.desc.bvid, card.cid);
                await share(item.desc.rid, card.cid, short_link);
            } else {
                magicJS.logger.info("- 获取视频失败，请重试或寻求帮助");
            }

            magicJS.logger.info("3️⃣ 投币任务");
            if (typeof config.coins.failures !== 'undefined' && config.coins.failures > 0){
                config.coins.failures = 0;    //重置投币失败次数
            }
            if (real_times === 0){
                magicJS.logger.info(`- 今日已完成 ${config.coins.time}`);
            } else {
                for (let i = 0; i < real_times; i ++) {
                    if (Math.floor(config.user.money) <= 5) {
                        magicJS.logger.info("- 硬币不足,投币失败");
                        break;
                    } else {
                        await coin();
                        await magicJS.utils.sleep(300); //减少频繁请求概率
                    }
                }
            }
            magicJS.logger.info("---- 将尝试额外任务");
        } else {
            magicJS.logger.info("---- 经验值任务均已完成,将尝试额外任务");
        }
        
        await liveSign();
        await silver2coin();
        await vipScoreSign();
        if (config.user.vipStatus === 1) {
            await vipExtraEx();
            await vipScoreGo();
            await vipScoreFan();
            await vipScoreMovie();
            await vipScoreDress();
            await vipWatchAccept();
            //B币券每月尝试两次领取
            let day = magicJS.utils.formatTime(new Date(), 'dd');
            if (day === '1' || day === '15') {
                if (config.user.vipType === 2) {
                    await vipPrivilege(1);
                    await magicJS.utils.sleep(800); //延迟执行，防止领劵延迟
                    let charge_mid = config.Settings?.charge_mid || config.user.mid;  //用户设置充电id
                    let bp_num = config.Settings?.bp_num || 5;  //用户设置充电数量
                    await Charge(charge_mid, bp_num);//充电
                    for (let i = 2; i <= 7; i++) await vipPrivilege(i);
                } else if (config.user.vipType === 1) {
                    await vipPrivilege(6);
                    await vipPrivilege(7);
                }
            } 
        }
        flag = !isFlag(exec_times);
        let title = `登录${config.user.num}/观看${config.watch.num}/分享${config.share.num}/投币${config.coins.num / 10}${flag ? "已完成" : "未完成"}`;
        magicJS.logger.info(`#### ${title}`);
        magicJS.logger.info(`- 登录时间: ${config.user.time || "暂无"}`);
        magicJS.logger.info(`- 观看时间: ${config.watch.time || "暂无"}`);
        magicJS.logger.info(`- 分享时间: ${config.share.time || "暂无"}`);
        magicJS.logger.info(`- 投币时间: ${config.coins.time || "暂无"}`);

        let notice = {
            title: `[${config.user.uname}]`,
            subTitle: `${flag ? "✅任务完成" : "❗️有未完成的任务"}`,
            content:
                `任务:登录(观看)${check("watch") ? "" : "+10exp"} 分享${check("share") ? "" : "+5exp"} 投币${check("coins") ? "" : "+50exp"}\n` +
                `经验:当前${config.user.level_info.current_exp}/下级${config.user.level_info.next_exp}/满级28800\n` +
                `等级:当前${config.user.level_info.current_level}级 升满级最快需${Math.ceil((config.user.v6_exp)/65)}天`,
        };
        magicJS.notification.post(notice.title, notice.subTitle, notice.content);
    } else {
        magicJS.notification.post(`任务失败`,`📅 ${startTime}`, "🤒请更新cookie")
    }
}

async function getAuthCode() {
    const body = {
        appkey: "27eb53fc9058f8c3",
        local_id: 0,
        ts: getTimestamp()
    };
    const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())));
    const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375');
    body['sign'] = sign;
    const myRequest = {
        url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        body: magicJS.objToQueryStr(body),
    };
    await magicJS.http.post(myRequest).then(response => {
        try {
            const body = response.body;
            if (body.code === 0 && body.message === "0") {
                magicJS.logger.info("- 获取auth_code成功");
                return body.data.auth_code;
            } else {
                magicJS.logger.info("- 获取auth_code失败");
                return "0";
            }
        } catch (e) {
            magicJS.logger.error(e);
        }
    }).catch(err => {
        const msg = `获取AuthCode异常\n${JSON.stringify(err)}`;
        magicJS.logger.error(msg);
    });
}

async function loginConfirm(auth_code) {
    const body = {
        auth_code,
        build: 7082000,
        csrf: config.cookie.bili_jct
    };
    const myRequest = {
        url: "https://passport.bilibili.com/x/passport-tv-login/h5/qrcode/confirm",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
            'cookie': `DedeUserID=${config.cookie.DedeUserID}; SESSDATA=${config.cookie.SESSDATA}`
        },
        body: magicJS.objToQueryStr(body),
    };
    await magicJS.http.post(myRequest).then(response => {
        try {
            const body = response.body;
            if (body.code === 0 && body.message === "0") {
                magicJS.logger.info("- 确认登录成功")
                return true;
            } else {
                magicJS.logger.info("- 确认登录失败")
                return false;
            }
        } catch (e) {
            magicJS.logger.error(e);
        }
    }).catch(err => {
        const msg = `确认登录异常\n${JSON.stringify(err)}`;
        magicJS.logger.error(msg);
    });
}

async function getAccessKey(auth_code) {
    const body = {
        appkey: "27eb53fc9058f8c3",
        auth_code,
        local_id: 0,
        ts: getTimestamp()
    }
    const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())));
    const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375');
    body['sign'] = sign;
    const myRequest = {
        url: "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        body: magicJS.objToQueryStr(body),
    };
    await magicJS.http.post(myRequest).then(response => {
        try {
            const body = response.body;
            if (body.code === 0 && body.message === "0") {
                magicJS.logger.info("- 获取access_key成功");
                return body.data.access_token;
            } else {
                magicJS.logger.info("- 获取access_key失败");
                return "0";
            }
        } catch (e) {
            magicJS.logger.error(e);
        }
    }).catch(err => {
        const msg = `获取AccessKey异常\n${JSON.stringify(err)}`;
        magicJS.logger.error(msg);
    });
}

async function watch(aid, bvid, cid) {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("1️⃣ 观看(登录)任务");
        if (check("watch")) {
            magicJS.logger.info(`- 正在观看(登录)(${bvid})`);
            const body = {
                aid,
                cid,
                bvid,
                mid: config.user.mid,
                csrf: config.cookie.bili_jct,
                played_time : 1,
                real_played_time: 1,
                realtime: 1,
                start_ts: getTimestamp(),
                type: 3,
                dt: 2,
                play_type: 0,
                from_spmid: 0,
                spmid: 0,
                auto_continued_play: 0,
                refer_url: "https%3A%2F%2Ft.bilibili.com%2F",
                bsource: ""
            };
            const myRequest = {
                url: 'https://api.bilibili.com/x/click-interface/web/heartbeat',
                headers: {
                    "cookie": config.cookieStr,
                    "referrer": `https://www.bilibili.com/video/${bvid}`
                },
                body: magicJS.objToQueryStr(body),
            };
            magicJS.http.post(myRequest).then(response => {
                const body = response.body;
                if (body?.code === 0) {
                    magicJS.logger.info(`- 累计观看(登录)次数 ${(config.watch.num || 0) + 1}`);
                    config.user.num = (config.user.num || 0) + 1;
                    config.watch.num = (config.watch.num || 0) + 1;
                    magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));
                } else {
                    magicJS.logger.info("- 观看失败, 失败原因: " + body?.message);
                }
                resolve(body);
            }).catch(err => {
                const msg = `观看异常\n${JSON.stringify(err)}`;
                magicJS.logger.error(msg);
                resolve();
            });
        } else {
            magicJS.logger.info(`- 今日已经观看 ${config.watch.time}`);
            resolve();
        }
    });
}

async function share(aid, cid, short_link) {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("2️⃣ 分享任务");
        if (check("share")) {
            magicJS.logger.info("- 正在分享, aid=" + aid);
            const body = {
                access_key: config.key.replace(/&actionKey=.*?&appkey=.*$/, ''),
                actionKey: 'appkey',
                appkey: '27eb53fc9058f8c3',
                build: '72700100',
                c_locale: 'zh-Hans_CN',
                device: 'phone',
                disable_rcmd: 0,
                link: short_link,
                mobi_app: 'iphone',
                object_extra_fields: '%7B%7D',
                oid: aid,
                panel_type: 1,
                platform: 'ios',
                s_locale:'zh-Hans_CN',
                share_channel: 'WEIXIN',
                share_id: 'main.ugc-video-detail.0.0.pv',
                share_origin: 'vinfo_share',
                sid: cid,
                spm_id: 'main.ugc-video-detail.0.0',
                statistics: '%7B%22appId%22%3A1%2C%22version%22%3A%227.27.0%22%2C%22abtest%22%3A%22%22%2C%22platform%22%3A1%7D',
                success: 1,
                ts: getTimestamp()
            }
            const sign = md5(magicJS.objToQueryStr(body) + 'c2ed53a74eeefe3cf99fbd01d8c9c375');
            body['sign'] = sign;
            const myRequest = {
                url: 'https://api.bilibili.com/x/share/finish',
                headers: {},
                body: magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())))
            };
            magicJS.http.post(myRequest).then(response => {
                const body = response.body;
                if (body?.code === 0) {
                    config.share.num = (config.share.num || 0) + 1;
                    magicJS.logger.info("- 分享成功");
                    magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));
                } else {
                    magicJS.logger.info("- 分享失败, 失败原因: " + body?.message);
                }
                resolve(body);
            }).catch(err => {
                const msg = `分享异常\n${JSON.stringify(err)}`;
                magicJS.logger.error(msg);
                resolve();
            });
        } else {
            magicJS.logger.info(`- 今日已经分享 ${config.share.time}`);
            resolve();
        }
    });
}

async function coin() {
    if (config.coins.num >= 50) {
        magicJS.logger.info(`- 今日已完成 ${config.coins.time}`);
        return;
    }
    let like_uid_list = await getFavUid();
    if (like_uid_list && like_uid_list.length > 0) {
        let aid = await getFavAid(like_uid_list);
        //magicJS.logger.info("即将投币的视频aid: " + aid)
        if (aid !== 0) {
            const body = {
                aid,
                multiply: 1,
                select_like: 0,
                cross_domain: true,
                csrf: config.cookie.bili_jct
            }
            const myRequest = {
                url: "https://api.bilibili.com/x/web-interface/coin/add",
                headers: {
                    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
                    'accept': 'application/json, text/plain, */*',
                    'content-type': 'application/x-www-form-urlencoded',
                    'origin': 'https://www.bilibili.com',
                    'referer': 'https://www.bilibili.com/video/BV1MT411G7fG?vd_source=1970993e2eff4af7be029aefcfa468b8',
                    'cookie': config.cookieStr + ';buvid3=fuckchenruilovelaoliu'
                },
                body: magicJS.objToQueryStr(body)
            }
            await magicJS.http.post(myRequest).then(async response => {
                try {
                    const body = response.body;
                    if (body?.code === 0 && body?.message === "0") {
                        magicJS.logger.info("- 投币成功");
                        config.user.money -= 1;
                        config.coins.num += 10;
                        magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));
                    } else {
                        magicJS.logger.info("- 投币失败,失败原因 " + body.message);
                        config.coins.failures = (config.coins.failures === 0 || typeof config.coins.failures === 'undefined' ? 1 : config.coins.failures + 1);
                        magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));
                        if (config.coins.failures < 11) {
                            magicJS.logger.info("- 正在重试...重试次数 " + (config.coins.failures - 1) + "(超过十次不再重试)");
                            await coin();
                        }
                    }
                } catch (e) {
                    magicJS.logger.error(e);
                } finally {
                }
            }).catch(err => {
                const msg = `投币异常\n${JSON.stringify(err)}`;
                magicJS.logger.error(msg);
            });
        } else {
            magicJS.logger.info("获取随机投币视频失败");
        }
    } else {
        magicJS.logger.info("获取随机关注用户列表失败");
    }
}

async function getFavUid() {
    return new Promise((resolve, reject) => {
        const myRequest = {
            url: `https://api.bilibili.com/x/relation/followings?vmid=${config.cookie.DedeUserID}&ps=10&order_type=attention`,
            headers: {
                'cookie': config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                let like_uid_list = new Array();
                if (body?.code === 0) {
                    magicJS.logger.info("- 获取关注列表成功");
                    let like_list = body?.data?.list;
                    for (let i = 0; i < like_list.length; i ++) {
                        like_uid_list[i] = like_list[i].mid;
                    }
                    resolve(like_uid_list);
                } else {
                    magicJS.logger.info("- 获取关注列表成失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                    resolve(like_uid_list);
                }
            } catch (e) {
                magicJS.logger.error(JSON.stringify(e));
                resolve();
            } finally {
            }
        }).catch(err => {
            const msg = `获取关注列表异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function getFavAid(arr) {
    return new Promise((resolve, reject) => {
        //magicJS.logger.info("- 获取关注列表中的随机视频")
        let random_int = Math.floor((Math.random()*arr.length));
        let random_mid = arr[random_int];
        let wbiSigns = getWbiSigns({mid: random_mid});
        const myRequest = {
            url: `https://api.bilibili.com/x/space/wbi/arc/search?${wbiSigns}`,
            headers: {
                'cookie': config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0) {
                    magicJS.logger.info("- 获取投币视频成功");
                    let vlist = body.data?.list?.vlist;
                    let random_v_int = Math.floor((Math.random() * vlist.length));
                    let aid = vlist[random_v_int]?.aid;
                    magicJS.logger.info("- 作者: " + vlist[random_v_int]['author'] + "; 视频标题: " + vlist[random_v_int]['title']);
                    resolve(aid);
                } else {
                    magicJS.logger.info("- 获取投币视频失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                    resolve(0);
                }
            } catch (e) {
                magicJS.logger.error(e);
                resolve();
            }
        }, reason => {
            magicJS.logger.info("- 获取投币视频失败");
            magicJS.logger.info("- 失败原因 " + magicJS.toStr(reason));
            resolve(0);
        }).catch(err => {
            const msg = `获取投币视频异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function silver2coin() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 银瓜子兑换硬币任务");
        const body = {
            csrf: config.cookie.bili_jct,
            csrf_token: config.cookie.bili_jct
        };
        const myRequest = {
            url: "https://api.live.bilibili.com/xlive/revenue/v1/wallet/silver2coin",
            headers: {
                'cookie': config.cookieStr
            },
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.post(myRequest).then(response => {
            try {
                let result = response.body;
                let title = `银瓜子转硬币`;
                // 兑换成功
                if (result && result.code === 0) {
                    let subTitle = `- ${result.message}`;
                    let detail = `- 成功兑换: ${result.data.coin} 个硬币\n当前银瓜子: ${result.data.silver} , 当前金瓜子: ${result.data.gold}`;
                    magicJS.logger.info(subTitle);
                    magicJS.logger.info(detail);
                    magicJS.notification.post(title, subTitle, detail);
                }
                // 兑换中止（重复兑换&银瓜子不足）
                else if (result && result.code === 403) {
                    let subTitle = "- 未成功兑换";
                    let detail = `- 原因: ${result.message}`;
                    magicJS.logger.info(subTitle);
                    magicJS.logger.info(detail);
                    magicJS.notification.post(title, subTitle, detail);
                }
                // 兑换失败
                else {
                    let subTitle = "- 兑换失败";
                    let detail = `- 原因: ${result.message}`;
                    magicJS.logger.info(subTitle);
                    magicJS.logger.info(detail);
                    magicJS.notification.post(title, subTitle, detail);
                }
            } catch (e) {
                magicJS.logger.error(e);
            } finally {
                resolve();
            }
        }).catch(err => {
            const msg = `兑换异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function liveSign() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 直播签到任务");
        const myRequest = {
            url: "https://api.live.bilibili.com/xlive/web-ucenter/v1/sign/DoSign",
            headers: {
                'cookie': config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                let body = response.body;
                if (body?.code === 0) {
                    magicJS.logger.info("- 签到成功");
                    magicJS.logger.info(`签到奖励:${body.data.text},连续签到${body.data.hadSignDays}天`);
                } else if (body && body.code === 1011040){
                    magicJS.logger.info("- 今日已完成");
                } else {
                    magicJS.logger.info("- 签到失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            } finally {
                resolve();
            }
        }).catch(err => {
            const msg = `签到异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipScoreSign() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 大会员大积分签到任务");
        if (config.user.vipStatus === 0) {
            magicJS.logger.info("- 当前用户非大会员, 无法完成任务");
            resolve();
        } else {
            if (check("score")) {
                const myRequest = {
                    url: "https://api.bilibili.com/pgc/activity/score/task/sign",
                    method: "POST",
                    headers: {
                        'Referer': 'https://big.bilibili.com/mobile/bigPoint/task',
                        'cookie': config.cookieStr
                    }
                };
                magicJS.http.get(myRequest).then(response => {
                    try {
                        const body = response.body;
                        if (body?.code === 0 && body?.message === "success") {
                            magicJS.logger.info("- 签到成功")
                            config.score.time = startTime
                            config.score.num = 1
                            magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config))
                        } else {
                            magicJS.logger.info("- 签到失败")
                            magicJS.logger.info("- 失败原因 " + body?.message)
                        }
                    } catch (e) {
                        magicJS.logger.error(e);
                    } finally {
                        resolve();
                    }
                }).catch(err => {
                    const msg = `签到异常\n${JSON.stringify(err)}`;
                    magicJS.logger.error(msg);
                    resolve();
                });
            } else {
                magicJS.logger.info("- 今日已完成");
                resolve();
            }
        }
    });
}

async function vipExtraEx() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 大会员每日额外经验值");
        const body = {
            csrf: config.cookie.bili_jct,
            ts: getTimestamp(),
            buvid: config.cookie.Buvid,
            mobi_app: 'iphone',
            platform: 'ios',
            appkey: '27eb53fc9058f8c3',
            access_key: config.key
        };
        const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())));
        const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375');
        body['sign'] = sign;
        const myRequest = {
            url: "https://api.bilibili.com/x/vip/experience/add",
            headers: {
                'accept': 'application/json, text/plain, */*',
                'app-key': 'iphone'
            },
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "0") {
                    magicJS.logger.info("- 成功获得10经验值");
                } else {
                    magicJS.logger.info("- 每日额外经验任务失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `获取额外经验异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipScoreGo() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 大会员浏览会员购10s任务");
        const myRequest = {
            url: "https://show.bilibili.com/api/activity/fire/common/event/dispatch",
            headers: {
                'Content-Type' : 'application/json',
                'Cookie': config.cookieStr
            },
            body: `{"eventId":"hevent_oy4b7h3epeb"}`
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "SUCCESS") {
                    magicJS.logger.info("- 成功获得10点大积分");
                } else {
                    magicJS.logger.info("- 浏览会员购任务失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `浏览会员购任务异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipScoreFan() {
    return new Promise((resolve, reject) => {
    magicJS.logger.info("#### 大会员浏览追番频道10s任务");
        const myRequest = {
            url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=jp_channel&sign=768d600feba34e6d1109e4157c0f0c5f&task_sign=557D1ACE13E9E81393259FFB621D6D0E`,
            method: "POST",
            headers: {}
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "success") {
                    magicJS.logger.info("- 成功获得10点大积分");
                } else {
                    magicJS.logger.info("- 浏览追番频道任务失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `浏览追番频道任务异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipScoreMovie() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 大会员浏览影视频道10s任务");
        const myRequest = {
            url: `https://api.bilibili.com/pgc/activity/deliver/task/complete?access_key=${config.key}&position=tv_channel&sign=09ece1c295cb86d74778b93c59c0da3a&task_sign=B7DA5FAE25C39F53C62C03076CF2878B`,
            method: "POST",
            headers: {}
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "success") {
                    magicJS.logger.info("- 成功获得10点大积分");
                } else {
                    magicJS.logger.info("- 浏览影视频道任务失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `浏览影视频道任务异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipScoreDress() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 大会员浏览装扮商城主页任务");
        const body = {
            csrf: config.cookie.bili_jct,
            ts: getTimestamp(),
            taskCode: 'dress-view',
            access_key: config.key
        };
        const myRequest = {
            url: 'https://api.bilibili.com/pgc/activity/score/task/complete/v2',
            headers: {},
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "success") {
                    magicJS.logger.info("- 成功获得10点大积分");
                } else {
                    magicJS.logger.info("- 浏览装扮商城主页任务失败");
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `浏览装扮商城主页任务异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipWatchAccept() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 接取大会员观看剧集10min任务");
        const body = {
            csrf: config.cookie.bili_jct,
            ts: getTimestamp(),
            taskCode: 'ogvwatchnew',
            mobi_app: 'iphone',
            platform: 'ios',
            appkey: '27eb53fc9058f8c3',
            access_key: config.key
        };
        const sortedBody = magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(body)).sort())));
        const sign = md5(sortedBody + 'c2ed53a74eeefe3cf99fbd01d8c9c375');
        body['sign'] = sign
        const myRequest = {
            url: 'https://api.bilibili.com/pgc/activity/score/task/receive/v2',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/615.2.9.10.4 (KHTML, like Gecko) Mobile/20F75 BiliApp/77200100 os/ios model/iPhone 15 Pro Max mobi_app/iphone build/77200100 osVer/17.4.1 network/2 channel/AppStore c_locale/zh-Hans_CN s_locale/zh-Hans_CN disable_rcmd/0',
                'Cookie': `SESSDATA=${config.cookie.SESSDATA}`,
                'Referer': `https://big.bilibili.com/mobile/bigPoint/task`
            },
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0 && body?.message === "success") {
                    magicJS.logger.info("- 大会员观看剧集任务接取成功, 需自行观看");
                } else {
                    magicJS.logger.info("- 大会员观看剧集任务接取失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `大会员观看剧集任务异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function vipPrivilege(type) {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 领取大会员月度福利");
        const body = {
            csrf: config.cookie.bili_jct,
            type
        };
        const myRequest = {
            url: 'https://api.bilibili.com/x/vip/privilege/receive',
            headers: {
                'Cookie': config.cookieStr
            },
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0) {
                    switch (type) {
                        case 1:
                            magicJS.logger.info("- 领取年度大会员每月B币券成功");
                            magicJS.notification.post("年度大会员月度福利", "B币券", "🎉🎉🎉领取成功");
                            break
                        case 2:
                            magicJS.logger.info("- 领取年度大会员每月会员购优惠券成功");
                            break
                        case 3:
                            magicJS.logger.info("- 领取年度大会员每月漫画福利券成功");
                            break
                        case 4:
                            magicJS.logger.info("- 领取年度大会员每月会员购包邮券成功");
                            break
                        case 5:
                            magicJS.logger.info("- 领取年度大会员每月漫画商城优惠券成功");
                            break
                        case 6:
                            magicJS.logger.info("- 领取大会员每月装扮体验卡成功");
                            break
                        case 7:
                            magicJS.logger.info("- 领取大会员每月课堂优惠券成功");
                            break
                        default:
                            break
                    }
                } else {
                    magicJS.logger.info("- 领取大会员每月福利失败, 福利编码为" + type);
                    magicJS.logger.info("- 失败原因 " + body?.message);
                    if (type === 1) {
                        magicJS.notification.post("年度大会员月度福利", "B币券领取失败", "失败原因为: " + body?.message);
                    }
                    //其他福利没什么用,失败也无需单独通知
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `领取大会员月度福利异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function Charge(mid, bp_num) {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### B币券自动充电");
        const body = {
            bp_num,
            is_bp_remains_prior: true,
            up_mid: mid,
            otype: 'up',
            oid: mid,
            csrf: config.cookie.bili_jct
        };
        const myRequest = {
            url: 'https://api.bilibili.com/x/ugcpay/web/v2/trade/elec/pay/quick',
            headers: {
                'Cookie': config.cookieStr
            },
            body: magicJS.objToQueryStr(body)
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0) {
                    if (body?.data?.status === 4) {
                        if (mid === config.user.mid) {
                            magicJS.logger.info("- 为自己充电成功");
                        } else {
                            magicJS.logger.info(`- 为用户id为${mid}的用户充电成功`);
                        }
                    } else if (body?.data?.status === -4) {
                        magicJS.logger.info("- 充电失败, B币不足");
                    } else {
                        magicJS.logger.info("- 充电失败");
                        magicJS.logger.info("- 失败原因 " + body?.message);
                    }
                } else {
                    magicJS.logger.info("- 充电失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            }
            resolve();
        }).catch(err => {
            const msg = `充电异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function getUserInfo() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 用户信息");
        const myRequest = {
            url: 'https://api.bilibili.com/x/web-interface/nav',
            headers: {
                "cookie": config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code) {
                    magicJS.logger.info("- ❌❌获得用户信息失败(请更新cookie)");
                    magicJS.data.write("bilibili_daily_bonus", null);
                    resolve(false);
                } else {
                    magicJS.logger.info("- 🎉cookie有效任务即将开始🎉");
                    config.user = body?.data;
                    config.user.num = check("user") ? 1 : (config.user.num || 0) + 1;
                    magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));

                    config.user.mext_exp = config.user.level_info.next_exp - config.user.level_info.current_exp;
                    config.user.next_day = Math.ceil(config.user.mext_exp / 15);
                    config.user.v6_exp = 28800 - config.user.level_info.current_exp;
                    config.user.v6_day = Math.ceil(config.user.v6_exp / 15);

                    if (config.user.vipStatus === 1) {
                        magicJS.logger.log("- 💖尊贵的大会员用户💖");
                    }
                    magicJS.logger.log("- 用户名称: " + config.user.uname);
                    magicJS.logger.log("- 用户ID: " + config.user.mid);
                    magicJS.logger.log("- 用户硬币: " + Math.floor(config.user.money));
                    magicJS.logger.log("- 用户B币: " + config.user.wallet.bcoin_balance);
                    magicJS.logger.log("- 用户等级: " + config.user.level_info.current_level);
                    magicJS.logger.log(
                        `- 当前经验: ${config.user.level_info.current_exp}/${config.user.level_info.next_exp}`
                    );
                    magicJS.logger.log(`- 升级还需经验: ${config.user.mext_exp}`);
                    magicJS.logger.log(
                        `- 距离下级还需: ${config.user.next_day}天(登录 观看 分享)`
                    );
                    magicJS.logger.log(
                        `- 距离满级还需: ${Math.max(0, config.user.v6_day)}天(登录 观看 分享)`
                    );
                    magicJS.logger.log(`- 剩余硬币最多可投: ${Math.floor((config.user.money)/5)}天`);
                    magicJS.logger.log(
                        "- 距离满级最快还需: " +
                        Math.max(0, Math.ceil(config.user.v6_exp / 65)) +
                            "天(日常 + 投币*5)"
                    );
                    resolve(true);
                }
            } catch (e) {
                magicJS.logger.error(JSON.stringify(e));
                resolve();
            }
        }, reason => {
            magicJS.notification.post(magicJS.scriptName, "- 获取用户信息失败", magicJS.toStr(reason));
            resolve(false);
        }).catch(err => {
            const msg = `用户信息异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function queryStatus() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 检查任务进行状况");
        const myRequest = {
            url: "https://api.bilibili.com/x/member/web/exp/reward",
            headers: {
                "cookie": config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.code === 0) {
                    if (body.data.login) {
                        magicJS.logger.info("- 今日已登录");
                        config.user.num = (config.user.num === 0 ? 1 : config.user.num);
                        if (!config['user'].hasOwnProperty("time")) {
                            config.user.time = startTime;
                        }
                    } else {
                        magicJS.logger.info("! 今日尚未登录");
                        config.user.num = 0;
                    }
                    if (body.data.watch){
                        magicJS.logger.info("- 今日已观看");
                        config.watch.num = (config.watch.num === 0 || typeof config.watch.num === 'undefined' ? 1 : config.watch.num);
                        if (!config['watch'].hasOwnProperty("time")) {
                            config.watch.time = startTime;
                        }
                    } else {
                        magicJS.logger.info("! 今日尚未观看");
                        config.watch.num = 0;
                    }
                    if (body.data.share){
                        magicJS.logger.info("- 今日已分享");
                        config.share.num = (config.share.num === 0 || typeof config.share.num === 'undefined' ? 1 : config.share.num);
                        if (!config['share'].hasOwnProperty("time")) {
                            config.share.time = startTime;
                        }
                    } else {
                        magicJS.logger.info("! 今日尚未分享");
                        config.share.num = 0;
                    }
                    if (body.data.coins === 50){
                        magicJS.logger.info("- 今日已投币")
                        if (!config['coins'].hasOwnProperty("time")) {
                            config.coins.time = startTime;
                        } else {
                            if (formatNow() > config.coins.time) {
                                config.coins.time = startTime;
                            }
                        }
                    } else if ((body.data.coins / 10) >= real_times) {
                        config.coins.time = startTime;
                        magicJS.logger.info("- 已完成用户设置的投币量");
                    } else if (config.user.money <= 5) {
                        magicJS.logger.info("! 硬币数不足");
                    } else {
                        magicJS.logger.info("! 今日投币未完成");
                    }
                    config.coins.num = body.data.coins;
                    magicJS.data.write("bilibili_daily_bonus", magicJS.toStr(config));
                } else {
                    magicJS.logger.info("- 查询失败");
                    magicJS.logger.info("- 失败原因 " + body?.message);
                }
            } catch (e) {
                magicJS.logger.error(e);
            } finally {
                resolve();
            }
        }).catch(err => {
            const msg = `检查任务进行状况异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

async function dynamic() {
    return new Promise((resolve, reject) => {
        magicJS.logger.info("#### 获取首页视频");
        const myRequest = {
            url: `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new?uid=${config.cookie.DedeUserID}&type_list=8&from=&platform=web`,
            headers: {
                "cookie": config.cookieStr
            }
        };
        magicJS.http.get(myRequest).then(response => {
            try {
                const body = response.body;
                if (body?.data?.cards) {
                    cards = body.data.cards;
                    const { user, watch, share } = config;
                    user.time = watch.time = share.time = startTime;
                    magicJS.logger.info("- 获取视频动态成功");
                } else {
                    magicJS.logger.info("- 获取视频动态失败");
                }
            } catch (e) {
                magicJS.logger.error(JSON.stringify(e));
            }
            resolve();
        }).catch(err => {
            const msg = `获取首页视频异常\n${JSON.stringify(err)}`;
            magicJS.logger.error(msg);
            resolve();
        });
    });
}

// Wbi签名获取
function getWbiSigns(requestParams) {
    // 从给定字符串生成特定的签名
    function generateSignature(baseString) {
        let signature = "";
        signatureIndices.forEach(index => {
            signature += baseString[index];
        });
        return signature.slice(0, 32);
    }

    // 主要函数来构建请求参数并生成最终的请求字符串
    function buildRequestWithSignature(params, imageKey, subscriptionKey) {
        const signatureBase = generateSignature(imageKey + subscriptionKey);
        const startTimeInMillisecond = new Date().getTime();
        const startTimeInSeconds = parseInt(startTimeInMillisecond / 1000);
        let queryString = "";

        // 添加时间戳到请求参数
        params = Object.assign(params, {
            wts: startTimeInSeconds
        });

        // 将参数对象转换为排序后的查询字符串
        queryString = objectToQueryString(params);

        // 生成请求ID并附加到查询字符串
        const requestId = md5(queryString + signatureBase);
        return queryString + "&w_rid=" + requestId;
    }

    // 转换对象为查询字符串
    function objectToQueryString(obj) {
        return magicJS.objToQueryStr(Object.fromEntries(new Map(Array.from(Object.entries(obj)).sort())));
    }

    // 获取图片和订阅的关键信息
    function getImageAndSubscriptionKeys() {
        const imageUrl = config.user.wbi_img.img_url;
        const subscriptionUrl = config.user.wbi_img.sub_url;

        return {
            img_key: imageUrl.substring(imageUrl.lastIndexOf("/") + 1).split(".")[0],
            sub_key: subscriptionUrl.substring(subscriptionUrl.lastIndexOf("/") + 1).split(".")[0]
        };
    }

    // 签名索引数组
    const signatureIndices = [
        46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39,
        12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63,
        57, 62, 11, 36, 20, 34, 44, 52
    ];

    // 提取图片和订阅关键信息
    const { img_key, sub_key } = getImageAndSubscriptionKeys();

    // 构建并返回请求字符串，包含签名
    return buildRequestWithSignature(requestParams, img_key, sub_key);
}



Main()
.catch((e) => magicJS.logger.error(`-\n ${e}`))
.finally(() => magicJS.done());

//---SyncByPyScript---MagicJS3-start
function MagicJS(e="MagicJS",t="INFO"){const n=()=>{const e="undefined"!=typeof $loon,t="undefined"!=typeof $task,r="undefined"!=typeof module,n="undefined"!=typeof $httpClient&&!e,o="undefined"!=typeof $storm,i="undefined"!=typeof $environment&&void 0!==$environment["stash-build"];var s=n||e||o||i;const a="undefined"!=typeof importModule;return{isLoon:e,isQuanX:t,isNode:r,isSurge:n,isStorm:o,isStash:i,isSurgeLike:s,isScriptable:a,get name(){return e?"Loon":t?"QuantumultX":r?"NodeJS":n?"Surge":a?"Scriptable":"unknown"},get build(){return n?$environment["surge-build"]:i?$environment["stash-build"]:o?$storm.buildVersion:void 0},get language(){if(n||i)return $environment.language},get version(){return n?$environment["surge-version"]:i?$environment["stash-version"]:o?$storm.appVersion:r?process.version:void 0},get system(){return n?$environment.system:r?process.platform:void 0},get systemVersion(){if(o)return $storm.systemVersion},get deviceName(){if(o)return $storm.deviceName}}},o=(r,e="INFO")=>{let n=e,t="\n";const o={SNIFFER:6,DEBUG:5,INFO:4,NOTIFY:3,WARNING:2,ERROR:1,CRITICAL:0,NONE:-1},i={SNIFFER:"",DEBUG:"",INFO:"",NOTIFY:"",WARNING:"❗ ",ERROR:"❌ ",CRITICAL:"❌ ",NONE:""},s=(e,t="INFO")=>{o[n]<o[t.toUpperCase()]||console.log(`██[${r}][${t}]`+i[t.toUpperCase()]+e+"\n")};return{getLevel:()=>n,setLevel:e=>{n=e},sniffer:(...e)=>{e=e.join(t);s(e,"SNIFFER")},log:(...e)=>{e=e.join(t);console.log(`██[${r}]`+e+"\n")},debug:(...e)=>{e=e.join(t);s(e,"DEBUG")},info:(...e)=>{e=e.join(t);s(e,"INFO")},notify:(...e)=>{e=e.join(t);s(e,"NOTIFY")},warning:(...e)=>{e=e.join(t);s(e,"WARNING")},error:(...e)=>{e=e.join(t);s(e,"ERROR")},retry:(...e)=>{e=e.join(t);s(e,"RETRY")}}};return new class{constructor(e,t){var r;this._startTime=Date.now(),this.version="3.0.0",this.scriptName=e,this.env=n(),this.logger=o(e,t),this.http="function"==typeof MagicHttp?MagicHttp(this.env,this.logger):void 0,this.data="function"==typeof MagicData?MagicData(this.env,this.logger):void 0,this.notification="function"==typeof MagicNotification?MagicNotification(this.scriptName,this.env,this.logger,this.http):void 0,this.utils="function"==typeof MagicUtils?MagicUtils(this.env,this.logger):void 0,this.qinglong="function"==typeof MagicQingLong?MagicQingLong(this.env,this.data,this.logger):void 0,void 0!==this.data&&(t=this.data.read("magic_loglevel"),r=this.data.read("magic_bark_url"),t&&this.logger.setLevel(t.toUpperCase()),r)&&this.notification.setBark(r),this.logger.info(e+", 开始执行!")}get isRequest(){return"undefined"!=typeof $request}get isStrictRequest(){return"undefined"!=typeof $request&&"undefined"==typeof $response}get isResponse(){return"undefined"!=typeof $response}get isDebug(){return"DEBUG"===this.logger.level}get request(){return"undefined"!=typeof $request?$request:void 0}get response(){if("undefined"!=typeof $response)return $response.hasOwnProperty("status")&&($response.statusCode=$response.status),$response.hasOwnProperty("statusCode")&&($response.status=$response.statusCode),$response}log(...e){this.logger.log(e)}toStr(e,t=null){try{return JSON.stringify(e)}catch{return t}}toObj(e,t=null){try{return JSON.parse(e)}catch{return t}}checkRecordRequestBody(){if(this.isRequest){var t=$request.body;if(t){var r=this.env,n=$request.path;let e=this.scriptName+"#"+n.replace("/","_");e=e.replace("?","#"),r.isQuanX&&$prefs.setValueForKey(t,e),(r.isLoon||r.isSurge)&&$persistentStore.write(t,e),r.isNode&&require("fs").writeFileSync(e+".json",t,{flag:"w"},e=>console.log(e))}}}getRequestBody(){var e=this.env,t=$request.path;let r=this.scriptName+"#"+t.replace("/","_");if(r=r.replace("?","#"),e.isSurge||e.isLoon)return $persistentStore.read(r);if(e.isQuanX)return $prefs.valueForKey(r);if(e.isNode){t=r+".json",e=require("fs");if(!e.existsSync(t))return JSON.parse(e.readFileSync(t))}}getResponseBody(){if($response)return $response.body}parseCookies(e,t=!1){let r={};return t?e&&e.split(";").forEach(function(e){e=e.split("=");r[e.shift().trim()]=decodeURIComponent(e.join("="))}):e&&e.split(";").forEach(function(e){e=e.split("=");r[e.shift().trim()]=e.join("=")}),r}serializeCookies(e,t=!1){var r=[];if(t)for(var n in e){var o=e[n],n=n+"="+encodeURIComponent(o);r.push(n)}else for(var i in e){var s=e[i],i=i+"="+s;r.push(i)}return r.join("; ")}parseSetCookies(e){var t=e.split(/,\s*/).map(e=>{var e=e.trim().split(/;\s*(?=[^=]+=[^;]*)/),t=e[0].split("=").map(e=>e.trim());const r={name:t[0],value:t[1]};return e.slice(1).forEach(e=>{var[e,t]=e.split("=").map(e=>e.trim());r[e]=t||!0}),r}),r=[];let n=0;for(;n<t.length;){var o,i=t[n];r.push(i),i.Expires?((o=t[n+1])&&(i.Expires=i.Expires+","+o.name),n+=2):n+=1}return r}objToQueryStr(t,r){let n="";for(const o in t){let e=t[o];null!=e&&""!==e&&("object"==typeof e?e=JSON.stringify(e):r&&(e=encodeURIComponent(e)),n+=`${o}=${e}&`)}return n=n.substring(0,n.length-1)}parseQueryStr(e){var t={},r=(e=-1<e.indexOf("?")?e.split("?")[1]:e).split("&");for(let e=0;e<r.length;e++){var n=r[e].split("=");t[n[0]]=n[1]}return t}deepClone(e,t){for(var r in t=t||{},e)"object"==typeof e[r]?(t[r]=e[r].constructor===Array?[]:{},this.deepClone(e[r],t[r])):t[r]=e[r];return t}formatDate(e,t){var r,n={"M+":e.getMonth()+1,"d+":e.getDate(),"H+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(r in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),n)new RegExp("("+r+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?n[r]:("00"+n[r]).substr((""+n[r]).length)));return t}parseDate(a,e){let l={y:0,M:1,d:0,H:0,h:0,m:0,s:0,S:0};(e=e||"yyyy-MM-dd").replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g,function(e,t,r,n,o,i,s){return a=a.replace(new RegExp(t+"(\\d{"+r.length+"})"+o),function(e,t){return l[n]=parseInt(t),""}),""}),l.M--;e=new Date(l.y,l.M,l.d,l.H,l.m,l.s);return 0!==l.S&&e.setMilliseconds(l.S),e}getBaseDoneHeaders(e={}){return Object.assign({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"POST,GET,OPTIONS,PUT,DELETE","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept"},e)}getHtmlDoneHeaders(){return this.getBaseDoneHeaders({"Content-Type":"text/html;charset=UTF-8"})}getJsonDoneHeaders(){return this.getBaseDoneHeaders({"Content-Type":"text/json; charset=utf-8",Connection:"keep-alive"})}doWxpusherSend(e){var t=this.getJsonDoneHeaders(),t=(t.Host="wxpusher.zjiecode.com",t["Content-Type"]="application/json;charset=UTF-8",{url:"https://wxpusher.zjiecode.com/api/send/message",headers:t,body:JSON.stringify(e)});return this.http.post(t)}fastWxpusherSend(e,t="",r=""){return this.doWxpusherSend({appToken:"AT_7wDWqSoT8xpJCQqJtHpshKhw7kXc0XCW",content:e,summary:t,contentType:1,topicIds:[],uids:["UID_6P4B00X6Zv8U2oKC0I2R09emxtqq"],url:r,verifyPay:!1,verifyPayType:0})}isEmpty(e){return void 0===e||null==e||""==e||"null"==e||"undefined"==e||0===e.length}base64Encode(e){var t,r,n,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,s,a;for(a=e.length,s=0,i="";s<a;){if(t=255&e.charCodeAt(s++),s==a){i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4)+"==";break}if(r=e.charCodeAt(s++),s==a){i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&r)>>4))+o.charAt((15&r)<<2)+"=";break}n=e.charCodeAt(s++),i=(i=(i=(i+=o.charAt(t>>2))+o.charAt((3&t)<<4|(240&r)>>4))+o.charAt((15&r)<<2|(192&n)>>6))+o.charAt(63&n)}return i}base64Decode(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";if(/([^\s]+[^0-9a-zA-Z\+\/\=]|[^0-9a-zA-Z\+\/\=]\s+)/.test(e))throw new Error("Invalid base64 input");var r,n,o,i,s,a,l=e.replace(/\s/g,"");let u="",c=0;for(;c<l.length;)o=t.indexOf(l.charAt(c++)),r=(15&(i=t.indexOf(l.charAt(c++))))<<4|(s=t.indexOf(l.charAt(c++)))>>2,n=(3&s)<<6|(a=t.indexOf(l.charAt(c++))),u+=String.fromCharCode(o<<2|i>>4),64!==s&&(u+=String.fromCharCode(r)),64!==a&&(u+=String.fromCharCode(n));return u=this.utf8Decode(u)}utf8Decode(t){let e=[],r=0,n=0,o=0;for(t=t.replace(/\r\n/g,"\n");r<t.length;){n=255&t.charCodeAt(r),o=0,o=n<=191?(n&=127,1):n<=223?(n&=31,2):n<=239?(n&=15,3):(n&=7,4);for(let e=1;e<o;++e)n=n<<6|63&t.charCodeAt(e+r);4===o?(n-=65536,e.push(String.fromCharCode(55296|n>>10&1023)),e.push(String.fromCharCode(56320|1023&n))):e.push(String.fromCharCode(n)),r+=o}return e.join("")}parseJwt(e){try{var t=e.split("."),r=t[0].replace(/-/g,"+").replace(/_/g,"/"),n=this.base64Decode(r).replace(/\0/g,""),o=JSON.parse(n),i=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=this.base64Decode(i).replace(/\0/g,"");return{header:o,payload:JSON.parse(s),signature:t[2]}}catch(e){return this.log(e),null}}costTime(){var e=this.scriptName+"执行完毕！",t=(this._endTime=(new Date).getTime(),this._endTime-this._startTime);this.logger.info(e+`耗时【${t/1e3}】秒`)}done=(e={})=>{this.costTime(),"undefined"!=typeof $done&&$done(e)}}(e,t)}function MagicHttp(d,p){var e;let g;d.isNode&&(e=require("axios"),g=e.create());class t{constructor(e=!0){this.handlers=[],this.isRequest=e}use(e,t,r){return"function"==typeof e&&p.debug("Register fulfilled "+e.name),"function"==typeof t&&p.debug("Register rejected "+t.name),this.handlers.push({fulfilled:e,rejected:t,synchronous:!(!r||"boolean"!=typeof r.synchronous)&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}forEach(t){this.handlers.forEach(e=>{null!==e&&t(e)})}}function f(e){let r={...e};return r.params&&!d.isNode&&(e=Object.keys(r.params).map(e=>{var t=encodeURIComponent(e);return r.url=r.url.replace(new RegExp(e+"=[^&]*","ig"),""),r.url=r.url.replace(new RegExp(t+"=[^&]*","ig"),""),t+"="+encodeURIComponent(r.params[e])}).join("&"),r.url.indexOf("?")<0&&(r.url+="?"),/(&|\?)$/g.test(r.url)||(r.url+="&"),r.url+=e,delete r.params,p.debug("Params to QueryString: "+r.url)),r}const h=(e,t=null)=>{if(e){t={...e,config:e.config||t,status:e.statusCode||e.status,body:e.body||e.data,headers:e.headers||e.header};if("string"==typeof t.body)try{t.body=JSON.parse(t.body)}catch{}return delete t.data,t}return e};const y=(e,t=null)=>{if(e&&400<=e.status)return p.debug("Raise exception when status code is "+e.status),{name:"RequestException",message:"Request failed with status code "+e.status,config:t||e.config,response:e}},m={request:new t,response:new t(!1)};let v=[],b=[],S=!0;function N(e){return e=f(e),p.debug(`HTTP ${e.method.toUpperCase()}:`+"\n"+JSON.stringify(e)),e}function E(t){try{t=t&&h(t),p.sniffer(`HTTP ${t.config.method.toUpperCase()}:`+"\n"+JSON.stringify(t.config)+"\nSTATUS CODE:\n"+t.status+"\nRESPONSE:\n"+("object"==typeof t.body?JSON.stringify(t.body):t.body));var e=y(t);return e?Promise.reject(e):t}catch(e){return p.error(e),t}}const r=(e,r)=>{let n;r=((e,t)=>{let r="object"==typeof t?{headers:{},...t}:{url:t,headers:{}};return r.method||(r.method=e),!0===(r=f(r)).rewrite&&(d.isSurge?(r.headers["X-Surge-Skip-Scripting"]=!1,delete r.rewrite):d.isQuanX&&(r.hints=!1,delete r.rewrite)),d.isSurgeLike?(t=r.headers["content-type"]||r.headers["Content-Type"],"GET"!==r.method&&t&&0<=t.indexOf("application/json")&&r.body instanceof Array&&(r.body=JSON.stringify(r.body),p.debug("Convert Array object to String: "+r.body))):d.isQuanX?(r.hasOwnProperty("body")&&"string"!=typeof r.body&&(r.body=JSON.stringify(r.body)),r.method=e):d.isNode&&("POST"===e||"PUT"===e||"PATCH"===e||"DELETE"===e?r.data=r.data||r.body:"GET"===e&&(r.params=r.params||r.body),delete r.body),r})(e.toUpperCase(),r),n=d.isNode?g:d.isSurgeLike?i=>new Promise((n,o)=>{$httpClient[e.toLowerCase()](i,(e,t,r)=>{e?(e={name:e.name||e,message:e.message||e,stack:e.stack||e,config:i,response:h(t)},o(e)):(t.config=i,t.body=r,n(t))})}):n=>new Promise((r,t)=>{$task.fetch(n).then(e=>{e=h(e,n);var t=y(e,n);if(t)return Promise.reject(t);r(e)}).catch(e=>{e={name:e.message||e.error,message:e.message||e.error,stack:e.error,config:n,response:e.response?h(e.response):null};t(e)})});let o;var t=r;try{v=[],b=[],m.request.forEach(e=>{"function"==typeof e.runWhen&&!1===e.runWhen(t)||(S=S&&e.synchronous,v.unshift(e.fulfilled,e.rejected))}),m.response.forEach(e=>{b.push(e.fulfilled,e.rejected)})}catch(e){p.error(`Failed to register interceptors: ${e}.`)}var i=[N,void 0],s=[E,void 0];if(S){for(p.debug("Interceptors are executed in synchronous mode"),Array.prototype.unshift.apply(v,i),v=v.concat([N,void 0]);v.length;){var a=v.shift(),l=v.shift();try{"function"==typeof a&&p.debug("Executing request fulfilled "+a.name),r=a(r)}catch(e){"function"==typeof l&&p.debug("Executing request rejected "+l.name),l(e);break}}try{o=(!d.isNode&&r.timeout?c:n)(r)}catch(e){return Promise.reject(e)}for(Array.prototype.unshift.apply(b,s);b.length;)o=o.then(b.shift(),b.shift());return o}{p.debug("Interceptors are executed in asynchronous mode");let t=[n,void 0];for(Array.prototype.unshift.apply(t,i),Array.prototype.unshift.apply(t,v),t=(t=t.concat(s)).concat(b),o=Promise.resolve(r);t.length;)try{let e=t.shift();var u=t.shift();"function"==typeof(e=!d.isNode&&r.timeout&&e===n?c:e)&&p.debug("Executing request fulfilled "+e.name),"function"==typeof u&&p.debug("Executing request rejected "+u.name),o=o.then(e,u)}catch(e){p.error("request exception: "+e)}return o}function c(r){try{var e=new Promise((e,t)=>{setTimeout(()=>{var e={message:`timeout of ${r.timeout}ms exceeded.`,config:r};t(e)},r.timeout)});return Promise.race([n(r),e])}catch(e){p.error(`Request Timeout exception: ${e}.`)}}};return{request:r,interceptors:m,convertHeadersToLowerCase:r=>Object.keys(r).reduce((e,t)=>(e[t.toLowerCase()]=r[t],e),{}),convertHeadersToCamelCase:r=>Object.keys(r).reduce((e,t)=>{return e[t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join("-")]=r[t],e},{}),modifyResponse:h,get:e=>r("GET",e),post:e=>r("POST",e),put:e=>r("PUT",e),patch:e=>r("PATCH",e),delete:e=>r("DELETE",e),head:e=>r("HEAD",e),options:e=>r("OPTIONS",e)}}function MagicData(d,p){let g={fs:void 0,data:{}};if(d.isNode){g.fs=require("fs");try{g.fs.accessSync("./magic.json",g.fs.constants.R_OK|g.fs.constants.W_OK)}catch(e){g.fs.writeFileSync("./magic.json","{}",{encoding:"utf8"})}g.data=require("./magic.json")}const s=(e,t)=>"object"!=typeof t&&e===t,a=e=>"true"===e||"false"!==e&&(void 0===e?null:e),l=(e,t,r,n)=>{if(r)try{e=!0===(e="string"==typeof e?JSON.parse(e):e).magic_session?e[r]:null}catch{e=null}if("string"==typeof e&&"null"!==e)try{e=JSON.parse(e)}catch{}return null==(e=!1===n&&e&&!0===e.magic_session?null:e)&&null!=t&&(e=t),e=a(e)},f=t=>{if("string"!=typeof t)return t instanceof Array||null==t||t!=t||"boolean"==typeof t?{}:t;{let e={};try{var r=typeof(e=JSON.parse(t));("object"!=r||e instanceof Array||"bool"==r||null===e)&&(e={})}catch{}return e}},u=(e,t=null,r="",n=!1,o=null)=>{let i="";return i=o||d.isNode?((e,t=null,r="",n=!1,o=null)=>{o=o||g.data;return val=o&&void 0!==o[e]&&null!==o[e]?o[e]:r?{}:null,val=l(val,t,r,n)})(e,t,r,n,o):(d.isSurgeLike?i=$persistentStore.read(e):d.isQuanX&&(i=$prefs.valueForKey(e)),l(i,t,r,n)),p.debug(`READ DATA [${e}]${r?`[${r}]`:""} <${typeof i}>`+"\n"+JSON.stringify(i)),i},c=(e,t,r="",n=null)=>{if(void 0===t||t!=t)return!1;d.isNode||"boolean"!=typeof t&&"number"!=typeof t||(t=String(t));let o="";var i,s,a,l,u,c;if(n||d.isNode?o=([i,s,a="",l=null]=[e,t,r,n],c=l||g.data,c=f(c),a?((u=f(c[i])).magic_session=!0,u[a]=s,c[i]=u):c[i]=s,null!==l&&(l=c),c):r?(d.isSurgeLike?o=$persistentStore.read(e)?$persistentStore.read(e):o:d.isQuanX&&(o=$prefs.valueForKey(e)?$prefs.valueForKey(e):o),(o=f(o)).magic_session=!0,o[r]=t):o=t,o&&"object"==typeof o&&(o=JSON.stringify(o,null,4)),p.debug(`WRITE DATA [${e}]${r?`[${r}]`:""} <${typeof t}>`+"\n"+JSON.stringify(t)),!n){if(d.isSurgeLike)return $persistentStore.write(o,e);if(d.isQuanX)return $prefs.setValueForKey(o,e);if(d.isNode)try{g.fs.writeFileSync("./magic.json",o)}catch(e){return p.error(e),!1}}return!0};return{read:u,write:c,del:(e,t="",r=null)=>{let n={};if(r||d.isNode)n=(o=e,i=t,s=r||g.data,s=f(s),i?(delete(obj=f(s[o]))[i],s[o]=obj):delete s[o],s),r?r=n:g.fs.writeFileSync("./magic.json",JSON.stringify(n,null,4));else if(t){d.isSurgeLike?n=$persistentStore.read(e):d.isQuanX&&(n=$prefs.valueForKey(e)),delete(n=f(n))[t];i=JSON.stringify(n,null,4);c(e,i)}else{if(d.isStorm)return $persistentStore.remove(e);if(d.isSurgeLike)return $persistentStore.write(null,e);if(d.isQuanX)return $prefs.removeValueForKey(e)}var o,i,s;p.debug(`DELETE KEY [${e}]`+(t?`[${t}]`:""))},update:(e,t,r,n=s,o=null)=>{var i;return t=a(t),!0!==n(u(e,null,r,!1,o),t)&&(i=c(e,t,r,o),e=u(e,null,r,!1,o),n===s&&"object"==typeof e?i:n(t,e))},allSessions:(e,t=null)=>{let r={};t=u(e,null,null,!0,t);return!0===(t=f(t)).magic_session&&delete(r={...t}).magic_session,p.debug(`READ ALL SESSIONS [${e}] <${typeof r}>`+"\n"+JSON.stringify(r,null,4)),r},allSessionNames:(e,t=null)=>{let r=[];t=u(e,null,null,!0,t),t=f(t);return r=!0!==t.magic_session?[]:Object.keys(t).filter(e=>"magic_session"!==e),p.debug(`READ ALL SESSIONS [${e}] <${typeof r}>`+"\n"+JSON.stringify(r,null,4)),r},defaultValueComparator:s,convertToObject:f}}function MagicNotification(i,o,s,a){let l=null,u=null,c=[];function d(e=i,t="",r="",n=""){n=(t=>{try{let e={};var r;return"string"==typeof t?0<t.length&&(o.isLoon?e={openUrl:t}:o.isQuanX?e={"open-url":t}:o.isSurge&&(e={url:t})):"object"==typeof t&&(o.isLoon?(e.openUrl=t["open-url"]||"",e.mediaUrl=t["media-url"]||""):o.isQuanX?e=t["open-url"]||t["media-url"]?t:{}:o.isSurge&&(r=t["open-url"]||t.openUrl,e=r?{url:r}:{})),e}catch(e){s.error("通知选项转换失败"+e)}return t})(n),1===arguments.length&&(e=i,t="",r=arguments[0]),s.notify("\ntitle:"+e+"\nsubTitle:"+t+"\nbody:"+r+"\noptions:"+("object"==typeof n?JSON.stringify(n):n)),o.isSurge?$notification.post(e,t,r,n):o.isLoon?n?$notification.post(e,t,r,n):$notification.post(e,t,r):o.isQuanX&&$notify(e,t,r,n),l&&u&&p(e,t,r)}function p(e=i,t="",r="",n){if(void 0===a||void 0===a.post)throw"Bark notification needs to import MagicHttp module.";e={url:l,headers:{"content-type":"application/json; charset=utf-8"},body:{title:e,body:t?t+"\n"+r:r,device_key:u}};a.post(e).catch(e=>{s.error("Bark notify error: "+e)})}return{post:d,debug:function(e=i,t="",r="",n=""){"DEBUG"===s.getLevel()&&(1===arguments.length&&(e=i,t="",r=arguments[0]),this.post(e,t,r,n))},bark:p,setBark:e=>{try{var t=e.replace(/\/+$/g,"");l=/^https?:\/\/([^/]*)/.exec(t)[0]+"/push",u=/\/([^\/]+)\/?$/.exec(t)[1]}catch(e){s.error(`Bark url error: ${e}.`)}},appendNotifyInfo:function(e,t){1==t?c=e:c.push(e)},prependNotifyInfo:function(e){c.splice(0,0,e)},msg:function(e,t,r,n){var o={};r&&(o["open-url"]=r),n&&(o["media-url"]=n),(t=t&&0!=t.length?t:Array.isArray(c)?c.join("\n"):c)&&0<t.length&&d(i,"",t,o)}}}function MagicUtils(n,u){const e=(e,t="yyyy-MM-dd hh:mm:ss")=>{var r,n={"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(r in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),n)new RegExp("("+r+")").test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?n[r]:("00"+n[r]).substr((""+n[r]).length)));return t};return{retry:(i,s=5,a=0,l=null)=>(...e)=>new Promise((r,n)=>{function o(...t){Promise.resolve().then(()=>i.apply(this,t)).then(e=>{"function"==typeof l?Promise.resolve().then(()=>l(e)).then(()=>{r(e)}).catch(e=>{1<=s?0<a?setTimeout(()=>o.apply(this,t),a):o.apply(this,t):n(e),s--}):r(e)}).catch(e=>{u.error(e),1<=s&&0<a?setTimeout(()=>o.apply(this,t),a):1<=s?o.apply(this,t):n(e),s--})}o.apply(this,e)}),formatTime:e,now:()=>e(new Date,"yyyy-MM-dd hh:mm:ss"),today:()=>e(new Date,"yyyy-MM-dd"),sleep:t=>new Promise(e=>setTimeout(e,t)),assert:(e,t=null)=>{var r;n.isNode?(r=require("assert"),t?r(e,t):r(e)):!0!==e&&u.error("AssertionError: "+(t||"The expression evaluated to a falsy value."))}}}function MagicQingLong(e,a,o){let i="",s="",l="",u="",c="",t="";const d="magic.json",p=MagicHttp(e,o);async function r(){return l=l||a.read("magic_qlclient"),u=u||a.read("magic_qlsecrt"),s=s||a.read("magic_qlname"),c=c||a.read("magic_qlpwd"),i&&l&&u?(o.info("Get token from QingLong Panel"),await p.get({url:"/open/auth/token",headers:{"content-type":"application/json"},params:{client_id:l,client_secret:u}}).then(e=>{if(!(0<Object.keys(e.body).length&&e.body.data&&e.body.data.token))throw new Error("Get QingLong Panel token failed.");o.info("Successfully logged in to QingLong Panel"),t=e.body.data.token,a.write("magic_qltoken",t)}).catch(e=>{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))})):i&&s&&c&&await p.post({url:"/api/user/login",headers:{"content-type":"application/json"},body:{username:s,password:c}}).then(e=>{o.info("Successfully logged in to QingLong Panel"),t=e.body.data.token,a.write("magic_qltoken",t)}).catch(e=>{o.error("Error logging in to QingLong Panel.\n"+(e.message||e))}),t}async function g(e){let t=[];return await p.post({url:"/api/envs",headers:{"content-type":"application/json"},body:e}).then(e=>{200===e.body.code?e.body.data.forEach(e=>{o.debug(`QINGLONG ADD ENV ${e.name} <${typeof e.value}> (${e.id})`+"\n"+JSON.stringify(e)),t.push(e.id)}):o.error("Error adding environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error adding environments variable from QingLong Panel.\n"+(e.message||e))}),t}async function n(n=null,e="",t){let o=[];return await p.get({url:"/api/envs",headers:{"content-type":"application/json"},params:{searchValue:e}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading environment variable from QingLong Panel.\n"+JSON.stringify(e));e=e.body.data;if(n){var t=[];for(const r of e)r.name===n&&o.push(r);o=t}o=e}).catch(e=>{throw new Error("Error reading environments variable from QingLong Panel.\n"+(e.message||e))}),o}async function f(e,t=""){let r="";return await p.get({url:"/api/scripts/"+e,params:{path:t}}).then(e=>{if(200!==e.body.code)throw new Error("Error reading data from QingLong Panel.\n"+JSON.stringify(e));r=e.body.data}).catch(e=>{throw new Error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r}async function h(e,t="",r=""){let n=!1;return await p.put({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:r}}).then(e=>{200===e.body.code?n=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n}return p.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),e.url.indexOf(i)<0&&(e.url=""+i+e.url),{...e,timeout:3e3}},void 0),p.interceptors.request.use(function(e){return(l=l||a.read("magic_qlclient"))&&(e.url=e.url.replace("/api/","/open/")),e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(async function(e){return(t=t||a.read("magic_qltoken",""))||await r(),e.headers.authorization="Bearer "+t,e},void 0,{runWhen:e=>e.url.indexOf("api/user/login")<0&&e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(function(e){return e.params={...e.params,t:Date.now()},e},void 0,{runWhen:e=>e.url.indexOf("open/auth/token")<0}),p.interceptors.request.use(function(e){return i=i||a.read("magic_qlurl"),t=t||a.read("magic_qltoken"),o.debug("QingLong url: "+i+"\nQingLong token: "+t),e},void 0),p.interceptors.response.use(void 0,async function(e){try{var t=e.message||e.error||JSON.stringify(e);return(0<=t.indexOf("NSURLErrorDomain")&&0<=t.indexOf("-1012")||e.response&&401===e.response.status)&&e.config&&!0!==e.config.refreshToken?(o.warning("QingLong Panel token has expired"),o.info("Refreshing the QingLong Panel token"),await r(),e.config.refreshToken=!0,o.info("Call the previous method again"),await p.request(e.config.method,e.config)):Promise.reject(e)}catch(e){return Promise.reject(e)}}),{url:i||a.read("magic_qlurl"),init:(e,t,r,n,o)=>{i=e,l=t,u=r,s=n,c=o},getToken:r,setEnv:async function(t,r,n=null){if(i=i||a.read("magic_qlurl"),null===n){var e=await g([{name:t,value:r}]);if(e&&1===e.length)return e[0]}else await p.put({url:"/api/envs",headers:{"content-type":"application/json"},body:{name:t,value:r,id:n}}).then(e=>{if(200===e.body.code)return o.debug(`QINGLONG UPDATE ENV ${t} <${typeof r}> (${n})`+"\n"+JSON.stringify(r)),!0;o.error("Error adding environment variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>(o.error("Error adding environment variable from QingLong Panel.\n"+(e.message||e)),!1))},setEnvs:g,getEnv:async function(e){let t=null;for(const r of await n())if(r.id===e){t=r;break}return t},getEnvs:n,delEnvs:async function(t){return p.delete({url:"/api/envs",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>200===e.body.code?(o.debug("QINGLONG DELETE ENV IDS: "+t),!0):(o.error("Error deleting environments variable from QingLong Panel.\n"+JSON.stringify(e)),!1)).catch(e=>{o.error("Error deleting environments variable from QingLong Panel.\n"+(e.message||e))})},disableEnvs:async function(t){let r=!1;return await p.put({url:"/api/envs/disable",headers:{accept:"application/json","accept-Language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG DISABLED ENV IDS: "+t),r=!0):o.error("Error disabling environments variable from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error disabling environments variable from QingLong Panel.\n"+(e.message||e))}),r},enableEnvs:async function(t){let r=!1;return await p.put({url:"/api/envs/enable",headers:{accept:"application/json","accept-language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",connection:"keep-alive","content-type":"application/json;charset=UTF-8","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30"},body:t}).then(e=>{200===e.body.code?(o.debug("QINGLONG ENABLED ENV IDS: "+t),r=!0):o.error("Error enabling environments variable from Qilong panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error enabling environments variable from Qilong panel.\n"+(e.message||e))}),r},addScript:async function(e,t="",r=""){let n=!1;return await p.post({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t,content:r}}).then(e=>{200===e.body.code?n=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),n},getScript:f,editScript:h,delScript:async function(e,t=""){let r=!1;return await p.delete({url:"/api/scripts",headers:{"content-type":"application/json"},body:{filename:e,path:t}}).then(e=>{200===e.body.code?r=!0:o.error("Error reading data from QingLong Panel.\n"+JSON.stringify(e))}).catch(e=>{o.error("Error reading data from QingLong Panel.\n"+(e.message||e))}),r},write:async function(e,t,r=""){var n=await f(d,""),o=a.convertToObject(n),e=a.write(e,t,r,o),n=JSON.stringify(o,null,4);return await h(d,"",n)&&e},read:async function(e,t,r="",n=!1){var o=await f(d,""),o=a.convertToObject(o);return a.read(e,t,r,n,o)},del:async function(e,t=""){var r=await f(d,""),n=a.convertToObject(r),e=a.del(e,t,n),r=JSON.stringify(n,null,4),t=await h(d,"",r);return e&&t},update:async function(e,t,r,n=a.defaultValueComparator){var o=await f(d,""),i=a.convertToObject(o),e=a.update(e,t,r,n,i);let s=!1;return!0===e&&(o=JSON.stringify(i,null,4),s=await h(d,"",o)),e&&s},batchWrite:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.write(t[0],t[1],void 0!==t[2]?t[2]:"",n);return r=JSON.stringify(n,null,4),h(d,"",r)},batchRead:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r),o=[];for(t of e){var i=a.read(t[0],t[1],void 0!==t[2]?t[2]:"","boolean"==typeof t[3]&&t[3],n);o.push(i)}return o},batchUpdate:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.update(t[0],t[1],void 0!==t[2]?t[2]:"",void 0!==t[3]?t.comparator:a.defaultValueComparator,n);return r=JSON.stringify(n,null,4),h(d,"",r)},batchDel:async function(...e){var t,r=await f(d,""),n=a.convertToObject(r);for(t of e)a.del(t[0],void 0!==t[1]?t[1]:"",n);return r=JSON.stringify(n,null,4),h(d,"",r)},allSessions:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessions(e,t)},allSessionNames:async function(e){var t=await f(d,""),t=a.convertToObject(t);return a.allSessionNames(e,t)}}}
//---SyncByPyScript---MagicJS3-end

//---SyncByPyScript---md5-start
!function(n){"use strict";function d(n,t){var r=(65535&n)+(65535&t);return(n>>16)+(t>>16)+(r>>16)<<16|65535&r}function f(n,t,r,e,o,u){return d((u=d(d(t,n),d(e,u)))<<o|u>>>32-o,r)}function l(n,t,r,e,o,u,c){return f(t&r|~t&e,n,t,o,u,c)}function g(n,t,r,e,o,u,c){return f(t&e|r&~e,n,t,o,u,c)}function v(n,t,r,e,o,u,c){return f(t^r^e,n,t,o,u,c)}function m(n,t,r,e,o,u,c){return f(r^(t|~e),n,t,o,u,c)}function c(n,t){var r,e,o,u;n[t>>5]|=128<<t%32,n[14+(t+64>>>9<<4)]=t;for(var c=1732584193,f=-271733879,i=-1732584194,a=271733878,h=0;h<n.length;h+=16)c=l(r=c,e=f,o=i,u=a,n[h],7,-680876936),a=l(a,c,f,i,n[h+1],12,-389564586),i=l(i,a,c,f,n[h+2],17,606105819),f=l(f,i,a,c,n[h+3],22,-1044525330),c=l(c,f,i,a,n[h+4],7,-176418897),a=l(a,c,f,i,n[h+5],12,1200080426),i=l(i,a,c,f,n[h+6],17,-1473231341),f=l(f,i,a,c,n[h+7],22,-45705983),c=l(c,f,i,a,n[h+8],7,1770035416),a=l(a,c,f,i,n[h+9],12,-1958414417),i=l(i,a,c,f,n[h+10],17,-42063),f=l(f,i,a,c,n[h+11],22,-1990404162),c=l(c,f,i,a,n[h+12],7,1804603682),a=l(a,c,f,i,n[h+13],12,-40341101),i=l(i,a,c,f,n[h+14],17,-1502002290),c=g(c,f=l(f,i,a,c,n[h+15],22,1236535329),i,a,n[h+1],5,-165796510),a=g(a,c,f,i,n[h+6],9,-1069501632),i=g(i,a,c,f,n[h+11],14,643717713),f=g(f,i,a,c,n[h],20,-373897302),c=g(c,f,i,a,n[h+5],5,-701558691),a=g(a,c,f,i,n[h+10],9,38016083),i=g(i,a,c,f,n[h+15],14,-660478335),f=g(f,i,a,c,n[h+4],20,-405537848),c=g(c,f,i,a,n[h+9],5,568446438),a=g(a,c,f,i,n[h+14],9,-1019803690),i=g(i,a,c,f,n[h+3],14,-187363961),f=g(f,i,a,c,n[h+8],20,1163531501),c=g(c,f,i,a,n[h+13],5,-1444681467),a=g(a,c,f,i,n[h+2],9,-51403784),i=g(i,a,c,f,n[h+7],14,1735328473),c=v(c,f=g(f,i,a,c,n[h+12],20,-1926607734),i,a,n[h+5],4,-378558),a=v(a,c,f,i,n[h+8],11,-2022574463),i=v(i,a,c,f,n[h+11],16,1839030562),f=v(f,i,a,c,n[h+14],23,-35309556),c=v(c,f,i,a,n[h+1],4,-1530992060),a=v(a,c,f,i,n[h+4],11,1272893353),i=v(i,a,c,f,n[h+7],16,-155497632),f=v(f,i,a,c,n[h+10],23,-1094730640),c=v(c,f,i,a,n[h+13],4,681279174),a=v(a,c,f,i,n[h],11,-358537222),i=v(i,a,c,f,n[h+3],16,-722521979),f=v(f,i,a,c,n[h+6],23,76029189),c=v(c,f,i,a,n[h+9],4,-640364487),a=v(a,c,f,i,n[h+12],11,-421815835),i=v(i,a,c,f,n[h+15],16,530742520),c=m(c,f=v(f,i,a,c,n[h+2],23,-995338651),i,a,n[h],6,-198630844),a=m(a,c,f,i,n[h+7],10,1126891415),i=m(i,a,c,f,n[h+14],15,-1416354905),f=m(f,i,a,c,n[h+5],21,-57434055),c=m(c,f,i,a,n[h+12],6,1700485571),a=m(a,c,f,i,n[h+3],10,-1894986606),i=m(i,a,c,f,n[h+10],15,-1051523),f=m(f,i,a,c,n[h+1],21,-2054922799),c=m(c,f,i,a,n[h+8],6,1873313359),a=m(a,c,f,i,n[h+15],10,-30611744),i=m(i,a,c,f,n[h+6],15,-1560198380),f=m(f,i,a,c,n[h+13],21,1309151649),c=m(c,f,i,a,n[h+4],6,-145523070),a=m(a,c,f,i,n[h+11],10,-1120210379),i=m(i,a,c,f,n[h+2],15,718787259),f=m(f,i,a,c,n[h+9],21,-343485551),c=d(c,r),f=d(f,e),i=d(i,o),a=d(a,u);return[c,f,i,a]}function i(n){for(var t="",r=32*n.length,e=0;e<r;e+=8)t+=String.fromCharCode(n[e>>5]>>>e%32&255);return t}function a(n){var t=[];for(t[(n.length>>2)-1]=void 0,e=0;e<t.length;e+=1)t[e]=0;for(var r=8*n.length,e=0;e<r;e+=8)t[e>>5]|=(255&n.charCodeAt(e/8))<<e%32;return t}function e(n){for(var t,r="0123456789abcdef",e="",o=0;o<n.length;o+=1)t=n.charCodeAt(o),e+=r.charAt(t>>>4&15)+r.charAt(15&t);return e}function r(n){return unescape(encodeURIComponent(n))}function o(n){return i(c(a(n=r(n)),8*n.length))}function u(n,t){return function(n,t){var r,e=a(n),o=[],u=[];for(o[15]=u[15]=void 0,16<e.length&&(e=c(e,8*n.length)),r=0;r<16;r+=1)o[r]=909522486^e[r],u[r]=1549556828^e[r];return t=c(o.concat(a(t)),512+8*t.length),i(c(u.concat(t),640))}(r(n),r(t))}function t(n,t,r){return t?r?u(t,n):e(u(t,n)):r?o(n):e(o(n))}"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:n.md5=t}(this);
//# sourceMappingURL=md5.min.js.map
//---SyncByPyScript---md5-end