/*
无边星链助手

[Script]
# > 无边星链助手
^https?:\/\/api\.wubian\.pro url script-request-body https://git.vsprit.com/shawenguan/Quantumult-X/raw/master/Scripts/wubian/wubianHelper.js
^https?:\/\/api\.wubian\.pro url script-response-body https://git.vsprit.com/shawenguan/Quantumult-X/raw/master/Scripts/wubian/wubianHelper.js

[MITM]
hostname = api.wubian.pro

*/

const scriptName = `无边星链助手`;
const magicJS = MagicJS(scriptName, "INFO");

const WuBianConstKey = {
    // 基础数据
    UserInfo: 'WubianUserInfo',
    Token: 'WubianProToken',
    BrowserProxyUrl: 'WubianBrowserProxyUrl',
    TenantId: 'WubianTenantId',
    MarketAlbumListData: 'WubianMarketAlbumListData',
    AllMarketGroupListData: 'WubianAllMarketGroupListData',
    MyAllArtModifyCountData: 'WubianMyAllArtModifyCountData',
    MyAllArtRealCountData: 'WubianMyAllArtRealCountData',
    MyArtCountCaptureEnabled: 'WubianMyArtCountCaptureEnabled',
    MyArtCountModifyMode: 'WubianMyArtCountModifyMode',
    ArtIdNameMapData: 'WubianArtIdNameMapData',

    DataMaskingEnabled: 'WubianDataMaskingEnabled',
    VerListMaskkingDataMap: 'WubianVerListMaskkingDataMap',

    AllUserSimpleInfo: 'WubianAllUserSimpleInfo',
    ScoreRankDaily: 'WubianScoreRankDaily',

    QueryOthersCollectUserName: 'WubianQueryOthersCollectUserName',
    QueryOthersCollectHashId: 'WubianQueryOthersCollectHashId',

    ActivityListData: 'WubianActivityListData',
    ActivityGoodsList: 'WubianActivityGoodsList',
    ActivityTaskCaptureEnabled: 'WubianActivityTaskCaptureEnabled',
    ActivityTagName: 'WubianActivityActivityTagName',
    ActivityIndexName: 'WubianActivityIndexName',
    ActivityId: 'WubianActivityId',

    SynthesisConcurrentMode: 'WubianSynthesisConcurrentMode',
    SynthesisRunsPerSecond: 'WubianSynthesisRunsPerSecond',
    SynthesisAmount: 'WubianSynthesisTargetAmount',
    SynthesisActivityDisabled: 'WubianSynthesisActivityDisabled',

    FirstOrderCaptureEnabled: 'WubianFirstOrderCaptureEnabled',
    FirstArtListData: 'WubianFirstArtListData',
    FirstGoodsId: 'WubianFirstGoodsId',
    FirstGoodsName: 'WubianFirstGoodsName',
    CreateFirstOrderData: 'WubianCreateFirstOrderData',
    FirstGrabConcurrentMode: 'WubianFirstGrabConcurrentMode',
    FirstGrabRunsPerSecond: 'WubianFirstGrabRunsPerSecond',

    ConsignmentCaptureEnabled: 'WubianConsignmentCaptureEnabled',
    MyCollectListData: 'WubianMyCollectListData',
    ConsignmentArtName: 'WubianConsignmentArtName',
    ConsignmentArtId: 'WubianConsignmentArtId',
    ConsignmentArtPrice: 'WubianConsignmentArtPrice',
    ConsignmentArtAmount: 'WubianConsignmentArtAmount',

    FastBuyCaptureEnabled: 'WubianFastBuyCaptureEnabled',
    FastBuyQuickModeEnabled: 'WubianFastBuyQuickModeEnabled',
    FastBuyArtName: 'WubianFastBuyArtName',
    FastBuyArtId: 'WubianFastBuyArtId',
    FastBuyArtPrice: 'WubianFastBuyArtPrice',
    FastBuyArtAmount: 'WubianFastBuyArtAmount',
    FastBuyArtInfo: 'WubianFastBuyArtInfo',
};

const gUserAgent = `Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app`;
const gHost = `api.wubian.pro`;
let gToken = magicJS.data.read(WuBianConstKey.Token, '');
const gCommonHeaders = {
    'Accept': `*/*`,
    'Accept-Encoding': `gzip, deflate, br`,
    'Connection': `keep-alive`,
    'Content-Type': `application/json`,
    'Cookie': `token=${gToken}`,
    'Host': gHost,
    'User-Agent': gUserAgent,
    'CLIENT-TYPE': `APP`,
    'token': gToken,
    'Accept-Language': `zh-CN,zh-Hans;q=0.9`
};

let gRetBody;

async function Main() {
    if (magicJS.isStrictRequest) {
        magicJS.checkRecordRequestBody();
    }
    if (magicJS.isRequest) {
        checkHandleRequest();
    } else {
        updateHeaders();
    }
    magicJS.notification.msg('');
    if (gRetBody) {
        magicJS.done({
            body: JSON.stringify(gRetBody)
        });
    } else {
        magicJS.done();
    }
}

