/******************************

> 慢慢买

*******************************

[rewrite_local]

^https?:\/\/apph5\.manmanbuy\.com\/taolijin\/(login.aspx|logserver.aspx) url script-request-body https://git.vsprit.com/shawenguan/Quantumult-X/raw/master/Scripts/manmanbuy/manmanbuyHelper.js

[MITM]

hostname=apph5.manmanbuy.com

********************************/

const SCRIPT_NAME = '慢慢买';
const GET_COOKIE_REGEX = /https:?\/\/apph5\.manmanbuy\.com\/taolijin\/logserver.aspx/;
const LOGIN_REGEX = /https?:\/\/apph5\.manmanbuy\.com\/taolijin\/login.aspx/
const CHECKIN_COOKIE_KEY = 'manmanbuy_checkin_cookie';
const LOGIN_BODY_KEY = 'manmanbuy_login_body';
const USERTOKEN_KEY = 'manmanbuy_usertoken';
const USERNAME_KEY = 'manmanbuy_username';
const DEVICEID_KEY = 'manmanbuy_deviceid';

let magicJS = MagicJS(SCRIPT_NAME, "INFO");
magicJS.unifiedPushUrl = magicJS.read('manmanbuy_unified_push_url') || magicJS.read('magicjs_unified_push_url');

let userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 - mmbWebBrowse - ios ';
let login_options = {
    url: 'https://apph5.manmanbuy.com/taolijin/login.aspx',
    headers: {
        'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'sec-fetch-site':'same-origin',
        'accept-language':'zh-CN,zh-Hans;q=0.9',
        'accept-encoding':'gzip, deflate, br',
        'sec-fetch-mode':'cors',
        'origin':'https://apph5.manmanbuy.com',
        'content-length':'66',
        'user-agent': userAgent,
        'referer':'https://apph5.manmanbuy.com/renwu/index.aspx?m_from=my_daka',
        'sec-fetch-dest':'empty',
        'cookie': '',
        'savedata': 'false'
    },
    body: ''
}

let checkin_options = {
    url: 'https://apph5.manmanbuy.com/renwu/index.aspx?m_from=my_daka',
    headers: {
        'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'sec-fetch-site':'none',
        'accept-encoding':'gzip, deflate, br',
        'sec-fetch-mode':'navigate',
        'user-agent':userAgent,
        'accept-language':'zh-CN,zh-Hans;q=0.9',
        'sec-fetch-dest':'document'
    },
    body: ''
}

async function Main() {
    if (magicJS.isRequest) {
        handleRequest();
        magicJS.done();
    } else {
        let loginResult = await login();
        if (loginResult) {
            let userInfo = await getUserInfo();
            if(userInfo){
                if(!userInfo.isTodayCheckin){
                    await checkIn();
                }else{
                    magicJS.notify(`今日已经签到，已连续签到${userInfo.continueCheckinCount}天`);
                }
            }else{
                magicJS.notify('❌获取用户信息失败');
            }
        }
        magicJS.done();
    }
}

