diff --git a/jd_bean_sign.js b/jd_bean_sign.js index 096f32a..ecbf3b3 100644 --- a/jd_bean_sign.js +++ b/jd_bean_sign.js @@ -1,315 +1,2066 @@ /* -京东多合一签到,自用,可N个京东账号 -活动入口:各处的签到汇总 Node.JS专用 -IOS软件用户请使用 https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js -更新时间:2021-6-18 -推送通知默认简洁模式(多账号只发送一次)。如需详细通知,设置环境变量 JD_BEAN_SIGN_NOTIFY_SIMPLE 为false即可(N账号推送N次通知)。 -Modified From github https://github.com/ruicky/jd_sign_bot - */ -const $ = new Env('京东多合一签到'); -const notify = $.isNode() ? require('./sendNotify') : ''; -//Node.js用户请在jdCookie.js处填写京东ck; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; -const exec = require('child_process').execSync -const fs = require('fs') -const download = require('download'); -let resultPath = "./result.txt"; -let JD_DailyBonusPath = "./JD_DailyBonus.js"; -let outPutUrl = './'; -let NodeSet = 'CookieSet.json'; -let cookiesArr = [], cookie = '', allMessage = '', jrBodyArr = [], jrBody = ''; +cron 0 0 * * * jd_bean_sign.js +金融签到有一定使用门槛,需要请仔细阅读下方文字: +JRBODY抓取网站:ms.jr.jd.com/gw/generic/hy/h5/m/appSign(进入金融APP签到页面手动签到);抓取请求body,格式:"reqData=xxx" +变量填写示例:JRBODY: reqData=xxx&reqData=xxx&&reqData=xxx(比如第三个号没有,则留空,长度要与CK一致) -if ($.isNode()) { - Object.keys(jdCookieNode).forEach((item) => { - cookiesArr.push(jdCookieNode[item]) +强烈建议用文件,环境变量太长了 +云函数用户在config分支新建diy/JRBODY.txt即可(也就是diy文件夹下新建JRBODY.txt).每行一个jrbody,结尾行写'Finish' +例子: +reqData=xxx +(这个号没有,这行空着) +reqData=xxx +Finish + +其他环境用户除了JRBODY环境变量可以选用JRBODY.txt文件,放在同目录下,格式同上. +注:优先识别环境变量,如使用txt文件请不要设置环境变量.JRBODY换行符(应为unix换行符)可能影响脚本读取! + +出现任何问题请先删除CookieSet.json(云函数不用操作) +云函数提示写入失败正常,无任何影响 + */ +console.log('京东多合一签到SCF开始') +const sendNotify = require('./sendNotify.js').sendNotify +const fs = require('fs') +const jr_file = 'JRBODY.txt' +const readline = require('readline') +let cookiesArr = [] +let notification = '' +const stopVar = process.env.JD_BEAN_STOP ? process.env.JD_BEAN_STOP : '2000-5000'; +console.log('Stop:',stopVar) + +async function processLineByLine(jrbodys) { + const fileStream = fs.createReadStream(jr_file) + const rl = readline.createInterface({ + input: fileStream, + crlfDelay: Infinity }) - if (process.env.JD_BEAN_SIGN_BODY) { - if (process.env.JD_BEAN_SIGN_BODY.indexOf('&') > -1) { - jrBodyArr = process.env.JD_BEAN_SIGN_BODY.split('&'); - } else if (process.env.JD_BEAN_SIGN_BODY.indexOf('\n') > -1) { - jrBodyArr = process.env.JD_BEAN_SIGN_BODY.split('\n'); - } else { - jrBodyArr = [process.env.JD_BEAN_SIGN_BODY]; + for await (let line of rl) { + line = line.trim() + if (line == 'Finish'){ + console.log(`识别到读取结束符号,结束.共读取${jrbodys.length}个`) + return + } + jrbodys.push(line) + } +} +(async () => { + const jdCookieNode = require('./jdCookie.js') + Object.keys(jdCookieNode).forEach((item) => { + let ck = jdCookieNode[item].trim() + if(ck.substring(ck.length-1) !== ';'){ + ck = ck + ';' + } + cookiesArr.push(ck) + }) + let jrbodys = [] + if(process.env.JRBODY) { + jrbodys = process.env.JRBODY.split('&') + }else{ + console.log(`未检测到JRBODY环境变量,开始检测${jr_file}`) + try { + await fs.accessSync('./'+jr_file, fs.constants.F_OK) + console.log(`${jr_file} '存在,读取配置'`) + await processLineByLine(jrbodys) + } catch (err) { + console.log(`${jr_file} '不存在,跳过'`) } } - if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => {}; -} -!(async() => { - if (!cookiesArr[0]) { - $.msg($.name, '【提示】请先获取cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', {"open-url": "https://bean.m.jd.com/bean/signIndex.action"}); - return; + if (jrbodys.length != cookiesArr.length) { + console.error(`CK和JRBODY长度不匹配,不使用JRBODY,请阅读脚本开头说明.当前ck长度:${cookiesArr.length},JRBODY长度:${jrbodys.length}`) + jrbodys = undefined } - process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE = process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE ? process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE : 'true'; - await requireConfig(); - // 下载最新代码 - await downFile(); - if (!await fs.existsSync(JD_DailyBonusPath)) { - console.log(`\nJD_DailyBonus.js 文件不存在,停止执行${$.name}\n`); - await notify.sendNotify($.name, `本次执行${$.name}失败,JD_DailyBonus.js 文件下载异常,详情请查看日志`) - return - } - const content = await fs.readFileSync(JD_DailyBonusPath, 'utf8') for (let i = 0; i < cookiesArr.length; i++) { - cookie = cookiesArr[i]; - if (cookie) { - $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]) - $.index = i + 1; - $.nickName = ''; - $.isLogin = true; - await TotalBean(); - console.log(`*****************开始京东账号${$.index} ${$.nickName || $.UserName}京豆签到*******************\n`); - if (!$.isLogin) { - $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, {"open-url": "https://bean.m.jd.com/bean/signIndex.action"}); - if ($.isNode()) { - await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); - } - continue + const data = { + 'cookie':cookiesArr[i] + } + if (jrbodys) { + if(jrbodys[i].startsWith('reqData=')){ + data['jrBody'] = jrbodys[i] + }else{ + console.log(`跳过第${i+1}个JRBODY,为空或格式不正确`) } - jrBody = '' - if (jrBodyArr && jrBodyArr.length) { - for (let key in Object.keys(jrBodyArr)) { - let vo = JSON.parse(jrBodyArr[key]) - if (decodeURIComponent(vo.pin) == $.UserName) { - jrBody = vo.body || '' + } + cookiesArr[i] = data + } + console.log('main block finished') +})() +.then(() => { +console.log('Nobyda签到部分开始') +/************************* + +京东多合一签到脚本 + +更新时间: 2021.09.09 20:20 v2.1.3 +有效接口: 20+ +脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js +电报频道: @NobyDa +问题反馈: @NobyDa_bot +如果转载: 请注明出处 + +************************* +【 QX, Surge, Loon 说明 】 : +************************* + +初次使用时, app配置文件添加脚本配置, 并启用Mitm后: + +Safari浏览器打开登录 https://home.m.jd.com/myJd/newhome.action 点击"我的"页面 +或者使用旧版网址 https://bean.m.jd.com/bean/signIndex.action 点击签到并且出现签到日历 +如果通知获取Cookie成功, 则可以使用此签到脚本. 注: 请勿在京东APP内获取!!! + +获取京东金融签到Body说明: 正确添加脚本配置后, 进入"京东金融"APP, 在"首页"点击"签到"并签到一次, 待通知提示成功即可. + +由于cookie的有效性(经测试网页Cookie有效周期最长31天),如果脚本后续弹出cookie无效的通知,则需要重复上述步骤。 +签到脚本将在每天的凌晨0:05执行, 您可以修改执行时间。 因部分接口京豆限量领取, 建议调整为凌晨签到。 + +BoxJs或QX Gallery订阅地址: https://raw.githubusercontent.com/NobyDa/Script/master/NobyDa_BoxJs.json + +************************* +【 配置多京东账号签到说明 】 : +************************* + +正确配置QX、Surge、Loon后, 并使用此脚本获取"账号1"Cookie成功后, 请勿点击退出账号(可能会导致Cookie失效), 需清除浏览器资料或更换浏览器登录"账号2"获取即可; 账号3或以上同理. +注: 如需清除所有Cookie, 您可开启脚本内"DeleteCookie"选项 (第114行) + +************************* +【 JSbox, Node.js 说明 】 : +************************* + +开启抓包app后, Safari浏览器登录 https://home.m.jd.com/myJd/newhome.action 点击个人中心页面后, 返回抓包app搜索关键字 info/GetJDUserInfoUnion 复制请求头Cookie字段填入json串数据内即可 + +如需获取京东金融签到Body, 可进入"京东金融"APP (iOS), 在"首页"点击"签到"并签到一次, 返回抓包app搜索关键字 h5/m/appSign 复制请求体填入json串数据内即可 +*/ + +var Key = ''; //该参数已废弃; 仅用于下游脚本的兼容, 请使用json串数据 ↓ + +var DualKey = ''; //该参数已废弃; 仅用于下游脚本的兼容, 请使用json串数据 ↓ + +var OtherKey = JSON.stringify(cookiesArr); //无限账号Cookie json串数据, 请严格按照json格式填写, 具体格式请看以下样例: + +/*以下样例为双账号("cookie"为必须,其他可选), 第一个账号仅包含Cookie, 第二个账号包含Cookie和金融签到Body: + +var OtherKey = `[{ + "cookie": "pt_key=xxx;pt_pin=yyy;" +}, { + "cookie": "pt_key=yyy;pt_pin=xxx;", + "jrBody": "reqData=xxx" +}]` + + 注1: 以上选项仅针对于JsBox或Node.js, 如果使用QX,Surge,Loon, 请使用脚本获取Cookie. + 注2: 多账号用户抓取"账号1"Cookie后, 请勿点击退出账号(可能会导致Cookie失效), 需清除浏览器资料或更换浏览器登录"账号2"抓取. + 注3: 如果使用Node.js, 需自行安装'request'模块. 例: npm install request -g + 注4: Node.js或JSbox环境下已配置数据持久化, 填写Cookie运行一次后, 后续更新脚本无需再次填写, 待Cookie失效后重新抓取填写即可. + 注5: 脚本将自动处理"持久化数据"和"手动填写cookie"之间的重复关系, 例如填写多个账号Cookie后, 后续其中一个失效, 仅需填写该失效账号的新Cookie即可, 其他账号不会被清除. + +************************* +【Surge 4.2+ 脚本配置】: +************************* + +[Script] +京东多合一签到 = type=cron,cronexp=5 0 * * *,wake-system=1,timeout=60,script-path=https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +获取京东Cookie = type=http-request,requires-body=1,pattern=^https:\/\/(api\.m|me-api|ms\.jr)\.jd\.com\/(client\.action\?functionId=signBean|user_new\/info\/GetJDUserInfoUnion\?|gw\/generic\/hy\/h5\/m\/appSign\?),script-path=https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +[MITM] +hostname = ms.jr.jd.com, me-api.jd.com, api.m.jd.com + +************************* +【Loon 2.1+ 脚本配置】: +************************* + +[Script] +cron "5 0 * * *" tag=京东多合一签到, script-path=https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +http-request ^https:\/\/(api\.m|me-api|ms\.jr)\.jd\.com\/(client\.action\?functionId=signBean|user_new\/info\/GetJDUserInfoUnion\?|gw\/generic\/hy\/h5\/m\/appSign\?) tag=获取京东Cookie, requires-body=true, script-path=https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +[MITM] +hostname = ms.jr.jd.com, me-api.jd.com, api.m.jd.com + +************************* +【 QX 1.0.10+ 脚本配置 】 : +************************* + +[task_local] +# 京东多合一签到 +5 0 * * * https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js, tag=京东多合一签到, img-url=https://raw.githubusercontent.com/NobyDa/mini/master/Color/jd.png,enabled=true + +[rewrite_local] +# 获取京东Cookie. +^https:\/\/(api\.m|me-api)\.jd\.com\/(client\.action\?functionId=signBean|user_new\/info\/GetJDUserInfoUnion\?) url script-request-header https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +# 获取钢镚签到body. +^https:\/\/ms\.jr\.jd\.com\/gw\/generic\/hy\/h5\/m\/appSign\? url script-request-body https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js + +[mitm] +hostname = ms.jr.jd.com, me-api.jd.com, api.m.jd.com + +*************************/ + +var LogDetails = false; //是否开启响应日志, true则开启 + +var stop = stopVar; //自定义延迟签到, 单位毫秒. 默认分批并发无延迟; 该参数接受随机或指定延迟(例: '2000'则表示延迟2秒; '2000-5000'则表示延迟最小2秒,最大5秒内的随机延迟), 如填入延迟则切换顺序签到(耗时较长), Surge用户请注意在SurgeUI界面调整脚本超时; 注: 该参数Node.js或JSbox环境下已配置数据持久化, 留空(var stop = '')即可清除. + +var DeleteCookie = false; //是否清除所有Cookie, true则开启. + +var boxdis = true; //是否开启自动禁用, false则关闭. 脚本运行崩溃时(如VPN断连), 下次运行时将自动禁用相关崩溃接口(仅部分接口启用), 崩溃时可能会误禁用正常接口. (该选项仅适用于QX,Surge,Loon) + +var ReDis = false; //是否移除所有禁用列表, true则开启. 适用于触发自动禁用后, 需要再次启用接口的情况. (该选项仅适用于QX,Surge,Loon) + +var out = 0; //接口超时退出, 用于可能发生的网络不稳定, 0则关闭. 如QX日志出现大量"JS Context timeout"后脚本中断时, 建议填写6000 + +var $nobyda = nobyda(); + +var merge = {}; + +var KEY = ''; + +async function all(cookie, jrBody) { + KEY = cookie; + merge = {}; + $nobyda.num++; + switch (stop) { + case 0: + await Promise.all([ + JingDongBean(stop), //京东京豆 + // JingDongStore(stop), //京东超市 + JingRongSteel(stop, jrBody), //金融钢镚 + // JingDongTurn(stop), //京东转盘 + // JDFlashSale(stop), //京东闪购 + // JingDongCash(stop), //京东现金红包 + // JDMagicCube(stop, 2), //京东小魔方 + // JingDongSubsidy(stop), //京东金贴 + JingDongGetCash(stop), //京东领现金 + // JingDongShake(stop), //京东摇一摇 + JDSecKilling(stop), //京东秒杀 + // JingRongDoll(stop, 'JRDoll', '京东金融-签壹', '4D25A6F482'), + // JingRongDoll(stop, 'JRThreeDoll', '京东金融-签叁', '69F5EC743C'), + // JingRongDoll(stop, 'JRFourDoll', '京东金融-签肆', '30C4F86264'), + // JingRongDoll(stop, 'JRFiveDoll', '京东金融-签伍', '1D06AA3B0F') + ]); + await Promise.all([ + // JDUserSignPre(stop, 'JDUndies', '京东商城-内衣', '4PgpL1xqPSW1sVXCJ3xopDbB1f69'), //京东内衣馆 + // JDUserSignPre(stop, 'JDCard', '京东商城-卡包', '7e5fRnma6RBATV9wNrGXJwihzcD'), //京东卡包 + // JDUserSignPre(stop, 'JDCustomized', '京东商城-定制', '2BJK5RBdvc3hdddZDS1Svd5Esj3R'), //京东定制 + // JDUserSignPre(stop, 'JDaccompany', '京东商城-陪伴', 'kPM3Xedz1PBiGQjY4ZYGmeVvrts'), //京东陪伴 + // JDUserSignPre(stop, 'JDShoes', '京东商城-鞋靴', '4RXyb1W4Y986LJW8ToqMK14BdTD'), //京东鞋靴 + // JDUserSignPre(stop, 'JDChild', '京东商城-童装', '3Af6mZNcf5m795T8dtDVfDwWVNhJ'), //京东童装馆 + // JDUserSignPre(stop, 'JDBaby', '京东商城-母婴', '3BbAVGQPDd6vTyHYjmAutXrKAos6'), //京东母婴馆 + // JDUserSignPre(stop, 'JD3C', '京东商城-数码', '4SWjnZSCTHPYjE5T7j35rxxuMTb6'), //京东数码电器馆 + // JDUserSignPre(stop, 'JDWomen', '京东商城-女装', 'DpSh7ma8JV7QAxSE2gJNro8Q2h9'), //京东女装馆 + // JDUserSignPre(stop, 'JDBook', '京东商城-图书', '3SC6rw5iBg66qrXPGmZMqFDwcyXi'), //京东图书 + // JDUserSignPre(stop, 'ReceiveJD', '京东商城-领豆', 'Ni5PUSK7fzZc4EKangHhqPuprn2'), //京东-领京豆 + JingRongDoll(stop, 'JTDouble', '京东金贴-双签', '1DF13833F7'), //京东金融 金贴双签 + // JingRongDoll(stop, 'XJDouble', '金融现金-双签', 'F68B2C3E71', '', '', '', 'xianjin') //京东金融 现金双签 + ]); + await Promise.all([ + // JDUserSignPre(stop, 'JDStory', '京东失眠-补贴', 'UcyW9Znv3xeyixW1gofhW2DAoz4'), //失眠补贴 + // JDUserSignPre(stop, 'JDPhone', '京东手机-小时', '4Vh5ybVr98nfJgros5GwvXbmTUpg'), //手机小时达 + // JDUserSignPre(stop, 'JDEsports', '京东商城-电竞', 'CHdHQhA5AYDXXQN9FLt3QUAPRsB'), //京东电竞 + // JDUserSignPre(stop, 'JDClothing', '京东商城-服饰', '4RBT3H9jmgYg1k2kBnHF8NAHm7m8'), //京东服饰 + // JDUserSignPre(stop, 'JDSuitcase', '京东商城-箱包', 'ZrH7gGAcEkY2gH8wXqyAPoQgk6t'), //京东箱包馆 + // JDUserSignPre(stop, 'JDSchool', '京东商城-校园', '2QUxWHx5BSCNtnBDjtt5gZTq7zdZ'), //京东校园 + // JDUserSignPre(stop, 'JDHealth', '京东商城-健康', 'w2oeK5yLdHqHvwef7SMMy4PL8LF'), //京东健康 + // JDUserSignPre(stop, 'JDShand', '京东拍拍-二手', '3S28janPLYmtFxypu37AYAGgivfp'), //京东拍拍二手 + // JDUserSignPre(stop, 'JDClean', '京东商城-清洁', '2Tjm6ay1ZbZ3v7UbriTj6kHy9dn6'), //京东清洁馆 + // JDUserSignPre(stop, 'JDCare', '京东商城-个护', '2tZssTgnQsiUqhmg5ooLSHY9XSeN'), //京东个人护理馆 + // JDUserSignPre(stop, 'JDJiaDian', '京东商城-家电', '3uvPyw1pwHARGgndatCXddLNUxHw'), // 京东小家电 + // JDUserSignPre(stop, 'JDJewels', '京东商城-珠宝', 'zHUHpTHNTaztSRfNBFNVZscyFZU'), //京东珠宝馆 + // JDUserSignPre(stop, 'JDMakeup', '京东商城-美妆', '2smCxzLNuam5L14zNJHYu43ovbAP'), //京东美妆馆 + // JDUserSignPre(stop, 'JDVege', '京东商城-菜场', 'Wcu2LVCFMkBP3HraRvb7pgSpt64'), //京东菜场 + // JDUserSignPre(stop, 'JDLive', '京东智能-生活', 'KcfFqWvhb5hHtaQkS4SD1UU6RcQ') //京东智能生活 + ]); + await JingRongDoll(stop, 'JDDouble', '金融京豆-双签', 'F68B2C3E71', '', '', '', 'jingdou'); //京东金融 京豆双签 + break; + default: + await JingDongBean(0); //京东京豆 + // await JingDongStore(Wait(stop)); //京东超市 + await JingRongSteel(Wait(stop), jrBody); //金融钢镚 + // await JingDongTurn(Wait(stop)); //京东转盘 + // await JDFlashSale(Wait(stop)); //京东闪购 + // await JingDongCash(Wait(stop)); //京东现金红包 + // await JDMagicCube(Wait(stop), 2); //京东小魔方 + await JingDongGetCash(Wait(stop)); //京东领现金 + // await JingDongSubsidy(Wait(stop)); //京东金贴 + // await JingDongShake(Wait(stop)); //京东摇一摇 + await JDSecKilling(Wait(stop)); //京东秒杀 + // await JingRongDoll(Wait(stop), 'JRThreeDoll', '京东金融-签叁', '69F5EC743C'); + // await JingRongDoll(Wait(stop), 'JRFourDoll', '京东金融-签肆', '30C4F86264'); + // await JingRongDoll(Wait(stop), 'JRFiveDoll', '京东金融-签伍', '1D06AA3B0F'); + // await JingRongDoll(Wait(stop), 'JRDoll', '京东金融-签壹', '4D25A6F482'); + // await JingRongDoll(Wait(stop), 'XJDouble', '金融现金-双签', 'F68B2C3E71', '', '', '', 'xianjin'); //京东金融 现金双签 + await JingRongDoll(Wait(stop), 'JTDouble', '京东金贴-双签', '1DF13833F7'); //京东金融 金贴双签 + // await JDUserSignPre(Wait(stop), 'JDStory', '京东失眠-补贴', 'UcyW9Znv3xeyixW1gofhW2DAoz4'); //失眠补贴 + // await JDUserSignPre(Wait(stop), 'JDPhone', '京东手机-小时', '4Vh5ybVr98nfJgros5GwvXbmTUpg'); //手机小时达 + // await JDUserSignPre(Wait(stop), 'JDCard', '京东商城-卡包', '7e5fRnma6RBATV9wNrGXJwihzcD'); //京东卡包 + // await JDUserSignPre(Wait(stop), 'JDUndies', '京东商城-内衣', '4PgpL1xqPSW1sVXCJ3xopDbB1f69'); //京东内衣馆 + // await JDUserSignPre(Wait(stop), 'JDEsports', '京东商城-电竞', 'CHdHQhA5AYDXXQN9FLt3QUAPRsB'); //京东电竞 + // await JDUserSignPre(Wait(stop), 'JDCustomized', '京东商城-定制', '2BJK5RBdvc3hdddZDS1Svd5Esj3R'); //京东定制 + // await JDUserSignPre(Wait(stop), 'JDSuitcase', '京东商城-箱包', 'ZrH7gGAcEkY2gH8wXqyAPoQgk6t'); //京东箱包馆 + // await JDUserSignPre(Wait(stop), 'JDClothing', '京东商城-服饰', '4RBT3H9jmgYg1k2kBnHF8NAHm7m8'); //京东服饰 + // await JDUserSignPre(Wait(stop), 'JDSchool', '京东商城-校园', '2QUxWHx5BSCNtnBDjtt5gZTq7zdZ'); //京东校园 + // await JDUserSignPre(Wait(stop), 'JDHealth', '京东商城-健康', 'w2oeK5yLdHqHvwef7SMMy4PL8LF'); //京东健康 + // await JDUserSignPre(Wait(stop), 'JDShoes', '京东商城-鞋靴', '4RXyb1W4Y986LJW8ToqMK14BdTD'); //京东鞋靴 + // await JDUserSignPre(Wait(stop), 'JDChild', '京东商城-童装', '3Af6mZNcf5m795T8dtDVfDwWVNhJ'); //京东童装馆 + // await JDUserSignPre(Wait(stop), 'JDBaby', '京东商城-母婴', '3BbAVGQPDd6vTyHYjmAutXrKAos6'); //京东母婴馆 + // await JDUserSignPre(Wait(stop), 'JD3C', '京东商城-数码', '4SWjnZSCTHPYjE5T7j35rxxuMTb6'); //京东数码电器馆 + // await JDUserSignPre(Wait(stop), 'JDWomen', '京东商城-女装', 'DpSh7ma8JV7QAxSE2gJNro8Q2h9'); //京东女装馆 + // await JDUserSignPre(Wait(stop), 'JDBook', '京东商城-图书', '3SC6rw5iBg66qrXPGmZMqFDwcyXi'); //京东图书 + // await JDUserSignPre(Wait(stop), 'JDShand', '京东拍拍-二手', '3S28janPLYmtFxypu37AYAGgivfp'); //京东拍拍二手 + // await JDUserSignPre(Wait(stop), 'JDMakeup', '京东商城-美妆', '2smCxzLNuam5L14zNJHYu43ovbAP'); //京东美妆馆 + // await JDUserSignPre(Wait(stop), 'JDVege', '京东商城-菜场', 'Wcu2LVCFMkBP3HraRvb7pgSpt64'); //京东菜场 + // await JDUserSignPre(Wait(stop), 'JDaccompany', '京东商城-陪伴', 'kPM3Xedz1PBiGQjY4ZYGmeVvrts'); //京东陪伴 + // await JDUserSignPre(Wait(stop), 'JDLive', '京东智能-生活', 'KcfFqWvhb5hHtaQkS4SD1UU6RcQ'); //京东智能生活 + // await JDUserSignPre(Wait(stop), 'JDClean', '京东商城-清洁', '2Tjm6ay1ZbZ3v7UbriTj6kHy9dn6'); //京东清洁馆 + // await JDUserSignPre(Wait(stop), 'JDCare', '京东商城-个护', '2tZssTgnQsiUqhmg5ooLSHY9XSeN'); //京东个人护理馆 + // await JDUserSignPre(Wait(stop), 'JDJiaDian', '京东商城-家电', '3uvPyw1pwHARGgndatCXddLNUxHw'); // 京东小家电馆 + // await JDUserSignPre(Wait(stop), 'ReceiveJD', '京东商城-领豆', 'Ni5PUSK7fzZc4EKangHhqPuprn2'); //京东-领京豆 + // await JDUserSignPre(Wait(stop), 'JDJewels', '京东商城-珠宝', 'zHUHpTHNTaztSRfNBFNVZscyFZU'); //京东珠宝馆 + await JingRongDoll(Wait(stop), 'JDDouble', '金融京豆-双签', 'F68B2C3E71', '', '', '', 'jingdou'); //京东金融 京豆双签 + break; + } + await Promise.all([ + TotalSteel(), //总钢镚查询 + TotalCash(), //总红包查询 + TotalBean(), //总京豆查询 + TotalSubsidy(), //总金贴查询 + TotalMoney() //总现金查询 + ]); + await notify(); //通知模块 +} + +function notify() { + return new Promise(resolve => { + try { + var bean = 0; + var steel = 0; + var cash = 0; + var money = 0; + var subsidy = 0; + var success = 0; + var fail = 0; + var err = 0; + var notify = ''; + for (var i in merge) { + bean += merge[i].bean ? Number(merge[i].bean) : 0 + steel += merge[i].steel ? Number(merge[i].steel) : 0 + cash += merge[i].Cash ? Number(merge[i].Cash) : 0 + money += merge[i].Money ? Number(merge[i].Money) : 0 + subsidy += merge[i].subsidy ? Number(merge[i].subsidy) : 0 + success += merge[i].success ? Number(merge[i].success) : 0 + fail += merge[i].fail ? Number(merge[i].fail) : 0 + err += merge[i].error ? Number(merge[i].error) : 0 + notify += merge[i].notify ? "\n" + merge[i].notify : "" + } + var Cash = merge.TotalCash && merge.TotalCash.TCash ? `${merge.TotalCash.TCash}红包` : "" + var Steel = merge.TotalSteel && merge.TotalSteel.TSteel ? `${merge.TotalSteel.TSteel}钢镚` : `` + var beans = merge.TotalBean && merge.TotalBean.Qbear ? `${merge.TotalBean.Qbear}京豆${Steel?`, `:``}` : "" + var Money = merge.TotalMoney && merge.TotalMoney.TMoney ? `${merge.TotalMoney.TMoney}现金${Cash?`, `:``}` : "" + var Subsidy = merge.TotalSubsidy && merge.TotalSubsidy.TSubsidy ? `${merge.TotalSubsidy.TSubsidy}金贴${Money||Cash?", ":""}` : "" + var Tbean = bean ? `${bean.toFixed(0)}京豆${steel?", ":""}` : "" + var TSteel = steel ? `${steel.toFixed(2)}钢镚` : "" + var TCash = cash ? `${cash.toFixed(2)}红包${subsidy||money?", ":""}` : "" + var TSubsidy = subsidy ? `${subsidy.toFixed(2)}金贴${money?", ":""}` : "" + var TMoney = money ? `${money.toFixed(2)}现金` : "" + var Ts = success ? `成功${success}个${fail||err?`, `:``}` : `` + var Tf = fail ? `失败${fail}个${err?`, `:``}` : `` + var Te = err ? `错误${err}个` : `` + var one = `【签到概览】: ${Ts+Tf+Te}${Ts||Tf||Te?`\n`:`获取失败\n`}` + var two = Tbean || TSteel ? `【签到奖励】: ${Tbean+TSteel}\n` : `` + var three = TCash || TSubsidy || TMoney ? `【其他奖励】: ${TCash+TSubsidy+TMoney}\n` : `` + var four = `【账号总计】: ${beans+Steel}${beans||Steel?`\n`:`获取失败\n`}` + var five = `【其他总计】: ${Subsidy+Money+Cash}${Subsidy||Money||Cash?`\n`:`获取失败\n`}` + var DName = merge.TotalBean && merge.TotalBean.nickname ? merge.TotalBean.nickname : "获取失败" + var cnNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]; + const Name = DualKey || OtherKey.length > 1 ? `【签到号${cnNum[$nobyda.num]||$nobyda.num}】: ${DName}\n` : `` + const disables = $nobyda.read("JD_DailyBonusDisables") + const amount = disables ? disables.split(",").length : 0 + const disa = !notify || amount ? `【温馨提示】: 检测到${$nobyda.disable?`上次执行意外崩溃, `:``}已禁用${notify?`${amount}个`:`所有`}接口, 如需开启请前往BoxJs或查看脚本内第118行注释.\n` : `` + $nobyda.notify("", "", Name + one + two + three + four + five + disa, { + 'media-url': $nobyda.headUrl || 'https://cdn.jsdelivr.net/gh/NobyDa/mini@master/Color/jd.png' + }); + $nobyda.headUrl = null; + if ($nobyda.isJSBox) { + $nobyda.st = (typeof($nobyda.st) == 'undefined' ? '' : $nobyda.st) + Name + one + two + three + four + five + "\n" + } + } catch (eor) { + $nobyda.notify("通知模块 " + eor.name + "‼️", JSON.stringify(eor), eor.message) + } finally { + resolve() + } + }); +} + +(async function ReadCookie() { + const EnvInfo = $nobyda.isJSBox ? "JD_Cookie" : "CookieJD"; + const EnvInfo2 = $nobyda.isJSBox ? "JD_Cookie2" : "CookieJD2"; + const EnvInfo3 = $nobyda.isJSBox ? "JD_Cookies" : "CookiesJD"; + const move = CookieMove($nobyda.read(EnvInfo) || Key, $nobyda.read(EnvInfo2) || DualKey, EnvInfo, EnvInfo2, EnvInfo3); + const cookieSet = $nobyda.read(EnvInfo3); + if (DeleteCookie) { + const write = $nobyda.write("", EnvInfo3); + throw new Error(`Cookie清除${write?`成功`:`失败`}, 请手动关闭脚本内"DeleteCookie"选项`); + } else if ($nobyda.isRequest) { + GetCookie() + } else if (Key || DualKey || (OtherKey || cookieSet || '[]') != '[]') { + if (($nobyda.isJSBox || $nobyda.isNode) && stop !== '0') $nobyda.write(stop, "JD_DailyBonusDelay"); + out = parseInt($nobyda.read("JD_DailyBonusTimeOut")) || out; + stop = Wait($nobyda.read("JD_DailyBonusDelay"), true) || Wait(stop, true); + boxdis = $nobyda.read("JD_Crash_disable") === "false" || $nobyda.isNode || $nobyda.isJSBox ? false : boxdis; + LogDetails = $nobyda.read("JD_DailyBonusLog") === "true" || LogDetails; + ReDis = ReDis ? $nobyda.write("", "JD_DailyBonusDisables") : ""; + $nobyda.num = 0; + if (Key) await all(Key); + if (DualKey && DualKey !== Key) await all(DualKey); + if ((OtherKey || cookieSet || '[]') != '[]') { + try { + OtherKey = checkFormat([...JSON.parse(OtherKey || '[]'), ...JSON.parse(cookieSet || '[]')]); + const updateSet = OtherKey.length ? $nobyda.write(JSON.stringify(OtherKey, null, 2), EnvInfo3) : ''; + for (let i = 0; i < OtherKey.length; i++) { + const ck = OtherKey[i].cookie; + const jr = OtherKey[i].jrBody; + if (ck != Key && ck != DualKey) { + await all(ck, jr) + } + } + } catch (e) { + throw new Error(`账号Cookie读取失败, 请检查Json格式. \n${e.message}`) + } + } + sendNotify("京东多合一签到SCF:",notification) + $nobyda.time(); + } else { + throw new Error('脚本终止, 未获取Cookie ‼️') + } +})().catch(e => { + $nobyda.notify("京东签到", "", e.message || JSON.stringify(e)) +}).finally(() => { + if ($nobyda.isJSBox) $intents.finish($nobyda.st); + $nobyda.done(); +}) + +function JingDongBean(s) { + merge.JDBean = {}; + return new Promise(resolve => { + if (disable("JDBean")) return resolve() + setTimeout(() => { + const JDBUrl = { + url: 'https://api.m.jd.com/client.action', + headers: { + Cookie: KEY + }, + body: 'functionId=signBeanIndex&appid=ld' + }; + $nobyda.post(JDBUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.code == 3) { + console.log("\n" + "京东商城-京豆Cookie失效 " + Details) + merge.JDBean.notify = "京东商城-京豆: 失败, 原因: Cookie失效‼️" + merge.JDBean.fail = 1 + } else if (data.match(/跳转至拼图/)) { + merge.JDBean.notify = "京东商城-京豆: 失败, 需要拼图验证 ⚠️" + merge.JDBean.fail = 1 + } else if (data.match(/\"status\":\"?1\"?/)) { + console.log("\n" + "京东商城-京豆签到成功 " + Details) + if (data.match(/dailyAward/)) { + merge.JDBean.notify = "京东商城-京豆: 成功, 明细: " + cc.data.dailyAward.beanAward.beanCount + "京豆 🐶" + merge.JDBean.bean = cc.data.dailyAward.beanAward.beanCount + } else if (data.match(/continuityAward/)) { + merge.JDBean.notify = "京东商城-京豆: 成功, 明细: " + cc.data.continuityAward.beanAward.beanCount + "京豆 🐶" + merge.JDBean.bean = cc.data.continuityAward.beanAward.beanCount + } else if (data.match(/新人签到/)) { + const quantity = data.match(/beanCount\":\"(\d+)\".+今天/) + merge.JDBean.bean = quantity ? quantity[1] : 0 + merge.JDBean.notify = "京东商城-京豆: 成功, 明细: " + (quantity ? quantity[1] : "无") + "京豆 🐶" + } else { + merge.JDBean.notify = "京东商城-京豆: 成功, 明细: 无京豆 🐶" + } + merge.JDBean.success = 1 + } else { + merge.JDBean.fail = 1 + console.log("\n" + "京东商城-京豆签到失败 " + Details) + if (data.match(/(已签到|新人签到)/)) { + merge.JDBean.notify = "京东商城-京豆: 失败, 原因: 已签过 ⚠️" + } else if (data.match(/人数较多|S101/)) { + merge.JDBean.notify = "京东商城-京豆: 失败, 签到人数较多 ⚠️" + } else { + merge.JDBean.notify = "京东商城-京豆: 失败, 原因: 未知 ⚠️" + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-京豆", "JDBean", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +// function JingDongTurn(s) { +// merge.JDTurn = {}, merge.JDTurn.notify = "", merge.JDTurn.success = 0, merge.JDTurn.bean = 0; +// return new Promise((resolve, reject) => { +// if (disable("JDTurn")) return reject() +// const JDTUrl = { +// url: 'https://api.m.jd.com/client.action?functionId=wheelSurfIndex&body=%7B%22actId%22%3A%22jgpqtzjhvaoym%22%2C%22appSource%22%3A%22jdhome%22%7D&appid=ld', +// headers: { +// Cookie: KEY, +// } +// }; +// $nobyda.get(JDTUrl, async function(error, response, data) { +// try { +// if (error) { +// throw new Error(error) +// } else { +// const cc = JSON.parse(data) +// const Details = LogDetails ? "response:\n" + data : ''; +// if (cc.data && cc.data.lotteryCode) { +// console.log("\n" + "京东商城-转盘查询成功 " + Details) +// return resolve(cc.data.lotteryCode) +// } else { +// merge.JDTurn.notify = "京东商城-转盘: 失败, 原因: 查询错误 ⚠️" +// merge.JDTurn.fail = 1 +// console.log("\n" + "京东商城-转盘查询失败 " + Details) +// } +// } +// } catch (eor) { +// $nobyda.AnError("京东转盘-查询", "JDTurn", eor, response, data) +// } finally { +// reject() +// } +// }) +// if (out) setTimeout(reject, out + s) +// }).then(data => { +// return JingDongTurnSign(s, data); +// }, () => {}); +// } + +function JingDongTurn(s) { + if (!merge.JDTurn) merge.JDTurn = {}, merge.JDTurn.notify = "", merge.JDTurn.success = 0, merge.JDTurn.bean = 0; + return new Promise(resolve => { + if (disable("JDTurn")) return resolve(); + setTimeout(() => { + const JDTUrl = { + url: `https://api.m.jd.com/client.action?functionId=babelGetLottery`, + headers: { + Cookie: KEY + }, + body: 'body=%7B%22enAwardK%22%3A%2295d235f2a09578c6613a1a029b26d12d%22%2C%22riskParam%22%3A%7B%7D%7D&client=wh5' + }; + $nobyda.post(JDTUrl, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + const also = merge.JDTurn.notify ? true : false + if (cc.code == 3) { + console.log("\n" + "京东转盘Cookie失效 " + Details) + merge.JDTurn.notify = "京东商城-转盘: 失败, 原因: Cookie失效‼️" + merge.JDTurn.fail = 1 + } else if (data.match(/(\"T216\"|活动结束)/)) { + merge.JDTurn.notify = "京东商城-转盘: 失败, 原因: 活动结束 ⚠️" + merge.JDTurn.fail = 1 + } else if (data.match(/\d+京豆/)) { + console.log("\n" + "京东商城-转盘签到成功 " + Details) + merge.JDTurn.bean += (cc.prizeName && cc.prizeName.split(/(\d+)/)[1]) || 0 + merge.JDTurn.notify += `${also?`\n`:``}京东商城-转盘: ${also?`多次`:`成功`}, 明细: ${merge.JDTurn.bean||`无`}京豆 🐶` + merge.JDTurn.success += 1 + if (cc.chances > 0) { + await JingDongTurnSign(2000) + } + } else if (data.match(/未中奖|擦肩而过/)) { + merge.JDTurn.notify += `${also?`\n`:``}京东商城-转盘: ${also?`多次`:`成功`}, 状态: 未中奖 🐶` + merge.JDTurn.success += 1 + if (cc.chances > 0) { + await JingDongTurnSign(2000) + } + } else { + console.log("\n" + "京东商城-转盘签到失败 " + Details) + merge.JDTurn.fail = 1 + if (data.match(/(机会已用完|次数为0)/)) { + merge.JDTurn.notify = "京东商城-转盘: 失败, 原因: 已转过 ⚠️" + } else if (data.match(/(T210|密码)/)) { + merge.JDTurn.notify = "京东商城-转盘: 失败, 原因: 无支付密码 ⚠️" + } else { + merge.JDTurn.notify += `${also?`\n`:``}京东商城-转盘: 失败, 原因: 未知 ⚠️${also?` (多次)`:``}` + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-转盘", "JDTurn", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingRongSteel(s, body) { + merge.JRSteel = {}; + return new Promise(resolve => { + if (disable("JRSteel")) return resolve(); + if (!body) { + merge.JRSteel.fail = 1; + merge.JRSteel.notify = "京东金融-钢镚: 失败, 未获取签到Body ⚠️"; + return resolve(); + } + setTimeout(() => { + const JRSUrl = { + url: 'https://ms.jr.jd.com/gw/generic/hy/h5/m/appSign', + headers: { + Cookie: KEY + }, + body: body || '' + }; + $nobyda.post(JRSUrl, function(error, response, data) { + try { + if (error) throw new Error(error) + const cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.resultCode == 0 && cc.resultData && cc.resultData.resBusiCode == 0) { + console.log("\n" + "京东金融-钢镚签到成功 " + Details) + merge.JRSteel.notify = `京东金融-钢镚: 成功, 获得钢镚奖励 💰` + merge.JRSteel.success = 1 + } else { + console.log("\n" + "京东金融-钢镚签到失败 " + Details) + merge.JRSteel.fail = 1 + if (cc.resultCode == 0 && cc.resultData && cc.resultData.resBusiCode == 15) { + merge.JRSteel.notify = "京东金融-钢镚: 失败, 原因: 已签过 ⚠️" + } else if (data.match(/未实名/)) { + merge.JRSteel.notify = "京东金融-钢镚: 失败, 账号未实名 ⚠️" + } else if (cc.resultCode == 3) { + merge.JRSteel.notify = "京东金融-钢镚: 失败, 原因: Cookie失效‼️" + } else { + const ng = (cc.resultData && cc.resultData.resBusiMsg) || cc.resultMsg + merge.JRSteel.notify = `京东金融-钢镚: 失败, ${`原因: ${ng||`未知`}`} ⚠️` + } + } + } catch (eor) { + $nobyda.AnError("京东金融-钢镚", "JRSteel", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingDongShake(s) { + if (!merge.JDShake) merge.JDShake = {}, merge.JDShake.success = 0, merge.JDShake.bean = 0, merge.JDShake.notify = ''; + return new Promise(resolve => { + if (disable("JDShake")) return resolve() + setTimeout(() => { + const JDSh = { + url: 'https://api.m.jd.com/client.action?appid=vip_h5&functionId=vvipclub_shaking', + headers: { + Cookie: KEY, + } + }; + $nobyda.get(JDSh, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + const also = merge.JDShake.notify ? true : false + if (data.match(/prize/)) { + console.log("\n" + "京东商城-摇一摇签到成功 " + Details) + merge.JDShake.success += 1 + if (cc.data.prizeBean) { + merge.JDShake.bean += cc.data.prizeBean.count || 0 + merge.JDShake.notify += `${also?`\n`:``}京东商城-摇摇: ${also?`多次`:`成功`}, 明细: ${merge.JDShake.bean || `无`}京豆 🐶` + } else if (cc.data.prizeCoupon) { + merge.JDShake.notify += `${also?`\n`:``}京东商城-摇摇: ${also?`多次, `:``}获得满${cc.data.prizeCoupon.quota}减${cc.data.prizeCoupon.discount}优惠券→ ${cc.data.prizeCoupon.limitStr}` + } else { + merge.JDShake.notify += `${also?`\n`:``}京东商城-摇摇: 成功, 明细: 未知 ⚠️${also?` (多次)`:``}` + } + if (cc.data.luckyBox.freeTimes != 0) { + await JingDongShake(s) + } + } else { + console.log("\n" + "京东商城-摇一摇签到失败 " + Details) + if (data.match(/true/)) { + merge.JDShake.notify += `${also?`\n`:``}京东商城-摇摇: 成功, 明细: 无奖励 🐶${also?` (多次)`:``}` + merge.JDShake.success += 1 + if (cc.data.luckyBox.freeTimes != 0) { + await JingDongShake(s) + } + } else { + merge.JDShake.fail = 1 + if (data.match(/(无免费|8000005|9000005)/)) { + merge.JDShake.notify = "京东商城-摇摇: 失败, 原因: 已摇过 ⚠️" + } else if (data.match(/(未登录|101)/)) { + merge.JDShake.notify = "京东商城-摇摇: 失败, 原因: Cookie失效‼️" + } else { + merge.JDShake.notify += `${also?`\n`:``}京东商城-摇摇: 失败, 原因: 未知 ⚠️${also?` (多次)`:``}` + } + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-摇摇", "JDShake", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JDUserSignPre(s, key, title, ac) { + merge[key] = {}; + if ($nobyda.isJSBox) { + return JDUserSignPre2(s, key, title, ac); + } else { + return JDUserSignPre1(s, key, title, ac); + } +} + +function JDUserSignPre1(s, key, title, acData, ask) { + return new Promise((resolve, reject) => { + if (disable(key, title, 1)) return reject() + const JDUrl = { + url: 'https://api.m.jd.com/?client=wh5&functionId=qryH5BabelFloors', + headers: { + Cookie: KEY + }, + opts: { + 'filter': 'try{var od=JSON.parse(body);var params=(od.floatLayerList||[]).filter(o=>o.params&&o.params.match(/enActK/)).map(o=>o.params).pop()||(od.floorList||[]).filter(o=>o.template=="signIn"&&o.signInfos&&o.signInfos.params&&o.signInfos.params.match(/enActK/)).map(o=>o.signInfos&&o.signInfos.params).pop();var tId=(od.floorList||[]).filter(o=>o.boardParams&&o.boardParams.turnTableId).map(o=>o.boardParams.turnTableId).pop();var page=od.paginationFlrs;return JSON.stringify({qxAct:params||null,qxTid:tId||null,qxPage:page||null})}catch(e){return `=> 过滤器发生错误: ${e.message}`}' + }, + body: `body=${encodeURIComponent(`{"activityId":"${acData}"${ask?`,"paginationParam":"2","paginationFlrs":"${ask}"`:``}}`)}` + }; + $nobyda.post(JDUrl, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const od = JSON.parse(data || '{}'); + const turnTableId = od.qxTid || (od.floorList || []).filter(o => o.boardParams && o.boardParams.turnTableId).map(o => o.boardParams.turnTableId).pop(); + const page = od.qxPage || od.paginationFlrs; + if (data.match(/enActK/)) { // 含有签到活动数据 + let params = od.qxAct || (od.floatLayerList || []).filter(o => o.params && o.params.match(/enActK/)).map(o => o.params).pop() + if (!params) { // 第一处找到签到所需数据 + // floatLayerList未找到签到所需数据,从floorList中查找 + let signInfo = (od.floorList || []).filter(o => o.template == 'signIn' && o.signInfos && o.signInfos.params && o.signInfos.params.match(/enActK/)) + .map(o => o.signInfos).pop(); + if (signInfo) { + if (signInfo.signStat == '1') { + console.log(`\n${title}重复签到`) + merge[key].notify = `${title}: 失败, 原因: 已签过 ⚠️` + merge[key].fail = 1 + } else { + params = signInfo.params; + } + } else { + merge[key].notify = `${title}: 失败, 活动查找异常 ⚠️` + merge[key].fail = 1 + } + } + if (params) { + return resolve({ + params: params + }); // 执行签到处理 + } + } else if (turnTableId) { // 无签到数据, 但含有关注店铺签到 + const boxds = $nobyda.read("JD_Follow_disable") === "false" ? false : true + if (boxds) { + console.log(`\n${title}关注店铺`) + return resolve(parseInt(turnTableId)) + } else { + merge[key].notify = `${title}: 失败, 需要关注店铺 ⚠️` + merge[key].fail = 1 + } + } else if (page && !ask) { // 无签到数据, 尝试带参查询 + const boxds = $nobyda.read("JD_Retry_disable") === "false" ? false : true + if (boxds) { + console.log(`\n${title}二次查询`) + return resolve(page) + } else { + merge[key].notify = `${title}: 失败, 请尝试开启增强 ⚠️` + merge[key].fail = 1 + } + } else { + merge[key].notify = `${title}: 失败, ${!data ? `需要手动执行` : `不含活动数据`} ⚠️` + merge[key].fail = 1 + } + } + reject() + } catch (eor) { + $nobyda.AnError(title, key, eor, response, data) + reject() + } + }) + if (out) setTimeout(reject, out + s) + }).then(data => { + disable(key, title, 2) + if (typeof(data) == "object") return JDUserSign1(s, key, title, encodeURIComponent(JSON.stringify(data))); + if (typeof(data) == "number") return JDUserSign2(s, key, title, data); + if (typeof(data) == "string") return JDUserSignPre1(s, key, title, acData, data); + }, () => disable(key, title, 2)) +} + +function JDUserSignPre2(s, key, title, acData) { + return new Promise((resolve, reject) => { + if (disable(key, title, 1)) return reject() + const JDUrl = { + url: `https://pro.m.jd.com/mall/active/${acData}/index.html`, + headers: { + Cookie: KEY, + } + }; + $nobyda.get(JDUrl, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const act = data.match(/\"params\":\"\{\\\"enActK.+?\\\"\}\"/) + const turnTable = data.match(/\"turnTableId\":\"(\d+)\"/) + const page = data.match(/\"paginationFlrs\":\"(\[\[.+?\]\])\"/) + if (act) { // 含有签到活动数据 + return resolve(act) + } else if (turnTable) { // 无签到数据, 但含有关注店铺签到 + const boxds = $nobyda.read("JD_Follow_disable") === "false" ? false : true + if (boxds) { + console.log(`\n${title}关注店铺`) + return resolve(parseInt(turnTable[1])) + } else { + merge[key].notify = `${title}: 失败, 需要关注店铺 ⚠️` + merge[key].fail = 1 + } + } else if (page) { // 无签到数据, 尝试带参查询 + const boxds = $nobyda.read("JD_Retry_disable") === "false" ? false : true + if (boxds) { + console.log(`\n${title}二次查询`) + return resolve(page[1]) + } else { + merge[key].notify = `${title}: 失败, 请尝试开启增强 ⚠️` + merge[key].fail = 1 + } + } else { + merge[key].notify = `${title}: 失败, ${!data ? `需要手动执行` : `不含活动数据`} ⚠️` + merge[key].fail = 1 + } + } + reject() + } catch (eor) { + $nobyda.AnError(title, key, eor, response, data) + reject() + } + }) + if (out) setTimeout(reject, out + s) + }).then(data => { + disable(key, title, 2) + if (typeof(data) == "object") return JDUserSign1(s, key, title, encodeURIComponent(`{${data}}`)); + if (typeof(data) == "number") return JDUserSign2(s, key, title, data) + if (typeof(data) == "string") return JDUserSignPre1(s, key, title, acData, data) + }, () => disable(key, title, 2)) +} + +function JDUserSign1(s, key, title, body) { + return new Promise(resolve => { + setTimeout(() => { + const JDUrl = { + url: 'https://api.m.jd.com/client.action?functionId=userSign', + headers: { + Cookie: KEY + }, + body: `body=${body}&client=wh5` + }; + $nobyda.post(JDUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? `response:\n${data}` : ''; + if (data.match(/签到成功/)) { + console.log(`\n${title}签到成功(1)${Details}`) + if (data.match(/\"text\":\"\d+京豆\"/)) { + merge[key].bean = data.match(/\"text\":\"(\d+)京豆\"/)[1] + } + merge[key].notify = `${title}: 成功, 明细: ${merge[key].bean || '无'}京豆 🐶` + merge[key].success = 1 + } else { + console.log(`\n${title}签到失败(1)${Details}`) + if (data.match(/(已签到|已领取)/)) { + merge[key].notify = `${title}: 失败, 原因: 已签过 ⚠️` + } else if (data.match(/(不存在|已结束|未开始)/)) { + merge[key].notify = `${title}: 失败, 原因: 活动已结束 ⚠️` + } else if (data.match(/\"code\":\"?3\"?/)) { + merge[key].notify = `${title}: 失败, 原因: Cookie失效‼️` + } else { + const ng = data.match(/\"(errorMessage|subCodeMsg)\":\"(.+?)\"/) + merge[key].notify = `${title}: 失败, ${ng?ng[2]:`原因: 未知`} ⚠️` + } + merge[key].fail = 1 + } + } + } catch (eor) { + $nobyda.AnError(title, key, eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +async function JDUserSign2(s, key, title, tid) { + return console.log(`\n${title} >> 可能需要拼图验证, 跳过签到 ⚠️`); + await new Promise(resolve => { + $nobyda.get({ + url: `https://jdjoy.jd.com/api/turncard/channel/detail?turnTableId=${tid}&invokeKey=ztmFUCxcPMNyUq0P`, + headers: { + Cookie: KEY + } + }, function(error, response, data) { + resolve() + }) + if (out) setTimeout(resolve, out + s) + }); + return new Promise(resolve => { + setTimeout(() => { + const JDUrl = { + url: 'https://jdjoy.jd.com/api/turncard/channel/sign?invokeKey=ztmFUCxcPMNyUq0P', + headers: { + lkt: '1629984131120', + lks: 'd7db92cf40ad5a8d54b9da2b561c5f84', + Cookie: KEY + }, + body: `turnTableId=${tid}` + }; + $nobyda.post(JDUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? `response:\n${data}` : ''; + if (data.match(/\"success\":true/)) { + console.log(`\n${title}签到成功(2)${Details}`) + if (data.match(/\"jdBeanQuantity\":\d+/)) { + merge[key].bean = data.match(/\"jdBeanQuantity\":(\d+)/)[1] + } + merge[key].notify = `${title}: 成功, 明细: ${merge[key].bean || '无'}京豆 🐶` + merge[key].success = 1 + } else { + const captcha = /请进行验证/.test(data); + if (data.match(/(已经签到|已经领取)/)) { + merge[key].notify = `${title}: 失败, 原因: 已签过 ⚠️` + } else if (data.match(/(不存在|已结束|未开始)/)) { + merge[key].notify = `${title}: 失败, 原因: 活动已结束 ⚠️` + } else if (data.match(/(没有登录|B0001)/)) { + merge[key].notify = `${title}: 失败, 原因: Cookie失效‼️` + } else if (!captcha) { + const ng = data.match(/\"(errorMessage|subCodeMsg)\":\"(.+?)\"/) + merge[key].notify = `${title}: 失败, ${ng?ng[2]:`原因: 未知`} ⚠️` + } + if (!captcha) merge[key].fail = 1; + console.log(`\n${title}签到失败(2)${captcha?`\n需要拼图验证, 跳过通知记录 ⚠️`:``}${Details}`) + } + } + } catch (eor) { + $nobyda.AnError(title, key, eor, response, data) + } finally { + resolve() + } + }) + }, 200 + s) + if (out) setTimeout(resolve, out + s + 200) + }); +} + +function JDFlashSale(s) { + merge.JDFSale = {}; + return new Promise(resolve => { + if (disable("JDFSale")) return resolve() + setTimeout(() => { + const JDPETUrl = { + url: 'https://api.m.jd.com/client.action?functionId=partitionJdSgin', + headers: { + Cookie: KEY + }, + body: "body=%7B%22version%22%3A%22v2%22%7D&client=apple&clientVersion=9.0.8&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&sign=6768e2cf625427615dd89649dd367d41&st=1597248593305&sv=121" + }; + $nobyda.post(JDPETUrl, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (cc.result && cc.result.code == 0) { + console.log("\n" + "京东商城-闪购签到成功 " + Details) + merge.JDFSale.bean = cc.result.jdBeanNum || 0 + merge.JDFSale.notify = "京东商城-闪购: 成功, 明细: " + (merge.JDFSale.bean || "无") + "京豆 🐶" + merge.JDFSale.success = 1 + } else { + console.log("\n" + "京东商城-闪购签到失败 " + Details) + if (data.match(/(已签到|已领取|\"2005\")/)) { + merge.JDFSale.notify = "京东商城-闪购: 失败, 原因: 已签过 ⚠️" + } else if (data.match(/不存在|已结束|\"2008\"|\"3001\"/)) { + await FlashSaleDivide(s); //瓜分京豆 + return + } else if (data.match(/(\"code\":\"3\"|\"1003\")/)) { + merge.JDFSale.notify = "京东商城-闪购: 失败, 原因: Cookie失效‼️" + } else { + const msg = data.match(/\"msg\":\"([\u4e00-\u9fa5].+?)\"/) + merge.JDFSale.notify = `京东商城-闪购: 失败, ${msg ? msg[1] : `原因: 未知`} ⚠️` + } + merge.JDFSale.fail = 1 + } + } + } catch (eor) { + $nobyda.AnError("京东商城-闪购", "JDFSale", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function FlashSaleDivide(s) { + return new Promise(resolve => { + setTimeout(() => { + const Url = { + url: 'https://api.m.jd.com/client.action?functionId=partitionJdShare', + headers: { + Cookie: KEY + }, + body: "body=%7B%22version%22%3A%22v2%22%7D&client=apple&clientVersion=9.0.8&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&sign=49baa3b3899b02bbf06cdf41fe191986&st=1597682588351&sv=111" + }; + $nobyda.post(Url, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (cc.result.code == 0) { + merge.JDFSale.success = 1 + merge.JDFSale.bean = cc.result.jdBeanNum || 0 + merge.JDFSale.notify = "京东闪购-瓜分: 成功, 明细: " + (merge.JDFSale.bean || "无") + "京豆 🐶" + console.log("\n" + "京东闪购-瓜分签到成功 " + Details) + } else { + merge.JDFSale.fail = 1 + console.log("\n" + "京东闪购-瓜分签到失败 " + Details) + if (data.match(/已参与|已领取|\"2006\"/)) { + merge.JDFSale.notify = "京东闪购-瓜分: 失败, 原因: 已瓜分 ⚠️" + } else if (data.match(/不存在|已结束|未开始|\"2008\"|\"2012\"/)) { + merge.JDFSale.notify = "京东闪购-瓜分: 失败, 原因: 活动已结束 ⚠️" + } else if (data.match(/\"code\":\"1003\"|未获取/)) { + merge.JDFSale.notify = "京东闪购-瓜分: 失败, 原因: Cookie失效‼️" + } else { + const msg = data.match(/\"msg\":\"([\u4e00-\u9fa5].+?)\"/) + merge.JDFSale.notify = `京东闪购-瓜分: 失败, ${msg ? msg[1] : `原因: 未知`} ⚠️` + } + } + } + } catch (eor) { + $nobyda.AnError("京东闪购-瓜分", "JDFSale", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingDongCash(s) { + merge.JDCash = {}; + return new Promise(resolve => { + if (disable("JDCash")) return resolve() + setTimeout(() => { + const JDCAUrl = { + url: 'https://api.m.jd.com/client.action?functionId=ccSignInNew', + headers: { + Cookie: KEY + }, + body: "body=%7B%22pageClickKey%22%3A%22CouponCenter%22%2C%22eid%22%3A%22O5X6JYMZTXIEX4VBCBWEM5PTIZV6HXH7M3AI75EABM5GBZYVQKRGQJ5A2PPO5PSELSRMI72SYF4KTCB4NIU6AZQ3O6C3J7ZVEP3RVDFEBKVN2RER2GTQ%22%2C%22shshshfpb%22%3A%22v1%5C%2FzMYRjEWKgYe%2BUiNwEvaVlrHBQGVwqLx4CsS9PH1s0s0Vs9AWk%2B7vr9KSHh3BQd5NTukznDTZnd75xHzonHnw%3D%3D%22%2C%22childActivityUrl%22%3A%22openapp.jdmobile%253a%252f%252fvirtual%253fparams%253d%257b%255c%2522category%255c%2522%253a%255c%2522jump%255c%2522%252c%255c%2522des%255c%2522%253a%255c%2522couponCenter%255c%2522%257d%22%2C%22monitorSource%22%3A%22cc_sign_ios_index_config%22%7D&client=apple&clientVersion=8.5.0&d_brand=apple&d_model=iPhone8%2C2&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&scope=11&screen=1242%2A2208&sign=1cce8f76d53fc6093b45a466e93044da&st=1581084035269&sv=102" + }; + $nobyda.post(JDCAUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (cc.busiCode == "0") { + console.log("\n" + "京东现金-红包签到成功 " + Details) + merge.JDCash.success = 1 + merge.JDCash.Cash = cc.result.signResult.signData.amount || 0 + merge.JDCash.notify = `京东现金-红包: 成功, 明细: ${merge.JDCash.Cash || `无`}红包 🧧` + } else { + console.log("\n" + "京东现金-红包签到失败 " + Details) + merge.JDCash.fail = 1 + if (data.match(/(\"busiCode\":\"1002\"|完成签到)/)) { + merge.JDCash.notify = "京东现金-红包: 失败, 原因: 已签过 ⚠️" + } else if (data.match(/(不存在|已结束)/)) { + merge.JDCash.notify = "京东现金-红包: 失败, 原因: 活动已结束 ⚠️" + } else if (data.match(/(\"busiCode\":\"3\"|未登录)/)) { + merge.JDCash.notify = "京东现金-红包: 失败, 原因: Cookie失效‼️" + } else { + const msg = data.split(/\"msg\":\"([\u4e00-\u9fa5].+?)\"/)[1]; + merge.JDCash.notify = `京东现金-红包: 失败, ${msg||`原因: 未知`} ⚠️` + } + } + } + } catch (eor) { + $nobyda.AnError("京东现金-红包", "JDCash", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JDMagicCube(s, sign) { + merge.JDCube = {}; + return new Promise((resolve, reject) => { + if (disable("JDCube")) return reject() + const JDUrl = { + url: `https://api.m.jd.com/client.action?functionId=getNewsInteractionInfo&appid=smfe${sign?`&body=${encodeURIComponent(`{"sign":${sign}}`)}`:``}`, + headers: { + Cookie: KEY, + } + }; + $nobyda.get(JDUrl, async (error, response, data) => { + try { + if (error) throw new Error(error) + const Details = LogDetails ? "response:\n" + data : ''; + console.log(`\n京东魔方-尝试查询活动(${sign}) ${Details}`) + if (data.match(/\"interactionId\":\d+/)) { + resolve({ + id: data.match(/\"interactionId\":(\d+)/)[1], + sign: sign || null + }) + } else if (data.match(/配置异常/) && sign) { + await JDMagicCube(s, sign == 2 ? 1 : null) + reject() + } else { + resolve(null) + } + } catch (eor) { + $nobyda.AnError("京东魔方-查询", "JDCube", eor, response, data) + reject() + } + }) + if (out) setTimeout(reject, out + s) + }).then(data => { + return JDMagicCubeSign(s, data) + }, () => {}); +} + +function JDMagicCubeSign(s, id) { + return new Promise(resolve => { + setTimeout(() => { + const JDMCUrl = { + url: `https://api.m.jd.com/client.action?functionId=getNewsInteractionLotteryInfo&appid=smfe${id?`&body=${encodeURIComponent(`{${id.sign?`"sign":${id.sign},`:``}"interactionId":${id.id}}`)}`:``}`, + headers: { + Cookie: KEY, + } + }; + $nobyda.get(JDMCUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (data.match(/(\"name\":)/)) { + console.log("\n" + "京东商城-魔方签到成功 " + Details) + merge.JDCube.success = 1 + if (data.match(/(\"name\":\"京豆\")/)) { + merge.JDCube.bean = cc.result.lotteryInfo.quantity || 0 + merge.JDCube.notify = `京东商城-魔方: 成功, 明细: ${merge.JDCube.bean || `无`}京豆 🐶` + } else { + merge.JDCube.notify = `京东商城-魔方: 成功, 明细: ${cc.result.lotteryInfo.name || `未知`} 🎉` + } + } else { + console.log("\n" + "京东商城-魔方签到失败 " + Details) + merge.JDCube.fail = 1 + if (data.match(/(一闪而过|已签到|已领取)/)) { + merge.JDCube.notify = "京东商城-魔方: 失败, 原因: 无机会 ⚠️" + } else if (data.match(/(不存在|已结束)/)) { + merge.JDCube.notify = "京东商城-魔方: 失败, 原因: 活动已结束 ⚠️" + } else if (data.match(/(\"code\":3)/)) { + merge.JDCube.notify = "京东商城-魔方: 失败, 原因: Cookie失效‼️" + } else { + merge.JDCube.notify = "京东商城-魔方: 失败, 原因: 未知 ⚠️" + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-魔方", "JDCube", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingDongSubsidy(s) { + merge.subsidy = {}; + return new Promise(resolve => { + if (disable("subsidy")) return resolve() + setTimeout(() => { + const subsidyUrl = { + url: 'https://ms.jr.jd.com/gw/generic/uc/h5/m/signIn7', + headers: { + Referer: "https://active.jd.com/forever/cashback/index", + Cookie: KEY + } + }; + $nobyda.get(subsidyUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (cc.resultCode == 0 && cc.resultData.data && cc.resultData.data.thisAmount) { + console.log("\n" + "京东商城-金贴签到成功 " + Details) + merge.subsidy.subsidy = cc.resultData.data.thisAmountStr + merge.subsidy.notify = `京东商城-金贴: 成功, 明细: ${merge.subsidy.subsidy||`无`}金贴 💰` + merge.subsidy.success = 1 + } else { + console.log("\n" + "京东商城-金贴签到失败 " + Details) + merge.subsidy.fail = 1 + if (data.match(/已存在|"thisAmount":0/)) { + merge.subsidy.notify = "京东商城-金贴: 失败, 原因: 无金贴 ⚠️" + } else if (data.match(/请先登录/)) { + merge.subsidy.notify = "京东商城-金贴: 失败, 原因: Cookie失效‼️" + } else { + const msg = data.split(/\"msg\":\"([\u4e00-\u9fa5].+?)\"/)[1]; + merge.subsidy.notify = `京东商城-金贴: 失败, ${msg||`原因: 未知`} ⚠️` + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-金贴", "subsidy", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingRongDoll(s, key, title, code, type, num, award, belong) { + merge[key] = {}; + return new Promise(resolve => { + if (disable(key)) return resolve() + setTimeout(() => { + const DollUrl = { + url: "https://nu.jr.jd.com/gw/generic/jrm/h5/m/process", + headers: { + Cookie: KEY + }, + body: `reqData=${encodeURIComponent(`{"actCode":"${code}","type":${type?type:`3`}${code=='F68B2C3E71'?`,"frontParam":{"belong":"${belong}"}`:code==`1DF13833F7`?`,"frontParam":{"channel":"JR","belong":4}`:``}}`)}` + }; + $nobyda.post(DollUrl, async function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + var cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.resultCode == 0) { + if (cc.resultData.data.businessData != null) { + console.log(`\n${title}查询成功 ${Details}`) + if (cc.resultData.data.businessData.pickStatus == 2) { + if (data.match(/\"rewardPrice\":\"\d.*?\"/)) { + const JRDoll_bean = data.match(/\"rewardPrice\":\"(\d.*?)\"/)[1] + const JRDoll_type = data.match(/\"rewardName\":\"金贴奖励\"/) ? true : false + await JingRongDoll(s, key, title, code, '4', JRDoll_bean, JRDoll_type) + } else { + merge[key].success = 1 + merge[key].notify = `${title}: 成功, 明细: 无奖励 🐶` + } + } else if (code == 'F68B2C3E71' || code == '1DF13833F7') { + if (!data.match(/"businessCode":"30\dss?q"/)) { + merge[key].success = 1 + const ct = data.match(/\"count\":\"?(\d.*?)\"?,/) + if (code == 'F68B2C3E71' && belong == 'xianjin') { + merge[key].Money = ct ? ct[1] > 9 ? `0.${ct[1]}` : `0.0${ct[1]}` : 0 + merge[key].notify = `${title}: 成功, 明细: ${merge[key].Money||`无`}现金 💰` + } else if (code == 'F68B2C3E71' && belong == 'jingdou') { + merge[key].bean = ct ? ct[1] : 0; + merge[key].notify = `${title}: 成功, 明细: ${merge[key].bean||`无`}京豆 🐶` + } else if (code == '1DF13833F7') { + merge[key].subsidy = ct ? ct[1] : 0; + merge[key].notify = `${title}: 成功, 明细: ${merge[key].subsidy||`无`}金贴 💰` + } + } else { + const es = cc.resultData.data.businessMsg + const ep = cc.resultData.data.businessData.businessMsg + const tp = data.match(/已领取|300ss?q/) ? `已签过` : `${ep||es||cc.resultMsg||`未知`}` + merge[key].notify = `${title}: 失败, 原因: ${tp} ⚠️` + merge[key].fail = 1 + } + } else { + merge[key].notify = `${title}: 失败, 原因: 已签过 ⚠️`; + merge[key].fail = 1 + } + } else if (cc.resultData.data.businessCode == 200) { + console.log(`\n${title}签到成功 ${Details}`) + if (!award) { + merge[key].bean = num ? num.match(/\d+/)[0] : 0 + } else { + merge[key].subsidy = num || 0 + } + merge[key].success = 1 + merge[key].notify = `${title}: 成功, 明细: ${(award?num:merge[key].bean)||`无`}${award?`金贴 💰`:`京豆 🐶`}` + } else { + console.log(`\n${title}领取异常 ${Details}`) + if (num) console.log(`\n${title} 请尝试手动领取, 预计可得${num}${award?`金贴`:`京豆`}: \nhttps://uf1.jr.jd.com/up/redEnvelopes/index.html?actCode=${code}\n`); + merge[key].fail = 1; + merge[key].notify = `${title}: 失败, 原因: 领取异常 ⚠️`; + } + } else { + console.log(`\n${title}签到失败 ${Details}`) + const redata = typeof(cc.resultData) == 'string' ? cc.resultData : '' + merge[key].notify = `${title}: 失败, ${cc.resultCode==3?`原因: Cookie失效‼️`:`${redata||'原因: 未知 ⚠️'}`}` + merge[key].fail = 1; + } + } + } catch (eor) { + $nobyda.AnError(title, key, eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingDongGetCash(s) { + merge.JDGetCash = {}; + return new Promise(resolve => { + if (disable("JDGetCash")) return resolve() + setTimeout(() => { + const GetCashUrl = { + url: 'https://api.m.jd.com/client.action?functionId=cash_sign&body=%7B%22remind%22%3A0%2C%22inviteCode%22%3A%22%22%2C%22type%22%3A0%2C%22breakReward%22%3A0%7D&client=apple&clientVersion=9.0.8&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&sign=7e2f8bcec13978a691567257af4fdce9&st=1596954745073&sv=111', + headers: { + Cookie: KEY, + } + }; + $nobyda.get(GetCashUrl, function(error, response, data) { + try { + if (error) { + throw new Error(error) + } else { + const cc = JSON.parse(data); + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.data.success && cc.data.result) { + console.log("\n" + "京东商城-现金签到成功 " + Details) + merge.JDGetCash.success = 1 + merge.JDGetCash.Money = cc.data.result.signCash || 0 + merge.JDGetCash.notify = `京东商城-现金: 成功, 明细: ${cc.data.result.signCash||`无`}现金 💰` + } else { + console.log("\n" + "京东商城-现金签到失败 " + Details) + merge.JDGetCash.fail = 1 + if (data.match(/\"bizCode\":201|已经签过/)) { + merge.JDGetCash.notify = "京东商城-现金: 失败, 原因: 已签过 ⚠️" + } else if (data.match(/\"code\":300|退出登录/)) { + merge.JDGetCash.notify = "京东商城-现金: 失败, 原因: Cookie失效‼️" + } else { + merge.JDGetCash.notify = "京东商城-现金: 失败, 原因: 未知 ⚠️" + } + } + } + } catch (eor) { + $nobyda.AnError("京东商城-现金", "JDGetCash", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JingDongStore(s) { + merge.JDGStore = {}; + return new Promise(resolve => { + if (disable("JDGStore")) return resolve() + setTimeout(() => { + $nobyda.get({ + url: 'https://api.m.jd.com/api?appid=jdsupermarket&functionId=smtg_sign&clientVersion=8.0.0&client=m&body=%7B%7D', + headers: { + Cookie: KEY, + Origin: `https://jdsupermarket.jd.com` + } + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const cc = JSON.parse(data); + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.data && cc.data.success === true && cc.data.bizCode === 0) { + console.log(`\n京东商城-超市签到成功 ${Details}`) + merge.JDGStore.success = 1 + merge.JDGStore.bean = cc.data.result.jdBeanCount || 0 + merge.JDGStore.notify = `京东商城-超市: 成功, 明细: ${merge.JDGStore.bean||`无`}京豆 🐶` + } else { + if (!cc.data) cc.data = {} + console.log(`\n京东商城-超市签到失败 ${Details}`) + const tp = cc.data.bizCode == 811 ? `已签过` : cc.data.bizCode == 300 ? `Cookie失效` : `${cc.data.bizMsg||`未知`}` + merge.JDGStore.notify = `京东商城-超市: 失败, 原因: ${tp}${cc.data.bizCode==300?`‼️`:` ⚠️`}` + merge.JDGStore.fail = 1 + } + } catch (eor) { + $nobyda.AnError("京东商城-超市", "JDGStore", eor, response, data) + } finally { + resolve() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }); +} + +function JDSecKilling(s) { //领券中心 + merge.JDSecKill = {}; + return new Promise((resolve, reject) => { + if (disable("JDSecKill")) return reject(); + setTimeout(() => { + $nobyda.post({ + url: 'https://api.m.jd.com/client.action', + headers: { + Cookie: KEY, + Origin: 'https://h5.m.jd.com' + }, + body: 'functionId=homePageV2&appid=SecKill2020' + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data); + if (cc.code == 203 || cc.code == 3 || cc.code == 101) { + merge.JDSecKill.notify = `京东秒杀-红包: 失败, 原因: Cookie失效‼️`; + } else if (cc.result && cc.result.projectId && cc.result.taskId) { + console.log(`\n京东秒杀-红包查询成功 ${Details}`) + return resolve({ + projectId: cc.result.projectId, + taskId: cc.result.taskId + }) + } else { + merge.JDSecKill.notify = `京东秒杀-红包: 失败, 暂无有效活动 ⚠️`; + } + merge.JDSecKill.fail = 1; + console.log(`\n京东秒杀-红包查询失败 ${Details}`) + reject() + } catch (eor) { + $nobyda.AnError("京东秒杀-查询", "JDSecKill", eor, response, data) + reject() + } + }) + }, s) + if (out) setTimeout(resolve, out + s) + }).then(async (id) => { + await new Promise(resolve => { + $nobyda.post({ + url: 'https://api.m.jd.com/client.action', + headers: { + Cookie: KEY, + Origin: 'https://h5.m.jd.com' + }, + body: `functionId=doInteractiveAssignment&body=%7B%22encryptProjectId%22%3A%22${id.projectId}%22%2C%22encryptAssignmentId%22%3A%22${id.taskId}%22%2C%22completionFlag%22%3Atrue%7D&client=wh5&appid=SecKill2020` + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data); + if (cc.code == 0 && cc.subCode == 0) { + console.log(`\n京东秒杀-红包签到成功 ${Details}`); + const qt = data.match(/"discount":(\d.*?),/); + merge.JDSecKill.success = 1; + merge.JDSecKill.Cash = qt ? qt[1] : 0; + merge.JDSecKill.notify = `京东秒杀-红包: 成功, 明细: ${merge.JDSecKill.Cash||`无`}红包 🧧`; + } else { + console.log(`\n京东秒杀-红包签到失败 ${Details}`); + merge.JDSecKill.fail = 1; + merge.JDSecKill.notify = `京东秒杀-红包: 失败, ${cc.subCode==103?`原因: 已领取`:cc.msg?cc.msg:`原因: 未知`} ⚠️`; + } + } catch (eor) { + $nobyda.AnError("京东秒杀-领取", "JDSecKill", eor, response, data); + } finally { + resolve(); + } + }) + }) + }, () => {}); +} + +function TotalSteel() { + merge.TotalSteel = {}; + return new Promise(resolve => { + if (disable("TSteel")) return resolve() + $nobyda.get({ + url: 'https://coin.jd.com/m/gb/getBaseInfo.html', + headers: { + Cookie: KEY + } + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const Details = LogDetails ? "response:\n" + data : ''; + if (data.match(/(\"gbBalance\":\d+)/)) { + console.log("\n" + "京东-总钢镚查询成功 " + Details) + const cc = JSON.parse(data) + merge.TotalSteel.TSteel = cc.gbBalance + } else { + console.log("\n" + "京东-总钢镚查询失败 " + Details) + } + } catch (eor) { + $nobyda.AnError("账户钢镚-查询", "TotalSteel", eor, response, data) + } finally { + resolve() + } + }) + if (out) setTimeout(resolve, out) + }); +} + +function TotalBean() { + merge.TotalBean = {}; + return new Promise(resolve => { + if (disable("Qbear")) return resolve() + $nobyda.get({ + url: 'https://me-api.jd.com/user_new/info/GetJDUserInfoUnion', + headers: { + Cookie: KEY + } + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const Details = LogDetails ? "response:\n" + data : ''; + const cc = JSON.parse(data) + if (cc.msg == 'success' && cc.retcode == 0) { + merge.TotalBean.nickname = cc.data.userInfo.baseInfo.nickname || "" + merge.TotalBean.Qbear = cc.data.assetInfo.beanNum || 0 + $nobyda.headUrl = cc.data.userInfo.baseInfo.headImageUrl || "" + console.log(`\n京东-总京豆查询成功 ${Details}`) + } else { + const name = decodeURIComponent(KEY.split(/pt_pin=(.+?);/)[1] || ''); + merge.TotalBean.nickname = cc.retcode == 1001 ? `${name} (CK失效‼️)` : ""; + console.log(`\n京东-总京豆查询失败 ${Details}`) + } + } catch (eor) { + $nobyda.AnError("账户京豆-查询", "TotalBean", eor, response, data) + } finally { + resolve() + } + }) + if (out) setTimeout(resolve, out) + }); +} + +function TotalCash() { + merge.TotalCash = {}; + return new Promise(resolve => { + if (disable("TCash")) return resolve() + $nobyda.post({ + url: 'https://api.m.jd.com/client.action?functionId=myhongbao_balance', + headers: { + Cookie: KEY + }, + body: "body=%7B%22fp%22%3A%22-1%22%2C%22appToken%22%3A%22apphongbao_token%22%2C%22childActivityUrl%22%3A%22-1%22%2C%22country%22%3A%22cn%22%2C%22openId%22%3A%22-1%22%2C%22childActivityId%22%3A%22-1%22%2C%22applicantErp%22%3A%22-1%22%2C%22platformId%22%3A%22appHongBao%22%2C%22isRvc%22%3A%22-1%22%2C%22orgType%22%3A%222%22%2C%22activityType%22%3A%221%22%2C%22shshshfpb%22%3A%22-1%22%2C%22platformToken%22%3A%22apphongbao_token%22%2C%22organization%22%3A%22JD%22%2C%22pageClickKey%22%3A%22-1%22%2C%22platform%22%3A%221%22%2C%22eid%22%3A%22-1%22%2C%22appId%22%3A%22appHongBao%22%2C%22childActiveName%22%3A%22-1%22%2C%22shshshfp%22%3A%22-1%22%2C%22jda%22%3A%22-1%22%2C%22extend%22%3A%22-1%22%2C%22shshshfpa%22%3A%22-1%22%2C%22activityArea%22%3A%22-1%22%2C%22childActivityTime%22%3A%22-1%22%7D&client=apple&clientVersion=8.5.0&d_brand=apple&networklibtype=JDNetworkBaseAF&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&sign=fdc04c3ab0ee9148f947d24fb087b55d&st=1581245397648&sv=120" + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const Details = LogDetails ? "response:\n" + data : ''; + if (data.match(/(\"totalBalance\":\d+)/)) { + console.log("\n" + "京东-总红包查询成功 " + Details) + const cc = JSON.parse(data) + merge.TotalCash.TCash = cc.totalBalance + } else { + console.log("\n" + "京东-总红包查询失败 " + Details) + } + } catch (eor) { + $nobyda.AnError("账户红包-查询", "TotalCash", eor, response, data) + } finally { + resolve() + } + }) + if (out) setTimeout(resolve, out) + }); +} + +function TotalSubsidy() { + merge.TotalSubsidy = {}; + return new Promise(resolve => { + if (disable("TotalSubsidy")) return resolve() + $nobyda.get({ + url: 'https://ms.jr.jd.com/gw/generic/uc/h5/m/mySubsidyBalance', + headers: { + Cookie: KEY, + Referer: 'https://active.jd.com/forever/cashback/index?channellv=wojingqb' + } + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.resultCode == 0 && cc.resultData && cc.resultData.data) { + console.log("\n京东-总金贴查询成功 " + Details) + merge.TotalSubsidy.TSubsidy = cc.resultData.data.balance || 0 + } else { + console.log("\n京东-总金贴查询失败 " + Details) + } + } catch (eor) { + $nobyda.AnError("账户金贴-查询", "TotalSubsidy", eor, response, data) + } finally { + resolve() + } + }) + if (out) setTimeout(resolve, out) + }); +} + +function TotalMoney() { + merge.TotalMoney = {}; + return new Promise(resolve => { + if (disable("TotalMoney")) return resolve() + $nobyda.get({ + url: 'https://api.m.jd.com/client.action?functionId=cash_exchangePage&body=%7B%7D&build=167398&client=apple&clientVersion=9.1.9&openudid=1fce88cd05c42fe2b054e846f11bdf33f016d676&sign=762a8e894dea8cbfd91cce4dd5714bc5&st=1602179446935&sv=102', + headers: { + Cookie: KEY + } + }, (error, response, data) => { + try { + if (error) throw new Error(error); + const cc = JSON.parse(data) + const Details = LogDetails ? "response:\n" + data : ''; + if (cc.code == 0 && cc.data && cc.data.bizCode == 0 && cc.data.result) { + console.log("\n京东-总现金查询成功 " + Details) + merge.TotalMoney.TMoney = cc.data.result.totalMoney || 0 + } else { + console.log("\n京东-总现金查询失败 " + Details) + } + } catch (eor) { + $nobyda.AnError("账户现金-查询", "TotalMoney", eor, response, data) + } finally { + resolve() + } + }) + if (out) setTimeout(resolve, out) + }); +} + +function disable(Val, name, way) { + const read = $nobyda.read("JD_DailyBonusDisables") + const annal = $nobyda.read("JD_Crash_" + Val) + if (annal && way == 1 && boxdis) { + var Crash = $nobyda.write("", "JD_Crash_" + Val) + if (read) { + if (read.indexOf(Val) == -1) { + var Crash = $nobyda.write(`${read},${Val}`, "JD_DailyBonusDisables") + console.log(`\n${name}-触发自动禁用 ‼️`) + merge[Val].notify = `${name}: 崩溃, 触发自动禁用 ‼️` + merge[Val].error = 1 + $nobyda.disable = 1 + } + } else { + var Crash = $nobyda.write(Val, "JD_DailyBonusDisables") + console.log(`\n${name}-触发自动禁用 ‼️`) + merge[Val].notify = `${name}: 崩溃, 触发自动禁用 ‼️` + merge[Val].error = 1 + $nobyda.disable = 1 + } + return true + } else if (way == 1 && boxdis) { + var Crash = $nobyda.write(name, "JD_Crash_" + Val) + } else if (way == 2 && annal) { + var Crash = $nobyda.write("", "JD_Crash_" + Val) + } + if (read && read.indexOf(Val) != -1) { + return true + } else { + return false + } +} + +function Wait(readDelay, ini) { + if (!readDelay || readDelay === '0') return 0 + if (typeof(readDelay) == 'string') { + var readDelay = readDelay.replace(/"|"|'|'/g, ''); //prevent novice + if (readDelay.indexOf('-') == -1) return parseInt(readDelay) || 0; + const raw = readDelay.split("-").map(Number); + const plan = parseInt(Math.random() * (raw[1] - raw[0] + 1) + raw[0], 10); + if (ini) console.log(`\n初始化随机延迟: 最小${raw[0]/1000}秒, 最大${raw[1]/1000}秒`); + // else console.log(`\n预计等待: ${(plan / 1000).toFixed(2)}秒`); + return ini ? readDelay : plan + } else if (typeof(readDelay) == 'number') { + return readDelay > 0 ? readDelay : 0 + } else return 0 +} + +function CookieMove(oldCk1, oldCk2, oldKey1, oldKey2, newKey) { + let update; + const move = (ck, del) => { + console.log(`京东${del}开始迁移!`); + update = CookieUpdate(null, ck).total; + update = $nobyda.write(JSON.stringify(update, null, 2), newKey); + update = $nobyda.write("", del); + } + if (oldCk1) { + const write = move(oldCk1, oldKey1); + } + if (oldCk2) { + const write = move(oldCk2, oldKey2); + } +} + +function checkFormat(value) { //check format and delete duplicates + let n, k, c = {}; + return value.reduce((t, i) => { + k = ((i.cookie || '').match(/(pt_key|pt_pin)=.+?;/g) || []).sort(); + if (k.length == 2) { + if ((n = k[1]) && !c[n]) { + i.userName = i.userName ? i.userName : decodeURIComponent(n.split(/pt_pin=(.+?);/)[1]); + i.cookie = k.join('') + if (i.jrBody && !i.jrBody.includes('reqData=')) { + console.log(`异常钢镚Body已过滤: ${i.jrBody}`) + delete i.jrBody; + } + c[n] = t.push(i); + } + } else { + console.log(`异常京东Cookie已过滤: ${i.cookie}`) + } + return t; + }, []) +} + +function CookieUpdate(oldValue, newValue, path = 'cookie') { + let item, type, name = (oldValue || newValue || '').split(/pt_pin=(.+?);/)[1]; + let total = $nobyda.read('CookiesJD'); + try { + total = checkFormat(JSON.parse(total || '[]')); + } catch (e) { + $nobyda.notify("京东签到", "", "Cookie JSON格式不正确, 即将清空\n可前往日志查看该数据内容!"); + console.log(`京东签到Cookie JSON格式异常: ${e.message||e}\n旧数据内容: ${total}`); + total = []; + } + for (let i = 0; i < total.length; i++) { + if (total[i].cookie && new RegExp(`pt_pin=${name};`).test(total[i].cookie)) { + item = i; + break; + } + } + if (newValue && item !== undefined) { + type = total[item][path] === newValue ? -1 : 2; + total[item][path] = newValue; + item = item + 1; + } else if (newValue && path === 'cookie') { + total.push({ + cookie: newValue + }); + type = 1; + item = total.length; + } + return { + total: checkFormat(total), + type, //-1: same, 1: add, 2:update + item, + name: decodeURIComponent(name) + }; +} + +function GetCookie() { + const req = $request; + if (req.method != 'OPTIONS' && req.headers) { + const CV = (req.headers['Cookie'] || req.headers['cookie'] || ''); + const ckItems = CV.match(/(pt_key|pt_pin)=.+?;/g); + if (/^https:\/\/(me-|)api(\.m|)\.jd\.com\/(client\.|user_new)/.test(req.url)) { + if (ckItems && ckItems.length == 2) { + const value = CookieUpdate(null, ckItems.join('')) + if (value.type !== -1) { + const write = $nobyda.write(JSON.stringify(value.total, null, 2), "CookiesJD") + $nobyda.notify(`用户名: ${value.name}`, ``, `${value.type==2?`更新`:`写入`}京东 [账号${value.item}] Cookie${write?`成功 🎉`:`失败 ‼️`}`) + } else { + console.log(`\n用户名: ${value.name}\n与历史京东 [账号${value.item}] Cookie相同, 跳过写入 ⚠️`) + } + } else { + throw new Error("写入Cookie失败, 关键值缺失\n可能原因: 非网页获取 ‼️"); + } + } else if (/^https:\/\/ms\.jr\.jd\.com\/gw\/generic\/hy\/h5\/m\/appSign\?/.test(req.url) && req.body) { + const value = CookieUpdate(CV, req.body, 'jrBody'); + if (value.type) { + const write = $nobyda.write(JSON.stringify(value.total, null, 2), "CookiesJD") + $nobyda.notify(`用户名: ${value.name}`, ``, `获取京东 [账号${value.item}] 钢镚Body${write?`成功 🎉`:`失败 ‼️`}`) + } else { + throw new Error("写入钢镚Body失败\n未获取该账号Cookie或关键值缺失‼️"); + } + } else if (req.url === 'http://www.apple.com/') { + throw new Error("类型错误, 手动运行请选择上下文环境为Cron ⚠️"); + } + } else if (!req.headers) { + throw new Error("写入Cookie失败, 请检查匹配URL或配置内脚本类型 ⚠️"); + } +} + +// Modified from yichahucha +function nobyda() { + const start = Date.now() + const isRequest = typeof $request != "undefined" + const isSurge = typeof $httpClient != "undefined" + const isQuanX = typeof $task != "undefined" + const isLoon = typeof $loon != "undefined" + const isJSBox = typeof $app != "undefined" && typeof $http != "undefined" + const isNode = typeof require == "function" && !isJSBox; + const NodeSet = 'CookieSet.json' + const node = (() => { + if (isNode) { + const request = require('request'); + const fs = require("fs"); + const path = require("path"); + return ({ + request, + fs, + path + }) + } else { + return (null) + } + })() + const notify = (title, subtitle, message, rawopts) => { + const Opts = (rawopts) => { //Modified from https://github.com/chavyleung/scripts/blob/master/Env.js + if (!rawopts) return rawopts + if (typeof rawopts === 'string') { + if (isLoon) return rawopts + else if (isQuanX) return { + 'open-url': rawopts + } + else if (isSurge) return { + url: rawopts + } + else return undefined + } else if (typeof rawopts === 'object') { + if (isLoon) { + let openUrl = rawopts.openUrl || rawopts.url || rawopts['open-url'] + let mediaUrl = rawopts.mediaUrl || rawopts['media-url'] + return { + openUrl, + mediaUrl + } + } else if (isQuanX) { + let openUrl = rawopts['open-url'] || rawopts.url || rawopts.openUrl + let mediaUrl = rawopts['media-url'] || rawopts.mediaUrl + return { + 'open-url': openUrl, + 'media-url': mediaUrl + } + } else if (isSurge) { + let openUrl = rawopts.url || rawopts.openUrl || rawopts['open-url'] + return { + url: openUrl } } } else { - jrBody = '' - } - await changeFile(content); - await execSign(); - } - } - //await deleteFile(JD_DailyBonusPath);//删除下载的JD_DailyBonus.js文件 - if ($.isNode() && allMessage && process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE === 'true') { - $.msg($.name, '', allMessage); - await notify.sendNotify($.name, allMessage) - } -})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) -async function execSign() { - console.log(`\n开始执行 ${$.name} 签到,请稍等...\n`); - try { - // if (notify.SCKEY || notify.BARK_PUSH || notify.DD_BOT_TOKEN || (notify.TG_BOT_TOKEN && notify.TG_USER_ID) || notify.IGOT_PUSH_KEY || notify.QQ_SKEY) { - // await exec(`${process.execPath} ${JD_DailyBonusPath} >> ${resultPath}`); - // const notifyContent = await fs.readFileSync(resultPath, "utf8"); - // console.log(`👇👇👇👇👇👇👇👇👇👇👇LOG记录👇👇👇👇👇👇👇👇👇👇👇\n${notifyContent}\n👆👆👆👆👆👆👆👆👆LOG记录👆👆👆👆👆👆👆👆👆👆👆`); - // } else { - // console.log('没有提供通知推送,则打印脚本执行日志') - // await exec(`${process.execPath} ${JD_DailyBonusPath}`, { stdio: "inherit" }); - // } - await exec(`${process.execPath} ${JD_DailyBonusPath} >> ${resultPath}`); - const notifyContent = await fs.readFileSync(resultPath, "utf8"); - console.error(`👇👇👇👇👇👇👇👇👇👇👇签到详情👇👇👇👇👇👇👇👇👇👇👇\n${notifyContent}\n👆👆👆👆👆👆👆👆👆签到详情👆👆👆👆👆👆👆👆👆👆👆`); - // await exec("node JD_DailyBonus.js", { stdio: "inherit" }); - // console.log('执行完毕', new Date(new Date().getTime() + 8 * 3600000).toLocaleDateString()) - //发送通知 - let BarkContent = ''; - if (fs.existsSync(resultPath)) { - const barkContentStart = notifyContent.indexOf('【签到概览】') - const barkContentEnd = notifyContent.length; - if (process.env.JD_BEAN_SIGN_STOP_NOTIFY !== 'true') { - if (process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE === 'true') { - if (barkContentStart > -1 && barkContentEnd > -1) { - BarkContent = notifyContent.substring(barkContentStart, barkContentEnd); - } - BarkContent = BarkContent.split('\n\n')[0]; - } else { - if (barkContentStart > -1 && barkContentEnd > -1) { - BarkContent = notifyContent.substring(barkContentStart, barkContentEnd); - } - } + return undefined } } - //不管哪个时区,这里得到的都是北京时间的时间戳; - const UTC8 = new Date().getTime() + new Date().getTimezoneOffset()*60000 + 28800000; - $.beanSignTime = new Date(UTC8).toLocaleString('zh', {hour12: false}); - //console.log(`脚本执行完毕时间:${$.beanSignTime}`) - if (BarkContent) { - allMessage += `【京东号 ${$.index}】: ${$.nickName || $.UserName}\n【签到时间】: ${$.beanSignTime}\n${BarkContent}${$.index !== cookiesArr.length ? '\n\n' : ''}`; - if (!process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE || (process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE && process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE !== 'true')) { - await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}`, `【签到号 ${$.index}】: ${$.nickName || $.UserName}\n【签到时间】: ${$.beanSignTime}\n${BarkContent}`); - } - } - //运行完成后,删除下载的文件 - await deleteFile(resultPath);//删除result.txt - await deleteFile('./CookieSet.json') - console.log(`\n\n*****************${new Date(new Date().getTime()).toLocaleString('zh', {hour12: false})} 京东账号${$.index} ${$.nickName || $.UserName} ${$.name}完成*******************\n\n`); - } catch (e) { - console.log("京东签到脚本执行异常:" + e); - } -} -async function downFile () { - let url = ''; - await downloadUrl(); - if ($.body) { - url = 'https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js'; - } else { - url = 'https://cdn.jsdelivr.net/gh/NobyDa/Script@master/JD-DailyBonus/JD_DailyBonus.js'; - } - try { - const options = { } - if (process.env.TG_PROXY_HOST && process.env.TG_PROXY_PORT) { - const tunnel = require("tunnel"); - const agent = { - https: tunnel.httpsOverHttp({ - proxy: { - host: process.env.TG_PROXY_HOST, - port: process.env.TG_PROXY_PORT * 1 - } - }) - } - Object.assign(options, { agent }) - } - await download(url, outPutUrl, options); - console.log(`JD_DailyBonus.js文件下载完毕\n\n`); - } catch (e) { - console.log("JD_DailyBonus.js 文件下载异常:" + e); - } -} - -async function changeFile (content) { - console.log(`开始替换变量`) - let newContent = content.replace(/var OtherKey = `.*`/, `var OtherKey = \`[{"cookie":"${cookie}","jrBody":"${jrBody}"}]\``); - newContent = newContent.replace(/const NodeSet = 'CookieSet.json'/, `const NodeSet = '${NodeSet}'`) - if (process.env.JD_BEAN_STOP && process.env.JD_BEAN_STOP !== '0') { - newContent = newContent.replace(/var stop = '0'/, `var stop = '${process.env.JD_BEAN_STOP}'`); - } - const zone = new Date().getTimezoneOffset(); - if (zone === 0) { - //此处针对UTC-0时区用户做的 - newContent = newContent.replace(/tm\s=.*/, `tm = new Date(new Date().toLocaleDateString()).getTime() - 28800000;`); - } - try { - await fs.writeFileSync(JD_DailyBonusPath, newContent, 'utf8'); - console.log('替换变量完毕'); - } catch (e) { - console.log("京东签到写入文件异常:" + e); - } -} -async function deleteFile(path) { - // 查看文件result.txt是否存在,如果存在,先删除 - const fileExists = await fs.existsSync(path); - // console.log('fileExists', fileExists); - if (fileExists) { - const unlinkRes = await fs.unlinkSync(path); - // console.log('unlinkRes', unlinkRes) - } -} -function TotalBean() { - return new Promise(async resolve => { - const options = { - "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, - "headers": { - "Accept": "application/json,text/plain, */*", - "Content-Type": "application/x-www-form-urlencoded", - "Accept-Encoding": "gzip, deflate, br", - "Accept-Language": "zh-cn", - "Connection": "keep-alive", - "Cookie": cookie, - "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", - "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1") - }, - "timeout": 10000 - } - $.post(options, (err, resp, data) => { - try { - if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) - } else { - if (data) { - data = JSON.parse(data); - if (data['retcode'] === 13) { - $.isLogin = false; //cookie过期 - return - } - if (data['retcode'] === 0) { - $.nickName = (data['base'] && data['base'].nickname) || $.UserName; - } else { - $.nickName = $.UserName - } - } else { - console.log(`京东服务器返回空数据`) - } - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(); - } + console.log(`${title}\n${subtitle}\n${message}`) + notification += message + if (isQuanX) $notify(title, subtitle, message, Opts(rawopts)) + if (isSurge) $notification.post(title, subtitle, message, Opts(rawopts)) + if (isJSBox) $push.schedule({ + title: title, + body: subtitle ? subtitle + "\n" + message : message }) - }) -} -function downloadUrl(url = 'https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js') { - return new Promise(resolve => { - const options = { url, "timeout": 10000 }; - if ($.isNode() && process.env.TG_PROXY_HOST && process.env.TG_PROXY_PORT) { - const tunnel = require("tunnel"); - const agent = { - https: tunnel.httpsOverHttp({ - proxy: { - host: process.env.TG_PROXY_HOST, - port: process.env.TG_PROXY_PORT * 1 - } - }) - } - Object.assign(options, { agent }) - } - $.get(options, async (err, resp, data) => { - try { - if (err) { - // console.log(`${JSON.stringify(err)}`) - console.log(`检测到您当前网络环境不能访问外网,将使用jsdelivr CDN下载JD_DailyBonus.js文件`); - await $.http.get({url: `https://purge.jsdelivr.net/gh/NobyDa/Script@master/JD-DailyBonus/JD_DailyBonus.js`, timeout: 10000}).then((resp) => { - if (resp.statusCode === 200) { - let { body } = resp; - body = JSON.parse(body); - if (body['success']) { - console.log(`JD_DailyBonus.js文件 CDN刷新成功`) - } else { - console.log(`JD_DailyBonus.js文件 CDN刷新失败`) - } - } - }); - } else { - $.body = data; - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(); - } - }) - }) -} -function requireConfig() { - return new Promise(resolve => { - // const file = 'jd_bean_sign.js'; - // fs.access(file, fs.constants.W_OK, (err) => { - // resultPath = err ? '/tmp/result.txt' : resultPath; - // JD_DailyBonusPath = err ? '/tmp/JD_DailyBonus.js' : JD_DailyBonusPath; - // outPutUrl = err ? '/tmp/' : outPutUrl; - // NodeSet = err ? '/tmp/CookieSet.json' : NodeSet; - // resolve() - // }); - //判断是否是云函数环境。原函数跟目录目录没有可写入权限,文件只能放到根目录下虚拟的/temp/文件夹(具有可写入权限) - resultPath = process.env.TENCENTCLOUD_RUNENV === 'SCF' ? '/tmp/result.txt' : resultPath; - JD_DailyBonusPath = process.env.TENCENTCLOUD_RUNENV === 'SCF' ? '/tmp/JD_DailyBonus.js' : JD_DailyBonusPath; - outPutUrl = process.env.TENCENTCLOUD_RUNENV === 'SCF' ? '/tmp/' : outPutUrl; - NodeSet = process.env.TENCENTCLOUD_RUNENV === 'SCF' ? '/tmp/CookieSet.json' : NodeSet; - resolve() - }) -} -function timeFormat(time) { - let date; - if (time) { - date = new Date(time) - } else { - date = new Date(); } - return date.getFullYear() + '-' + ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()); -} -function Env(t,e){"undefined"!=typeof process&&JSON.stringify(process.env).indexOf("GITHUB")>-1&&process.exit(0);class s{constructor(t){this.env=t}send(t,e="GET"){t="string"==typeof t?{url:t}:t;let s=this.get;return"POST"===e&&(s=this.post),new Promise((e,i)=>{s.call(this,t,(t,s,r)=>{t?i(t):e(s)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t,this.http=new s(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.isNeedRewrite=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,e),this.log("",`🔔${this.name}, 开始!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const i=this.getdata(t);if(i)try{s=JSON.parse(this.getdata(t))}catch{}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return!1}}getScript(t){return new Promise(e=>{this.get({url:t},(t,s,i)=>e(i))})}runScript(t,e){return new Promise(s=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let r=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");r=r?1*r:20,r=e&&e.timeout?e.timeout:r;const[o,h]=i.split("@"),n={url:`http://${h}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:r},headers:{"X-Key":o,Accept:"*/*"}};this.post(n,(t,e,i)=>s(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e);if(!s&&!i)return{};{const i=s?t:e;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){return{}}}}}writedata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),e=this.path.resolve(process.cwd(),this.dataFile),s=this.fs.existsSync(t),i=!s&&this.fs.existsSync(e),r=JSON.stringify(this.data);s?this.fs.writeFileSync(t,r):i?this.fs.writeFileSync(e,r):this.fs.writeFileSync(t,r)}}lodash_get(t,e,s){const i=e.replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const t of i)if(r=Object(r)[t],void 0===r)return s;return r}lodash_set(t,e,s){return Object(t)!==t?t:(Array.isArray(e)||(e=e.toString().match(/[^.[\]]+/g)||[]),e.slice(0,-1).reduce((t,s,i)=>Object(t[s])===t[s]?t[s]:t[s]=Math.abs(e[i+1])>>0==+e[i+1]?[]:{},t)[e[e.length-1]]=s,t)}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,s,i]=/^@(.*?)\.(.*?)$/.exec(t),r=s?this.getval(s):"";if(r)try{const t=JSON.parse(r);e=t?this.lodash_get(t,i,""):e}catch(t){e=""}}return e}setdata(t,e){let s=!1;if(/^@/.test(e)){const[,i,r]=/^@(.*?)\.(.*?)$/.exec(e),o=this.getval(i),h=i?"null"===o?null:o||"{}":"{}";try{const e=JSON.parse(h);this.lodash_set(e,r,t),s=this.setval(JSON.stringify(e),i)}catch(e){const o={};this.lodash_set(o,r,t),s=this.setval(JSON.stringify(o),i)}}else s=this.setval(t,e);return s}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,e){return this.isSurge()||this.isLoon()?$persistentStore.write(t,e):this.isQuanX()?$prefs.setValueForKey(t,e):this.isNode()?(this.data=this.loaddata(),this.data[e]=t,this.writedata(),!0):this.data&&this.data[e]||null}initGotEnv(t){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,e=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?(this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.get(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)})):this.isQuanX()?(this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t))):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const s=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),e.cookieJar=this.ckjar}}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)}))}post(t,e=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())this.isSurge()&&this.isNeedRewrite&&(t.headers=t.headers||{},Object.assign(t.headers,{"X-Surge-Skip-Scripting":!1})),$httpClient.post(t,(t,s,i)=>{!t&&s&&(s.body=i,s.statusCode=s.status),e(t,s,i)});else if(this.isQuanX())t.method="POST",this.isNeedRewrite&&(t.opts=t.opts||{},Object.assign(t.opts,{hints:!1})),$task.fetch(t).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>e(t));else if(this.isNode()){this.initGotEnv(t);const{url:s,...i}=t;this.got.post(s,i).then(t=>{const{statusCode:s,statusCode:i,headers:r,body:o}=t;e(null,{status:s,statusCode:i,headers:r,body:o},o)},t=>{const{message:s,response:i}=t;e(s,i,i&&i.body)})}}time(t,e=null){const s=e?new Date(e):new Date;let i={"M+":s.getMonth()+1,"d+":s.getDate(),"H+":s.getHours(),"m+":s.getMinutes(),"s+":s.getSeconds(),"q+":Math.floor((s.getMonth()+3)/3),S:s.getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(s.getFullYear()+"").substr(4-RegExp.$1.length)));for(let e in i)new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?i[e]:("00"+i[e]).substr((""+i[e]).length)));return t}msg(e=t,s="",i="",r){const o=t=>{if(!t)return t;if("string"==typeof t)return this.isLoon()?t:this.isQuanX()?{"open-url":t}:this.isSurge()?{url:t}:void 0;if("object"==typeof t){if(this.isLoon()){let e=t.openUrl||t.url||t["open-url"],s=t.mediaUrl||t["media-url"];return{openUrl:e,mediaUrl:s}}if(this.isQuanX()){let e=t["open-url"]||t.url||t.openUrl,s=t["media-url"]||t.mediaUrl;return{"open-url":e,"media-url":s}}if(this.isSurge()){let e=t.url||t.openUrl||t["open-url"];return{url:e}}}};if(this.isMute||(this.isSurge()||this.isLoon()?$notification.post(e,s,i,o(r)):this.isQuanX()&&$notify(e,s,i,o(r))),!this.isMuteLog){let t=["","==============📣系统通知📣=============="];t.push(e),s&&t.push(s),i&&t.push(i),console.log(t.join("\n")),this.logs=this.logs.concat(t)}}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,e){const s=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();s?this.log("",`❗️${this.name}, 错误!`,t.stack):this.log("",`❗️${this.name}, 错误!`,t)}wait(t){return new Promise(e=>setTimeout(e,t))}done(t={}){const e=(new Date).getTime(),s=(e-this.startTime)/1e3;this.log("",`🔔${this.name}, 结束! 🕛 ${s} 秒`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,e)} + const write = (value, key) => { + if (isQuanX) return $prefs.setValueForKey(value, key) + if (isSurge) return $persistentStore.write(value, key) + if (isNode) { + try { + if (!node.fs.existsSync(node.path.resolve(__dirname, NodeSet))) + node.fs.writeFileSync(node.path.resolve(__dirname, NodeSet), JSON.stringify({})); + const dataValue = JSON.parse(node.fs.readFileSync(node.path.resolve(__dirname, NodeSet))); + if (value) dataValue[key] = value; + if (!value) delete dataValue[key]; + return node.fs.writeFileSync(node.path.resolve(__dirname, NodeSet), JSON.stringify(dataValue)); + } catch (er) { + return AnError('Node.js持久化写入', null, er); + } + } + if (isJSBox) { + if (!value) return $file.delete(`shared://${key}.txt`); + return $file.write({ + data: $data({ + string: value + }), + path: `shared://${key}.txt` + }) + } + } + const read = (key) => { + if (isQuanX) return $prefs.valueForKey(key) + if (isSurge) return $persistentStore.read(key) + if (isNode) { + try { + if (!node.fs.existsSync(node.path.resolve(__dirname, NodeSet))) return null; + const dataValue = JSON.parse(node.fs.readFileSync(node.path.resolve(__dirname, NodeSet))) + return dataValue[key] + } catch (er) { + return AnError('Node.js持久化读取', null, er) + } + } + if (isJSBox) { + if (!$file.exists(`shared://${key}.txt`)) return null; + return $file.read(`shared://${key}.txt`).string + } + } + const adapterStatus = (response) => { + if (response) { + if (response.status) { + response["statusCode"] = response.status + } else if (response.statusCode) { + response["status"] = response.statusCode + } + } + return response + } + const get = (options, callback) => { + options.headers['User-Agent'] = 'JD4iPhone/167169 (iPhone; iOS 13.4.1; Scale/3.00)' + if (isQuanX) { + if (typeof options == "string") options = { + url: options + } + options["method"] = "GET" + //options["opts"] = { + // "hints": false + //} + $task.fetch(options).then(response => { + callback(null, adapterStatus(response), response.body) + }, reason => callback(reason.error, null, null)) + } + if (isSurge) { + options.headers['X-Surge-Skip-Scripting'] = false + $httpClient.get(options, (error, response, body) => { + callback(error, adapterStatus(response), body) + }) + } + if (isNode) { + node.request(options, (error, response, body) => { + callback(error, adapterStatus(response), body) + }) + } + if (isJSBox) { + if (typeof options == "string") options = { + url: options + } + options["header"] = options["headers"] + options["handler"] = function(resp) { + let error = resp.error; + if (error) error = JSON.stringify(resp.error) + let body = resp.data; + if (typeof body == "object") body = JSON.stringify(resp.data); + callback(error, adapterStatus(resp.response), body) + }; + $http.get(options); + } + } + const post = (options, callback) => { + options.headers['User-Agent'] = 'JD4iPhone/167169 (iPhone; iOS 13.4.1; Scale/3.00)' + if (options.body) options.headers['Content-Type'] = 'application/x-www-form-urlencoded' + if (isQuanX) { + if (typeof options == "string") options = { + url: options + } + options["method"] = "POST" + //options["opts"] = { + // "hints": false + //} + $task.fetch(options).then(response => { + callback(null, adapterStatus(response), response.body) + }, reason => callback(reason.error, null, null)) + } + if (isSurge) { + options.headers['X-Surge-Skip-Scripting'] = false + $httpClient.post(options, (error, response, body) => { + callback(error, adapterStatus(response), body) + }) + } + if (isNode) { + node.request.post(options, (error, response, body) => { + callback(error, adapterStatus(response), body) + }) + } + if (isJSBox) { + if (typeof options == "string") options = { + url: options + } + options["header"] = options["headers"] + options["handler"] = function(resp) { + let error = resp.error; + if (error) error = JSON.stringify(resp.error) + let body = resp.data; + if (typeof body == "object") body = JSON.stringify(resp.data) + callback(error, adapterStatus(resp.response), body) + } + $http.post(options); + } + } + const AnError = (name, keyname, er, resp, body) => { + if (typeof(merge) != "undefined" && keyname) { + if (!merge[keyname].notify) { + merge[keyname].notify = `${name}: 异常, 已输出日志 ‼️` + } else { + merge[keyname].notify += `\n${name}: 异常, 已输出日志 ‼️ (2)` + } + merge[keyname].error = 1 + } + return console.log(`\n‼️${name}发生错误\n‼️名称: ${er.name}\n‼️描述: ${er.message}${JSON.stringify(er).match(/\"line\"/)?`\n‼️行列: ${JSON.stringify(er)}`:``}${resp&&resp.status?`\n‼️状态: ${resp.status}`:``}${body?`\n‼️响应: ${resp&&resp.status!=503?body:`Omit.`}`:``}`) + } + const time = () => { + const end = ((Date.now() - start) / 1000).toFixed(2) + return console.log('\n签到用时: ' + end + ' 秒') + } + const done = (value = {}) => { + if (isQuanX) return $done(value) + if (isSurge) isRequest ? $done(value) : $done() + } + return { + AnError, + isRequest, + isJSBox, + isSurge, + isQuanX, + isLoon, + isNode, + notify, + write, + read, + get, + post, + time, + done + } +}; +}).catch(e => { +console.error("ERRROR:",e) +}) diff --git a/jd_jrmx.py b/jd_jrmx.py new file mode 100644 index 0000000..6310954 --- /dev/null +++ b/jd_jrmx.py @@ -0,0 +1,273 @@ +# -*- coding:utf-8 -*- +#依赖管理-Python3-添加依赖PyExecJS +#依赖安装:进入容器执行:pip3 install PyExecJS +#想拿券的cookie环境变量JDJR_COOKIE,格式就是普通的cookie格式(pt_key=xxx;pt_pin=xxx) +#活动每天早上10点开始截止到这个月28号,建议corn 5 0 10 * * * + +""" +cron: 5 0 10 * * * +new Env('京东金融分享助力'); +""" + +import execjs +import requests +import json +import time +import os +import re +import sys +import random +import string +import urllib +from urllib.parse import quote + + +#以下部分参考Curtin的脚本:https://github.com/curtinlv/JD-Script + + +def randomuserAgent(): + global uuid,addressid,iosVer,iosV,clientVersion,iPhone,ADID,area,lng,lat + + uuid=''.join(random.sample(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','a','b','c','z'], 40)) + addressid = ''.join(random.sample('1234567898647', 10)) + iosVer = ''.join(random.sample(["15.1.1","14.5.1", "14.4", "14.3", "14.2", "14.1", "14.0.1"], 1)) + iosV = iosVer.replace('.', '_') + clientVersion=''.join(random.sample(["10.3.0", "10.2.7", "10.2.4"], 1)) + iPhone = ''.join(random.sample(["8", "9", "10", "11", "12", "13"], 1)) + ADID = ''.join(random.sample('0987654321ABCDEF', 8)) + '-' + ''.join(random.sample('0987654321ABCDEF', 4)) + '-' + ''.join(random.sample('0987654321ABCDEF', 4)) + '-' + ''.join(random.sample('0987654321ABCDEF', 4)) + '-' + ''.join(random.sample('0987654321ABCDEF', 12)) + + + area=''.join(random.sample('0123456789', 2)) + '_' + ''.join(random.sample('0123456789', 4)) + '_' + ''.join(random.sample('0123456789', 5)) + '_' + ''.join(random.sample('0123456789', 4)) + lng='119.31991256596'+str(random.randint(100,999)) + lat='26.1187118976'+str(random.randint(100,999)) + + + UserAgent='' + if not UserAgent: + return f'jdapp;iPhone;10.0.4;{iosVer};{uuid};network/wifi;ADID/{ADID};model/iPhone{iPhone},1;addressid/{addressid};appBuild/167707;jdSupportDarkMode/0;Mozilla/5.0 (iPhone; CPU iPhone OS {iosV} like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/null;supportJDSHWK/1' + else: + return UserAgent + +#以上部分参考Curtin的脚本:https://github.com/curtinlv/JD-Script + + +def printf(text): + print(text+'\n') + sys.stdout.flush() + + +def load_send(): + global send + cur_path = os.path.abspath(os.path.dirname(__file__)) + sys.path.append(cur_path) + if os.path.exists(cur_path + "/sendNotify.py"): + try: + from sendNotify import send + except: + send=False + printf("加载通知服务失败~") + else: + send=False + printf("加载通知服务失败~") +load_send() + + + +def get_remarkinfo(): + url='http://127.0.0.1:5600/api/envs' + try: + with open('/ql/config/auth.json', 'r') as f: + token=json.loads(f.read())['token'] + headers={ + 'Accept':'application/json', + 'authorization':'Bearer '+token, + } + response=requests.get(url=url,headers=headers) + + for i in range(len(json.loads(response.text)['data'])): + if json.loads(response.text)['data'][i]['name']=='JD_COOKIE': + try: + if json.loads(response.text)['data'][i]['remarks'].find('@@')==-1: + remarkinfos[json.loads(response.text)['data'][i]['value'].split(';')[1].replace('pt_pin=','')]=json.loads(response.text)['data'][i]['remarks'].replace('remark=','') + else: + remarkinfos[json.loads(response.text)['data'][i]['value'].split(';')[1].replace('pt_pin=','')]=json.loads(response.text)['data'][i]['remarks'].split("@@")[0].replace('remark=','').replace(';','') + except: + pass + except: + printf('读取auth.json文件出错,跳过获取备注') + + +def JDSignValidator(url): + with open('JDJRSignValidator.js', 'r', encoding='utf-8') as f: + jstext = f.read() + ctx = execjs.compile(jstext) + result = ctx.call('getBody', url) + fp=result['fp'] + a=result['a'] + d=result['d'] + return fp,a,d + + +def geteid(a,d): + url=f'https://gia.jd.com/fcf.html?a={a}' + data=f'&d={d}' + headers={ + 'Host':'gia.jd.com', + 'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8', + 'Origin':'https://jrmkt.jd.com', + 'Accept-Encoding':'gzip, deflate, br', + 'Connection':'keep-alive', + 'Accept':'*/*', + 'User-Agent':UserAgent, + 'Referer':'https://jrmkt.jd.com/', + 'Content-Length':'376', + 'Accept-Language':'zh-CN,zh-Hans;q=0.9', + } + response=requests.post(url=url,headers=headers,data=data) + return response.text + + + +def gettoken(): + url='https://gia.jd.com/m.html' + headers={'User-Agent':UserAgent} + response=requests.get(url=url,headers=headers) + return response.text.split(';')[0].replace('var jd_risk_token_id = \'','').replace('\'','') + + +def getsharetasklist(ck,eid,fp,token): + url='https://ms.jr.jd.com/gw/generic/bt/h5/m/getShareTaskList' + data='reqData='+quote('{"extMap":{"eid":"%s","fp":"%s","sdkToken":"","token":"%s","appType":"1","pageUrl":"https://btfront.jd.com/release/shareCouponRedemption/helpList/?channelId=17&channelName=pdy&jrcontainer=h5&jrlogin=true&jrcloseweb=false"},"channelId":"17","bizGroup":18}'%(eid,fp,token)) + headers={ + 'Host':'ms.jr.jd.com', + 'Content-Type':'application/x-www-form-urlencoded', + 'Origin':'https://btfront.jd.com', + 'Accept-Encoding':'gzip, deflate, br', + 'Cookie':ck, + 'Connection':'keep-alive', + 'Accept':'application/json, text/plain, */*', + 'User-Agent':UserAgent, + 'Referer':'https://btfront.jd.com/', + 'Content-Length':str(len(data)), + 'Accept-Language':'zh-CN,zh-Hans;q=0.9' + } + try: + response=requests.post(url=url,headers=headers,data=data) + for i in range(len(json.loads(response.text)['resultData']['data'])): + if json.loads(response.text)['resultData']['data'][i]['couponBigWord']=='12' and json.loads(response.text)['resultData']['data'][i]['couponSmallWord']=='期': + printf('12期免息券活动id:'+str(json.loads(response.text)['resultData']['data'][i]['activityId'])) + return json.loads(response.text)['resultData']['data'][i]['activityId'] + break + except: + printf('获取任务信息出错,程序即将退出!') + os._exit(0) + + + +def obtainsharetask(ck,eid,fp,token,activityid): + url='https://ms.jr.jd.com/gw/generic/bt/h5/m/obtainShareTask' + data='reqData='+quote('{"extMap":{"eid":"%s","fp":"%s","sdkToken":"","token":"%s","appType":"1","pageUrl":"https://btfront.jd.com/release/shareCouponRedemption/helpList/?channelId=17&channelName=pdy&jrcontainer=h5&jrlogin=true&jrcloseweb=false"},"activityId":%s}'%(eid,fp,token,activityid)) + headers={ + 'Host':'ms.jr.jd.com', + 'Content-Type':'application/x-www-form-urlencoded', + 'Origin':'https://btfront.jd.com', + 'Accept-Encoding':'gzip, deflate, br', + 'Cookie':ck, + 'Connection':'keep-alive', + 'Accept':'application/json, text/plain, */*', + 'User-Agent':UserAgent, + 'Referer':'https://btfront.jd.com/', + 'Content-Length':str(len(data)), + 'Accept-Language':'zh-CN,zh-Hans;q=0.9' + } + try: + response=requests.post(url=url,headers=headers,data=data) + printf('obtainActivityId:'+json.loads(response.text)['resultData']['data']['obtainActivityId']) + printf('inviteCode:'+json.loads(response.text)['resultData']['data']['inviteCode']) + return json.loads(response.text)['resultData']['data']['obtainActivityId']+'@'+json.loads(response.text)['resultData']['data']['inviteCode'] + except: + printf('开启任务出错,程序即将退出!') + os._exit(0) + + +def assist(ck,eid,fp,token,obtainActivityid,invitecode): + url='https://ms.jr.jd.com/gw/generic/bt/h5/m/helpFriend' + data='reqData='+quote('{"extMap":{"eid":"%s","fp":"%s","sdkToken":"","token":"%s","appType":"10","pageUrl":"https://btfront.jd.com/release/shareCouponRedemption/sharePage/?obtainActivityId=%s&channelId=17&channelName=pdy&jrcontainer=h5&jrcloseweb=false&jrlogin=true&inviteCode=%s"},"obtainActivityId":"%s","inviteCode":"%s"}'%(eid,fp,token,obtainActivityid,invitecode,obtainActivityid,invitecode)) + headers={ + 'Host':'ms.jr.jd.com', + 'Content-Type':'application/x-www-form-urlencoded', + 'Origin':'https://btfront.jd.com', + 'Accept-Encoding':'gzip, deflate, br', + 'Cookie':ck, + 'Connection':'keep-alive', + 'Accept':'application/json, text/plain, */*', + 'User-Agent':UserAgent, + 'Referer':'https://btfront.jd.com/', + 'Content-Length':str(len(data)), + 'Accept-Language':'zh-CN,zh-Hans;q=0.9' + } + try: + response=requests.post(url=url,headers=headers,data=data) + if response.text.find('本次助力活动已完成')!=-1: + send('京东白条12期免息优惠券助力完成','去京东金融-白条-我的-我的优惠券看看吧') + printf('助力完成,程序即将退出!') + os._exit(0) + else: + if json.loads(response.text)['resultData']['result']['code']=='0000': + printf('助力成功') + elif json.loads(response.text)['resultData']['result']['code']=='M1003': + printf('该用户未开启白条,助力失败!') + elif json.loads(response.text)['resultData']['result']['code']=='U0002': + printf('该用户白条账户异常,助力失败!') + elif json.loads(response.text)['resultData']['result']['code']=='E0004': + printf('该活动仅限受邀用户参与,助力失败!') + else: + print(response.text) + except: + try: + print(response.text) + except: + printf('助力出错,可能是cookie过期了') + + + +if __name__ == '__main__': + remarkinfos={} + get_remarkinfo() + + + jdjrcookie=os.environ["JDJR_COOKIE"] + + UserAgent=randomuserAgent() + info=JDSignValidator('https://jrmfp.jr.jd.com/') + eid=json.loads(geteid(info[1],info[2]).split('_*')[1])['eid'] + fp=info[0] + token=gettoken() + activityid=getsharetasklist(jdjrcookie,eid,fp,token) + inviteinfo=obtainsharetask(jdjrcookie,eid,fp,token,activityid) + + + try: + cks = os.environ["JD_COOKIE"].split("&") + except: + f = open("/jd/config/config.sh", "r", encoding='utf-8') + cks = re.findall(r'Cookie[0-9]*="(pt_key=.*?;pt_pin=.*?;)"', f.read()) + f.close() + for ck in cks: + ptpin = re.findall(r"pt_pin=(.*?);", ck)[0] + try: + if remarkinfos[ptpin]!='': + printf("--账号:" + remarkinfos[ptpin] + "--") + username=remarkinfos[ptpin] + else: + printf("--无备注账号:" + urllib.parse.unquote(ptpin) + "--") + username=urllib.parse.unquote(ptpin) + except: + printf("--账号:" + urllib.parse.unquote(ptpin) + "--") + username=urllib.parse.unquote(ptpin) + UserAgent=randomuserAgent() + info=JDSignValidator('https://jrmfp.jr.jd.com/') + eid=json.loads(geteid(info[1],info[2]).split('_*')[1])['eid'] + fp=info[0] + token=gettoken() + assist(ck,eid,fp,token,inviteinfo.split('@')[0],inviteinfo.split('@')[1]) diff --git a/jd_m_sign.js b/jd_m_sign.js index ebcd994..322c1c1 100644 --- a/jd_m_sign.js +++ b/jd_m_sign.js @@ -6,7 +6,7 @@ =========================== [task_local] #京东通天塔--签到 -3 0 * * * jd_m_sign.js, tag=京东通天塔--签到, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jd.png, enabled=true +3 1,11 * * * jd_m_sign.js, tag=京东通天塔--签到, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jd.png, enabled=true */ const $ = new Env('京东通天塔--签到'); @@ -64,14 +64,18 @@ async function jdsign() { try { console.log(`签到开始........`) await getInfo("https://pro.m.jd.com/mall/active/3S28janPLYmtFxypu37AYAGgivfp/index.html");//拍拍二手签到 - await $.wait(1000) - await getInfo("https://pro.m.jd.com/mall/active/4QjXVcRyTcRaLPaU6z2e3Sw1QzWE/index.html");//全城购签到 - await $.wait(1000) - await getInfo("https://prodev.m.jd.com/mall/active/3MFSkPGCDZrP2WPKBRZdiKm9AZ7D/index.html");//同城签到 - await $.wait(1000) + await $.wait(2000) await getInfo("https://pro.m.jd.com/mall/active/kPM3Xedz1PBiGQjY4ZYGmeVvrts/index.html");//陪伴 - await $.wait(1000) + await $.wait(2000) await getInfo("https://pro.m.jd.com/mall/active/3SC6rw5iBg66qrXPGmZMqFDwcyXi/index.html");//京东图书 + await $.wait(2000) + await getInfo("https://prodev.m.jd.com/mall/active/412SRRXnKE1Q4Y6uJRWVT6XhyseG/index.html");//京东服装 +// await getInfo("https://pro.m.jd.com/mall/active/ZrH7gGAcEkY2gH8wXqyAPoQgk6t/index.html");//箱包签到 +// await $.wait(1000) +// await getInfo("https://pro.m.jd.com/mall/active/4RXyb1W4Y986LJW8ToqMK14BdTD/index.html");//鞋靴馆签到 + +// await $.wait(1000) +// await getInfo("https://pro.m.jd.com/mall/active/3joSPpr7RgdHMbcuqoRQ8HbcPo9U/index.html");//生活特权签到 } catch (e) { $.logErr(e) } diff --git a/jd_pet.js b/jd_pet.js index 636ed8c..8ce6155 100644 --- a/jd_pet.js +++ b/jd_pet.js @@ -1,1062 +1,1076 @@ -/* -东东萌宠 更新地址: jd_pet.js -更新时间:2021-05-21 -活动入口:京东APP我的-更多工具-东东萌宠 -已支持IOS多京东账号,Node.js支持N个京东账号 -脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js - -互助码shareCode请先手动运行脚本查看打印可看到 -一天只能帮助5个人。多出的助力码无效 - -=================================Quantumultx========================= -[task_local] -#东东萌宠 -15 6-18/6 * * * jd_pet.js, tag=东东萌宠, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jdmc.png, enabled=true - -=================================Loon=================================== -[Script] -cron "15 6-18/6 * * *" script-path=jd_pet.js,tag=东东萌宠 - -===================================Surge================================ -东东萌宠 = type=cron,cronexp="15 6-18/6 * * *",wake-system=1,timeout=3600,script-path=jd_pet.js - -====================================小火箭============================= -东东萌宠 = type=cron,script-path=jd_pet.js, cronexpr="15 6-18/6 * * *", timeout=3600, enable=true - - */ -const $ = new Env('东东萌宠互助版'); -let cookiesArr = [], cookie = '', jdPetShareArr = [], isBox = false, allMessage = ''; -let message = '', subTitle = '', option = {}; -let jdNotify = false; //是否关闭通知,false打开通知推送,true关闭通知推送 -const JD_API_HOST = 'https://api.m.jd.com/client.action'; -let goodsUrl = '', taskInfoKey = []; -let notify = $.isNode() ? require('./sendNotify') : ''; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; -let newShareCodes = []; -let NoNeedCodes = []; -if ($.isNode()) { - Object.keys(jdCookieNode).forEach((item) => { - if (jdCookieNode[item]) { - cookiesArr.push(jdCookieNode[item]) - } - }) - if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') - console.log = () => {}; -} else { - cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); -} - -let NowHour = new Date().getHours(); -let llhelp=true; -if ($.isNode() && process.env.CC_NOHELPAFTER8) { - console.log(NowHour); - if (process.env.CC_NOHELPAFTER8=="true"){ - if (NowHour>8){ - llhelp=false; - console.log(`现在是9点后时段,不启用互助....`); - } - } -} - -console.log(`共${cookiesArr.length}个京东账号\n`); - -!(async() => { - if (!cookiesArr[0]) { - $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { - "open-url": "https://bean.m.jd.com/bean/signIndex.action" - }); - return; - } - if (llhelp){ - console.log('开始收集您的互助码,用于账号内部互助,请稍等...'); - for (let i = 0; i < cookiesArr.length; i++) { - if (cookiesArr[i]) { - cookie = cookiesArr[i]; - $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); - $.index = i + 1; - $.isLogin = true; - $.nickName = ''; - await TotalBean(); - - if (!$.isLogin) { - $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { - "open-url": "https://bean.m.jd.com/bean/signIndex.action" - }); - - if ($.isNode()) { - await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); - } - continue; - } - message = ''; - subTitle = ''; - goodsUrl = ''; - taskInfoKey = []; - option = {}; - await GetShareCode(); - } - } - console.log('\n互助码收集完毕,开始执行日常任务...\n'); - } - - for (let i = 0; i < cookiesArr.length; i++) { - if (cookiesArr[i]) { - cookie = cookiesArr[i]; - $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); - $.index = i + 1; - $.isLogin = true; - $.nickName = ''; - await TotalBean(); - console.log(`开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); - if (!$.isLogin) { - $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { - "open-url": "https://bean.m.jd.com/bean/signIndex.action" - }); - - if ($.isNode()) { - await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); - } - continue; - } - message = ''; - subTitle = ''; - goodsUrl = ''; - taskInfoKey = []; - option = {}; - await jdPet(); - } - } - if ($.isNode() && allMessage && $.ctrTemp) { - await notify.sendNotify(`${$.name}`, `${allMessage}`) - } -})() -.catch((e) => { - $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') -}) -.finally(() => { - $.done(); -}) -async function jdPet() { - try { - //查询jd宠物信息 - const initPetTownRes = await request('initPetTown'); - message = `【京东账号${$.index}】${$.nickName || $.UserName}\n`; - if (initPetTownRes.code === '0' && initPetTownRes.resultCode === '0' && initPetTownRes.message === 'success') { - $.petInfo = initPetTownRes.result; - if ($.petInfo.userStatus === 0) { - await slaveHelp(); //助力好友 - $.log($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n萌宠活动未开启\n请手动去京东APP开启活动\n入口:我的->游戏与互动->查看更多开启`); - return - } - if (!$.petInfo.goodsInfo) { - $.msg($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`, { - "open-url": "openapp.jdmoble://" - }); - if ($.isNode()) - await notify.sendNotify(`${$.name} - ${$.index} - ${$.nickName || $.UserName}`, `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`); - return - } - goodsUrl = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsUrl; - // option['media-url'] = goodsUrl; - // console.log(`初始化萌宠信息完成: ${JSON.stringify(petInfo)}`); - if ($.petInfo.petStatus === 5) { - await slaveHelp(); //可以兑换而没有去兑换,也能继续助力好友 - option['open-url'] = "openApp.jdMobile://"; - $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】${$.petInfo.goodsInfo.goodsName}已可领取\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); - if ($.isNode()) { - await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n${$.petInfo.goodsInfo.goodsName}已可领取`); - } - return - } else if ($.petInfo.petStatus === 6) { - await slaveHelp(); //已领取红包,但未领养新的,也能继续助力好友 - option['open-url'] = "openApp.jdMobile://"; - $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】已领取红包,但未继续领养新的物品\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); - if ($.isNode()) { - await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n已领取红包,但未继续领养新的物品`); - } - return - } - //console.log(`\n【京东账号${$.index}(${$.UserName})的${$.name}好友互助码】${$.petInfo.shareCode}\n`); - await taskInit(); - if ($.taskInit.resultCode === '9999' || !$.taskInit.result) { - console.log('初始化任务异常, 请稍后再试'); - return - } - $.taskInfo = $.taskInit.result; - - await petSport(); //遛弯 - if (llhelp){ - await slaveHelp(); //助力好友 - } - await masterHelpInit(); //获取助力的信息 - await doTask(); //做日常任务 - await feedPetsAgain(); //再次投食 - await energyCollect(); //收集好感度 - await showMsg(); - - } else if (initPetTownRes.code === '0') { - console.log(`初始化萌宠失败: ${initPetTownRes.message}`); - } - } catch (e) { - $.logErr(e) - const errMsg = `京东账号${$.index} ${$.nickName || $.UserName}\n任务执行异常,请检查执行日志 ‼️‼️`; - if ($.isNode()) - await notify.sendNotify(`${$.name}`, errMsg); - $.msg($.name, '', `${errMsg}`) - } -} - -async function GetShareCode() { - try { - //查询jd宠物信息 - const initPetTownRes = await request('initPetTown'); - if (initPetTownRes.code === '0' && initPetTownRes.resultCode === '0' && initPetTownRes.message === 'success') { - $.petInfo = initPetTownRes.result; - if ($.petInfo.userStatus == 0 || $.petInfo.petStatus == 5 || $.petInfo.petStatus == 6 || !$.petInfo.goodsInfo) { - console.log(`【京东账号${$.index}(${$.UserName})的互助码】\n宠物状态不能被助力,跳过...`); - return; - } - console.log(`【京东账号${$.index}(${$.UserName})的互助码】\n${$.petInfo.shareCode}`); - newShareCodes.push($.petInfo.shareCode); - } - } catch (e) { - $.logErr(e) - const errMsg = `【京东账号${$.index} ${$.nickName || $.UserName}】\n任务执行异常,请检查执行日志 ‼️‼️`; - if ($.isNode()) - await notify.sendNotify(`${$.name}`, errMsg); - $.msg($.name, '', `${errMsg}`); - } -} - -// 收取所有好感度 -async function energyCollect() { - console.log('开始收取任务奖励好感度'); - let function_id = arguments.callee.name.toString(); - const response = await request(function_id); - // console.log(`收取任务奖励好感度完成:${JSON.stringify(response)}`); - if (response.resultCode === '0') { - message += `【第${response.result.medalNum + 1}块勋章完成进度】${response.result.medalPercent}%,还需收集${response.result.needCollectEnergy}好感\n`; - message += `【已获得勋章】${response.result.medalNum}块,还需收集${response.result.needCollectMedalNum}块即可兑换奖品“${$.petInfo.goodsInfo.goodsName}”\n`; - } -} -//再次投食 -async function feedPetsAgain() { - const response = await request('initPetTown'); //再次初始化萌宠 - if (response.code === '0' && response.resultCode === '0' && response.message === 'success') { - $.petInfo = response.result; - let foodAmount = $.petInfo.foodAmount; //剩余狗粮 - if (foodAmount - 100 >= 10) { - for (let i = 0; i < parseInt((foodAmount - 100) / 10); i++) { - const feedPetRes = await request('feedPets'); - console.log(`投食feedPetRes`); - if (feedPetRes.resultCode == 0 && feedPetRes.code == 0) { - console.log('投食成功') - } - } - const response2 = await request('initPetTown'); - $.petInfo = response2.result; - subTitle = $.petInfo.goodsInfo.goodsName; - // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; - // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; - } else { - console.log("目前剩余狗粮:【" + foodAmount + "】g,不再继续投食,保留部分狗粮用于完成第二天任务"); - subTitle = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsName; - // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; - // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; - } - } else { - console.log(`初始化萌宠失败: ${JSON.stringify($.petInfo)}`); - } -} - -async function doTask() { - const { - signInit, - threeMealInit, - firstFeedInit, - feedReachInit, - inviteFriendsInit, - browseShopsInit, - taskList - } = $.taskInfo; - for (let item of taskList) { - if ($.taskInfo[item].finished) { - console.log(`任务 ${item} 已完成`) - } - } - //每日签到 - if (signInit && !signInit.finished) { - await signInitFun(); - } - // 首次喂食 - if (firstFeedInit && !firstFeedInit.finished) { - await firstFeedInitFun(); - } - // 三餐 - if (threeMealInit && !threeMealInit.finished) { - if (threeMealInit.timeRange === -1) { - console.log(`未到三餐时间`); - } else { - await threeMealInitFun(); - } - } - if (browseShopsInit && !browseShopsInit.finished) { - await browseShopsInitFun(); - } - let browseSingleShopInitList = []; - taskList.map((item) => { - if (item.indexOf('browseSingleShopInit') > -1) { - browseSingleShopInitList.push(item); - } - }); - // 去逛逛好货会场 - for (let item of browseSingleShopInitList) { - const browseSingleShopInitTask = $.taskInfo[item]; - if (browseSingleShopInitTask && !browseSingleShopInitTask.finished) { - await browseSingleShopInit(browseSingleShopInitTask); - } - } - if (inviteFriendsInit && !inviteFriendsInit.finished) { - await inviteFriendsInitFun(); - } - // 投食10次 - if (feedReachInit && !feedReachInit.finished) { - await feedReachInitFun(); - } -} -// 好友助力信息 -async function masterHelpInit() { - let res = await request(arguments.callee.name.toString()); - // console.log(`助力信息: ${JSON.stringify(res)}`); - if (res.code === '0' && res.resultCode === '0') { - if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length >= 5) { - if (!res.result.addedBonusFlag) { - console.log("开始领取额外奖励"); - let getHelpAddedBonusResult = await request('getHelpAddedBonus'); - if (getHelpAddedBonusResult.resultCode === '0') { - message += `【额外奖励${getHelpAddedBonusResult.result.reward}领取】${getHelpAddedBonusResult.message}\n`; - } - console.log(`领取30g额外奖励结果:【${getHelpAddedBonusResult.message}】`); - } else { - console.log("已经领取过5好友助力额外奖励"); - message += `【额外奖励】已领取\n`; - } - } else { - console.log("助力好友未达到5个") - message += `【额外奖励】领取失败,原因:给您助力的人未达5个\n`; - } - if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length > 0) { - console.log('帮您助力的好友的名单开始') - let str = ''; - res.result.masterHelpPeoples.map((item, index) => { - if (index === (res.result.masterHelpPeoples.length - 1)) { - str += item.nickName || "匿名用户"; - } else { - str += (item.nickName || "匿名用户") + ','; - } - }) - message += `【助力您的好友】${str}\n`; - } - } -} -/** - * 助力好友, 暂时支持一个好友, 需要拿到shareCode - * shareCode为你要助力的好友的 - * 运行脚本时你自己的shareCode会在控制台输出, 可以将其分享给他人 - */ -async function slaveHelp() { - let helpPeoples = ''; - for (let code of newShareCodes) { - if(NoNeedCodes){ - var llnoneed=false; - for (let NoNeedCode of NoNeedCodes) { - if (code==NoNeedCode){ - llnoneed=true; - break; - } - } - if(llnoneed){ - console.log(`${code}助力已满,跳过...`); - continue; - } - } - console.log(`开始助力京东账号${$.index} - ${$.nickName || $.UserName}的好友: ${code}`); - if (!code) - continue; - let response = await request(arguments.callee.name.toString(), { - 'shareCode': code - }); - if (response.code === '0' && response.resultCode === '0') { - if (response.result.helpStatus === 0) { - console.log('已给好友: 【' + response.result.masterNickName + '】助力成功'); - helpPeoples += response.result.masterNickName + ','; - } else if (response.result.helpStatus === 1) { - // 您今日已无助力机会 - console.log(`助力好友${response.result.masterNickName}失败,您今日已无助力机会`); - break; - } else if (response.result.helpStatus === 2) { - //该好友已满5人助力,无需您再次助力 - NoNeedCodes.push(code); - console.log(`该好友${response.result.masterNickName}已满5人助力,无需您再次助力`); - } else { - console.log(`助力其他情况:${JSON.stringify(response)}`); - } - } else { - if(response.message=="已经助过力"){ - console.log(`此账号今天已经跑过助力了,跳出....`); - break; - }else{ - console.log(`助力好友结果: ${response.message}`); - } - - } - } - if (helpPeoples && helpPeoples.length > 0) { - message += `【您助力的好友】${helpPeoples.substr(0, helpPeoples.length - 1)}\n`; - } -} -// 遛狗, 每天次数上限10次, 随机给狗粮, 每次遛狗结束需调用getSportReward领取奖励, 才能进行下一次遛狗 -async function petSport() { - console.log('开始遛弯'); - let times = 1 - const code = 0 - let resultCode = 0 - do { - let response = await request(arguments.callee.name.toString()) - console.log(`第${times}次遛狗完成: ${JSON.stringify(response)}`); - resultCode = response.resultCode; - if (resultCode == 0) { - let sportRevardResult = await request('getSportReward'); - console.log(`领取遛狗奖励完成: ${JSON.stringify(sportRevardResult)}`); - } - times++; - } while (resultCode == 0 && code == 0) - if (times > 1) { - // message += '【十次遛狗】已完成\n'; - } -} -// 初始化任务, 可查询任务完成情况 -async function taskInit() { - console.log('开始任务初始化'); - $.taskInit = await request(arguments.callee.name.toString(), { - "version": 1 - }); -} -// 每日签到, 每天一次 -async function signInitFun() { - console.log('准备每日签到'); - const response = await request("getSignReward"); - console.log(`每日签到结果: ${JSON.stringify(response)}`); - if (response.code === '0' && response.resultCode === '0') { - console.log(`【每日签到成功】奖励${response.result.signReward}g狗粮\n`); - // message += `【每日签到成功】奖励${response.result.signReward}g狗粮\n`; - } else { - console.log(`【每日签到】${response.message}\n`); - // message += `【每日签到】${response.message}\n`; - } -} - -// 三餐签到, 每天三段签到时间 -async function threeMealInitFun() { - console.log('准备三餐签到'); - const response = await request("getThreeMealReward"); - console.log(`三餐签到结果: ${JSON.stringify(response)}`); - if (response.code === '0' && response.resultCode === '0') { - console.log(`【定时领狗粮】获得${response.result.threeMealReward}g\n`); - // message += `【定时领狗粮】获得${response.result.threeMealReward}g\n`; - } else { - console.log(`【定时领狗粮】${response.message}\n`); - // message += `【定时领狗粮】${response.message}\n`; - } -} - -// 浏览指定店铺 任务 -async function browseSingleShopInit(item) { - console.log(`开始做 ${item.title} 任务, ${item.desc}`); - const body = { - "index": item['index'], - "version": 1, - "type": 1 - }; - const body2 = { - "index": item['index'], - "version": 1, - "type": 2 - }; - const response = await request("getSingleShopReward", body); - // console.log(`点击进去response::${JSON.stringify(response)}`); - if (response.code === '0' && response.resultCode === '0') { - const response2 = await request("getSingleShopReward", body2); - // console.log(`浏览完毕领取奖励:response2::${JSON.stringify(response2)}`); - if (response2.code === '0' && response2.resultCode === '0') { - console.log(`【浏览指定店铺】获取${response2.result.reward}g\n`); - // message += `【浏览指定店铺】获取${response2.result.reward}g\n`; - } - } -} - -// 浏览店铺任务, 任务可能为多个? 目前只有一个 -async function browseShopsInitFun() { - console.log('开始浏览店铺任务'); - let times = 0; - let resultCode = 0; - let code = 0; - do { - let response = await request("getBrowseShopsReward"); - console.log(`第${times}次浏览店铺结果: ${JSON.stringify(response)}`); - code = response.code; - resultCode = response.resultCode; - times++; - } while (resultCode == 0 && code == 0 && times < 5) - console.log('浏览店铺任务结束'); -} -// 首次投食 任务 -function firstFeedInitFun() { - console.log('首次投食任务合并到10次喂食任务中\n'); -} - -// 邀请新用户 -async function inviteFriendsInitFun() { - console.log('邀请新用户功能未实现'); - if ($.taskInfo.inviteFriendsInit.status == 1 && $.taskInfo.inviteFriendsInit.inviteFriendsNum > 0) { - // 如果有邀请过新用户,自动领取60gg奖励 - const res = await request('getInviteFriendsReward'); - if (res.code == 0 && res.resultCode == 0) { - console.log(`领取邀请新用户奖励成功,获得狗粮现有狗粮${$.taskInfo.inviteFriendsInit.reward}g,${res.result.foodAmount}g`); - message += `【邀请新用户】获取狗粮${$.taskInfo.inviteFriendsInit.reward}g\n`; - } - } -} - -/** - * 投食10次 任务 - */ -async function feedReachInitFun() { - console.log('投食任务开始...'); - let finishedTimes = $.taskInfo.feedReachInit.hadFeedAmount / 10; //已经喂养了几次 - let needFeedTimes = 10 - finishedTimes; //还需要几次 - let tryTimes = 20; //尝试次数 - do { - console.log(`还需要投食${needFeedTimes}次`); - const response = await request('feedPets'); - console.log(`本次投食结果: ${JSON.stringify(response)}`); - if (response.resultCode == 0 && response.code == 0) { - needFeedTimes--; - } - if (response.resultCode == 3003 && response.code == 0) { - console.log('剩余狗粮不足, 投食结束'); - needFeedTimes = 0; - } - tryTimes--; - } while (needFeedTimes > 0 && tryTimes > 0) - console.log('投食任务结束...\n'); -} -async function showMsg() { - if ($.isNode() && process.env.PET_NOTIFY_CONTROL) { - $.ctrTemp = `${process.env.PET_NOTIFY_CONTROL}` === 'false'; - } else if ($.getdata('jdPetNotify')) { - $.ctrTemp = $.getdata('jdPetNotify') === 'false'; - } else { - $.ctrTemp = `${jdNotify}` === 'false'; - } - // jdNotify = `${notify.petNotifyControl}` === 'false' && `${jdNotify}` === 'false' && $.getdata('jdPetNotify') === 'false'; - if ($.ctrTemp) { - $.msg($.name, subTitle, message, option); - if ($.isNode()) { - allMessage += `${subTitle}\n${message}${$.index !== cookiesArr.length ? '\n\n' : ''}` - // await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}`, `${subTitle}\n${message}`); - } - } else { - $.log(`\n${message}\n`); - } -} -function TotalBean() { - return new Promise(async resolve => { - const options = { - "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, - "headers": { - "Accept": "application/json,text/plain, */*", - "Content-Type": "application/x-www-form-urlencoded", - "Accept-Encoding": "gzip, deflate, br", - "Accept-Language": "zh-cn", - "Connection": "keep-alive", - "Cookie": cookie, - "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", - "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1") - } - } - $.post(options, (err, resp, data) => { - try { - if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) - } else { - if (data) { - data = JSON.parse(data); - if (data['retcode'] === 13) { - $.isLogin = false; //cookie过期 - return - } - if (data['retcode'] === 0 && data.base && data.base.nickname) { - $.nickName = data.base.nickname; - } - } else { - console.log(`京东服务器返回空数据`) - } - } - } catch (e) { - $.logErr(e) - } - finally { - resolve(); - } - }) - }) -} -// 请求 -async function request(function_id, body = {}) { - await $.wait(3000); //歇口气儿, 不然会报操作频繁 - return new Promise((resolve, reject) => { - $.post(taskUrl(function_id, body), (err, resp, data) => { - try { - if (err) { - console.log('\n东东萌宠: API查询请求失败 ‼️‼️'); - console.log(JSON.stringify(err)); - $.logErr(err); - } else { - data = JSON.parse(data); - } - } catch (e) { - $.logErr(e, resp); - } - finally { - resolve(data) - } - }) - }) -} -// function taskUrl(function_id, body = {}) { -// return { -// url: `${JD_API_HOST}?functionId=${function_id}&appid=wh5&loginWQBiz=pet-town&body=${escape(JSON.stringify(body))}`, -// headers: { -// Cookie: cookie, -// UserAgent: $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), -// } -// }; -// } -function taskUrl(function_id, body = {}) { - body["version"] = 2; - body["channel"] = 'app'; - return { - url: `${JD_API_HOST}?functionId=${function_id}`, - body: `body=${escape(JSON.stringify(body))}&appid=wh5&loginWQBiz=pet-town&clientVersion=9.0.4`, - headers: { - 'Cookie': cookie, - 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), - 'Host': 'api.m.jd.com', - 'Content-Type': 'application/x-www-form-urlencoded', - } - }; -} -function jsonParse(str) { - if (typeof str == "string") { - try { - return JSON.parse(str); - } catch (e) { - console.log(e); - $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') - return []; - } - } -} -// prettier-ignore -function Env(t, e) { - "undefined" != typeof process && JSON.stringify(process.env).indexOf("GITHUB") > -1 && process.exit(0); - class s { - constructor(t) { - this.env = t - } - send(t, e = "GET") { - t = "string" == typeof t ? { - url: t - } - : t; - let s = this.get; - return "POST" === e && (s = this.post), - new Promise((e, i) => { - s.call(this, t, (t, s, r) => { - t ? i(t) : e(s) - }) - }) - } - get(t) { - return this.send.call(this.env, t) - } - post(t) { - return this.send.call(this.env, t, "POST") - } - } - return new class { - constructor(t, e) { - this.name = t, - this.http = new s(this), - this.data = null, - this.dataFile = "box.dat", - this.logs = [], - this.isMute = !1, - this.isNeedRewrite = !1, - this.logSeparator = "\n", - this.startTime = (new Date).getTime(), - Object.assign(this, e), - this.log("", `🔔${this.name}, 开始!`) - } - isNode() { - return "undefined" != typeof module && !!module.exports - } - isQuanX() { - return "undefined" != typeof $task - } - isSurge() { - return "undefined" != typeof $httpClient && "undefined" == typeof $loon - } - isLoon() { - return "undefined" != typeof $loon - } - toObj(t, e = null) { - try { - return JSON.parse(t) - } catch { - return e - } - } - toStr(t, e = null) { - try { - return JSON.stringify(t) - } catch { - return e - } - } - getjson(t, e) { - let s = e; - const i = this.getdata(t); - if (i) - try { - s = JSON.parse(this.getdata(t)) - } catch {} - return s - } - setjson(t, e) { - try { - return this.setdata(JSON.stringify(t), e) - } catch { - return !1 - } - } - getScript(t) { - return new Promise(e => { - this.get({ - url: t - }, (t, s, i) => e(i)) - }) - } - runScript(t, e) { - return new Promise(s => { - let i = this.getdata("@chavy_boxjs_userCfgs.httpapi"); - i = i ? i.replace(/\n/g, "").trim() : i; - let r = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); - r = r ? 1 * r : 20, - r = e && e.timeout ? e.timeout : r; - const[o, h] = i.split("@"), - n = { - url: `http://${h}/v1/scripting/evaluate`, - body: { - script_text: t, - mock_type: "cron", - timeout: r - }, - headers: { - "X-Key": o, - Accept: "*/*" - } - }; - this.post(n, (t, e, i) => s(i)) - }).catch(t => this.logErr(t)) - } - loaddata() { - if (!this.isNode()) - return {}; { - this.fs = this.fs ? this.fs : require("fs"), - this.path = this.path ? this.path : require("path"); - const t = this.path.resolve(this.dataFile), - e = this.path.resolve(process.cwd(), this.dataFile), - s = this.fs.existsSync(t), - i = !s && this.fs.existsSync(e); - if (!s && !i) - return {}; { - const i = s ? t : e; - try { - return JSON.parse(this.fs.readFileSync(i)) - } catch (t) { - return {} - } - } - } - } - writedata() { - if (this.isNode()) { - this.fs = this.fs ? this.fs : require("fs"), - this.path = this.path ? this.path : require("path"); - const t = this.path.resolve(this.dataFile), - e = this.path.resolve(process.cwd(), this.dataFile), - s = this.fs.existsSync(t), - i = !s && this.fs.existsSync(e), - r = JSON.stringify(this.data); - s ? this.fs.writeFileSync(t, r) : i ? this.fs.writeFileSync(e, r) : this.fs.writeFileSync(t, r) - } - } - lodash_get(t, e, s) { - const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); - let r = t; - for (const t of i) - if (r = Object(r)[t], void 0 === r) - return s; - return r - } - lodash_set(t, e, s) { - return Object(t) !== t ? t : (Array.isArray(e) || (e = e.toString().match(/[^.[\]]+/g) || []), e.slice(0, -1).reduce((t, s, i) => Object(t[s]) === t[s] ? t[s] : t[s] = Math.abs(e[i + 1]) >> 0 == +e[i + 1] ? [] : {}, t)[e[e.length - 1]] = s, t) - } - getdata(t) { - let e = this.getval(t); - if (/^@/.test(t)) { - const[, s, i] = /^@(.*?)\.(.*?)$/.exec(t), - r = s ? this.getval(s) : ""; - if (r) - try { - const t = JSON.parse(r); - e = t ? this.lodash_get(t, i, "") : e - } catch (t) { - e = "" - } - } - return e - } - setdata(t, e) { - let s = !1; - if (/^@/.test(e)) { - const[, i, r] = /^@(.*?)\.(.*?)$/.exec(e), - o = this.getval(i), - h = i ? "null" === o ? null : o || "{}" : "{}"; - try { - const e = JSON.parse(h); - this.lodash_set(e, r, t), - s = this.setval(JSON.stringify(e), i) - } catch (e) { - const o = {}; - this.lodash_set(o, r, t), - s = this.setval(JSON.stringify(o), i) - } - } else - s = this.setval(t, e); - return s - } - getval(t) { - return this.isSurge() || this.isLoon() ? $persistentStore.read(t) : this.isQuanX() ? $prefs.valueForKey(t) : this.isNode() ? (this.data = this.loaddata(), this.data[t]) : this.data && this.data[t] || null - } - setval(t, e) { - return this.isSurge() || this.isLoon() ? $persistentStore.write(t, e) : this.isQuanX() ? $prefs.setValueForKey(t, e) : this.isNode() ? (this.data = this.loaddata(), this.data[e] = t, this.writedata(), !0) : this.data && this.data[e] || null - } - initGotEnv(t) { - this.got = this.got ? this.got : require("got"), - this.cktough = this.cktough ? this.cktough : require("tough-cookie"), - this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar, - t && (t.headers = t.headers ? t.headers : {}, void 0 === t.headers.Cookie && void 0 === t.cookieJar && (t.cookieJar = this.ckjar)) - } - get(t, e = (() => {})) { - t.headers && (delete t.headers["Content-Type"], delete t.headers["Content-Length"]), - this.isSurge() || this.isLoon() ? (this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { - "X-Surge-Skip-Scripting": !1 - })), $httpClient.get(t, (t, s, i) => { - !t && s && (s.body = i, s.statusCode = s.status), - e(t, s, i) - })) : this.isQuanX() ? (this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { - hints: !1 - })), $task.fetch(t).then(t => { - const { - statusCode: s, - statusCode: i, - headers: r, - body: o - } = t; - e(null, { - status: s, - statusCode: i, - headers: r, - body: o - }, o) - }, t => e(t))) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { - try { - if (t.headers["set-cookie"]) { - const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); - s && this.ckjar.setCookieSync(s, null), - e.cookieJar = this.ckjar - } - } catch (t) { - this.logErr(t) - } - }).then(t => { - const { - statusCode: s, - statusCode: i, - headers: r, - body: o - } = t; - e(null, { - status: s, - statusCode: i, - headers: r, - body: o - }, o) - }, t => { - const { - message: s, - response: i - } = t; - e(s, i, i && i.body) - })) - } - post(t, e = (() => {})) { - if (t.body && t.headers && !t.headers["Content-Type"] && (t.headers["Content-Type"] = "application/x-www-form-urlencoded"), t.headers && delete t.headers["Content-Length"], this.isSurge() || this.isLoon()) - this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { - "X-Surge-Skip-Scripting": !1 - })), $httpClient.post(t, (t, s, i) => { - !t && s && (s.body = i, s.statusCode = s.status), - e(t, s, i) - }); - else if (this.isQuanX()) - t.method = "POST", this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { - hints: !1 - })), $task.fetch(t).then(t => { - const { - statusCode: s, - statusCode: i, - headers: r, - body: o - } = t; - e(null, { - status: s, - statusCode: i, - headers: r, - body: o - }, o) - }, t => e(t)); - else if (this.isNode()) { - this.initGotEnv(t); - const { - url: s, - ...i - } = t; - this.got.post(s, i).then(t => { - const { - statusCode: s, - statusCode: i, - headers: r, - body: o - } = t; - e(null, { - status: s, - statusCode: i, - headers: r, - body: o - }, o) - }, t => { - const { - message: s, - response: i - } = t; - e(s, i, i && i.body) - }) - } - } - time(t, e = null) { - const s = e ? new Date(e) : new Date; - let i = { - "M+": s.getMonth() + 1, - "d+": s.getDate(), - "H+": s.getHours(), - "m+": s.getMinutes(), - "s+": s.getSeconds(), - "q+": Math.floor((s.getMonth() + 3) / 3), - S: s.getMilliseconds() - }; - /(y+)/.test(t) && (t = t.replace(RegExp.$1, (s.getFullYear() + "").substr(4 - RegExp.$1.length))); - for (let e in i) - new RegExp("(" + e + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? i[e] : ("00" + i[e]).substr(("" + i[e]).length))); - return t - } - msg(e = t, s = "", i = "", r) { - const o = t => { - if (!t) - return t; - if ("string" == typeof t) - return this.isLoon() ? t : this.isQuanX() ? { - "open-url": t - } - : this.isSurge() ? { - url: t - } - : void 0; - if ("object" == typeof t) { - if (this.isLoon()) { - let e = t.openUrl || t.url || t["open-url"], - s = t.mediaUrl || t["media-url"]; - return { - openUrl: e, - mediaUrl: s - } - } - if (this.isQuanX()) { - let e = t["open-url"] || t.url || t.openUrl, - s = t["media-url"] || t.mediaUrl; - return { - "open-url": e, - "media-url": s - } - } - if (this.isSurge()) { - let e = t.url || t.openUrl || t["open-url"]; - return { - url: e - } - } - } - }; - if (this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, o(r)) : this.isQuanX() && $notify(e, s, i, o(r))), !this.isMuteLog) { - let t = ["", "==============📣系统通知📣=============="]; - t.push(e), - s && t.push(s), - i && t.push(i), - console.log(t.join("\n")), - this.logs = this.logs.concat(t) - } - } - log(...t) { - t.length > 0 && (this.logs = [...this.logs, ...t]), - console.log(t.join(this.logSeparator)) - } - logErr(t, e) { - const s = !this.isSurge() && !this.isQuanX() && !this.isLoon(); - s ? this.log("", `❗️${this.name}, 错误!`, t.stack) : this.log("", `❗️${this.name}, 错误!`, t) - } - wait(t) { - return new Promise(e => setTimeout(e, t)) - } - done(t = {}) { - const e = (new Date).getTime(), - s = (e - this.startTime) / 1e3; - this.log("", `🔔${this.name}, 结束! 🕛 ${s} 秒`), - this.log(), - (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) - } - } - (t, e) -} +/* +东东萌宠 更新地址: jd_pet.js +更新时间:2021-05-21 +活动入口:京东APP我的-更多工具-东东萌宠 +已支持IOS多京东账号,Node.js支持N个京东账号 +脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js + +互助码shareCode请先手动运行脚本查看打印可看到 +一天只能帮助5个人。多出的助力码无效 + +=================================Quantumultx========================= +[task_local] +#东东萌宠 +15 6-18/6 * * * jd_pet.js, tag=东东萌宠, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jdmc.png, enabled=true + +=================================Loon=================================== +[Script] +cron "15 6-18/6 * * *" script-path=jd_pet.js,tag=东东萌宠 + +===================================Surge================================ +东东萌宠 = type=cron,cronexp="15 6-18/6 * * *",wake-system=1,timeout=3600,script-path=jd_pet.js + +====================================小火箭============================= +东东萌宠 = type=cron,script-path=jd_pet.js, cronexpr="15 6-18/6 * * *", timeout=3600, enable=true + + */ +const $ = new Env('东东萌宠互助版'); +let cookiesArr = [], cookie = '', jdPetShareArr = [], isBox = false, allMessage = ''; +let message = '', subTitle = '', option = {}; +let jdNotify = false; //是否关闭通知,false打开通知推送,true关闭通知推送 +const JD_API_HOST = 'https://api.m.jd.com/client.action'; +let goodsUrl = '', taskInfoKey = []; +let notify = $.isNode() ? require('./sendNotify') : ''; +const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +let newShareCodes = []; +let NoNeedCodes = []; +if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + if (jdCookieNode[item]) { + cookiesArr.push(jdCookieNode[item]) + } + }) + if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') + console.log = () => {}; +} else { + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); +} + +let NowHour = new Date().getHours(); +let llhelp=true; +if ($.isNode() && process.env.CC_NOHELPAFTER8) { + console.log(NowHour); + if (process.env.CC_NOHELPAFTER8=="true"){ + if (NowHour>8){ + llhelp=false; + console.log(`现在是9点后时段,不启用互助....`); + } + } +} +let WP_APP_TOKEN_ONE = ""; +if ($.isNode()) { + if (process.env.WP_APP_TOKEN_ONE) { + WP_APP_TOKEN_ONE = process.env.WP_APP_TOKEN_ONE; + } +} +if(WP_APP_TOKEN_ONE) + console.log(`检测到已配置Wxpusher的Token,启用一对一推送...`); +else + console.log(`检测到未配置Wxpusher的Token,禁用一对一推送...`); + +console.log(`共${cookiesArr.length}个京东账号\n`); + +!(async() => { + if (!cookiesArr[0]) { + $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + return; + } + if (llhelp){ + console.log('开始收集您的互助码,用于账号内部互助,请稍等...'); + for (let i = 0; i < cookiesArr.length; i++) { + if (cookiesArr[i]) { + cookie = cookiesArr[i]; + $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); + $.index = i + 1; + $.isLogin = true; + $.nickName = ''; + await TotalBean(); + + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + + if ($.isNode()) { + await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + } + continue; + } + message = ''; + subTitle = ''; + goodsUrl = ''; + taskInfoKey = []; + option = {}; + await GetShareCode(); + } + } + console.log('\n互助码收集完毕,开始执行日常任务...\n'); + } + + for (let i = 0; i < cookiesArr.length; i++) { + if (cookiesArr[i]) { + cookie = cookiesArr[i]; + $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); + $.index = i + 1; + $.isLogin = true; + $.nickName = ''; + await TotalBean(); + console.log(`开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + + if ($.isNode()) { + await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + } + continue; + } + message = ''; + subTitle = ''; + goodsUrl = ''; + taskInfoKey = []; + option = {}; + await jdPet(); + } + } + if ($.isNode() && allMessage && $.ctrTemp) { + await notify.sendNotify(`${$.name}`, `${allMessage}`) + } +})() +.catch((e) => { + $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') +}) +.finally(() => { + $.done(); +}) +async function jdPet() { + try { + //查询jd宠物信息 + const initPetTownRes = await request('initPetTown'); + message = `【京东账号${$.index}】${$.nickName || $.UserName}\n`; + if (initPetTownRes.code === '0' && initPetTownRes.resultCode === '0' && initPetTownRes.message === 'success') { + $.petInfo = initPetTownRes.result; + if ($.petInfo.userStatus === 0) { + await slaveHelp(); //助力好友 + $.log($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n萌宠活动未开启\n请手动去京东APP开启活动\n入口:我的->游戏与互动->查看更多开启`); + return + } + if (!$.petInfo.goodsInfo) { + $.msg($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`, { + "open-url": "openapp.jdmoble://" + }); + if ($.isNode()) + await notify.sendNotify(`${$.name} - ${$.index} - ${$.nickName || $.UserName}`, `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`); + return + } + goodsUrl = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsUrl; + // option['media-url'] = goodsUrl; + // console.log(`初始化萌宠信息完成: ${JSON.stringify(petInfo)}`); + if ($.petInfo.petStatus === 5) { + await slaveHelp(); //可以兑换而没有去兑换,也能继续助力好友 + option['open-url'] = "openApp.jdMobile://"; + $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】${$.petInfo.goodsInfo.goodsName}已可领取\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); + if ($.isNode()) { + await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n${$.petInfo.goodsInfo.goodsName}已可领取`); + } + if ($.isNode() && WP_APP_TOKEN_ONE) { + await notify.sendNotifybyWxPucher($.name, `【提醒⏰】${$.petInfo.goodsInfo.goodsName}已可领取\n【领取步骤】京东->我的->东东萌宠兑换京东红包,可以用于京东app的任意商品.`, `${$.UserName}`); + } + return + } else if ($.petInfo.petStatus === 6) { + await slaveHelp(); //已领取红包,但未领养新的,也能继续助力好友 + option['open-url'] = "openApp.jdMobile://"; + $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】已领取红包,但未继续领养新的物品\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); + if ($.isNode()) { + await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n已领取红包,但未继续领养新的物品`); + } + + return + } + //console.log(`\n【京东账号${$.index}(${$.UserName})的${$.name}好友互助码】${$.petInfo.shareCode}\n`); + await taskInit(); + if ($.taskInit.resultCode === '9999' || !$.taskInit.result) { + console.log('初始化任务异常, 请稍后再试'); + return + } + $.taskInfo = $.taskInit.result; + + await petSport(); //遛弯 + if (llhelp){ + await slaveHelp(); //助力好友 + } + await masterHelpInit(); //获取助力的信息 + await doTask(); //做日常任务 + await feedPetsAgain(); //再次投食 + await energyCollect(); //收集好感度 + await showMsg(); + + } else if (initPetTownRes.code === '0') { + console.log(`初始化萌宠失败: ${initPetTownRes.message}`); + } + } catch (e) { + $.logErr(e) + const errMsg = `京东账号${$.index} ${$.nickName || $.UserName}\n任务执行异常,请检查执行日志 ‼️‼️`; + if ($.isNode()) + await notify.sendNotify(`${$.name}`, errMsg); + $.msg($.name, '', `${errMsg}`) + } +} + +async function GetShareCode() { + try { + //查询jd宠物信息 + const initPetTownRes = await request('initPetTown'); + if (initPetTownRes.code === '0' && initPetTownRes.resultCode === '0' && initPetTownRes.message === 'success') { + $.petInfo = initPetTownRes.result; + if ($.petInfo.userStatus == 0 || $.petInfo.petStatus == 5 || $.petInfo.petStatus == 6 || !$.petInfo.goodsInfo) { + console.log(`【京东账号${$.index}(${$.UserName})的互助码】\n宠物状态不能被助力,跳过...`); + return; + } + console.log(`【京东账号${$.index}(${$.UserName})的互助码】\n${$.petInfo.shareCode}`); + newShareCodes.push($.petInfo.shareCode); + } + } catch (e) { + $.logErr(e) + const errMsg = `【京东账号${$.index} ${$.nickName || $.UserName}】\n任务执行异常,请检查执行日志 ‼️‼️`; + if ($.isNode()) + await notify.sendNotify(`${$.name}`, errMsg); + $.msg($.name, '', `${errMsg}`); + } +} + +// 收取所有好感度 +async function energyCollect() { + console.log('开始收取任务奖励好感度'); + let function_id = arguments.callee.name.toString(); + const response = await request(function_id); + // console.log(`收取任务奖励好感度完成:${JSON.stringify(response)}`); + if (response.resultCode === '0') { + message += `【第${response.result.medalNum + 1}块勋章完成进度】${response.result.medalPercent}%,还需收集${response.result.needCollectEnergy}好感\n`; + message += `【已获得勋章】${response.result.medalNum}块,还需收集${response.result.needCollectMedalNum}块即可兑换奖品“${$.petInfo.goodsInfo.goodsName}”\n`; + } +} +//再次投食 +async function feedPetsAgain() { + const response = await request('initPetTown'); //再次初始化萌宠 + if (response.code === '0' && response.resultCode === '0' && response.message === 'success') { + $.petInfo = response.result; + let foodAmount = $.petInfo.foodAmount; //剩余狗粮 + if (foodAmount - 100 >= 10) { + for (let i = 0; i < parseInt((foodAmount - 100) / 10); i++) { + const feedPetRes = await request('feedPets'); + console.log(`投食feedPetRes`); + if (feedPetRes.resultCode == 0 && feedPetRes.code == 0) { + console.log('投食成功') + } + } + const response2 = await request('initPetTown'); + $.petInfo = response2.result; + subTitle = $.petInfo.goodsInfo.goodsName; + // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; + // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; + } else { + console.log("目前剩余狗粮:【" + foodAmount + "】g,不再继续投食,保留部分狗粮用于完成第二天任务"); + subTitle = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsName; + // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; + // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; + } + } else { + console.log(`初始化萌宠失败: ${JSON.stringify($.petInfo)}`); + } +} + +async function doTask() { + const { + signInit, + threeMealInit, + firstFeedInit, + feedReachInit, + inviteFriendsInit, + browseShopsInit, + taskList + } = $.taskInfo; + for (let item of taskList) { + if ($.taskInfo[item].finished) { + console.log(`任务 ${item} 已完成`) + } + } + //每日签到 + if (signInit && !signInit.finished) { + await signInitFun(); + } + // 首次喂食 + if (firstFeedInit && !firstFeedInit.finished) { + await firstFeedInitFun(); + } + // 三餐 + if (threeMealInit && !threeMealInit.finished) { + if (threeMealInit.timeRange === -1) { + console.log(`未到三餐时间`); + } else { + await threeMealInitFun(); + } + } + if (browseShopsInit && !browseShopsInit.finished) { + await browseShopsInitFun(); + } + let browseSingleShopInitList = []; + taskList.map((item) => { + if (item.indexOf('browseSingleShopInit') > -1) { + browseSingleShopInitList.push(item); + } + }); + // 去逛逛好货会场 + for (let item of browseSingleShopInitList) { + const browseSingleShopInitTask = $.taskInfo[item]; + if (browseSingleShopInitTask && !browseSingleShopInitTask.finished) { + await browseSingleShopInit(browseSingleShopInitTask); + } + } + if (inviteFriendsInit && !inviteFriendsInit.finished) { + await inviteFriendsInitFun(); + } + // 投食10次 + if (feedReachInit && !feedReachInit.finished) { + await feedReachInitFun(); + } +} +// 好友助力信息 +async function masterHelpInit() { + let res = await request(arguments.callee.name.toString()); + // console.log(`助力信息: ${JSON.stringify(res)}`); + if (res.code === '0' && res.resultCode === '0') { + if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length >= 5) { + if (!res.result.addedBonusFlag) { + console.log("开始领取额外奖励"); + let getHelpAddedBonusResult = await request('getHelpAddedBonus'); + if (getHelpAddedBonusResult.resultCode === '0') { + message += `【额外奖励${getHelpAddedBonusResult.result.reward}领取】${getHelpAddedBonusResult.message}\n`; + } + console.log(`领取30g额外奖励结果:【${getHelpAddedBonusResult.message}】`); + } else { + console.log("已经领取过5好友助力额外奖励"); + message += `【额外奖励】已领取\n`; + } + } else { + console.log("助力好友未达到5个") + message += `【额外奖励】领取失败,原因:给您助力的人未达5个\n`; + } + if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length > 0) { + console.log('帮您助力的好友的名单开始') + let str = ''; + res.result.masterHelpPeoples.map((item, index) => { + if (index === (res.result.masterHelpPeoples.length - 1)) { + str += item.nickName || "匿名用户"; + } else { + str += (item.nickName || "匿名用户") + ','; + } + }) + message += `【助力您的好友】${str}\n`; + } + } +} +/** + * 助力好友, 暂时支持一个好友, 需要拿到shareCode + * shareCode为你要助力的好友的 + * 运行脚本时你自己的shareCode会在控制台输出, 可以将其分享给他人 + */ +async function slaveHelp() { + let helpPeoples = ''; + for (let code of newShareCodes) { + if(NoNeedCodes){ + var llnoneed=false; + for (let NoNeedCode of NoNeedCodes) { + if (code==NoNeedCode){ + llnoneed=true; + break; + } + } + if(llnoneed){ + console.log(`${code}助力已满,跳过...`); + continue; + } + } + console.log(`开始助力京东账号${$.index} - ${$.nickName || $.UserName}的好友: ${code}`); + if (!code) + continue; + let response = await request(arguments.callee.name.toString(), { + 'shareCode': code + }); + if (response.code === '0' && response.resultCode === '0') { + if (response.result.helpStatus === 0) { + console.log('已给好友: 【' + response.result.masterNickName + '】助力成功'); + helpPeoples += response.result.masterNickName + ','; + } else if (response.result.helpStatus === 1) { + // 您今日已无助力机会 + console.log(`助力好友${response.result.masterNickName}失败,您今日已无助力机会`); + break; + } else if (response.result.helpStatus === 2) { + //该好友已满5人助力,无需您再次助力 + NoNeedCodes.push(code); + console.log(`该好友${response.result.masterNickName}已满5人助力,无需您再次助力`); + } else { + console.log(`助力其他情况:${JSON.stringify(response)}`); + } + } else { + if(response.message=="已经助过力"){ + console.log(`此账号今天已经跑过助力了,跳出....`); + break; + }else{ + console.log(`助力好友结果: ${response.message}`); + } + + } + } + if (helpPeoples && helpPeoples.length > 0) { + message += `【您助力的好友】${helpPeoples.substr(0, helpPeoples.length - 1)}\n`; + } +} +// 遛狗, 每天次数上限10次, 随机给狗粮, 每次遛狗结束需调用getSportReward领取奖励, 才能进行下一次遛狗 +async function petSport() { + console.log('开始遛弯'); + let times = 1 + const code = 0 + let resultCode = 0 + do { + let response = await request(arguments.callee.name.toString()) + console.log(`第${times}次遛狗完成: ${JSON.stringify(response)}`); + resultCode = response.resultCode; + if (resultCode == 0) { + let sportRevardResult = await request('getSportReward'); + console.log(`领取遛狗奖励完成: ${JSON.stringify(sportRevardResult)}`); + } + times++; + } while (resultCode == 0 && code == 0) + if (times > 1) { + // message += '【十次遛狗】已完成\n'; + } +} +// 初始化任务, 可查询任务完成情况 +async function taskInit() { + console.log('开始任务初始化'); + $.taskInit = await request(arguments.callee.name.toString(), { + "version": 1 + }); +} +// 每日签到, 每天一次 +async function signInitFun() { + console.log('准备每日签到'); + const response = await request("getSignReward"); + console.log(`每日签到结果: ${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + console.log(`【每日签到成功】奖励${response.result.signReward}g狗粮\n`); + // message += `【每日签到成功】奖励${response.result.signReward}g狗粮\n`; + } else { + console.log(`【每日签到】${response.message}\n`); + // message += `【每日签到】${response.message}\n`; + } +} + +// 三餐签到, 每天三段签到时间 +async function threeMealInitFun() { + console.log('准备三餐签到'); + const response = await request("getThreeMealReward"); + console.log(`三餐签到结果: ${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + console.log(`【定时领狗粮】获得${response.result.threeMealReward}g\n`); + // message += `【定时领狗粮】获得${response.result.threeMealReward}g\n`; + } else { + console.log(`【定时领狗粮】${response.message}\n`); + // message += `【定时领狗粮】${response.message}\n`; + } +} + +// 浏览指定店铺 任务 +async function browseSingleShopInit(item) { + console.log(`开始做 ${item.title} 任务, ${item.desc}`); + const body = { + "index": item['index'], + "version": 1, + "type": 1 + }; + const body2 = { + "index": item['index'], + "version": 1, + "type": 2 + }; + const response = await request("getSingleShopReward", body); + // console.log(`点击进去response::${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + const response2 = await request("getSingleShopReward", body2); + // console.log(`浏览完毕领取奖励:response2::${JSON.stringify(response2)}`); + if (response2.code === '0' && response2.resultCode === '0') { + console.log(`【浏览指定店铺】获取${response2.result.reward}g\n`); + // message += `【浏览指定店铺】获取${response2.result.reward}g\n`; + } + } +} + +// 浏览店铺任务, 任务可能为多个? 目前只有一个 +async function browseShopsInitFun() { + console.log('开始浏览店铺任务'); + let times = 0; + let resultCode = 0; + let code = 0; + do { + let response = await request("getBrowseShopsReward"); + console.log(`第${times}次浏览店铺结果: ${JSON.stringify(response)}`); + code = response.code; + resultCode = response.resultCode; + times++; + } while (resultCode == 0 && code == 0 && times < 5) + console.log('浏览店铺任务结束'); +} +// 首次投食 任务 +function firstFeedInitFun() { + console.log('首次投食任务合并到10次喂食任务中\n'); +} + +// 邀请新用户 +async function inviteFriendsInitFun() { + console.log('邀请新用户功能未实现'); + if ($.taskInfo.inviteFriendsInit.status == 1 && $.taskInfo.inviteFriendsInit.inviteFriendsNum > 0) { + // 如果有邀请过新用户,自动领取60gg奖励 + const res = await request('getInviteFriendsReward'); + if (res.code == 0 && res.resultCode == 0) { + console.log(`领取邀请新用户奖励成功,获得狗粮现有狗粮${$.taskInfo.inviteFriendsInit.reward}g,${res.result.foodAmount}g`); + message += `【邀请新用户】获取狗粮${$.taskInfo.inviteFriendsInit.reward}g\n`; + } + } +} + +/** + * 投食10次 任务 + */ +async function feedReachInitFun() { + console.log('投食任务开始...'); + let finishedTimes = $.taskInfo.feedReachInit.hadFeedAmount / 10; //已经喂养了几次 + let needFeedTimes = 10 - finishedTimes; //还需要几次 + let tryTimes = 20; //尝试次数 + do { + console.log(`还需要投食${needFeedTimes}次`); + const response = await request('feedPets'); + console.log(`本次投食结果: ${JSON.stringify(response)}`); + if (response.resultCode == 0 && response.code == 0) { + needFeedTimes--; + } + if (response.resultCode == 3003 && response.code == 0) { + console.log('剩余狗粮不足, 投食结束'); + needFeedTimes = 0; + } + tryTimes--; + } while (needFeedTimes > 0 && tryTimes > 0) + console.log('投食任务结束...\n'); +} +async function showMsg() { + if ($.isNode() && process.env.PET_NOTIFY_CONTROL) { + $.ctrTemp = `${process.env.PET_NOTIFY_CONTROL}` === 'false'; + } else if ($.getdata('jdPetNotify')) { + $.ctrTemp = $.getdata('jdPetNotify') === 'false'; + } else { + $.ctrTemp = `${jdNotify}` === 'false'; + } + // jdNotify = `${notify.petNotifyControl}` === 'false' && `${jdNotify}` === 'false' && $.getdata('jdPetNotify') === 'false'; + if ($.ctrTemp) { + $.msg($.name, subTitle, message, option); + if ($.isNode()) { + allMessage += `${subTitle}\n${message}${$.index !== cookiesArr.length ? '\n\n' : ''}` + // await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}`, `${subTitle}\n${message}`); + } + } else { + $.log(`\n${message}\n`); + } +} +function TotalBean() { + return new Promise(async resolve => { + const options = { + "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, + "headers": { + "Accept": "application/json,text/plain, */*", + "Content-Type": "application/x-www-form-urlencoded", + "Accept-Encoding": "gzip, deflate, br", + "Accept-Language": "zh-cn", + "Connection": "keep-alive", + "Cookie": cookie, + "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", + "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1") + } + } + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + data = JSON.parse(data); + if (data['retcode'] === 13) { + $.isLogin = false; //cookie过期 + return + } + if (data['retcode'] === 0 && data.base && data.base.nickname) { + $.nickName = data.base.nickname; + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e) + } + finally { + resolve(); + } + }) + }) +} +// 请求 +async function request(function_id, body = {}) { + await $.wait(3000); //歇口气儿, 不然会报操作频繁 + return new Promise((resolve, reject) => { + $.post(taskUrl(function_id, body), (err, resp, data) => { + try { + if (err) { + console.log('\n东东萌宠: API查询请求失败 ‼️‼️'); + console.log(JSON.stringify(err)); + $.logErr(err); + } else { + data = JSON.parse(data); + } + } catch (e) { + $.logErr(e, resp); + } + finally { + resolve(data) + } + }) + }) +} +// function taskUrl(function_id, body = {}) { +// return { +// url: `${JD_API_HOST}?functionId=${function_id}&appid=wh5&loginWQBiz=pet-town&body=${escape(JSON.stringify(body))}`, +// headers: { +// Cookie: cookie, +// UserAgent: $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), +// } +// }; +// } +function taskUrl(function_id, body = {}) { + body["version"] = 2; + body["channel"] = 'app'; + return { + url: `${JD_API_HOST}?functionId=${function_id}`, + body: `body=${escape(JSON.stringify(body))}&appid=wh5&loginWQBiz=pet-town&clientVersion=9.0.4`, + headers: { + 'Cookie': cookie, + 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), + 'Host': 'api.m.jd.com', + 'Content-Type': 'application/x-www-form-urlencoded', + } + }; +} +function jsonParse(str) { + if (typeof str == "string") { + try { + return JSON.parse(str); + } catch (e) { + console.log(e); + $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') + return []; + } + } +} +// prettier-ignore +function Env(t, e) { + "undefined" != typeof process && JSON.stringify(process.env).indexOf("GITHUB") > -1 && process.exit(0); + class s { + constructor(t) { + this.env = t + } + send(t, e = "GET") { + t = "string" == typeof t ? { + url: t + } + : t; + let s = this.get; + return "POST" === e && (s = this.post), + new Promise((e, i) => { + s.call(this, t, (t, s, r) => { + t ? i(t) : e(s) + }) + }) + } + get(t) { + return this.send.call(this.env, t) + } + post(t) { + return this.send.call(this.env, t, "POST") + } + } + return new class { + constructor(t, e) { + this.name = t, + this.http = new s(this), + this.data = null, + this.dataFile = "box.dat", + this.logs = [], + this.isMute = !1, + this.isNeedRewrite = !1, + this.logSeparator = "\n", + this.startTime = (new Date).getTime(), + Object.assign(this, e), + this.log("", `🔔${this.name}, 开始!`) + } + isNode() { + return "undefined" != typeof module && !!module.exports + } + isQuanX() { + return "undefined" != typeof $task + } + isSurge() { + return "undefined" != typeof $httpClient && "undefined" == typeof $loon + } + isLoon() { + return "undefined" != typeof $loon + } + toObj(t, e = null) { + try { + return JSON.parse(t) + } catch { + return e + } + } + toStr(t, e = null) { + try { + return JSON.stringify(t) + } catch { + return e + } + } + getjson(t, e) { + let s = e; + const i = this.getdata(t); + if (i) + try { + s = JSON.parse(this.getdata(t)) + } catch {} + return s + } + setjson(t, e) { + try { + return this.setdata(JSON.stringify(t), e) + } catch { + return !1 + } + } + getScript(t) { + return new Promise(e => { + this.get({ + url: t + }, (t, s, i) => e(i)) + }) + } + runScript(t, e) { + return new Promise(s => { + let i = this.getdata("@chavy_boxjs_userCfgs.httpapi"); + i = i ? i.replace(/\n/g, "").trim() : i; + let r = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); + r = r ? 1 * r : 20, + r = e && e.timeout ? e.timeout : r; + const[o, h] = i.split("@"), + n = { + url: `http://${h}/v1/scripting/evaluate`, + body: { + script_text: t, + mock_type: "cron", + timeout: r + }, + headers: { + "X-Key": o, + Accept: "*/*" + } + }; + this.post(n, (t, e, i) => s(i)) + }).catch(t => this.logErr(t)) + } + loaddata() { + if (!this.isNode()) + return {}; { + this.fs = this.fs ? this.fs : require("fs"), + this.path = this.path ? this.path : require("path"); + const t = this.path.resolve(this.dataFile), + e = this.path.resolve(process.cwd(), this.dataFile), + s = this.fs.existsSync(t), + i = !s && this.fs.existsSync(e); + if (!s && !i) + return {}; { + const i = s ? t : e; + try { + return JSON.parse(this.fs.readFileSync(i)) + } catch (t) { + return {} + } + } + } + } + writedata() { + if (this.isNode()) { + this.fs = this.fs ? this.fs : require("fs"), + this.path = this.path ? this.path : require("path"); + const t = this.path.resolve(this.dataFile), + e = this.path.resolve(process.cwd(), this.dataFile), + s = this.fs.existsSync(t), + i = !s && this.fs.existsSync(e), + r = JSON.stringify(this.data); + s ? this.fs.writeFileSync(t, r) : i ? this.fs.writeFileSync(e, r) : this.fs.writeFileSync(t, r) + } + } + lodash_get(t, e, s) { + const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); + let r = t; + for (const t of i) + if (r = Object(r)[t], void 0 === r) + return s; + return r + } + lodash_set(t, e, s) { + return Object(t) !== t ? t : (Array.isArray(e) || (e = e.toString().match(/[^.[\]]+/g) || []), e.slice(0, -1).reduce((t, s, i) => Object(t[s]) === t[s] ? t[s] : t[s] = Math.abs(e[i + 1]) >> 0 == +e[i + 1] ? [] : {}, t)[e[e.length - 1]] = s, t) + } + getdata(t) { + let e = this.getval(t); + if (/^@/.test(t)) { + const[, s, i] = /^@(.*?)\.(.*?)$/.exec(t), + r = s ? this.getval(s) : ""; + if (r) + try { + const t = JSON.parse(r); + e = t ? this.lodash_get(t, i, "") : e + } catch (t) { + e = "" + } + } + return e + } + setdata(t, e) { + let s = !1; + if (/^@/.test(e)) { + const[, i, r] = /^@(.*?)\.(.*?)$/.exec(e), + o = this.getval(i), + h = i ? "null" === o ? null : o || "{}" : "{}"; + try { + const e = JSON.parse(h); + this.lodash_set(e, r, t), + s = this.setval(JSON.stringify(e), i) + } catch (e) { + const o = {}; + this.lodash_set(o, r, t), + s = this.setval(JSON.stringify(o), i) + } + } else + s = this.setval(t, e); + return s + } + getval(t) { + return this.isSurge() || this.isLoon() ? $persistentStore.read(t) : this.isQuanX() ? $prefs.valueForKey(t) : this.isNode() ? (this.data = this.loaddata(), this.data[t]) : this.data && this.data[t] || null + } + setval(t, e) { + return this.isSurge() || this.isLoon() ? $persistentStore.write(t, e) : this.isQuanX() ? $prefs.setValueForKey(t, e) : this.isNode() ? (this.data = this.loaddata(), this.data[e] = t, this.writedata(), !0) : this.data && this.data[e] || null + } + initGotEnv(t) { + this.got = this.got ? this.got : require("got"), + this.cktough = this.cktough ? this.cktough : require("tough-cookie"), + this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar, + t && (t.headers = t.headers ? t.headers : {}, void 0 === t.headers.Cookie && void 0 === t.cookieJar && (t.cookieJar = this.ckjar)) + } + get(t, e = (() => {})) { + t.headers && (delete t.headers["Content-Type"], delete t.headers["Content-Length"]), + this.isSurge() || this.isLoon() ? (this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { + "X-Surge-Skip-Scripting": !1 + })), $httpClient.get(t, (t, s, i) => { + !t && s && (s.body = i, s.statusCode = s.status), + e(t, s, i) + })) : this.isQuanX() ? (this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { + hints: !1 + })), $task.fetch(t).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => e(t))) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { + try { + if (t.headers["set-cookie"]) { + const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); + s && this.ckjar.setCookieSync(s, null), + e.cookieJar = this.ckjar + } + } catch (t) { + this.logErr(t) + } + }).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => { + const { + message: s, + response: i + } = t; + e(s, i, i && i.body) + })) + } + post(t, e = (() => {})) { + if (t.body && t.headers && !t.headers["Content-Type"] && (t.headers["Content-Type"] = "application/x-www-form-urlencoded"), t.headers && delete t.headers["Content-Length"], this.isSurge() || this.isLoon()) + this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { + "X-Surge-Skip-Scripting": !1 + })), $httpClient.post(t, (t, s, i) => { + !t && s && (s.body = i, s.statusCode = s.status), + e(t, s, i) + }); + else if (this.isQuanX()) + t.method = "POST", this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { + hints: !1 + })), $task.fetch(t).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => e(t)); + else if (this.isNode()) { + this.initGotEnv(t); + const { + url: s, + ...i + } = t; + this.got.post(s, i).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => { + const { + message: s, + response: i + } = t; + e(s, i, i && i.body) + }) + } + } + time(t, e = null) { + const s = e ? new Date(e) : new Date; + let i = { + "M+": s.getMonth() + 1, + "d+": s.getDate(), + "H+": s.getHours(), + "m+": s.getMinutes(), + "s+": s.getSeconds(), + "q+": Math.floor((s.getMonth() + 3) / 3), + S: s.getMilliseconds() + }; + /(y+)/.test(t) && (t = t.replace(RegExp.$1, (s.getFullYear() + "").substr(4 - RegExp.$1.length))); + for (let e in i) + new RegExp("(" + e + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? i[e] : ("00" + i[e]).substr(("" + i[e]).length))); + return t + } + msg(e = t, s = "", i = "", r) { + const o = t => { + if (!t) + return t; + if ("string" == typeof t) + return this.isLoon() ? t : this.isQuanX() ? { + "open-url": t + } + : this.isSurge() ? { + url: t + } + : void 0; + if ("object" == typeof t) { + if (this.isLoon()) { + let e = t.openUrl || t.url || t["open-url"], + s = t.mediaUrl || t["media-url"]; + return { + openUrl: e, + mediaUrl: s + } + } + if (this.isQuanX()) { + let e = t["open-url"] || t.url || t.openUrl, + s = t["media-url"] || t.mediaUrl; + return { + "open-url": e, + "media-url": s + } + } + if (this.isSurge()) { + let e = t.url || t.openUrl || t["open-url"]; + return { + url: e + } + } + } + }; + if (this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, o(r)) : this.isQuanX() && $notify(e, s, i, o(r))), !this.isMuteLog) { + let t = ["", "==============📣系统通知📣=============="]; + t.push(e), + s && t.push(s), + i && t.push(i), + console.log(t.join("\n")), + this.logs = this.logs.concat(t) + } + } + log(...t) { + t.length > 0 && (this.logs = [...this.logs, ...t]), + console.log(t.join(this.logSeparator)) + } + logErr(t, e) { + const s = !this.isSurge() && !this.isQuanX() && !this.isLoon(); + s ? this.log("", `❗️${this.name}, 错误!`, t.stack) : this.log("", `❗️${this.name}, 错误!`, t) + } + wait(t) { + return new Promise(e => setTimeout(e, t)) + } + done(t = {}) { + const e = (new Date).getTime(), + s = (e - this.startTime) / 1e3; + this.log("", `🔔${this.name}, 结束! 🕛 ${s} 秒`), + this.log(), + (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) + } + } + (t, e) +} diff --git a/jd_petrw.js b/jd_petrw.js new file mode 100644 index 0000000..09fedda --- /dev/null +++ b/jd_petrw.js @@ -0,0 +1,953 @@ +/* +东东萌宠 更新地址: jd_pet.js +更新时间:2021-05-21 +活动入口:京东APP我的-更多工具-东东萌宠 +已支持IOS多京东账号,Node.js支持N个京东账号 +脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js + +互助码shareCode请先手动运行脚本查看打印可看到 +一天只能帮助5个人。多出的助力码无效 + +=================================Quantumultx========================= +[task_local] +#东东萌宠 +15 6-18/6 * * * jd_pet.js, tag=东东萌宠, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jdmc.png, enabled=true + +=================================Loon=================================== +[Script] +cron "15 6-18/6 * * *" script-path=jd_pet.js,tag=东东萌宠 + +===================================Surge================================ +东东萌宠 = type=cron,cronexp="15 6-18/6 * * *",wake-system=1,timeout=3600,script-path=jd_pet.js + +====================================小火箭============================= +东东萌宠 = type=cron,script-path=jd_pet.js, cronexpr="15 6-18/6 * * *", timeout=3600, enable=true + + */ +const $ = new Env('东东萌宠任务'); +let cookiesArr = [], cookie = '', jdPetShareArr = [], isBox = false, allMessage = ''; +let message = '', subTitle = '', option = {}; +let jdNotify = false; //是否关闭通知,false打开通知推送,true关闭通知推送 +const JD_API_HOST = 'https://api.m.jd.com/client.action'; +let goodsUrl = '', taskInfoKey = []; +let notify = $.isNode() ? require('./sendNotify') : ''; +const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +let newShareCodes = []; +let NoNeedCodes = []; +let lnrun = 0; +if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + if (jdCookieNode[item]) { + cookiesArr.push(jdCookieNode[item]) + } + }) + if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') + console.log = () => {}; +} else { + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); +} + +console.log(`共${cookiesArr.length}个京东账号\n`); + +!(async() => { + if (!cookiesArr[0]) { + $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + return; + } + for (let i = 0; i < cookiesArr.length; i++) { + if (cookiesArr[i]) { + cookie = cookiesArr[i]; + $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); + $.index = i + 1; + $.isLogin = true; + $.nickName = ''; + await TotalBean(); + console.log(`开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + + if ($.isNode()) { + await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + } + continue; + } + message = ''; + subTitle = ''; + goodsUrl = ''; + taskInfoKey = []; + option = {}; + lnrun++; + await jdPet(); + if (lnrun == 3) { + console.log(`\n【访问接口次数达到3次,休息一分钟.....】\n`); + await $.wait(60 * 1000); + lnrun = 0; + } + } + } + if ($.isNode() && allMessage && $.ctrTemp) { + await notify.sendNotify(`${$.name}`, `${allMessage}`) + } +})() +.catch((e) => { + $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') +}) +.finally(() => { + $.done(); +}) +async function jdPet() { + try { + //查询jd宠物信息 + const initPetTownRes = await request('initPetTown'); + message = `【京东账号${$.index}】${$.nickName || $.UserName}\n`; + if (initPetTownRes.code === '0' && initPetTownRes.resultCode === '0' && initPetTownRes.message === 'success') { + $.petInfo = initPetTownRes.result; + if ($.petInfo.userStatus === 0) { + $.log($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n萌宠活动未开启\n请手动去京东APP开启活动\n入口:我的->游戏与互动->查看更多开启`); + return + } + if (!$.petInfo.goodsInfo) { + $.msg($.name, '', `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`, { + "open-url": "openapp.jdmoble://" + }); + if ($.isNode()) + await notify.sendNotify(`${$.name} - ${$.index} - ${$.nickName || $.UserName}`, `【提示】京东账号${$.index}${$.nickName || $.UserName}\n暂未选购新的商品`); + return + } + goodsUrl = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsUrl; + // option['media-url'] = goodsUrl; + // console.log(`初始化萌宠信息完成: ${JSON.stringify(petInfo)}`); + if ($.petInfo.petStatus === 5) { + option['open-url'] = "openApp.jdMobile://"; + $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】${$.petInfo.goodsInfo.goodsName}已可领取\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); + if ($.isNode()) { + await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n${$.petInfo.goodsInfo.goodsName}已可领取`); + } + return + } else if ($.petInfo.petStatus === 6) { + option['open-url'] = "openApp.jdMobile://"; + $.msg($.name, ``, `【京东账号${$.index}】${$.nickName || $.UserName}\n【提醒⏰】已领取红包,但未继续领养新的物品\n请去京东APP或微信小程序查看\n点击弹窗即达`, option); + if ($.isNode()) { + await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}奖品已可领取`, `京东账号${$.index} ${$.nickName || $.UserName}\n已领取红包,但未继续领养新的物品`); + } + return + } + //console.log(`\n【京东账号${$.index}(${$.UserName})的${$.name}好友互助码】${$.petInfo.shareCode}\n`); + await taskInit(); + if ($.taskInit.resultCode === '9999' || !$.taskInit.result) { + console.log('初始化任务异常, 请稍后再试'); + return + } + $.taskInfo = $.taskInit.result; + + await petSport(); //遛弯 + await masterHelpInit(); //获取助力的信息 + await doTask(); //做日常任务 + await feedPetsAgain(); //再次投食 + await energyCollect(); //收集好感度 + //await showMsg(); + + } else if (initPetTownRes.code === '0') { + console.log(`初始化萌宠失败: ${initPetTownRes.message}`); + } + } catch (e) { + $.logErr(e) + const errMsg = `京东账号${$.index} ${$.nickName || $.UserName}\n任务执行异常,请检查执行日志 ‼️‼️`; + if ($.isNode()) + await notify.sendNotify(`${$.name}`, errMsg); + $.msg($.name, '', `${errMsg}`) + } +} + +// 收取所有好感度 +async function energyCollect() { + console.log('开始收取任务奖励好感度'); + let function_id = arguments.callee.name.toString(); + const response = await request(function_id); + // console.log(`收取任务奖励好感度完成:${JSON.stringify(response)}`); + if (response.resultCode === '0') { + message += `【第${response.result.medalNum + 1}块勋章完成进度】${response.result.medalPercent}%,还需收集${response.result.needCollectEnergy}好感\n`; + message += `【已获得勋章】${response.result.medalNum}块,还需收集${response.result.needCollectMedalNum}块即可兑换奖品“${$.petInfo.goodsInfo.goodsName}”\n`; + } +} +//再次投食 +async function feedPetsAgain() { + const response = await request('initPetTown'); //再次初始化萌宠 + if (response.code === '0' && response.resultCode === '0' && response.message === 'success') { + $.petInfo = response.result; + let foodAmount = $.petInfo.foodAmount; //剩余狗粮 + if (foodAmount - 100 >= 10) { + for (let i = 0; i < parseInt((foodAmount - 100) / 10); i++) { + const feedPetRes = await request('feedPets'); + await $.wait(5 * 1000); + console.log(`投食feedPetRes`); + if (feedPetRes.resultCode == 0 && feedPetRes.code == 0) { + console.log('投食成功') + } + } + const response2 = await request('initPetTown'); + $.petInfo = response2.result; + subTitle = $.petInfo.goodsInfo.goodsName; + // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; + // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; + } else { + console.log("目前剩余狗粮:【" + foodAmount + "】g,不再继续投食,保留部分狗粮用于完成第二天任务"); + subTitle = $.petInfo.goodsInfo && $.petInfo.goodsInfo.goodsName; + // message += `【与爱宠相识】${$.petInfo.meetDays}天\n`; + // message += `【剩余狗粮】${$.petInfo.foodAmount}g\n`; + } + } else { + console.log(`初始化萌宠失败: ${JSON.stringify($.petInfo)}`); + } +} + +async function doTask() { + const { + signInit, + threeMealInit, + firstFeedInit, + feedReachInit, + inviteFriendsInit, + browseShopsInit, + taskList + } = $.taskInfo; + for (let item of taskList) { + if ($.taskInfo[item].finished) { + console.log(`任务 ${item} 已完成`) + } + } + //每日签到 + if (signInit && !signInit.finished) { + await signInitFun(); + } + // 首次喂食 + if (firstFeedInit && !firstFeedInit.finished) { + await firstFeedInitFun(); + } + // 三餐 + if (threeMealInit && !threeMealInit.finished) { + if (threeMealInit.timeRange === -1) { + console.log(`未到三餐时间`); + } else { + await threeMealInitFun(); + } + } + if (browseShopsInit && !browseShopsInit.finished) { + await browseShopsInitFun(); + } + let browseSingleShopInitList = []; + taskList.map((item) => { + if (item.indexOf('browseSingleShopInit') > -1) { + browseSingleShopInitList.push(item); + } + }); + // 去逛逛好货会场 + for (let item of browseSingleShopInitList) { + const browseSingleShopInitTask = $.taskInfo[item]; + if (browseSingleShopInitTask && !browseSingleShopInitTask.finished) { + await browseSingleShopInit(browseSingleShopInitTask); + } + } + if (inviteFriendsInit && !inviteFriendsInit.finished) { + await inviteFriendsInitFun(); + } + // 投食10次 + if (feedReachInit && !feedReachInit.finished) { + lnrun++; + await feedReachInitFun(); + if (lnrun == 5) { + console.log(`\n【访问接口次数达到5次,休息半分钟.....】\n`); + await $.wait(30 * 1000); + lnrun = 0; + } + } +} +// 好友助力信息 +async function masterHelpInit() { + let res = await request(arguments.callee.name.toString()); + // console.log(`助力信息: ${JSON.stringify(res)}`); + if (res.code === '0' && res.resultCode === '0') { + if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length >= 5) { + if (!res.result.addedBonusFlag) { + console.log("开始领取额外奖励"); + let getHelpAddedBonusResult = await request('getHelpAddedBonus'); + if (getHelpAddedBonusResult.resultCode === '0') { + message += `【额外奖励${getHelpAddedBonusResult.result.reward}领取】${getHelpAddedBonusResult.message}\n`; + } + console.log(`领取30g额外奖励结果:【${getHelpAddedBonusResult.message}】`); + } else { + console.log("已经领取过5好友助力额外奖励"); + message += `【额外奖励】已领取\n`; + } + } else { + console.log("助力好友未达到5个") + message += `【额外奖励】领取失败,原因:给您助力的人未达5个\n`; + } + if (res.result.masterHelpPeoples && res.result.masterHelpPeoples.length > 0) { + console.log('帮您助力的好友的名单开始') + let str = ''; + res.result.masterHelpPeoples.map((item, index) => { + if (index === (res.result.masterHelpPeoples.length - 1)) { + str += item.nickName || "匿名用户"; + } else { + str += (item.nickName || "匿名用户") + ','; + } + }) + message += `【助力您的好友】${str}\n`; + } + } +} +// 遛狗, 每天次数上限10次, 随机给狗粮, 每次遛狗结束需调用getSportReward领取奖励, 才能进行下一次遛狗 +async function petSport() { + console.log('开始遛弯'); + let times = 1 + const code = 0 + let resultCode = 0 + do { + let response = await request(arguments.callee.name.toString()) + console.log(`第${times}次遛狗完成: ${JSON.stringify(response)}`); + resultCode = response.resultCode; + if (resultCode == 0) { + let sportRevardResult = await request('getSportReward'); + console.log(`领取遛狗奖励完成: ${JSON.stringify(sportRevardResult)}`); + } else if (resultCode == 1013) { + let sportRevardResult = await request('getSportReward', {"version":1}); + console.log(`领取遛狗奖励完成: ${JSON.stringify(sportRevardResult)}`); + if (sportRevardResult.resultCode == 0) resultCode = 0 + } + times++; + } while (resultCode == 0 && code == 0) + if (times > 1) { + // message += '【十次遛狗】已完成\n'; + } +} +// 初始化任务, 可查询任务完成情况 +async function taskInit() { + console.log('开始任务初始化'); + $.taskInit = await request(arguments.callee.name.toString(), { + "version": 1 + }); +} +// 每日签到, 每天一次 +async function signInitFun() { + console.log('准备每日签到'); + const response = await request("getSignReward"); + console.log(`每日签到结果: ${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + console.log(`【每日签到成功】奖励${response.result.signReward}g狗粮\n`); + // message += `【每日签到成功】奖励${response.result.signReward}g狗粮\n`; + } else { + console.log(`【每日签到】${response.message}\n`); + // message += `【每日签到】${response.message}\n`; + } +} + +// 三餐签到, 每天三段签到时间 +async function threeMealInitFun() { + console.log('准备三餐签到'); + const response = await request("getThreeMealReward"); + console.log(`三餐签到结果: ${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + console.log(`【定时领狗粮】获得${response.result.threeMealReward}g\n`); + // message += `【定时领狗粮】获得${response.result.threeMealReward}g\n`; + } else { + console.log(`【定时领狗粮】${response.message}\n`); + // message += `【定时领狗粮】${response.message}\n`; + } +} + +// 浏览指定店铺 任务 +async function browseSingleShopInit(item) { + console.log(`开始做 ${item.title} 任务, ${item.desc}`); + const body = { + "index": item['index'], + "version": 1, + "type": 1 + }; + const body2 = { + "index": item['index'], + "version": 1, + "type": 2 + }; + const response = await request("getSingleShopReward", body); + // console.log(`点击进去response::${JSON.stringify(response)}`); + if (response.code === '0' && response.resultCode === '0') { + const response2 = await request("getSingleShopReward", body2); + // console.log(`浏览完毕领取奖励:response2::${JSON.stringify(response2)}`); + if (response2.code === '0' && response2.resultCode === '0') { + console.log(`【浏览指定店铺】获取${response2.result.reward}g\n`); + // message += `【浏览指定店铺】获取${response2.result.reward}g\n`; + } + } +} + +// 浏览店铺任务, 任务可能为多个? 目前只有一个 +async function browseShopsInitFun() { + console.log('开始浏览店铺任务'); + let times = 0; + let resultCode = 0; + let code = 0; + do { + let response = await request("getBrowseShopsReward"); + console.log(`第${times}次浏览店铺结果: ${JSON.stringify(response)}`); + code = response.code; + resultCode = response.resultCode; + times++; + } while (resultCode == 0 && code == 0 && times < 5) + console.log('浏览店铺任务结束'); +} +// 首次投食 任务 +function firstFeedInitFun() { + console.log('首次投食任务合并到10次喂食任务中\n'); +} + +// 邀请新用户 +async function inviteFriendsInitFun() { + console.log('邀请新用户功能未实现'); + if ($.taskInfo.inviteFriendsInit.status == 1 && $.taskInfo.inviteFriendsInit.inviteFriendsNum > 0) { + // 如果有邀请过新用户,自动领取60gg奖励 + const res = await request('getInviteFriendsReward'); + if (res.code == 0 && res.resultCode == 0) { + console.log(`领取邀请新用户奖励成功,获得狗粮现有狗粮${$.taskInfo.inviteFriendsInit.reward}g,${res.result.foodAmount}g`); + message += `【邀请新用户】获取狗粮${$.taskInfo.inviteFriendsInit.reward}g\n`; + } + } +} + +/** + * 投食10次 任务 + */ +async function feedReachInitFun() { + console.log('投食任务开始...'); + let finishedTimes = $.taskInfo.feedReachInit.hadFeedAmount / 10; //已经喂养了几次 + let needFeedTimes = 10 - finishedTimes; //还需要几次 + let tryTimes = 10; //尝试次数 + do { + console.log(`还需要投食${needFeedTimes}次`); + const response = await request('feedPets'); + await $.wait(5 * 1000); + console.log(`本次投食结果: ${JSON.stringify(response)}`); + if (response.resultCode == 0 && response.code == 0) { + needFeedTimes--; + } + if (response.resultCode == 3003 && response.code == 0) { + console.log('剩余狗粮不足, 投食结束'); + needFeedTimes = 0; + } + tryTimes--; + } while (needFeedTimes > 0 && tryTimes > 0) + console.log('投食任务结束...\n'); +} +async function showMsg() { + if ($.isNode() && process.env.PET_NOTIFY_CONTROL) { + $.ctrTemp = `${process.env.PET_NOTIFY_CONTROL}` === 'false'; + } else if ($.getdata('jdPetNotify')) { + $.ctrTemp = $.getdata('jdPetNotify') === 'false'; + } else { + $.ctrTemp = `${jdNotify}` === 'false'; + } + // jdNotify = `${notify.petNotifyControl}` === 'false' && `${jdNotify}` === 'false' && $.getdata('jdPetNotify') === 'false'; + if ($.ctrTemp) { + $.msg($.name, subTitle, message, option); + if ($.isNode()) { + allMessage += `${subTitle}\n${message}${$.index !== cookiesArr.length ? '\n\n' : ''}` + // await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName || $.UserName}`, `${subTitle}\n${message}`); + } + } else { + $.log(`\n${message}\n`); + } +} +function TotalBean() { + return new Promise(async resolve => { + const options = { + "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, + "headers": { + "Accept": "application/json,text/plain, */*", + "Content-Type": "application/x-www-form-urlencoded", + "Accept-Encoding": "gzip, deflate, br", + "Accept-Language": "zh-cn", + "Connection": "keep-alive", + "Cookie": cookie, + "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", + "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1") + } + } + $.post(options, (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + data = JSON.parse(data); + if (data['retcode'] === 13) { + $.isLogin = false; //cookie过期 + return + } + if (data['retcode'] === 0 && data.base && data.base.nickname) { + $.nickName = data.base.nickname; + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e) + } + finally { + resolve(); + } + }) + }) +} +// 请求 +async function request(function_id, body = {}) { + await $.wait(5 * 1000); //歇口气儿, 不然会报操作频繁 + return new Promise((resolve, reject) => { + $.post(taskUrl(function_id, body), (err, resp, data) => { + try { + if (err) { + console.log('\n东东萌宠: API查询请求失败 ‼️‼️'); + console.log(JSON.stringify(err)); + $.logErr(err); + } else { + data = JSON.parse(data); + } + } catch (e) { + $.logErr(e, resp); + } + finally { + resolve(data) + } + }) + }) +} +// function taskUrl(function_id, body = {}) { +// return { +// url: `${JD_API_HOST}?functionId=${function_id}&appid=wh5&loginWQBiz=pet-town&body=${escape(JSON.stringify(body))}`, +// headers: { +// Cookie: cookie, +// UserAgent: $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), +// } +// }; +// } +function taskUrl(function_id, body = {}) { + body["version"] = 2; + body["channel"] = 'app'; + return { + url: `${JD_API_HOST}?functionId=${function_id}`, + body: `body=${encodeURIComponent(JSON.stringify(body))}&appid=wh5&loginWQBiz=pet-town&clientVersion=9.0.4`, + headers: { + 'Cookie': cookie, + 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), + 'Host': 'api.m.jd.com', + 'Content-Type': 'application/x-www-form-urlencoded', + } + }; +} +function jsonParse(str) { + if (typeof str == "string") { + try { + return JSON.parse(str); + } catch (e) { + console.log(e); + $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') + return []; + } + } +} +// prettier-ignore +function Env(t, e) { + "undefined" != typeof process && JSON.stringify(process.env).indexOf("GITHUB") > -1 && process.exit(0); + class s { + constructor(t) { + this.env = t + } + send(t, e = "GET") { + t = "string" == typeof t ? { + url: t + } + : t; + let s = this.get; + return "POST" === e && (s = this.post), + new Promise((e, i) => { + s.call(this, t, (t, s, r) => { + t ? i(t) : e(s) + }) + }) + } + get(t) { + return this.send.call(this.env, t) + } + post(t) { + return this.send.call(this.env, t, "POST") + } + } + return new class { + constructor(t, e) { + this.name = t, + this.http = new s(this), + this.data = null, + this.dataFile = "box.dat", + this.logs = [], + this.isMute = !1, + this.isNeedRewrite = !1, + this.logSeparator = "\n", + this.startTime = (new Date).getTime(), + Object.assign(this, e), + this.log("", `🔔${this.name}, 开始!`) + } + isNode() { + return "undefined" != typeof module && !!module.exports + } + isQuanX() { + return "undefined" != typeof $task + } + isSurge() { + return "undefined" != typeof $httpClient && "undefined" == typeof $loon + } + isLoon() { + return "undefined" != typeof $loon + } + toObj(t, e = null) { + try { + return JSON.parse(t) + } catch { + return e + } + } + toStr(t, e = null) { + try { + return JSON.stringify(t) + } catch { + return e + } + } + getjson(t, e) { + let s = e; + const i = this.getdata(t); + if (i) + try { + s = JSON.parse(this.getdata(t)) + } catch {} + return s + } + setjson(t, e) { + try { + return this.setdata(JSON.stringify(t), e) + } catch { + return !1 + } + } + getScript(t) { + return new Promise(e => { + this.get({ + url: t + }, (t, s, i) => e(i)) + }) + } + runScript(t, e) { + return new Promise(s => { + let i = this.getdata("@chavy_boxjs_userCfgs.httpapi"); + i = i ? i.replace(/\n/g, "").trim() : i; + let r = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); + r = r ? 1 * r : 20, + r = e && e.timeout ? e.timeout : r; + const[o, h] = i.split("@"), + n = { + url: `http://${h}/v1/scripting/evaluate`, + body: { + script_text: t, + mock_type: "cron", + timeout: r + }, + headers: { + "X-Key": o, + Accept: "*/*" + } + }; + this.post(n, (t, e, i) => s(i)) + }).catch(t => this.logErr(t)) + } + loaddata() { + if (!this.isNode()) + return {}; { + this.fs = this.fs ? this.fs : require("fs"), + this.path = this.path ? this.path : require("path"); + const t = this.path.resolve(this.dataFile), + e = this.path.resolve(process.cwd(), this.dataFile), + s = this.fs.existsSync(t), + i = !s && this.fs.existsSync(e); + if (!s && !i) + return {}; { + const i = s ? t : e; + try { + return JSON.parse(this.fs.readFileSync(i)) + } catch (t) { + return {} + } + } + } + } + writedata() { + if (this.isNode()) { + this.fs = this.fs ? this.fs : require("fs"), + this.path = this.path ? this.path : require("path"); + const t = this.path.resolve(this.dataFile), + e = this.path.resolve(process.cwd(), this.dataFile), + s = this.fs.existsSync(t), + i = !s && this.fs.existsSync(e), + r = JSON.stringify(this.data); + s ? this.fs.writeFileSync(t, r) : i ? this.fs.writeFileSync(e, r) : this.fs.writeFileSync(t, r) + } + } + lodash_get(t, e, s) { + const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); + let r = t; + for (const t of i) + if (r = Object(r)[t], void 0 === r) + return s; + return r + } + lodash_set(t, e, s) { + return Object(t) !== t ? t : (Array.isArray(e) || (e = e.toString().match(/[^.[\]]+/g) || []), e.slice(0, -1).reduce((t, s, i) => Object(t[s]) === t[s] ? t[s] : t[s] = Math.abs(e[i + 1]) >> 0 == +e[i + 1] ? [] : {}, t)[e[e.length - 1]] = s, t) + } + getdata(t) { + let e = this.getval(t); + if (/^@/.test(t)) { + const[, s, i] = /^@(.*?)\.(.*?)$/.exec(t), + r = s ? this.getval(s) : ""; + if (r) + try { + const t = JSON.parse(r); + e = t ? this.lodash_get(t, i, "") : e + } catch (t) { + e = "" + } + } + return e + } + setdata(t, e) { + let s = !1; + if (/^@/.test(e)) { + const[, i, r] = /^@(.*?)\.(.*?)$/.exec(e), + o = this.getval(i), + h = i ? "null" === o ? null : o || "{}" : "{}"; + try { + const e = JSON.parse(h); + this.lodash_set(e, r, t), + s = this.setval(JSON.stringify(e), i) + } catch (e) { + const o = {}; + this.lodash_set(o, r, t), + s = this.setval(JSON.stringify(o), i) + } + } else + s = this.setval(t, e); + return s + } + getval(t) { + return this.isSurge() || this.isLoon() ? $persistentStore.read(t) : this.isQuanX() ? $prefs.valueForKey(t) : this.isNode() ? (this.data = this.loaddata(), this.data[t]) : this.data && this.data[t] || null + } + setval(t, e) { + return this.isSurge() || this.isLoon() ? $persistentStore.write(t, e) : this.isQuanX() ? $prefs.setValueForKey(t, e) : this.isNode() ? (this.data = this.loaddata(), this.data[e] = t, this.writedata(), !0) : this.data && this.data[e] || null + } + initGotEnv(t) { + this.got = this.got ? this.got : require("got"), + this.cktough = this.cktough ? this.cktough : require("tough-cookie"), + this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar, + t && (t.headers = t.headers ? t.headers : {}, void 0 === t.headers.Cookie && void 0 === t.cookieJar && (t.cookieJar = this.ckjar)) + } + get(t, e = (() => {})) { + t.headers && (delete t.headers["Content-Type"], delete t.headers["Content-Length"]), + this.isSurge() || this.isLoon() ? (this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { + "X-Surge-Skip-Scripting": !1 + })), $httpClient.get(t, (t, s, i) => { + !t && s && (s.body = i, s.statusCode = s.status), + e(t, s, i) + })) : this.isQuanX() ? (this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { + hints: !1 + })), $task.fetch(t).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => e(t))) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { + try { + if (t.headers["set-cookie"]) { + const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); + s && this.ckjar.setCookieSync(s, null), + e.cookieJar = this.ckjar + } + } catch (t) { + this.logErr(t) + } + }).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => { + const { + message: s, + response: i + } = t; + e(s, i, i && i.body) + })) + } + post(t, e = (() => {})) { + if (t.body && t.headers && !t.headers["Content-Type"] && (t.headers["Content-Type"] = "application/x-www-form-urlencoded"), t.headers && delete t.headers["Content-Length"], this.isSurge() || this.isLoon()) + this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { + "X-Surge-Skip-Scripting": !1 + })), $httpClient.post(t, (t, s, i) => { + !t && s && (s.body = i, s.statusCode = s.status), + e(t, s, i) + }); + else if (this.isQuanX()) + t.method = "POST", this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { + hints: !1 + })), $task.fetch(t).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => e(t)); + else if (this.isNode()) { + this.initGotEnv(t); + const { + url: s, + ...i + } = t; + this.got.post(s, i).then(t => { + const { + statusCode: s, + statusCode: i, + headers: r, + body: o + } = t; + e(null, { + status: s, + statusCode: i, + headers: r, + body: o + }, o) + }, t => { + const { + message: s, + response: i + } = t; + e(s, i, i && i.body) + }) + } + } + time(t, e = null) { + const s = e ? new Date(e) : new Date; + let i = { + "M+": s.getMonth() + 1, + "d+": s.getDate(), + "H+": s.getHours(), + "m+": s.getMinutes(), + "s+": s.getSeconds(), + "q+": Math.floor((s.getMonth() + 3) / 3), + S: s.getMilliseconds() + }; + /(y+)/.test(t) && (t = t.replace(RegExp.$1, (s.getFullYear() + "").substr(4 - RegExp.$1.length))); + for (let e in i) + new RegExp("(" + e + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? i[e] : ("00" + i[e]).substr(("" + i[e]).length))); + return t + } + msg(e = t, s = "", i = "", r) { + const o = t => { + if (!t) + return t; + if ("string" == typeof t) + return this.isLoon() ? t : this.isQuanX() ? { + "open-url": t + } + : this.isSurge() ? { + url: t + } + : void 0; + if ("object" == typeof t) { + if (this.isLoon()) { + let e = t.openUrl || t.url || t["open-url"], + s = t.mediaUrl || t["media-url"]; + return { + openUrl: e, + mediaUrl: s + } + } + if (this.isQuanX()) { + let e = t["open-url"] || t.url || t.openUrl, + s = t["media-url"] || t.mediaUrl; + return { + "open-url": e, + "media-url": s + } + } + if (this.isSurge()) { + let e = t.url || t.openUrl || t["open-url"]; + return { + url: e + } + } + } + }; + if (this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, o(r)) : this.isQuanX() && $notify(e, s, i, o(r))), !this.isMuteLog) { + let t = ["", "==============📣系统通知📣=============="]; + t.push(e), + s && t.push(s), + i && t.push(i), + console.log(t.join("\n")), + this.logs = this.logs.concat(t) + } + } + log(...t) { + t.length > 0 && (this.logs = [...this.logs, ...t]), + console.log(t.join(this.logSeparator)) + } + logErr(t, e) { + const s = !this.isSurge() && !this.isQuanX() && !this.isLoon(); + s ? this.log("", `❗️${this.name}, 错误!`, t.stack) : this.log("", `❗️${this.name}, 错误!`, t) + } + wait(t) { + return new Promise(e => setTimeout(e, t)) + } + done(t = {}) { + const e = (new Date).getTime(), + s = (e - this.startTime) / 1e3; + this.log("", `🔔${this.name}, 结束! 🕛 ${s} 秒`), + this.log(), + (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) + } + } + (t, e) +} diff --git a/jd_tyt.js b/jd_tyt.js index f2242a8..f1223d0 100644 --- a/jd_tyt.js +++ b/jd_tyt.js @@ -1,13 +1,11 @@ /* -入口 极速版 赚金币 推一推 -助力前三 - +旁白 [task_local] -#搞基大神-推一推 -3 1 * * * http://47.101.146.160/scripts/jd_tyt.js, tag=搞基大神-推一推, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jd.png, enabled=true +#快速推一推 +0 1 * * * jd_tyt.js, tag=推一推, img-url= */ -const $ = new Env('推一推');//助力前三个可助力的账号 +const $ = new Env('极速版-推推赚大钱');//助力前八个可助力的账号不满意去57行改即可 const notify = $.isNode() ? require('./sendNotify') : ''; //Node.js用户请在jdCookie.js处填写京东ck; const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; @@ -15,9 +13,7 @@ const JD_API_HOST = 'https://api.m.jd.com'; //IOS等用户直接用NobyDa的jd cookie let cookiesArr = [], cookie = '', message; let status = '' - let inviteCodes = [] - if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { cookiesArr.push(jdCookieNode[item]) @@ -32,7 +28,6 @@ if ($.isNode()) { $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { "open-url": "https://bean.m.jd.com/bean/signIndex.action" }); return; } - for (let i = 0; i < cookiesArr.length; i++) { if (cookiesArr[i]) { cookie = cookiesArr[i]; @@ -52,17 +47,15 @@ if ($.isNode()) { continue } } - console.log('\n入口 狗东极速版 赚金币 推一推\n'); - console.log('\n本脚本无任何内置助力\n如果你发现有那么就是别人二改加的\n一切与本人无关\n'); + console.log('\n入口→极速版→赚金币→推推赚大钱\n'); await info() await coinDozerBackFlow() await getCoinDozerInfo() - console.log('\n注意助力前三个可助力的账号\n'); - if (inviteCodes.length >= 3) { + console.log('\n助力前八个可助力的账号不满意去57行改即可\n'); + if (inviteCodes.length >= 7) { break } } - console.log('\n#######开始助力前三个可助力的账号#######\n'); cookiesArr.sort(function () { return .5 - Math.random(); @@ -96,24 +89,19 @@ if ($.isNode()) { .finally(() => { $.done(); }) - - function info() { return new Promise((resolve) => { const nm = { - url: `${JD_API_HOST}`, - body: `functionId=initiateCoinDozer&body={"actId":"d5a8c7198ee54de093d2adb04089d3ec","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636014459632&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, + url: `https://api.m.jd.com/?_t=1646094718628`, + body: `functionId=initiateCoinDozer&body={"actId":"49f40d2f40b3470e8d6c39aa4866c7ff","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636014459632&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, headers: { - "Cookie": cookie, "Origin": "https://pushgold.jd.com", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36", - } } $.post(nm, async (err, resp, data) => { - try { if (err) { console.log(`${JSON.stringify(err)}`) @@ -149,7 +137,7 @@ function coinDozerBackFlow() { const nm = { url: `${JD_API_HOST}`, - body: `functionId=coinDozerBackFlow&body={"actId":"d5a8c7198ee54de093d2adb04089d3ec","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636015617899&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, + body: `functionId=coinDozerBackFlow&body={"actId":"49f40d2f40b3470e8d6c39aa4866c7ff","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636015617899&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, headers: { "Cookie": cookie, @@ -190,7 +178,7 @@ function helpCoinDozer(packetId) { return new Promise((resolve) => { const nm = { url: `${JD_API_HOST}`, - body: `functionId=helpCoinDozer&appid=station-soa-h5&client=H5&clientVersion=1.0.0&t=1636015855103&body={"actId":"d5a8c7198ee54de093d2adb04089d3ec","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s","packetId":"${packetId}"}&_ste=1&_stk=appid,body,client,clientVersion,functionId,t&h5st=20211104165055104;9806356985655163;10005;tk01wd1ed1d5f30nBDriGzaeVZZ9vuiX+cBzRLExSEzpfTriRD0nxU6BbRIOcSQvnfh74uInjSeb6i+VHpnHrBJdVwzs;017f330f7a84896d31a8d6017a1504dc16be8001273aaea9a04a8d04aad033d9`, + body: `functionId=helpCoinDozer&appid=station-soa-h5&client=H5&clientVersion=1.0.0&t=1636015855103&body={"actId":"49f40d2f40b3470e8d6c39aa4866c7ff","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s","packetId":"${packetId}"}&_ste=1&_stk=appid,body,client,clientVersion,functionId,t&h5st=20211104165055104;9806356985655163;10005;tk01wd1ed1d5f30nBDriGzaeVZZ9vuiX+cBzRLExSEzpfTriRD0nxU6BbRIOcSQvnfh74uInjSeb6i+VHpnHrBJdVwzs;017f330f7a84896d31a8d6017a1504dc16be8001273aaea9a04a8d04aad033d9`, headers: { "Cookie": cookie, @@ -226,13 +214,11 @@ function helpCoinDozer(packetId) { }) }) } - - function help(packetId) { return new Promise((resolve) => { const nm = { url: `${JD_API_HOST}`, - body: `functionId=helpCoinDozer&appid=station-soa-h5&client=H5&clientVersion=1.0.0&t=1623120183787&body={"actId":"d5a8c7198ee54de093d2adb04089d3ec","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s","packetId":"${packetId}","helperStatus":"0"}&_ste=1&_stk=appid,body,client,clientVersion,functionId,t&h5st=20210608104303790;8489907903583162;10005;tk01w89681aa9a8nZDdIanIyWnVuWFLK4gnqY+05WKcPY3NWU2dcfa73B7PBM7ufJEN0U+4MyHW5N2mT/RNMq72ycJxH;7e6b956f1a8a71b269a0038bbb4abd24bcfb834a88910818cf1bdfc55b7b96e5`, + body: `functionId=helpCoinDozer&appid=station-soa-h5&client=H5&clientVersion=1.0.0&t=1623120183787&body={"actId":"49f40d2f40b3470e8d6c39aa4866c7ff","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s","packetId":"${packetId}","helperStatus":"0"}&_ste=1&_stk=appid,body,client,clientVersion,functionId,t&h5st=20210608104303790;8489907903583162;10005;tk01w89681aa9a8nZDdIanIyWnVuWFLK4gnqY+05WKcPY3NWU2dcfa73B7PBM7ufJEN0U+4MyHW5N2mT/RNMq72ycJxH;7e6b956f1a8a71b269a0038bbb4abd24bcfb834a88910818cf1bdfc55b7b96e5`, headers: { "Cookie": cookie, @@ -263,10 +249,8 @@ function help(packetId) { if (data.msg.indexOf("完成") != -1) { $.ok = true } - } } - } catch (e) { $.logErr(e, resp) } finally { @@ -281,13 +265,11 @@ function getCoinDozerInfo() { const nm = { url: `${JD_API_HOST}`, - body: `functionId=getCoinDozerInfo&body={"actId":"d5a8c7198ee54de093d2adb04089d3ec","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636015858295&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, + body: `functionId=getCoinDozerInfo&body={"actId":"49f40d2f40b3470e8d6c39aa4866c7ff","channel":"coin_dozer","antiToken":"","referer":"-1","frontendInitStatus":"s"}&appid=megatron&client=ios&clientVersion=14.3&t=1636015858295&networkType=4g&eid=&fp=-1&frontendInitStatus=s&uuid=8888&osVersion=14.3&d_brand=&d_model=&agent=-1&pageClickKey=-1&screen=400*700&platform=3&lang=zh_CN`, headers: { - "Cookie": cookie, "Origin": "https://pushgold.jd.com", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36", - } } $.post(nm, async (err, resp, data) => { @@ -300,7 +282,7 @@ function getCoinDozerInfo() { if (safeGet(data)) { data = JSON.parse(data); if (data.success == true && data?.data?.sponsorActivityInfo?.packetId) { - console.log('叼毛:' + data.data.sponsorActivityInfo.initiatorNickname) + console.log('CK:' + data.data.sponsorActivityInfo.initiatorNickname) console.log('邀请码:' + data.data.sponsorActivityInfo.packetId) console.log('推出:' + data.data.sponsorActivityInfo.dismantledAmount) if (data.data && data.data.sponsorActivityInfo.packetId) {