function checkHandleRequest() {
    const url = $request.url;
    const path = $request.path;
    magicJS.logger.info(`请求url=${url}#${$request.method}`);
    magicJS.logger.info(`请求body=${magicJS.getRequestBody()}`);
    if ($request && $request.method != 'OPTIONS') {
        switch (path) {
            case '/vmf/app/login/mobileLogin':
                handleMobileLogin();
                break;
            case '/vmf/app/user/collect/list':
                // 我的-产品品类列表
                handleUserCollectList();
                break;
            case '/vmf/app/user/collect/verList':
                // 我的-某一个产品的列表详情
                handleUserVerList();
                break;
            case '/vmf/app/user/getBatchGiveArtIds':
                break;
            case '/vmf/app/user/batchRole':
                // 批量下单钱包列表
                handleBatchRole();
                break;
            case '/vmf/app/market/goodsInfo':
                // 我的-某产品详情
                handleGoodsInfo();
                break;
            case 'vmf/app/market/confirmGoodsInfo':
                handleConfirmGoodsInfo();
                break;
            case '/vmf/app/common/getInitData':
                handleInitData();
                break;
            case '/vmf/app/index/topBannerList':
                break;
            case '/vmf/app/index/bannerArticleList':
                break;
            case '/vmf/app/index/artList':
                // 首发产品
                handleFirstArtList();
                break;
            case '/vmf/app/index/firstArtInfo':
                // 首发产品详情，市场产品详情
                handleFirstArtInfo();
                break;
            case '/vmf/app/market/confirmArtInfo':
                // 首发产品购买信息确认页面
                break;
            case '/vmf/app/order/createFirstOrder':
                // 创建发售订单
                break;
            case '/vmf/app/index/littleMinerInfo':
                break;
            case '/vmf/app/article/category':
                break;
            case '/vmf/app/article/listByCategory':
                // 公告列表
                handleNoticeList();
                break;
            case '/vmf/app/article/info':
                // 公告详情
                handleNoticeInfo();
                break;
            case '/vmf/app/article/selectArticleByType':
                // 产品相关的历史公告
                break;
            case '/vmf/app/index/recommend':
                // 推荐
                break;
            case '/vmf/app/index/firstArtInfo':
                // 产品信息
                break;
            case '/vmf/app/user/batchRole':
                break;
            case '/vmf/app/market/albumList':
                // 市场分区专辑列表
                handleMarketAlbumList();
                break;
            case '/vmf/app/market/groupList':
                // 市场产品寄售列表信息
                hadnleMarketGroupList();
                break;
            case '/vmf/app/market/saleRecord':
                // 市场最近成交记录
                break;
            case '/vmf/app/market/artInfo':
                // 市场寄售时产品详情
                break;
            case '/vmf/app/market/verList':
                // 市场某产品寄售列表
                handleMarketVerList();
                break;
            case '/vmf/app/order/entrustArtInfo':
                // 市场某产品委托限价范围
                break;
            case '/vmf/app/order/createEntrustOrder':
                // 创建委托订单
                break;
            case '/vmf/app/order/cancelEntrustOrder':
                // 取消委托订单
                break;
            case '/vmf/app/pay/cashier':
                // 支付收银台钱包选择列表
                break;
            case '/vmf/app/pay/getUrl':
                // 获取支付地址
                break;
            case '/vmf/app/pay/payResult':
                break;
            case '/vmf/app/synthesis/activityList':
                handleActivityList();
                break;
            case '/vmf/app/synthesis/convertGoodsList':
                handleCvtGoodsList();
                break;
            case '/vmf/app/synthesis/createConvertOrder':
                break;
            case '/vmf/app/synthesis/compositeGoodsList':
                handleCompositeGoodsList();
                break;
            case '/vmf/app/synthesis/createCompositeOrder':
                break;
            case 'vmf/app/order/list':
                // 订单列表
                handleOrderList();
                break;
            case '/vmf/app/order/info':
                // 订单详情
                handleOrderInfo();
                break;
            default:
                if (path.indexOf('/vmf/app/order/createFirstOrder') != -1) {
                    handleCreateFirstOrder();
                }
                break;
        }
    }
}

function handleHeaders() {
    if ($request && $request.method != 'OPTIONS') {
        let headers = $request.headers;
        let newToken = headers['token'];
        let oldToken = magicJS.data.read(WuBianConstKey.Token, null);
        if (newToken) {
            if (newToken != oldToken) {
                magicJS.logger.info(`当前Token刷新到最新`);
                magicJS.notification.appendNotifyInfo(`🎉当前Token刷新到最新`);
            } else {
                magicJS.logger.info(`当前Token已经是最新无需更新`);
            }
            magicJS.data.write(WuBianConstKey.Token, newToken);
        } else {
            let newCookieStr = headers['Cookie'];
            if (newCookieStr) {
                let cookieDict = magicJS.parseCookies(newCookieStr);
                if (cookieDict['token'] != void 0) {
                    newToken = ookieDict['token'];
                    magicJS.data.write(WuBianConstKey.Token, newToken);
                    magicJS.logger.info(`当前Token刷新到最新`);
                }
            }
        }

    }
}

function updateHeaders() {
    gToken = magicJS.data.read(WuBianConstKey.Token, '');
    gCommonHeaders['token'] = gToken;
    gCommonHeaders['cookie'] = `token=${gToken}`;
}

function getResponsePlainData() {
    let data = magicJS.getResponseBody();
    if (!data) {
        return;
    }
    try {
        return JSON.parse(data);
    } catch (err) {
        magicJS.logger.info(data);
        magicJS.logger.error(err);
    }
}

function getRequestPlainData() {
    let data = magicJS.getRequestBody();
    let reqData = null;
    if (data) {
        reqData = JSON.parse(data);
    } else {
        reqData = magicJS.parseQueryStr($request.url);
    }
    return reqData;
}

function getQueryPlainData() {
    let params = magicJS.parseQueryStr($request.url);
    return params;
}

function compareCookieStr(cookieStr1, cookieStr2) {
    let cookieDict1 = magicJS.parseCookies(cookieStr1);
    let cookieDict2 = magicJS.parseCookies(cookieStr2);
    let skipKeys = [];
    let retCode = 0;
    for (let key in cookieDict1) {
        if (!skipKeys.includes(key)) {
            if (cookieDict1[key] != void 0 && cookieDict2[key] != void 0 && cookieDict1[key] != cookieDict2[key]) {
                magicJS.logger.info(`${key}`);
                retCode = -1;
                break;
            }
        }
    }
    return retCode;
}