function handleRequest(){
    const request = magicJS.request;
    if (LOGIN_REGEX.test(request.url) && request.headers.hasOwnProperty('savedata') == false) {
        let hisBody = magicJS.read(LOGIN_BODY_KEY, 'default');
        if (hisBody != request.body) {
            magicJS.write(LOGIN_BODY_KEY, request.body, 'default');
            let reqParams = magicJS.parseQueryStr(request.body);
            let username = reqParams.u_name;
            let usertoken = reqParams.u_token;
            if(username && usertoken){
                magicJS.write(USERTOKEN_KEY, usertoken, 'default');
                magicJS.write(USERNAME_KEY, username, 'default');
            }
            magicJS.log('获取登录Body成功。')
            magicJS.notify('🎈获取登录Body成功！！');
        } else {
            magicJS.log('登录Body没有变化，无需更新。')
        }
    } else if (GET_COOKIE_REGEX.test(request.url)) {
        try {
            let hisCookie = magicJS.read(CHECKIN_COOKIE_KEY, 'default');
            let cookie = request.headers['Cookie'];
            let reqParams = magicJS.parseQueryStr(request.body);
            let devicedId = reqParams.deviceid;
            let username = reqParams.username;
            let hisDevicedId = magicJS.read(DEVICEID_KEY, 'default');
            let hisUsername = magicJS.read(USERNAME_KEY, 'default');
            if (hisCookie != cookie || devicedId != hisDevicedId || hisUsername != username) {
                magicJS.write(DEVICEID_KEY, devicedId, 'default');
                magicJS.write(USERNAME_KEY, username, 'default');
                magicJS.write(CHECKIN_COOKIE_KEY, cookie, 'default');
                magicJS.log('获取签到Cookie和Body成功。')
                magicJS.notify('🎈获取签到Cookie和Body成功！！');
            } else {
                magicJS.logInfo(`Cookie没有变化，无需更新。`);
            }
        } catch (err) {
            magicJS.log(`获取签到Cookie和Body失败，执行异常${err}`);
            magicJS.notify('❌获取签到Cookie和Body失败，执行异常！！');
        }
    }
}

function login(){
    return new Promise((resolve) => {
        let cookie = magicJS.read(CHECKIN_COOKIE_KEY, 'default');
        let body = magicJS.read(LOGIN_BODY_KEY, 'default');
        let username = magicJS.read(USERNAME_KEY, 'default');
        let usertoken = magicJS.read(USERTOKEN_KEY, 'default');

        // magicJS.log(`cookie=${cookie}`);
        // magicJS.log(`username=${username}`);
        // magicJS.log(`usertoken=${usertoken}`);
        if (!!cookie && !!username && !!usertoken) {
            body = `action=newtokenlogin&u_name=${username}&u_token=${usertoken}`;
            login_options.headers['cookie'] = cookie;
            login_options.body = body;
            magicJS.post(login_options, (err, resp, data) => {
                if (err) {
                    magicJS.log(`登录失败，http请求异常:${err}`);
                    resolve(false);
                } else {
                    try {
                        let obj = JSON.parse(data);
                        if (obj['code'] == 1) {
                            magicJS.log('登录成功');
                            resolve(true);
                        } else {
                            magicJS.log(`登录失败，接口响应不合法：${data}`);
                            magicJS.notify('❌登录失败，接口响应不合法。');
                            resolve(false);
                        }
                    } catch (err) {
                        magicJS.log(`登录失败，执行异常：${err}，接口响应：${data}`);
                        magicJS.notify('❌登录失败，执行异常。');
                        resolve(false);
                    }
                }
            });
        } else {
            magicJS.notify('❌登录失败，请先获取登录Cookie和Body！！');
            resolve(false);
        }
    });
}

function getUserInfo(){
    return new Promise((resolve) => {
        let cookie = magicJS.read(CHECKIN_COOKIE_KEY, 'default');
        let devicedId = magicJS.read(DEVICEID_KEY, 'default');
        let username = magicJS.read(USERNAME_KEY, 'default');
        let body = `action=get_user_info&username=${username}&c_devid=${devicedId}&isAjaxInvoke=true`;
        if (!!cookie && !!body) {
            checkin_options.referer = 'https://apph5.manmanbuy.com/renwu/index.aspx?m_from=my_daka';
            checkin_options.url = 'https://apph5.manmanbuy.com/renwu/index.aspx';
            checkin_options.headers['cookie'] = cookie;
            checkin_options.body = body;
            magicJS.post(checkin_options, (err, resp, data) => {
                let retData = null;
                if (err) {
                    magicJS.log(`获取用户信息失败，http请求异常:${err}`);
                } else {
                    try {
                        magicJS.log(data);
                        let obj = JSON.parse(data);
                        if (obj['code'] == 1) {
                            retData = obj.data;
                        }
                    } catch (err) {
                        magicJS.log(`获取用户信息失败，执行异常：${err}，接口响应：${data}`);
                    }
                }
                resolve(retData);
            })
        } else {
            resolve();
        }
    });
}

