diff --git a/jd_dreamFactory.js b/jd_dreamFactory.js index 29b6119e..1e2b59f0 100644 --- a/jd_dreamFactory.js +++ b/jd_dreamFactory.js @@ -1,265 +1,817 @@ /* 京东京喜工厂 -未完,待续 */ -const $hammer = (() => { - const isRequest = "undefined" != typeof $request, - isSurge = "undefined" != typeof $httpClient, - isQuanX = "undefined" != typeof $task; - const log = (...n) => { for (let i in n) console.log(n[i]) }; - const alert = (title, body = "", subtitle = "", link = "", option) => { - if (isSurge) return $notification.post(title, subtitle, body, link); - if (isQuanX) return $notify(title, subtitle, (link && !body ? link : body), option); - log("==============📣系统通知📣=============="); - log("title:", title, "subtitle:", subtitle, "body:", body, "link:", link); + +const $ = new Env('京喜工厂'); +const JD_API_HOST = 'https://m.jingxi.com'; + +let ele, factoryId; + +let message = '', subTitle = '', option = {}; +const notify = $.isNode() ? require('./sendNotify') : ''; +let jdNotify = false;//是否关闭通知,false打开通知推送,true关闭通知推送 + +let cookiesArr = [], cookie = ''; +const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + cookiesArr.push(jdCookieNode[item]) + }) + if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => { }; - const read = key => { - if (isSurge) return $persistentStore.read(key); - if (isQuanX) return $prefs.valueForKey(key); - }, - write = (key, val) => { - if (isSurge) return $persistentStore.write(key, val); - if (isQuanX) return $prefs.setValueForKey(key, val); - }; - const request = (method, params, callback) => { - /** - * - * params(): {url: , headers: , body: } | - * - * callback( - * error, - * {status: , headers: , body: } | "" - * ) - * - */ - let options = {}; - if (typeof params == "string") { - options.url = params; - } else { - options.url = params.url; - if (typeof params == "object") { - params.headers && (options.headers = params.headers); - params.body && (options.body = params.body); - } - } - method = method.toUpperCase(); - - const writeRequestErrorLog = function (m, u) { - return err => { - log("=== request error -s--"); - log(`${m} ${u}`, err); - log("=== request error -e--"); - }; - }(method, options.url); - - if (isSurge) { - const _runner = method == "GET" ? $httpClient.get : $httpClient.post; - return _runner(options, (error, response, body) => { - if (error == null || error == "") { - response.body = body; - callback("", response); - } else { - writeRequestErrorLog(error); - callback(error, ""); - } - }); - } - if (isQuanX) { - options.method = method; - $task.fetch(options).then( - response => { - response.status = response.statusCode; - delete response.statusCode; - callback("", response); - }, - reason => { - writeRequestErrorLog(reason.error); - callback(reason.error, ""); - } - ); - } - }; - const done = (value = {}) => { - if (isQuanX) return isRequest ? $done(value) : null; - if (isSurge) return isRequest ? $done(value) : $done(); - }; - return { isRequest, isSurge, isQuanX, log, alert, read, write, request, done }; -})(); - - -//京东接口地址 -const JD_API_HOST = 'https://wq.jd.com'; - -//直接用NobyDa的jd cookie -// const cookie = $hammer.read('CookieJD'); -const cookie = 'unpl=V2_ZzNtbUAHRRx0DxZVch9aBWIBRllLAhMSfQtDUnxLWVdnBhpcclRCFnQUR1JnGFUUZAMZXURcQhJFOEZVehhdDWMEGllyZ0sdGwgLVBUaMgUqTl9tQVdzFEUIQlx%252bGlwAZAAXW0tRRhZ9DU5TfRpsNWcFIl1DVkIUcgBBVnkaVDU8VnxbEgJDESFYRFNyHllQVwIiXHJWc0MbCEdVehteBmYAEhBCU0sQdghDV3gcWgxhBhFVR19EE3Y4R2R4; PPRD_P=CT.138912.3.26-UUID.1594174344038855825195; __jda=122270672.1594174344038855825195.1594174344.1594619829.1594628524.29; __jdb=122270672.4.1594174344038855825195|29.1594628524; __jdc=122270672; __jdv=122270672%7Ckong%7Ct_1000170136%7Ctuiguang%7Cnotset%7C1594569450665; __wga=1594631325352.1594630264664.1594619828892.1594619828892.3.2; _tj_rvurl=https%3A//wq.jd.com/cube/front/activePublish/dream_factory_report/380556.html%3Fptag%3D138912.3.26%26lng%3D113.321134%26lat%3D23.139617%26sid%3D6c732f3e20be25526c2e67df89e488dw%26un_area%3D19_1601_50258_51885; cid=8; mba_muid=1594174344038855825195.33.1594631325409; mba_sid=33.18; retina=1; shshshfp=3f7499d014a4f06d56edfb5378a934ee; shshshfpb=w5O9mqDoHWvVwOS9jAYB%20zg%3D%3D; shshshsID=ed6e17a13e5b4921d09de669e2b06c89_3_1594631325584; wqmnx1=MDEyNjM1M3B3am1ncmZyZHR0My4mMTImMjlzYzNlNjdld2ExMDIxNjg1NnBoOTsuNWE0ZWVjYmRla2lEQS0tLS1ENXV0ZTNVL3NpTzFlaDFkczAzaFA7dTEzcGV5ZG9yZXYxcE1HYWVKZXJDbzs0Ly9hOTBjZmEyMTswZzAwdGFvfDUwMTY7O2RlO0o1Mi5JMztsLlA7IG4gX2tjWHBiNi5LLGVrby80cEpLMWY3bjI0MllPT1UhSCU%3D; wxa_level=1; pt_key=app_openAAJfBSQbAEBjl86WMnH-4g3Is6PISRQsx5CU-pQolK0klfaTVHmW5nfZL7DkOGhtRWp6ttQKfdDSiHZ1el6DX2SEjWkotlT2; pt_pin=%E8%A2%AB%E6%8A%98%E5%8F%A0%E7%9A%84%E8%AE%B0%E5%BF%8633; pwdt_id=%E8%A2%AB%E6%8A%98%E5%8F%A0%E7%9A%84%E8%AE%B0%E5%BF%8633; sid=6c732f3e20be25526c2e67df89e488dw; wq_area=19_1601_3633%7C3; visitkey=270851475495567; jxsid=15946198288819114076; sc_width=414; webp=0; shshshfpa=b134218e-f14e-6005-fa8e-52d2bc02126f-1594364440'; -let shareCodes = [ - 'V5LkjP4WRyjeCKR9VRwcRX0bBuTz7MEK0-E99EJ7u0k=', -]; -let factoryId, productionId, userTaskStatusList, dailyTask = [], produceTask = []; -const name = '京喜工厂'; -let message = ''; -let subTitle = ''; -const Task = step() -Task.next(); -function* step() { - const startTime = Date.now(); - yield userInfo(); - yield collectElectricity(); - yield investElectric(); - yield taskList(); - //yield produceTaskFun();//生产任务 - const end = ((Date.now() - startTime) / 1000).toFixed(2); - console.log(`\n完成${name}脚本耗时: ${end} 秒\n`); - $hammer.alert(name, message, subTitle); +} else { + cookiesArr.push(...[$.getdata('CookieJD'), $.getdata('CookieJD2')]) } +!(async () => { + if (!cookiesArr[0]) { + $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', {"open-url": "https://bean.m.jd.com/"}); + 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(`\n***********开始【京东账号${$.index}】${$.nickName || $.UserName}********\n`); + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/`, {"open-url": "https://bean.m.jd.com/"}); -function produceTaskFun() { - for (let item of produceTask) { - if (item.awardStatus !== 1) { - if (item.completedTimes >= item.targetTimes) { - const url = `/newtasksys/newtasksys_front/Award?source=dreamfactory&bizCode=dream_factory&taskId=${item.taskId}&sceneval=2&g_login_type=1`; - request(url).then((res) => { - console.log(`每日任务完成结果${JSON.stringify(res)}}`); - try { - if (res.ret === 0) { - console.log(`${item.taskName}任务完成`) - } - } catch (e) { - console.log(`${item.taskName}任务异常`) - } - }) + if ($.isNode()) { + await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + } else { + $.setdata('', `CookieJD${i ? i + 1 : ""}`);//cookie失效,故清空cookie。$.setdata('', `CookieJD${i ? i + 1 : "" }`);//cookie失效,故清空cookie。 + } + continue } + message = ''; + subTitle = ''; + goodsUrl = ''; + taskInfoKey = []; + option = {}; + await jdDreamFactory(); } } - Task.next(); +})() + .catch((e) => { + $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') + }) + .finally(() => { + $.done(); + }) + +function msleep(n) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n); } +function sleep(n) { + msleep(n * 1000); +} + +async function jdDreamFactory() { + ele = 0; + await userInfo(); + await getUserElectricity(); + await taskList(); + await investElectric(); + // await assistFriend('gB99tYLjvPcEFloDgamoBw=='); + await hireAward(); + await stealFriend(); + await showMsg(); +} + + // 收取发电机的电力 -function collectElectricity() { - const url = `/dreamfactory/generator/CollectCurrentElectricity?zone=dream_factory&apptoken=&pgtimestamp=&phoneID=&factoryid=${factoryId}&doubleflag=1&sceneval=2`; - request(url).then((res) => { - try { - if (res.ret === 0) { - console.log(`成功从发电机收取${res.data.CollectElectricity}电力`); - } - Task.next(); - } catch (e) { - console.log('收集电力异常') - } - }) -} -// 投入电力 -function investElectric() { - const url = `/dreamfactory/userinfo/InvestElectric?zone=dream_factory&productionId=${productionId}&sceneval=2&g_login_type=1`; - request(url).then((res) => { - try { - if (res.ret === 0) { - console.log(`成功投入电力${res.data.investElectric}电力`); - message += `【投入电力】${res.data.investElectric}`; - } else { - console.log(`投入失败,${res.message}`); - } - Task.next(); - } catch (e) { - console.log('收集电力异常') - } - }) -} -// 初始化任务 -function taskList() { - const url = `/newtasksys/newtasksys_front/GetUserTaskStatusList?source=dreamfactory&bizCode=dream_factory&sceneval=2&g_login_type=1`; - request(url).then((res) => { - try { - //console.log(`${JSON.stringify(res)}`) - //console.log(res) - if (res.ret === 0) { - userTaskStatusList = res.data.userTaskStatusList; - for (let item of res.data.userTaskStatusList) { - if (item.dateType === 2) { - dailyTask.push(item); - } - if (item.dateType === 1) { - produceTask.push(item); +function collectElectricity(factoryId = factoryId, help = false) { + return new Promise(async resolve => { + const url = `/dreamfactory/generator/CollectCurrentElectricity?zone=dream_factory&apptoken=&pgtimestamp=&phoneID=&factoryid=${factoryId}&doubleflag=1&sceneval=2&g_login_type=1`; + + $.get(taskurl(url), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + data = JSON.parse(data); + if (data['ret'] === 0) { + if (help) { + ele += Number(data.data['loginPinCollectElectricity']) + console.log(`帮助好友收取 ${data.data['CollectElectricity']} 电力,获得 ${data.data['loginPinCollectElectricity']} 电力`); + message += `【帮助好友】帮助成功,获得 ${data.data['loginPinCollectElectricity']} 电力\n` + } else { + + ele += Number(data.data['CollectElectricity']) + console.log(`收取 ${data.data['loginPinCollectElectricity']} 电力`); + message += `【收取发电站】收取成功,获得 ${data.data['CollectElectricity']} 电力\n` + } + + } else { + // console.log(data) + } + } else { + console.log(`京东服务器返回空数据`) } } - Task.next(); + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); } - } catch (e) { - console.log('初始化任务异常') - } - }).catch((error) => { - console.log(error) + }) }) } -//初始化个人信息 + +// 投入电力 +function investElectric() { + return new Promise(async resolve => { + const url = `/dreamfactory/userinfo/InvestElectric?zone=dream_factory&productionId=${productionId}&sceneval=2&g_login_type=1`; + $.get(taskurl(url), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + // console.log(data) + data = JSON.parse(data); + if (data.ret === 0) { + console.log(`成功投入电力${data.data.investElectric}电力`); + message += `【投入电力】投入成功,共计 ${data.data.investElectric} 电力\n`; + } else { + console.log(`投入失败,${data.msg}`); + message += `【投入电力】投入失败,${data.msg}\n`; + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 初始化任务 +function taskList() { + return new Promise(async resolve => { + const url = `/newtasksys/newtasksys_front/GetUserTaskStatusList?source=dreamfactory&bizCode=dream_factory&sceneval=2&g_login_type=1`; + $.get(taskurl(url), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + // console.log(data) + data = JSON.parse(data); + let userTaskStatusList = data['data']['userTaskStatusList']; + for (let i = 0; i < userTaskStatusList.length; ++i) { + const vo = userTaskStatusList[i]; + if (vo['awardStatus'] !== 1) { + if (vo.completedTimes >= vo.targetTimes) { + console.log(`任务:${vo.description}可完成`) + await completeTask(vo.taskId, vo.taskName) + sleep(1); + } else { + switch (vo.taskType) { + case 2: // 逛一逛任务 + case 6: // 浏览商品任务 + case 9: // 开宝箱 + for (let i = vo.completedTimes; i <= vo.configTargetTimes; ++i) { + console.log(`去做任务:${vo.taskName}`) + await doTask(vo.taskId) + await completeTask(vo.taskId, vo.taskName) + sleep(1); + } + break + case 4: // 招工 + break + case 5: + // 收集类 + break + case 1: // 登陆领奖 + default: + break + } + } + } + } + console.log(`完成任务:共领取${ele}电力`) + message += `【每日任务】领奖成功,共计 ${ele} 电力\n`; + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 获得用户电力情况 +function getUserElectricity() { + return new Promise(async resolve => { + const url = `/dreamfactory/generator/QueryCurrentElectricityQuantity?zone=dream_factory&factoryid=${factoryId}&sceneval=2&g_login_type=1` + $.get(taskurl(url), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + // console.log(data) + data = JSON.parse(data); + if (data['ret'] === 0) { + console.log(`发电机:当前 ${data.data.currentElectricityQuantity} 电力,最大值 ${data.data.maxElectricityQuantity} 电力`) + if (data.data.currentElectricityQuantity === data.data.maxElectricityQuantity + && data.data.doubleElectricityFlag) { + console.log(`发电机:电力可翻倍并收获`) + await collectElectricity() + } else { + message += `【发电机电力】当前 ${data.data.currentElectricityQuantity} 电力,未达到收获标准\n` + } + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 收取招工电力 +function hireAward() { + return new Promise(async resolve => { + const url = `/dreamfactory/friend/HireAward?zone=dream_factory&date=${new Date().Format("yyyyMMdd")}&type=0&sceneval=2&g_login_type=1` + $.get(taskurl(url), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + data = JSON.parse(data); + if (data['ret'] === 0) { + console.log(`打工电力:收取成功`) + message += `【打工电力】:收取成功\n` + } else { + console.log(`打工电力:收取失败,${data.msg}`) + message += `【打工电力】:收取失败,${data.msg}\n` + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 帮助用户 +function assistFriend(sharepin) { + + return new Promise(async resolve => { + const url = `/dreamfactory/friend/AssistFriend?zone=dream_factory&sharepin=${sharepin}&sceneval=2&g_login_type=1` + $.get(taskurl(url), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + data = JSON.parse(data); + if (data['ret'] === 0) { + console.log(`助力朋友:${sharepin}成功`) + } else { + console.log(`助力朋友:${data.msg}`) + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 任务领奖 +function completeTask(taskId, taskName) { + return new Promise(async resolve => { + const url = `/newtasksys/newtasksys_front/Award?source=dreamfactory&bizCode=dream_factory&taskId=${taskId}&sceneval=2&g_login_type=1`; + $.get(taskurl(url), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + // console.log(data) + data = JSON.parse(data); + switch (data['data']['awardStatus']) { + case 1: + ele += Number(data['data']['prizeInfo'].replace('\\n', '')) + console.log(`领取${taskName}任务奖励成功,收获:${Number(data['data']['prizeInfo'].replace('\\n', ''))}电力`); + break + case 1013: + case 0: + console.log(`领取${taskName}任务奖励失败,任务已领奖`); + break + default: + console.log(`领取${taskName}任务奖励失败,${data['msg']}`) + break + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 完成任务 +function doTask(taskId) { + return new Promise(async resolve => { + const url = `/newtasksys/newtasksys_front/DoTask?source=dreamfactory&bizCode=dream_factory&taskId=${taskId}&sceneval=2&g_login_type=1`; + $.get(taskurl(url), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (data) { + // console.log(data) + data = JSON.parse(data); + if (data.ret === 0) { + console.log("做任务完成!") + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 初始化个人信息 function userInfo() { - const url = `/dreamfactory/userinfo/GetUserInfo?zone=dream_factory&pin=&sharePin=&shareType=&materialTuanPin=&materialTuanId=&sceneval=2`; - request(url).then((response) => { - try { - // taskInfo = res.data.result.taskInfos; - if (response.ret === 0) { - const { data } = response; - // !data.productionList && !data.factoryList + return new Promise(async resolve => { + const url = `/dreamfactory/userinfo/GetUserInfo?zone=dream_factory&pin=&sharePin=&shareType=&materialTuanPin=&materialTuanId=&sceneval=2`; + $.get(taskurl(url), (err, resp, data) => { + data = JSON.parse(data); + if (data['ret'] === 0) { + data = data['data']; if (data.factoryList && data.productionList) { const production = data.productionList[0]; const factory = data.factoryList[0]; factoryId = factory.factoryId;//工厂ID productionId = production.productionId;//商品ID subTitle = data.user.pin; - console.log(`\n我的分享码\n${data.user.encryptPin}\n`); - // console.log(`进度:${(production.investedElectric/production.needElectric).toFixed(2) * 100}%\n`); + console.log(`当前电力:${data.user.electric}`) + console.log(`分享码: ${data.user.encryptPin}`); + console.log(`生产进度:${(production.investedElectric / production.needElectric).toFixed(2) * 100}%`); message += `【生产进度】${((production.investedElectric / production.needElectric) * 100).toFixed(2)}%\n`; - Task.next(); } else { - return $hammer.alert(name, '\n【提示】此账号京喜工厂活动未开始\n请手动去京东APP->游戏与互动->查看更多->京喜工厂 开启活动\n'); + console.log('【提示】此账号京喜工厂活动未开始\n请手动去京东APP->游戏与互动->查看更多->京喜工厂 开启活动\n') } - } else { - Task.return(); } - } catch (e) { - console.log(e); - console.log('初始化任务异常'); - } + resolve() + }) }) } -//等待一下 -function sleep(s) { - return new Promise((resolve, reject) => { - setTimeout(() => { - resolve(); - }, s * 1000); + +function stealFriend() { + return new Promise(async resolve => { + const url = `//dreamfactory/friend/QueryFactoryManagerList?zone=dream_factory&sceneval=2`; + $.get(taskurl(url), (err, resp, data) => { + data = JSON.parse(data); + if (data['ret'] === 0) { + data = data['data']; + for (let i = 0; i < data.list.length; ++i) { + let pin = data.list[i]['encryptPin']; + getFactoryIdByPin(pin).then(async (facId) => { + await collectElectricity(facId,true) + }).catch(err => { + + }) + } + } + resolve() + }) }) } -async function request(url, body = {}) { - await sleep(2); //歇口气儿, 不然会报操作频繁 +function getFactoryIdByPin(pin) { return new Promise((resolve, reject) => { - $hammer.request('GET', taskurl(url, body), (error, response) => { - if(error){ - $hammer.log("Error:", error); - }else{ - //console.log(response.body) - resolve(JSON.parse(response.body)); + const url = `/dreamfactory/userinfo/GetUserInfoByPin?zone=dream_factory&pin=${pin}&sceneval=2`; + $.get(taskurl(url), (err, resp, data) => { + data = JSON.parse(data); + if (data['ret'] === 0) { + resolve(data['data']['factoryList'][0]['factoryId']) + } else { + reject() } }) }) } +async function showMsg() { + let ctrTemp; + if ($.isNode() && process.env.DREAMFACTORY_NOTIFY_CONTROL) { + ctrTemp = `${process.env.DREAMFACTORY_NOTIFY_CONTROL}` === 'false'; + } else if ($.getdata('jdDreamFactory')) { + ctrTemp = $.getdata('jdDreamFactory') === 'false'; + } else { + ctrTemp = `${jdNotify}` === 'false'; + } + if (ctrTemp) { + $.msg($.name, subTitle, message, option); + if ($.isNode()) { + await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName}`, `${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": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.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 + } + $.nickName = data['base'].nickname; + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} + +// 生成url function taskurl(url, body) { return { url: `${JD_API_HOST}${url}`, headers: { - 'Cookie' : cookie, - 'Host': 'wq.jd.com', + 'Cookie': cookie, + 'Host': 'm.jingxi.com', 'Accept': '*/*', 'Connection': 'keep-alive', - 'User-Agent': 'jdapp;iPhone;9.0.4;13.5.1;;Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1', + 'User-Agent': 'jdpingou;iPhone;3.14.4;14.0;ae75259f6ca8378672006fc41079cd8c90c53be8;network/wifi;model/iPhone10,2;appBuild/100351;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/1;hasOCPay/0;supportBestPay/0;session/62;pap/JA2015_311210;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148', 'Accept-Language': 'zh-cn', 'Referer': 'https://wqsd.jd.com/pingou/dream_factory/index.html', 'Accept-Encoding': 'gzip, deflate, br', } } -} \ No newline at end of file +} + +Date.prototype.Format = function (fmt) { //author: meizz + var o = { + "M+": this.getMonth() + 1, //月份 + "d+": this.getDate(), //日 + "h+": this.getHours(), //小时 + "m+": this.getMinutes(), //分 + "s+": this.getSeconds(), //秒 + "q+": Math.floor((this.getMonth() + 3) / 3), //季度 + "S": this.getMilliseconds() //毫秒 + }; + if (/(y+)/.test(fmt)) + fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); + for (var k in o) + if (new RegExp("(" + k + ")").test(fmt)) + fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); + return fmt; +} + +// prettier-ignore +function Env(t, e) { + 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, o) => { + 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.logSeparator = "\n", this.startTime = (new Date).getTime(), Object.assign(this, e), this.log("", `\ud83d\udd14${this.name}, \u5f00\u59cb!`) + } + + 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 o = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); + o = o ? 1 * o : 20, o = e && e.timeout ? e.timeout : o; + const [r, h] = i.split("@"), a = { + url: `http://${h}/v1/scripting/evaluate`, + body: {script_text: t, mock_type: "cron", timeout: o}, + headers: {"X-Key": r, Accept: "*/*"} + }; + this.post(a, (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), o = JSON.stringify(this.data); + s ? this.fs.writeFileSync(t, o) : i ? this.fs.writeFileSync(e, o) : this.fs.writeFileSync(t, o) + } + } + + lodash_get(t, e, s) { + const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); + let o = t; + for (const t of i) if (o = Object(o)[t], void 0 === o) return s; + return o + } + + 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), o = s ? this.getval(s) : ""; + if (o) try { + const t = JSON.parse(o); + e = t ? this.lodash_get(t, i, "") : e + } catch (t) { + e = "" + } + } + return e + } + + setdata(t, e) { + let s = !1; + if (/^@/.test(e)) { + const [, i, o] = /^@(.*?)\.(.*?)$/.exec(e), r = this.getval(i), h = i ? "null" === r ? null : r || "{}" : "{}"; + try { + const e = JSON.parse(h); + this.lodash_set(e, o, t), s = this.setval(JSON.stringify(e), i) + } catch (e) { + const r = {}; + this.lodash_set(r, o, t), s = this.setval(JSON.stringify(r), 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() ? $httpClient.get(t, (t, s, i) => { + !t && s && (s.body = i, s.statusCode = s.status), e(t, s, i) + }) : this.isQuanX() ? $task.fetch(t).then(t => { + const {statusCode: s, statusCode: i, headers: o, body: r} = t; + e(null, {status: s, statusCode: i, headers: o, body: r}, r) + }, t => e(t)) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { + try { + const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); + this.ckjar.setCookieSync(s, null), e.cookieJar = this.ckjar + } catch (t) { + this.logErr(t) + } + }).then(t => { + const {statusCode: s, statusCode: i, headers: o, body: r} = t; + e(null, {status: s, statusCode: i, headers: o, body: r}, r) + }, t => e(t))) + } + + 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()) $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", $task.fetch(t).then(t => { + const {statusCode: s, statusCode: i, headers: o, body: r} = t; + e(null, {status: s, statusCode: i, headers: o, body: r}, r) + }, 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: o, body: r} = t; + e(null, {status: s, statusCode: i, headers: o, body: r}, r) + }, t => e(t)) + } + } + + time(t) { + let e = { + "M+": (new Date).getMonth() + 1, + "d+": (new Date).getDate(), + "H+": (new Date).getHours(), + "m+": (new Date).getMinutes(), + "s+": (new Date).getSeconds(), + "q+": Math.floor(((new Date).getMonth() + 3) / 3), + S: (new Date).getMilliseconds() + }; + /(y+)/.test(t) && (t = t.replace(RegExp.$1, ((new Date).getFullYear() + "").substr(4 - RegExp.$1.length))); + for (let s in e) new RegExp("(" + s + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? e[s] : ("00" + e[s]).substr(("" + e[s]).length))); + return t + } + + msg(e = t, s = "", i = "", o) { + const r = t => { + if (!t || !this.isLoon() && this.isSurge()) return t; + if ("string" == typeof t) return this.isLoon() ? t : this.isQuanX() ? {"open-url": t} : void 0; + if ("object" == typeof t) { + if (this.isLoon()) { + let e = t.openUrl || t["open-url"], s = t.mediaUrl || t["media-url"]; + return {openUrl: e, mediaUrl: s} + } + if (this.isQuanX()) { + let e = t["open-url"] || t.openUrl, s = t["media-url"] || t.mediaUrl; + return {"open-url": e, "media-url": s} + } + } + }; + this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, r(o)) : this.isQuanX() && $notify(e, s, i, r(o))); + let h = ["", "==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="]; + h.push(e), s && h.push(s), i && h.push(i), console.log(h.join("\n")), this.logs = this.logs.concat(h) + } + + 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("", `\u2757\ufe0f${this.name}, \u9519\u8bef!`, t.stack) : this.log("", `\u2757\ufe0f${this.name}, \u9519\u8bef!`, t) + } + + wait(t) { + return new Promise(e => setTimeout(e, t)) + } + + done(t = {}) { + const e = (new Date).getTime(), s = (e - this.startTime) / 1e3; + this.log("", `\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${s} \u79d2`), this.log(), (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) + } + }(t, e) +}