function appendCookieStr(newCookieStr) {
    let cookieStr = magicJS.data.read(WuBianConstKey.Cookie, null);
    let cookieDict = magicJS.parseCookies(cookieStr);
    let newCookieDict = magicJS.parseCookies(newCookieStr);
    for (let key in newCookieDict) {
        cookieDict[key] = newCookieDict[key];
    }
    cookieStr = magicJS.serializeCookies(cookieDict);
    magicJS.data.write(WuBianConstKey.Cookie, cookieStr);
}

/**
 * 登录后获取用户信息，然后持久化保存在本地
 * @returns
 */
function handleMobileLogin() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    /*
    // 结果示例：
    let result = {
        "code": 200,
        "data": {
            "rankInfoHide": 0,
            "hashId": "80n19034n1",
            "cancellation": 0,
            "mobile": "134*****115",
            "isAuth": 1,
            "isSecurityPassword": 1,
            "tokenExpireTime": 1728625959,
            "avatar": "/assets/img/avatar01.png",
            "token": "bccafa59-d04c-48c9-82f6-08829155b2c6",
            "address": "0x3dc7d16739d0f169977f589788007c33a0e8996d",
            "locksold": 0,
            "gameUserId": 0,
            "nickname": "WBXL-9115",
            "email": "",
            "score": 0,
            "lockown": 0
        },
        "msg": "成功",
        "fail": false
    }
    */
    magicJS.data.write(WuBianConstKey.UserInfo, rspData.data);
    if (isDataMaskingEnabled()) {
        rspData.data.nickname = '测试专用001';
        rspData.data.address = '0x0000000000000000000000000000000000000001';
        rspData.data.avatar = '/uploads/20240930/c8a5a0d2aa889057e2d79334b70ffd9d.png';
        gRetBody = rspData;
    }
    let token = rspData.data.token;
    let expireDate = new Date(rspData.data.tokenExpireTime * 1000);
    magicJS.data.write(WuBianConstKey.Token, token);
    magicJS.notification.appendNotifyInfo(`🎉当前Token刷新到最新，过期时间：${magicJS.formatDate(expireDate, 'yyyy-MM-dd HH:mm:ss')}`);
}

function handleUserCollectList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    handleHeaders();
    let reqData = getRequestPlainData();
    if (reqData.state == 1) {//1=收藏中 2=转让中 3=已转让
        let artIdNameMapData = magicJS.data.read(WuBianConstKey.ArtIdNameMapData, {});
        let realCntDict = getMyAllArtRealCountData();
        let modCntDict = getAllArtModifyCountDict();
        let list = rspData.data.list;
        for (let i = list.length - 1; i >= 0; i--) {
            const artInfo = list[i];
            artIdNameMapData[artInfo.artId] = artInfo.title;
            realCntDict[artInfo.title] = artInfo.total;
        }
        magicJS.data.write(WuBianConstKey.ArtIdNameMapData, artIdNameMapData);
        if (isMyArtCountCaptureEnabled()) {
            for (let i = list.length - 1; i >= 0; i--) {
                const artInfo = list[i];
                realCntDict[artInfo.title] = artInfo.total;
            }
            setAllArtRealCountDict(realCntDict);
        }
        if (isMyArtCountModifyMode()) {
            for (let i = list.length - 1; i >= 0; i--) {
                const artInfo = list[i];
                checkArticleModify(artInfo, modCntDict);
                if (artInfo.total == 0) {
                    list.splice(i, 1);
                    modCntDict[artInfo.title] = 0;
                }
            }
            gRetBody = rspData;
            setAllArtModifyCountDict(modCntDict);
        }
    }
}

function handleUserVerList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    if (isMyArtCountModifyMode()) {
        let reqData = getRequestPlainData();
        let artHashId = reqData.artHashId;
        let count = getArtModifyCountByHashId(artHashId);
        if (count != void 0) {
            rspData.data.total = count;
            gRetBody = rspData;
        }
        if (isDataMaskingEnabled()) {
            let page = reqData.page;
            let verListMap = magicJS.data.read(WuBianConstKey.VerListMaskkingDataMap, {});
            if (page == 1) {
                verListMap = {};
            }
            let verList = rspData.data.list;
            for (let i = 0; i < verList.length; i++) {
                let verInfo = verList[i];
                let maskStr = desensitizeNumber(verInfo.ver);
                if (!verListMap[maskStr]) {
                    verListMap[maskStr] = [];
                }
                verListMap[maskStr].push(verInfo.ver);
                verInfo.ver = maskStr;
            }
            magicJS.data.write(WuBianConstKey.VerListMaskkingDataMap, verListMap);
            gRetBody = rspData;
        }
    }
}

function handleBatchRole() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    let walletList = rspData.data.walletList;
    let firstInfo = walletList[0];
    if (firstInfo) {
        let batchLockNums = [10, 5, 2, 1];
        for (let i = 1; i < batchLockNums.length; i++) {
            if (!walletList[i]) {
                walletList[i] = {
                    tips: firstInfo.tips,
                    name: firstInfo.name,
                    walletId: firstInfo.walletId,
                }
            }
            walletList[i].batchLockNum = batchLockNums[i];
        }
        gRetBody = rspData;
    }
}

function desensitizeNumber(number, maskChar = '*', leastPadCount = 3) {
    // 将数字转换为字符串
    let str = number.toString();
    // 保留最后一位，其他位用脱敏字符替换
    let repCount = Math.max(leastPadCount, str.length - 1);
    return maskChar.repeat(repCount) + str[str.length - 1];
}

function getVerNumByMaskStr(maskStr) {
    let verListMap = magicJS.data.read(WuBianConstKey.VerListMaskkingDataMap, {});
    let arr = verListMap[maskStr];
    if (arr && arr.length > 0) {
        return getRandomElement(arr);
    }
    return maskStr;
}

function getRandomElement(arr) {
    // 生成一个随机索引
    const randomIndex = Math.floor(Math.random() * arr.length);
    // 返回随机索引处的元素
    return arr[randomIndex];
}

function getArtNameByHashId(hashId) {
    let artIdNameMapData = magicJS.data.read(WuBianConstKey.ArtIdNameMapData, {});
    return artIdNameMapData[hashId];
}