function checkIn(){
    return new Promise((resolve) => {
        let cookie = magicJS.read(CHECKIN_COOKIE_KEY, 'default');
        let devicedId = magicJS.read(DEVICEID_KEY, 'default');
        let username = magicJS.read(USERNAME_KEY, 'default');
        let body = `action=checkin&username=${username}&c_devid=${devicedId}&isAjaxInvoke=true`;
        if (!!cookie && !!body) {
            checkin_options.url = 'https://apph5.manmanbuy.com/renwu/index.aspx?m_from=my_daka';
            checkin_options.headers['cookie'] = cookie;
            checkin_options.body = body;
            magicJS.post(checkin_options, (err, resp, data) => {
                if (err) {
                    magicJS.log(`签到失败，http请求异常:${err}`);
                } else {
                    try {
                        let obj = JSON.parse(data);
                        if (obj['code'] == 1) {
                            magicJS.log(`签到成功，获得积分${obj['data']['jifen']}，已连续签到${obj['data']['zt']}天！！`);
                            magicJS.notify(`🎉签到成功\n🎁获得积分${obj['data']['jifen']}，已连续签到${obj['data']['zt']}天！！`)
                        } else if (obj['code'] == 0) {
                            magicJS.log(`签到失败，可能是重复签到，接口响应：${data}`);
                            magicJS.notify('❌签到失败，可能是重复签到！！');
                        } else {
                            magicJS.log(`签到失败，接口响应不合法：${data}`);
                            magicJS.notify('❌签到失败，接口响应不合法！！');
                        }
                    } catch (err) {
                        magicJS.log(`签到失败，执行异常：${err}，接口响应：${data}`);
                        magicJS.notify('❌签到失败，执行异常！！');
                    }
                }
                resolve();
            })
        } else {
            magicJS.notify('❌签到失败，请先获取签到Cookie！！');
            resolve();
        }
    });
}


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