function getAllArtModifyCountDict() {
    let dict = {};
    let str = magicJS.data.read(WuBianConstKey.MyAllArtModifyCountData, '');
    if (str && str.trim().length > 0) {
        let lineArr = str.split('\n');
        for (let i = 0; i < lineArr.length; i++) {
            let kvArr = lineArr[i].trim().split('=');
            let name = kvArr[0].trim();
            if (kvArr[1]) {
                let count = parseInt(kvArr[1].trim());
                dict[name] = count;
            }
        }
    }
    return dict;
}

function setAllArtModifyCountDict(dict) {
    let str = '';
    for (let name in dict) {
        str += `${name}=${dict[name]}\n`;
    }
    magicJS.data.write(WuBianConstKey.MyAllArtModifyCountData, str);
}

function getArtModifyCountByName(name) {
    let dict = getAllArtModifyCountDict();
    return dict[name];
}

function getArtModifyCountByHashId(hashId) {
    let name = getArtNameByHashId(hashId);
    if (!name) {
        return null;
    }
    return getArtModifyCountByName(name);
}

function checkArticleModify(artInfo, modifyCntDict) {
    let title = artInfo.title;
    if (modifyCntDict[title] != void 0) {
        artInfo.total = modifyCntDict[title];
    }
}

function getMyAllArtRealCountData() {
    let dict = {};
    let str = magicJS.data.read(WuBianConstKey.MyAllArtRealCountData, '');
    if (str && str.trim().length > 0) {
        let lineArr = str.split('\n');
        for (let i = 0; i < lineArr.length; i++) {
            let kvArr = lineArr[i].trim().split('=');
            let name = kvArr[0].trim();
            if (kvArr[1]) {
                let count = parseInt(kvArr[1].trim());
                dict[name] = count;
            }
        }
    }
    return dict;
}

function setAllArtRealCountDict(dict) {
    let str = '';
    for (let name in dict) {
        str += `${name}=${dict[name]}\n`;
    }
    magicJS.data.write(WuBianConstKey.MyAllArtRealCountData, str);
}

function handleInitData() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    handleHeaders();
}

function handleNoticeList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    let reqData = getRequestPlainData();
    let tenantId = reqData.tenantId;
    magicJS.data.write(WuBianConstKey.TenantId, tenantId);
    if (reqData.page == 1) {
        let oneNotice = {
            "hashId": "468xab6e",
            "category": "系统公告",
            "icon": "/uploads/icon/系统公告.png",
            "title": "【神秘空间】应有尽有等你来探索！",
            "image": "",
            "createdTime": magicJS.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
            "type": 0,
            "categoryType": 6,
            "url": ""
        };
        rspData.data.list.splice(1, 0, oneNotice);
        gRetBody = rspData;
    }
}

function handleNoticeInfo() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    let reqData = getRequestPlainData();
    let hashId = reqData.hashId;
    if (hashId == '468xab6e') {
        let marketAlbumList = magicJS.data.read(WuBianConstKey.MarketAlbumListData, []);
        let marketGroupLstDict = magicJS.data.read(WuBianConstKey.AllMarketGroupListData, {});
        let baseLstDict = [];
        let relationLstDict = [];
        let tempId = 1;
        for (let artId in marketGroupLstDict) {
            const artInfo = marketGroupLstDict[artId];
            const groupName = artInfo.groupName;
            const artInfoA = {
                sortId: artInfo.sortId,
                hash_id: artInfo.artId,
                id: tempId,
                image: artInfo.image,
                title: artInfo.title,
                event: "art",
                type: { syn: "合成兑换", act: "空投", art: "藏品", pri: "抽奖", article: "公告" },
            };
            if (!baseLstDict[groupName]) {
                baseLstDict[groupName] = [];
            }
            baseLstDict[groupName].push(artInfoA);
            tempId += 1;
            const artInfoB = {
                sortId: artInfo.sortId,
                jumpType: "",
                url: "",
                timeList: [],
                title: artInfo.onSale == 1 ? artInfo.title : artInfo.title + '(停售)',
                image: artInfo.image,
                activityType: "",
                authorName: artInfo.brandName,
                type: "art",
                typeName: "",
                categoryType: "",
                relationId: artInfo.artId,
            };
            if (!relationLstDict[groupName]) {
                relationLstDict[groupName] = [];
            }
            relationLstDict[groupName].push(artInfoB);
        }
        let artLstText = ``;
        let relationAllList = [];
        for (let t = 0; t < marketAlbumList.length; t++) {
            const albumInfo = marketAlbumList[t];
            const albumName = albumInfo.name;
            if (albumName.indexOf('推荐') >= 0) {
                continue;
            }
            artLstText += `<p><strong><span style="color:#E53333;">&nbsp; &nbsp; <span style="color:#000000;">${albumName}：</span></span></strong></p>`;
            let artLstSubText = ``;
            let baseList = baseLstDict[albumName] || [];
            let relationList = relationLstDict[albumName] || [];
            baseList.sort((a, b) => a.sortId - b.sortId);
            relationList.sort((a, b) => a.sortId - b.sortId);
            relationAllList = relationAllList.concat(relationList);
            for (let i = 0; i < baseList.length; ++i) {
                let element = baseList[i];
                let dataStr = JSON.stringify(element);
                dataStr = dataStr.replace(/"/g, "&quot;");
                let tmpStr = `<input ` +
                    `style="align-content:center;width:80%;height:35px;background:#18bc9c;color:#FFFFFF;" readonly="readonly" ` +
                    `disabled="disabled" ` +
                    `name="relation['art'][]" ` +
                    `value="[显示]藏品:${element.title}" ` +
                    `data-event="art" ` +
                    `data-id="${element.hash_id}" ` +
                    `data-show="1" ` +
                    `data="${dataStr}" />`;
                artLstSubText += tmpStr;
            };
            artLstText += `<p><strong><span style="color:#E53333;">${artLstSubText}<br /></span></strong></p>`;
        }
        // magicJS.logger.info(artLstText);
        let dateStr = magicJS.formatDate(new Date(), 'yyyy年M月d日');
        let content = `
            <p><br /></p>
            <p style="white-space:normal;"><strong>以下过往开放过的藏品：</strong></p>
            <p><br /></p>
            ${artLstText}
            <p><strong><span style="color:#E53333;"><br /></span></strong></p>
            <p><strong><span style="color:#E53333;"><br /></span></strong></p>
            <p><strong><span style="color:#E53333;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span></strong></p>
            <p style="white-space:normal;text-align:right;"><strong><b>无边星链运营团队</b></strong></p>
            <p style="white-space:normal;text-align:right;"><strong><b><br /></b></strong></p>
            <p style="white-space:normal;text-align:right;"><strong><b>${dateStr}</b></strong></p>
            <p><br /></p>
        `;
        dateStr = magicJS.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss');
        rspData.data.createdTime = dateStr;
        rspData.data.content = content;
        rspData.data.relationList = relationAllList;
        rspData.data.title = '欢迎来到神秘空间';
        gRetBody = rspData;
    }
}

function handleMarketAlbumList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    if (rspData.data && rspData.data.length > 0) {
        magicJS.data.write(WuBianConstKey.MarketAlbumListData, rspData.data);
    }
}

function hadnleMarketGroupList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }
    let reqData = getRequestPlainData();
    let dataDict = magicJS.data.read(WuBianConstKey.AllMarketGroupListData, {});
    let sortId = (reqData.page - 1) * 20 + 1;
    let list = rspData.data?.list || [];
    let groupName = '';
    let nowTime = Date.now();

    let artIdNameMapData = magicJS.data.read(WuBianConstKey.ArtIdNameMapData, {});
    for (let i = 0; i < list.length; ++i) {
        let item = list[i];
        dataDict[item.artId] = item;
        item.sortId = sortId;
        item.onSale = 1;
        item.updateTime = nowTime;
        sortId += 1;
        groupName = item.groupName;
        artIdNameMapData[item.artId] = item.title;
    }
    magicJS.data.write(WuBianConstKey.ArtIdNameMapData, artIdNameMapData);
    for (let artId in dataDict) {
        let item = dataDict[artId];
        if (item.updateTime == void 0) {
            item.updateTime = 0;
        }
        if (item.sortId == void 0) {
            item.sortId = 9999;
        }
        if (item.updateTime < nowTime - 2 * 24 * 3600 * 1000) {
            item.onSale = 0;
            item.sortId = 9999;
        } else {
            item.onSale = 1;
        }
    }
    magicJS.data.write(WuBianConstKey.AllMarketGroupListData, dataDict);
}

function handleMarketVerList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (rspData.code != 200) {
        return;
    }

    let verList = rspData.data.list;
    for (let i = 0; i < verList.length; i++) {
        let verInfo = verList[i];
        verInfo.wallet = `${verInfo.wallet}\n市场流通：${rspData.data.total}`;
    }
    gRetBody = rspData;
}

function handleActivityList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    let reqData = getRequestPlainData();
    // 1=合成活动，2=置换活动，3=分解活动，4=兑换活动
    let activityType = reqData.activityType || 0;
    let page = reqData.page;
    let key = `${WuBianConstKey.ActivityListData}#${activityType}`;
    let list = rspData.data.list;

    let dataDict = magicJS.data.read(key, {});
    let nowTime = Math.floor(Date.now() / 1000);
    for (let item of list) {
        // name
        // startTime
        // endTime
        // hashId
        // activityType
        // type 0=合成 1=兑换或置换
        // status -1=未开始 1=进行中 2=已结束
        const hashId = item.hashId;
        dataDict[hashId] = item;
        // item.startTime = Math.floor(Date.now() / 1000 - 3600);
        // item.endTime = Math.floor(Date.now() / 1000 + 3600);
        if (nowTime < item.endTime + 24 * 3600) {
            if (item.status == -1) {
                item.name = `${item.name}(未开始)`;
            } else if (item.status == 2) {
                item.name = `${item.name}(已结束)`;
                item.endTime = item.endTime + 24 * 3600;
                item.status = 1;
            }
        }
    }
    magicJS.data.write(key, dataDict);

    gRetBody = rspData;
}

function isActivityTaskCaptureEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.ActivityTaskCaptureEnabled, true);
    return isEnabled;
}

function isFirstOrderCaptureEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.FirstOrderCaptureEnabled, true);
    return isEnabled;
}

function isConsignmentCaptureEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.ConsignmentCaptureEnabled, true);
    return isEnabled;
}

function isFastBuyCaptureEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.FastBuyCaptureEnabled, true);
    return isEnabled;
}

function setActivityDisabled(activityId, bDisabled = true) {
    let key = `${WuBianConstKey.SynthesisActivityDisabled}#${activityId}`;
    magicJS.data.write(key, bDisabled);
}

function isMyArtCountCaptureEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.MyArtCountCaptureEnabled, true);
    return isEnabled;
}
function isMyArtCountModifyMode() {
    let isEnabled = magicJS.data.read(WuBianConstKey.MyArtCountModifyMode, false);
    return isEnabled;
}

function isDataMaskingEnabled() {
    let isEnabled = magicJS.data.read(WuBianConstKey.DataMaskingEnabled, true);
    return isEnabled;
}


function handleCvtGoodsList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    let reqData = getRequestPlainData();
    let activityId = reqData.activityId || 'default';
    if (isActivityTaskCaptureEnabled()) {
        let activityInfo = rspData.data.activityInfo;
        activityId = activityInfo.activityId;
        magicJS.data.write(WuBianConstKey.ActivityId, activityId);
        magicJS.data.write(WuBianConstKey.ActivityIndexName, activityInfo.name);
        magicJS.data.write(WuBianConstKey.SynthesisAmount, 10);
        activityInfo.type = 1;
        setActivityDisabled(activityId, false);

        magicJS.notification.appendNotifyInfo(`🎉[${activityInfo.name}]兑换数据采集成功！`);
    }
    let key = `${WuBianConstKey.ActivityGoodsList}#${activityId}`;
    magicJS.data.write(key, rspData.data);
}