//---SyncByPyScript---MagicJS2-start
function MagicJS(e="MagicJS",t="INFO"){return new class{constructor(){if(this._startTime=Date.now(),this.version="2.2.3.7",this.scriptName=e,this.logLevels={DEBUG:5,INFO:4,NOTIFY:3,WARNING:2,ERROR:1,CRITICAL:0,NONE:-1},this.isLoon="undefined"!=typeof $loon,this.isQuanX="undefined"!=typeof $task,this.isJSBox="undefined"!=typeof $drive,this.isNode="undefined"!=typeof module&&!this.isJSBox,this.isSurge="undefined"!=typeof $httpClient&&!this.isLoon,this.node={request:void 0,fs:void 0,data:{}},this.iOSUserAgent="Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Mobile/15E148 Safari/604.1",this.pcUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",this._logLevel="INFO",this.logLevel=t,this._barkUrl="",this._barkKey="",this.isNode){this.node.fs=require("fs"),this.node.request=require("request");try{this.node.fs.accessSync("./magic.json",this.node.fs.constants.R_OK|this.node.fs.constants.W_OK)}catch(e){this.node.fs.writeFileSync("./magic.json","{}",{encoding:"utf8"})}this.node.data=require("./magic.json")}else this.isJSBox&&($file.exists("drive://MagicJS")||$file.mkdir("drive://MagicJS"),$file.exists("drive://MagicJS/magic.json")||$file.write({data:$data({string:"{}"}),path:"drive://MagicJS/magic.json"}));this.log(e+", 开始执行!")}set barkUrl(e){try{var t=e.replace(/\/+$/g,"");this._barkUrl=/^https?:\/\/([^/]*)/.exec(t)[0]+"/push",this._barkKey=/\/([^\/]+)\/?$/.exec(t)[1]}catch(e){this.logDebug("Bark config error.")}}set logLevel(e){var t=this.read("magicjs_loglevel");this._logLevel=t||e.toUpperCase()}get logLevel(){return this._logLevel}get isRequest(){return"undefined"!=typeof $request&&"undefined"==typeof $response}get isResponse(){return"undefined"!=typeof $response}get isDebug(){return"DEBUG"===this.logLevel}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}get platform(){return this.isSurge?"Surge":this.isQuanX?"Quantumult X":this.isLoon?"Loon":this.isJSBox?"JSBox":this.isNode?"Node.js":"Unknown"}read(t,s=""){let i="";this.isSurge||this.isLoon?i=$persistentStore.read(t):this.isQuanX?i=$prefs.valueForKey(t):this.isNode?i=this.node.data:this.isJSBox&&(i=$file.read("drive://MagicJS/magic.json").string);try{this.isNode&&(i=i[t]),this.isJSBox&&(i=JSON.parse(i)[t]),s&&(i=(i="string"==typeof i?JSON.parse(i):i)&&"object"==typeof i?i[s]:null)}catch(e){this.logError(e),i=s?{}:null,this.del(t)}void 0===i&&(i=null);try{var e;i&&"string"==typeof i&&"object"==typeof(e=JSON.parse(i))&&e&&(i=e)}catch(e){}return this.logDebug(`READ DATA [${t}]${s?`[${s}]`:""}(${typeof i})`+"\n"+JSON.stringify(i)),i}write(t,e,s=""){let i=s?{}:"";if(s&&(this.isSurge||this.isLoon)?i=$persistentStore.read(t):s&&this.isQuanX?i=$prefs.valueForKey(t):this.isNode?i=this.node.data:this.isJSBox&&(i=JSON.parse($file.read("drive://MagicJS/magic.json").string)),s){try{i="object"==typeof(i="string"==typeof i?JSON.parse(i):i)&&i?i:{}}catch(e){this.logError(e),this.del(t),i={}}this.isJSBox||this.isNode?(i[t]&&"object"==typeof i[t]||(i[t]={}),i[t].hasOwnProperty(s)||(i[t][s]=null),void 0===e?delete i[t][s]:i[t][s]=e):void 0===e?delete i[s]:i[s]=e}else this.isNode||this.isJSBox?void 0===e?delete i[t]:i[t]=e:i=void 0===e?null:e;"object"==typeof i&&(i=JSON.stringify(i)),this.isSurge||this.isLoon?$persistentStore.write(i,t):this.isQuanX?$prefs.setValueForKey(i,t):this.isNode?this.node.fs.writeFileSync("./magic.json",i):this.isJSBox&&$file.write({data:$data({string:i}),path:"drive://MagicJS/magic.json"}),this.logDebug(`WRITE DATA [${t}]${s?`[${s}]`:""}(${typeof e})`+"\n"+JSON.stringify(e))}del(e,t=""){this.logDebug(`DELETE KEY [${e}]`+(t?`[${t}]`:"")),this.write(e,null,t)}notify(e=this.scriptName,t="",s="",i=""){i=(e=>{let t={};return"string"==typeof e?0<e.length&&(this.isLoon?t={openUrl:e}:this.isQuanX?t={"open-url":e}:this.isSurge&&(t={url:e})):"object"==typeof e&&(this.isLoon?(t.openUrl=e["open-url"]||"",t.mediaUrl=e["media-url"]||""):this.isQuanX?t=e["open-url"]||e["media-url"]?e:{}:this.isSurge&&(e=e["open-url"]||e.openUrl,t=e?{url:e}:{})),t})(i),1==arguments.length&&(e=this.scriptName,t="",s=arguments[0]),this.logNotify("\ntitle:"+e+"\nsubTitle:"+t+"\nbody:"+s+"\noptions:"+("object"==typeof i?JSON.stringify(i):i)),this.isSurge?$notification.post(e,t,s,i):this.isLoon?i?$notification.post(e,t,s,i):$notification.post(e,t,s):this.isQuanX?$notify(e,t,s,i):this.isJSBox&&$push.schedule({title:e,body:t?t+"\n"+s:s}),this._barkUrl&&this._barkKey&&this.notifyBark(e,t,s)}notifyDebug(e=this.scriptName,t="",s="",i=""){"DEBUG"===this.logLevel&&(1==arguments.length&&(e=this.scriptName,t="",s=arguments[0]),this.notify(e,t,s,i))}notifyBark(e=this.scriptName,t="",s="",i){e={url:this._barkUrl,headers:{"Content-Type":"application/json; charset=utf-8"},body:{title:e,body:t?t+"\n"+s:s,device_key:this._barkKey}};this.post(e,e=>{})}log(e,t="INFO"){this.logLevels[this._logLevel]<this.logLevels[t.toUpperCase()]||console.log(`██[${this.scriptName}][${t}]`+e+"\n")}logDebug(e){this.log(e,"DEBUG")}logInfo(e){this.log(e,"INFO")}logNotify(e){this.log(e,"NOTIFY")}logWarning(e){this.log(e,"WARNING")}logError(e){this.log(e,"ERROR")}logRetry(e){this.log(e,"RETRY")}adapterHttpOptions(e,t){let s="object"==typeof e?Object.assign({},e):{url:e,headers:{}},i=(s.hasOwnProperty("header")&&!s.hasOwnProperty("headers")&&(s.headers=s.header,delete s.header),s.headers&&"object"==typeof s.headers&&(s.headers["User-Agent"]||s.headers["user-agent"])||(s.headers&&"object"==typeof s.headers||(s.headers={}),this.isNode?s.headers["User-Agent"]=this.pcUserAgent:s.headers["User-Agent"]=this.iOSUserAgent),!1);return(i="object"==typeof s.opts&&(!0===s.opts.hints||!0===s.opts["Skip-Scripting"])||"object"==typeof s.headers&&!0===s.headers["X-Surge-Skip-Scripting"]?!0:i)||(this.isSurge?s.headers["X-Surge-Skip-Scripting"]=!1:this.isLoon?s.headers["X-Requested-With"]="XMLHttpRequest":this.isQuanX&&("object"!=typeof s.opts&&(s.opts={}),s.opts.hints=!1)),this.isSurge&&!i||delete s.headers["X-Surge-Skip-Scripting"],!this.isQuanX&&s.hasOwnProperty("opts")&&delete s.opts,this.isQuanX&&s.hasOwnProperty("opts")&&delete s.opts["Skip-Scripting"],"GET"===t&&!this.isNode&&s.body&&(e=Object.keys(s.body).map(e=>void 0===s.body?"":encodeURIComponent(e)+"="+encodeURIComponent(s.body[e])).join("&"),s.url.indexOf("?")<0&&(s.url+="?"),s.url.lastIndexOf("&")+1!=s.url.length&&s.url.lastIndexOf("?")+1!=s.url.length&&(s.url+="&"),s.url+=e,delete s.body),this.isQuanX?(s.hasOwnProperty("body")&&"string"!=typeof s.body&&(s.body=JSON.stringify(s.body)),s.method=t):this.isNode?(delete s.headers["Accept-Encoding"],"object"==typeof s.body&&("GET"===t?(s.qs=s.body,delete s.body):"POST"===t&&(s.json=!0,s.body=s.body))):this.isJSBox&&(s.header=s.headers,delete s.headers),s}adapterHttpResponse(e){let t={body:e.body,headers:e.headers,json:()=>JSON.parse(t.body)};return e.hasOwnProperty("statusCode")&&e.statusCode&&(t.status=e.statusCode),t}get(e,i){e=this.adapterHttpOptions(e,"GET");this.logDebug("HTTP GET: "+JSON.stringify(e)),this.isSurge||this.isLoon?$httpClient.get(e,i):this.isQuanX?$task.fetch(e).then(e=>{e.status=e.statusCode,i(null,e,e.body)},e=>i(e.error,null,null)):this.isNode?this.node.request.get(e,(e,t,s)=>{t=this.adapterHttpResponse(t),i(e,t,s)}):this.isJSBox&&(e.handler=e=>{var t=e.error?JSON.stringify(e.error):void 0,s="object"==typeof e.data?JSON.stringify(e.data):e.data;i(t,e.response,s)},$http.get(e))}getPromise(e){return new Promise((s,i)=>{magicJS.get(e,(e,t)=>{e?i(e):s(t)})})}post(e,i){var t,e=this.adapterHttpOptions(e,"POST");this.logDebug("HTTP POST: "+JSON.stringify(e)),this.isSurge||this.isLoon?$httpClient.post(e,i):this.isQuanX?$task.fetch(e).then(e=>{e.status=e.statusCode,i(null,e,e.body)},e=>{i(e.error,null,null)}):this.isNode?((t=this.node.request.post(e,i)).status=t.statusCode,delete t.statusCode):this.isJSBox&&(e.handler=e=>{var t=e.error?JSON.stringify(e.error):void 0,s="object"==typeof e.data?JSON.stringify(e.data):e.data;i(t,e.response,s)},$http.post(e,{}))}costTime(){var e=this.scriptName+"执行完毕！",t=(this._endTime=(new Date).getTime(),this._endTime-this._startTime);this.log(e+`耗时【${t/1e3}】秒`)}done(e={}){this.costTime(),"undefined"!=typeof $done&&$done(e)}isToday(e){var t;return null!=e&&(t=new Date,"string"==typeof e&&(e=new Date(e)),t.getFullYear()==e.getFullYear())&&t.getMonth()==e.getMonth()&&t.getDay()==e.getDay()}isNumber(e){return"NaN"!==parseFloat(e).toString()}attempt(e,t=null){return e.then(e=>[null,e]).catch(e=>(this.logError(e),[e,t]))}retry(r,n=5,a=0,h=null){return(...e)=>new Promise((s,i)=>{function o(...t){Promise.resolve().then(()=>r.apply(this,t)).then(e=>{"function"==typeof h?Promise.resolve().then(()=>h(e)).then(()=>{s(e)}).catch(e=>{1<=n?0<a?setTimeout(()=>o.apply(this,t),a):o.apply(this,t):i(e),n--}):s(e)}).catch(e=>{this.logRetry(e),1<=n&&0<a?setTimeout(()=>o.apply(this,t),a):1<=n?o.apply(this,t):i(e),n--})}o.apply(this,e)})}formatTime(e,t="yyyy-MM-dd hh:mm:ss"){var s,i={"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(s in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),i)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?i[s]:("00"+i[s]).substr((""+i[s]).length)));return t}now(){return this.formatTime(new Date,"yyyy-MM-dd hh:mm:ss")}today(){return this.formatTime(new Date,"yyyy-MM-dd")}sleep(t){return new Promise(e=>setTimeout(e,t))}objToQueryStr(t,s){let i="";for(const o in t){let e=t[o];null!=e&&""!==e&&("object"==typeof e?e=JSON.stringify(e):s&&(e=encodeURIComponent(e)),i+=`${o}=${e}&`)}return i=i.substring(0,i.length-1)}parseQueryStr(e){var t={},s=(e=-1<e.indexOf("?")?e.split("?")[1]:e).split("&");for(let e=0;e<s.length;e++){var i=s[e].split("=");t[i[0]]=i[1]}return t}deepClone(e,t){for(var s in t=t||{},e)"object"==typeof e[s]?(t[s]=e[s].constructor===Array?[]:{},this.deepClone(e[s],t[s])):t[s]=e[s];return t}convertToObject(t){if("string"!=typeof t)return t instanceof Array||null==t||t!=t||"boolean"==typeof t?{}:t;{let e={};try{var s=typeof(e=JSON.parse(t));("object"!=s||e instanceof Array||"boolean"==s||null===e)&&(e={})}catch{}return e}}}(e)}
//---SyncByPyScript---MagicJS2-end