function handleCompositeGoodsList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    let reqData = getRequestPlainData();
    let activityId = reqData.id || 'default';
    if (isActivityTaskCaptureEnabled()) {
        let activityInfo = rspData.data.activityInfo;
        activityId = activityInfo.activityId;
        magicJS.data.write(WuBianConstKey.ActivityId, activityId);
        magicJS.data.write(WuBianConstKey.ActivityIndexName, activityInfo.name);
        magicJS.data.write(WuBianConstKey.SynthesisAmount, 10);
        activityInfo.type = 0;
        setActivityDisabled(activityId, false);

        magicJS.notification.appendNotifyInfo(`🎉[${activityInfo.name}]合成数据采集成功！`);
    }
    let key = `${WuBianConstKey.ActivityGoodsList}#${activityId}`;
    magicJS.data.write(key, rspData.data);
}

function handleFirstArtList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    // 结果示例
    /*
    let result = {
        "code": 200,
        "data": {
            "total": 1,
            "next": 0,
            "list": [
                {
                    "category": 1,
                    "coverImage": "",
                    "refreshTime": 1725881400,
                    "count": 10000,
                    "type": 1,
                    "title": "星链计划",
                    "avatar": "/uploads/20240830/c18be0bb7951859b97a7a2afba9d33a2.jpg",
                    "image": "/uploads/20240909/0c5d20baa4c00a3390b131b84bf8d592.jpg",
                    "tagList": [

                    ],
                    "price": 138,
                    "attachFileType": 1,
                    "artId": "3oe8bev8",
                    "nickname": "无边星链",
                    "status": "1" // 1=进行中 2=已结束
                }
            ]
        },
        "msg": "成功",
        "fail": false
    }
    */

    // let result = {
    //     "code": 200,
    //     "data": {
    //         "total": 1,
    //         "next": 0,
    //         "list": [
    //             {
    //                 "category": 1,
    //                 "coverImage": "",
    //                 "refreshTime": 1725881400,
    //                 "count": 10000,
    //                 "type": 1,
    //                 "title": "星链计划",
    //                 "avatar": "/uploads/20240830/c18be0bb7951859b97a7a2afba9d33a2.jpg",
    //                 "image": "/uploads/20240909/0c5d20baa4c00a3390b131b84bf8d592.jpg",
    //                 "tagList": [

    //                 ],
    //                 "price": 138,
    //                 "attachFileType": 1,
    //                 "artId": "3oe8bev8",
    //                 "nickname": "无边星链",
    //                 "status": "1"
    //             }
    //         ]
    //     },
    //     "msg": "成功",
    //     "fail": false
    // }
    // rspData = result;
    let artDataDict = magicJS.data.read(WuBianConstKey.FirstArtListData, {});
    let reqData = getRequestPlainData();
    if (reqData && reqData.page == 1) {
        artDataDict = {};
    }
    let artList = rspData.data.list;
    for (let item of artList) {
        const artId = item.artId;
        artDataDict[artId] = item;
    }
    magicJS.data.write(WuBianConstKey.FirstArtListData, artDataDict);

    gRetBody = rspData;
}

function getFirstArtData(artId) {
    let artDataDict = magicJS.data.read(WuBianConstKey.FirstArtListData, {});
    return artDataDict[artId];
}

function getFirstArtName(artId) {
    let data = getFirstArtData(artId);
    if (data) {
        return data.title;
    }
    return `${artId}`;
}

function checkIsValidFirstArt(artId) {
    let artData = getFirstArtData(artId);
    if (artData) {
        if (artData.status == 1) {
            return true;
        }
    }
    return false;
}


function handleGoodsInfo() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }

    /* 结果示例：
    let result = {
        "code": 200,
        "data": {
            "giveInfo": "",
            "resellInfo": "",
            "author": {
                "avatar": "/uploads/20240830/c18be0bb7951859b97a7a2afba9d33a2.jpg",
                "address": "0x96d1e7792e13c655b311e68e71d56698346786ce",
                "isAuthor": 1,
                "id": "657v3oean1",
                "bio": "",
                "isFocus": "",
                "nickName": "无边星链"
            },
            "owner": {
                "avatar": "/assets/img/avatar01.png",
                "address": "0x3dc7d16739d0f169977f589788007c33a0e8996d",
                "isAuthor": 0,
                "id": "80n19034n1",
                "bio": "",
                "isFocus": "",
                "nickName": "******5"
            },
            "button": [
                {
                    "key": "NONE",
                    "disable": 1,
                    "highlight": ""
                }
            ],
            "isBox": 0,
            "paymentInfo": {
                "walletType": "",
                "isBuy": 0,
                "price": 48,
                "serviceRate": "0.07",
                "saleMinPrice": "",
                "saleMaxPrice": "",
                "mainOrderSn": "",
                "beginSaleTime": "",
                "walletId": ""
            },
            "info": {
                "lock": false,
                "tokenId": "182894170004127",
                "status": 2,
                "title": "星链计划",
                "image": "/uploads/20240909/0c5d20baa4c00a3390b131b84bf8d592.jpg",
                "count": 10000,
                "images": "",
                "contractAddress": "0x3a7ddb3129c52e8304ba1124a6d5c5f6622d8038",
                "type": 1,
                "brandName": "无边星链",
                "id": "e3nl20k41n4d",
                "ver": 4127,
                "attachFileType": 1,
                "circulationNum": 7500,
                "groupName": "限价区",
                "json": "{\"entrustEnable\":\"1\"}",
                "artId": "3oe8bev8",
                "isLike": 0,
                "attachFile": "",
                "content": "在浩渺的宇宙中，人类的探索从未停止。【星链计划】便是对人类太空探索梦想的独特诠释。这件藏品以精湛的工艺呈现出星链在太空中的壮丽景象。神秘深邃的背景中，无数颗卫星如同璀璨的明珠，以特定的轨道排列，仿佛一条闪耀着科技之光的银河。每一颗卫星都刻画得细致入微，金属质感的外壳散发着冷冽的光泽，彰显着现代科技的强大魅力。星链计划不仅代表着在宇宙领域的重大突破，更是人类向太空进军的勇敢尝试，也是对人类无限创造力的致敬。它不仅具有极高的艺术价值，更是历史与未来的交汇点，让你在欣赏它的同时，仿佛能感受到宇宙的浩瀚与人类的伟大。",
                "description": ""
            }
        },
        "msg": "成功",
        "fail": false
    }
    */
    let artInfo = rspData.data.info;
    let paymentInfo = rspData.data.paymentInfo;
    if (isConsignmentCaptureEnabled()) {
        let oldArtId = magicJS.data.read(WuBianConstKey.ConsignmentArtId, null);
        if (oldArtId != artInfo.artId) {
            if (typeof paymentInfo.saleMaxPrice == 'number') {
                magicJS.data.write(WuBianConstKey.ConsignmentArtPrice, paymentInfo.saleMaxPrice);
            } else {
                if (paymentInfo.price > 0) {
                    magicJS.data.write(WuBianConstKey.ConsignmentArtPrice, paymentInfo.price);
                } else {
                    magicJS.data.write(WuBianConstKey.ConsignmentArtPrice, 9999);
                }
            }
        }
        magicJS.data.write(WuBianConstKey.ConsignmentArtId, artInfo.artId);
        magicJS.data.write(WuBianConstKey.ConsignmentArtName, artInfo.title);
        magicJS.notification.appendNotifyInfo(`🎉[${artInfo.title}]一键寄售数据采集成功！`);
    }
    let authorInfo = rspData.data.author;
    if (typeof paymentInfo.saleMinPrice == 'string' && paymentInfo.saleMinPrice.length == 0) {
        paymentInfo.saleMinPrice = 1;
    }
    if (typeof paymentInfo.saleMaxPrice == 'string' && paymentInfo.saleMaxPrice.length == 0) {
        paymentInfo.saleMaxPrice = 99999;
    }

    let buttons = rspData.data.button;
    if (buttons[0].disable == 1) {
        // let mapList = [
        //     ["DESTROY", "已销毁"],
        //     ["LOCKING", "锁定中"],
        //     ["OPENED", "已开启"],
        //     ["SOLD", "已售出"],
        //     ["PAY", "立即购买"],
        //     ["DRIVE", "车辆试驾"],
        //     ["AVATAR", "设为头像"],
        //     ["CLOSE_SALE", "取消寄售"],
        //     ["SALE", "平台寄售"],
        //     ["GIVE", "转赠好友"],
        //     ["OPEN_BOX", "打开宝箱"],
        //     ["SYNTHESISING", "合成中"],
        //     ["NONE", "暂未开放"],
        //     ["CONVERT", "兑换"],
        //     ["SHARE", "分享"],
        //     ["RESELL", "转售"],
        // ];
        let frtBtnKey = buttons[0]?.key;
        if (frtBtnKey == void 0 || frtBtnKey == 'NONE') {
            buttons[0].disable = 0;
            buttons[0].key = 'SALE';
            buttons[1] = {
                disable: 0,
                key: 'GIVE',
            };
            authorInfo.nickName = `${authorInfo.nickName}#改`;
        }
    }
    let owner = rspData.data.owner;
    if (owner) {
        let userDataCache = magicJS.data.read(WuBianConstKey.AllUserSimpleInfo, {});
        if (!userDataCache[owner.id]) {
            userDataCache[owner.id] = {
                nickName: owner.nickName,
                hashId: owner.id,
                address: owner.address,
            };
        }
    }

    gRetBody = rspData;
}

function handleConfirmGoodsInfo() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    let owner = data.owner;
    if (owner) {
        let userDataCache = magicJS.data.read(WuBianConstKey.AllUserSimpleInfo, {});
        if (!userDataCache[owner.id]) {
            userDataCache[owner.id] = {
                nickName: owner.nickName,
                hashId: owner.id,
                address: owner.address,
            };
        } else {
            userDataCache[owner.id].nickName = owner.nickName;
            userDataCache[owner.id].hashId = owner.id;
            userDataCache[owner.id].address = owner.address;
        }
    }
}

function handleFirstArtInfo() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }

    if (rspData.code != 200) {
        return;
    }
    /* 结果示例：
    let result = {
        "code": 200,
        "data": {
            "artInfo": {
                "description": "",
                "brandName": "无边星链",
                "preBookTime": 600,
                "contractAddress": "0x3a7ddb3129c52e8304ba1124a6d5c5f6622d8038",
                "json": "{\"entrustEnable\":\"1\"}",
                "count": 10000,
                "isLike": 0,
                "type": 1,
                "title": "星链计划",
                "image": "/uploads/20240909/0c5d20baa4c00a3390b131b84bf8d592.jpg",
                "btnContent": "",
                "attachfile": "",
                "attachfileType": 1,
                "images": [

                ],
                "groupName": "限价区",
                "artId": "3oe8bev8",
                "circulationNum": 8723,
                "status": 2,
                "content": "在浩渺的宇宙中，人类的探索从未停止。【星链计划】便是对人类太空探索梦想的独特诠释。这件藏品以精湛的工艺呈现出星链在太空中的壮丽景象。神秘深邃的背景中，无数颗卫星如同璀璨的明珠，以特定的轨道排列，仿佛一条闪耀着科技之光的银河。每一颗卫星都刻画得细致入微，金属质感的外壳散发着冷冽的光泽，彰显着现代科技的强大魅力。星链计划不仅代表着在宇宙领域的重大突破，更是人类向太空进军的勇敢尝试，也是对人类无限创造力的致敬。它不仅具有极高的艺术价值，更是历史与未来的交汇点，让你在欣赏它的同时，仿佛能感受到宇宙的浩瀚与人类的伟大。"
            },
            "authorInfo": {
                "avatar": "/uploads/20240830/c18be0bb7951859b97a7a2afba9d33a2.jpg",
                "address": "0x96d1e7792e13c655b311e68e71d56698346786ce",
                "isAuthor": 1,
                "id": "657v3oean1",
                "bio": "",
                "isFocus": "",
                "nickName": "无边星链"
            },
            "covertInfo": "",
            "payInfo": {
                "category": 1,
                "enableConsignment": 0,
                "price": 138,
                "limited": 0,
                "refreshTime": 0,
                "btnContent": "立即购买",
                "serviceRate": "0.07",
                "saleMaxPrice": 438,
                "saleMinPrice": 1
            }
        },
        "msg": "成功",
        "fail": false
    }
    */
    let artInfo = rspData.data.artInfo;
    let authorInfo = rspData.data.authorInfo;
    let payInfo = rspData.data.payInfo;

    if (checkIsValidFirstArt(artInfo.artId)) {
        if (isFirstOrderCaptureEnabled()) {
            magicJS.data.write(WuBianConstKey.CreateFirstOrderData, {
                title: artInfo.title,
                artId: artInfo.artId,
                price: artInfo.price,
                num: payInfo.limited,
            });
            magicJS.data.write(WuBianConstKey.FirstGoodsId, artInfo.artId);
            magicJS.data.write(WuBianConstKey.FirstGoodsName, artInfo.title);
            magicJS.notification.appendNotifyInfo(`🎉产品[${artInfo.title}]首发数据采集成功！`);
        }
    } else {
        if (isFastBuyCaptureEnabled()) {
            let oldArtId = magicJS.data.read(WuBianConstKey.FastBuyArtId, null);
            if (oldArtId != artInfo.artId) {
                magicJS.data.write(WuBianConstKey.FastBuyArtPrice, payInfo.saleMinPrice || 1);
            }
            magicJS.data.write(WuBianConstKey.FastBuyArtId, artInfo.artId);
            magicJS.data.write(WuBianConstKey.FastBuyArtName, artInfo.title);
            magicJS.data.write(WuBianConstKey.FastBuyArtInfo, artInfo);
            magicJS.notification.appendNotifyInfo(`🎉产品[${artInfo.title}]快捷购买数据采集成功！`);
        }
    }

    artInfo.title = `${artInfo.title}(流通:${artInfo.circulationNum})`;

    // 购买寄售强开
    if (payInfo.enableConsignment == 0) {
        payInfo.enableConsignment = 1;
        authorInfo.nickName = `${authorInfo.nickName}#改`;
        magicJS.logger.info(`强制开启批量购买功能`);
    }

    // payInfo只跟首发相关
    // 强制开启首发购买
    // artInfo.status = 1;
    if (payInfo.limited < 1) {
        // 购买数量强开
        payInfo.limited = 999;
        magicJS.logger.info(`强制开启购买数量限制`);
    }
    if (payInfo.refreshTime == 0) {
        payInfo.refreshTime = Math.floor(Date.now() / 1000);
    }
    gRetBody = rspData;
}

function handleCreateFirstOrder() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    if (isFirstOrderCaptureEnabled()) {
        // `https://api.wubian.pro/vmf/app/order/createFirstOrder?token=80n19034n1`
        let reqData = JSON.parse(magicJS.getRequestBody());
        let queryParams = magicJS.parseQueryStr($request.url);
        magicJS.data.write(WuBianConstKey.CreateFirstOrderData, {
            token: queryParams.token,
            artId: reqData.artHashId,
            price: reqData.price,
            num: reqData.num,
        });
        magicJS.data.write(WuBianConstKey.FirstGoodsId, reqData.artHashId);
        magicJS.notification.appendNotifyInfo(`🎉产品[${getFirstArtName(reqData.artHashId)}]首发数据采集成功！`);
    }
}

function handleOrderList() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
    /**
     *
    结果示例：
        {
            "code": 200,
            "data": {
                "total": 283,
                "next": 1,
                "list": [
                    {
                        "state": 8,
                        "orderTypeName": "兑换订单",
                        "orderSn": "20240919200738282206032433",
                        "createdTime": "2024-09-19 20:07:38",
                        "count": 82781,
                        "authorName": "无边星链",
                        "title": "玉兔捣药分解活动！",
                        "price": 0,
                        "image": "/uploads/20240919/ca5a67f98ed6396fd548752caa3d8974.png",
                        "ver": "#22314/82781",
                        "orderType": 6,
                        "num": 6,
                        "lockTime": 0,
                        "stateDesc": "已兑换",
                        "buttonList": []
                    }
                ]
            },
            "msg": "成功",
            "fail": false
        }


     */
    // let mapList = [
    //     ["CANCEL_CONSIGNMENT", "取消寄售"],
    //     ["VIEW_GOODS", "查看藏品"],
    //     ["CANCEL_ORDER", "取消订单"],
    //     ["PAY", "去支付"],
    //     ["GOODS_LIBRARY", "藏品库"],
    //     ["BUY_ANOTHER", "继续购买"],
    //     ["ORDER_CONFIRM", "订单确认中"],
    //     ["INVOICE", "申请发票"],
    //     ["UPDATE_PRICE", "修改价格"],
    //     ["CANCEL_COMPETE", "取消竞价"],
    //     ["CANCEL_ENTRUST", "取消委托"]
    // ];
}

function handleOrderInfo() {
    let rspData = getResponsePlainData();
    if (!rspData) {
        return;
    }
}

Main().catch((e) => magicJS.logger.log(`-\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