From 1906f6b483838ed89681fc9f43f24fcba1a9e179 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 17 Aug 2021 11:49:22 -0400 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=8E=2008-17=2011:49?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker/crontab_list.sh | 3 + jd_DrawEntrance.js | 235 +++++++++ jd_appliances.js | 234 +++++++++ jd_bean_change.js | 319 ++++++------ jd_bean_home.js | 1074 +++++++++++++++++++++++++++------------- jd_bean_sign.js | 358 +++++++++----- jd_beauty.js | 107 ++-- jd_blueCoin.js | 58 +-- jd_bookshop.js | 715 +++++++++++++------------- 9 files changed, 1996 insertions(+), 1107 deletions(-) create mode 100755 jd_DrawEntrance.js create mode 100755 jd_appliances.js diff --git a/docker/crontab_list.sh b/docker/crontab_list.sh index 1cd6f9e..ec77352 100755 --- a/docker/crontab_list.sh +++ b/docker/crontab_list.sh @@ -180,5 +180,8 @@ 5 0 * * * node /scripts/jx_sign.js >> /scripts/logs/jx_sign.log 2>&1 #来客有礼小程序 45 4 * * * node /scripts/jd_senbeans.js >> /scripts/logs/jd_senbeans.log 2>&1 +#大乐透 +15 6 * * * node /scripts/jd_DrawEntrance.js >> /scripts/logs/jd_DrawEntrance.log 2>&1 + ##############可选脚本############## diff --git a/jd_DrawEntrance.js b/jd_DrawEntrance.js new file mode 100755 index 0000000..f4aff77 --- /dev/null +++ b/jd_DrawEntrance.js @@ -0,0 +1,235 @@ +/* +天天优惠大乐透 +活动入口-领券-券后9.9 +脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js +============Quantumultx=============== +[task_local] +15 6 * * * jd_DrawEntrance.js, tag=天天优惠大乐透, enabled=true +================Loon============== +[Script] +cron "15 6 * * *" script-path=jd_DrawEntrance.js,tag=天天优惠大乐透 +===============Surge================= +天天优惠大乐透 = type=cron,cronexp="15 6 * * *",wake-system=1,timeout=3600,script-path=jd_DrawEntrance.js +============小火箭========= +天天优惠大乐透 = type=cron,script-path=jd_DrawEntrance.js, cronexpr="15 6 * * *", timeout=3600, enable=true + */ +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("天天优惠大乐透"); +const notify = $.isNode() ? require('./sendNotify') : ''; +//Node.js用户请在jdCookie.js处填写京东ck; +const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +let jdNotify = false; //是否关闭通知,false打开通知推送,true关闭通知推送 +//IOS等用户直接用NobyDa的jd cookie +let cookiesArr = [], + cookie = '', + message = ''; +if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + cookiesArr.push(jdCookieNode[item]) + }) + if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => {}; +} else { + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jd_helpers.safeGet($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); +} +const JD_API_HOST = 'https://api.m.jd.com/api'; +!(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 = ''; + // message = ''; //不重置信息内容 + await TotalBean(); + console.log(`\n******开始【京东账号${$.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 + } + $.ADID = getUUID('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 1); + $.UUID = getUUID('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); + $.noChance = false; + await extend(); + for (let x = 0; x < 3; x++) { + if ($.noChance) { + continue + } + $.log("\n尝试抽奖") + await doLuckDrawEntrance(); + await $.wait(1000 * 1) + } + } + } + if (message !== "") { + if ($.isNode()) { + await notify.sendNotify($.name, message) + } else { + $.msg($.name, '', message) + } + } +})() +.catch((e) => { + $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') + }) + .finally(() => { + $.done(); + }) + +function extend() { + return new Promise(resolve => { + $.post(taskUrl("getLuckyDrawResourceConfig", { + "platformType": "1" + }), async (err, resp, data) => { + try { + if (err) { + console.log(err) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + $.extend = data.result.luckyDrawConfig.extend + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(data); + } + }) + }) +} + +function doLuckDrawEntrance() { + let body = { + "platformType": "1", + "extend": $.extend + } + return new Promise(resolve => { + $.post(taskUrl("doLuckDrawEntrance", body), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`${$.name} API请求失败,请检查网路重试`) + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (data.success && "luckyDrawData" in data.result) { + if (data.result.luckyDrawData.checkWinOrNot) { //调整判断的顺序 + switch (data.result.luckyDrawData.couponType) { + case '2': + console.log(` 成功领取优惠券:${data.result.luckyDrawData.discount}\n ${data.result.luckyDrawData.quotaDesc},${data.result.luckyDrawData.prizeName}`) + break; + case '0': + console.log(` 成功领取无门槛红包:${data.result.luckyDrawData.quota}`) + //message += `\n【京东账号${$.index}】${$.nickName || $.UserName} \n 成功领取无门槛红包:${data.result.luckyDrawData.quota}`//增加通知内容 + break; + default: + console.log(JSON.stringify(data)) //这边把对象已文本形式输出,避免对象中的属性有数组形式造成不完全打印 + break; + } + } else { + $.noChance = true; + console.log("已经没有次数了"); + } + } + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(data); + } + }) + }) +} + +function taskUrl(function_id, body = {}) { + return { + url: `${JD_API_HOST}?functionId=${function_id}&body=${escape(JSON.stringify(body))}&appid=XPMSGC2019&client=m&clientVersion=1.0.0&area=19_1601_3633_63252&geo=[object Object]&uuid=${$.UUID}`, + headers: { + "Cookie": cookie, + "Host": "api.m.jd.com", + "Origin": "https://h5.m.jd.com", + "Content-Length": "0", + "Connection": "keep-alive", + "Accept": "application/json, text/plain, */*", + "User-Agent": `jdapp;iPhone;9.5.0;13.5;${$.UUID};network/wifi;ADID/${$.ADID};supportApplePay/0;hasUPPay/0;hasOCPay/0;model/iPhone11,6;addressid/138222502;supportBestPay/0;appBuild/167638;jdSupportDarkMode/0;Mozilla/5.0 (iPhone; CPU iPhone OS 13_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1`, + "Accept-Language": "zh-cn", + "Referer": "https://h5.m.jd.com/babelDiy/Zeus/yj8mbcm6roENn7qhNdhiekyeqtd/index.html", + "Accept-Encoding": "gzip, deflate, br", + "Content-Type": "text/plain", + } + } +} + +function getUUID(format = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', UpperCase = 0) { + return format.replace(/[xy]/g, function (c) { + var r = Math.random() * 16 | 0, + v = c == 'x' ? r : (r & 0x3 | 0x8); + if (UpperCase) { + uuid = v.toString(36).toUpperCase(); + } else { + uuid = v.toString(36) + } + return uuid; + }); +} + +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": `jdapp;iPhone;9.5.0;13.5;${$.UUID};network/wifi;ADID/${$.ADID};supportApplePay/0;hasUPPay/0;hasOCPay/0;model/iPhone11,6;addressid/138222502;supportBestPay/0;appBuild/167638;jdSupportDarkMode/0;Mozilla/5.0 (iPhone; CPU iPhone OS 13_5 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) { + $.nickName = (data['base'] && data['base'].nickname) || $.UserName; + } else { + $.nickName = $.UserName + } + } else { + console.log(`京东服务器返回空数据`) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); + } + }) + }) +} \ No newline at end of file diff --git a/jd_appliances.js b/jd_appliances.js new file mode 100755 index 0000000..1dd210a --- /dev/null +++ b/jd_appliances.js @@ -0,0 +1,234 @@ +/** + * 执行一次就可以了,最多10个豆子 + * cron 54 5 9-15 8 * + * 不要问我是哪个活动,问了我也不告诉你,我也找不到入口了 + */ + const jd_helpers = require("./utils/JDHelpers.js"); + const jd_env = require("./utils/JDEnv.js"); + const $ = jd_env.env("家电815周年庆礼包"); + const jdCookieNode = $.isNode() ? require("./jdCookie.js") : ""; + const notify = $.isNode() ? require("./sendNotify") : ""; + let cookiesArr = []; + if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + cookiesArr.push(jdCookieNode[item]); + }); + if (process.env.JD_DEBUG && process.env.JD_DEBUG === "false") console.log = () => {}; + } else { + cookiesArr = [$.getdata("CookieJD"), $.getdata("CookieJD2"), ...jd_helpers.jsonParse($.getdata("CookiesJD") || "[]").map((item) => item.cookie)].filter((item) => !!item); + } + !(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++) { + await getUA(); + $.index = i + 1; + $.cookie = cookiesArr[i]; + $.isLogin = true; + $.nickName = ""; + $.UserName = decodeURIComponent($.cookie.match(/pt_pin=([^; ]+)(?=;?)/) && $.cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); + await TotalBean(); + console.log(`\n*****开始【京东账号${$.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; + } + await main(); + await $.wait(1000); + } + })() + .catch((e) => { + $.log("", `❌ ${$.name}, 失败! 原因: ${e}!`, ""); + }) + .finally(() => { + $.done(); + }); + + async function main() { + $.activityInfo = {}; + await takePostRequest("index"); + if (JSON.stringify($.activityInfo) === "{}") { + console.log(`获取活动详情失败`); + return; + } + await $.wait(500); + await doTask(); + } + + async function doTask() { + if ($.activityInfo.tasksList && $.activityInfo.tasksList.length > 0) { + $.tasksList = $.activityInfo.tasksList; + for (let i = 0; i < $.tasksList.length; i++) { + $.oneTask = $.tasksList[i]; + if ($.oneTask.finishNum === 1) { + console.log(`任务:${$.oneTask.taskName},已完成`); + continue; + } + console.log(`任务:${$.oneTask.taskName},去执行`); + await takePostRequest("doTask"); + if ($.hotFlag) { + break; + } + await $.wait(5000); + await takePostRequest("getReward"); + await $.wait(500); + } + } + } + + async function takePostRequest(type) { + let body = ""; + switch (type) { + case "index": + body = `appid=anniversary-celebra&functionId=jd_interaction_prod&body={"apiMapping":"/api/index/index"}&t=${Date.now()}&loginType=2`; + break; + case "doTask": + body = `appid=anniversary-celebra&functionId=jd_interaction_prod&body={"parentId":"${$.oneTask.parentId}","taskId":"${ + $.oneTask.taskId + }","apiMapping":"/api/task/doTask"}&t=${Date.now()}&loginType=2`; + break; + case "getReward": + body = `appid=anniversary-celebra&functionId=jd_interaction_prod&body={"parentId":"${$.oneTask.parentId}","taskId":"${$.oneTask.taskId}","timeStamp":${ + $.timeStamp + },"apiMapping":"/api/task/getReward"}&t=${Date.now()}&loginType=2`; + break; + default: + console.log(`错误${type}`); + } + let myRequest = getPostRequest(body); + return new Promise(async (resolve) => { + $.post(myRequest, (err, resp, data) => { + try { + if (data) { + dealReturn(type, data); + } else { + console.log(`返回空`); + } + } catch (e) { + console.log(data); + $.logErr(e, resp); + } finally { + resolve(); + } + }); + }); + } + function dealReturn(type, data) { + try { + data = JSON.parse(data); + } catch (e) { + console.log(`执行任务异常`); + console.log(data); + $.runFalag = false; + } + switch (type) { + case "index": + if (data && data.code === 200) { + $.activityInfo = data.data; + } + break; + case "doTask": + if (data && data.code === 200) { + $.timeStamp = data.data.timeStamp; + } else { + $.hotFlag = true; + console.log(JSON.stringify(data)); + } + break; + case "getReward": + if (data && data.code === 200) { + console.log(`执行成功,获得京豆:${data.data.jbean || 0}`); + } else { + console.log(JSON.stringify(data)); + } + break; + default: + console.log(JSON.stringify(data)); + } + } + function getPostRequest(body) { + let url = `https://api.m.jd.com/api`; + const headers = { + Accept: `application/json, text/plain, */*`, + Origin: `https://welfare.m.jd.com`, + "Accept-Encoding": `gzip, deflate, br`, + Cookie: $.cookie, + "Content-Type": `application/x-www-form-urlencoded`, + Host: `api.m.jd.com`, + Connection: `keep-alive`, + "User-Agent": $.UA, + Referer: `https://welfare.m.jd.com/`, + "Accept-Language": `zh-cn`, + }; + return { url: url, headers: headers, body: body }; + } + async function getUA() { + $.UA = `jdapp;iPhone;10.0.10;14.3;${randomString( + 40 + )};network/wifi;model/iPhone12,1;addressid/3364463029;appBuild/167764;jdSupportDarkMode/0;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 randomString(e) { + e = e || 32; + let t = "abcdef0123456789", + a = t.length, + n = ""; + for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a)); + return 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) { + $.nickName = (data["base"] && data["base"].nickname) || $.UserName; + } else { + $.nickName = $.UserName; + } + } else { + console.log(`京东服务器返回空数据`); + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + }); + }); + } \ No newline at end of file diff --git a/jd_bean_change.js b/jd_bean_change.js index 360a8ff..e4d84bd 100755 --- a/jd_bean_change.js +++ b/jd_bean_change.js @@ -20,50 +20,55 @@ cron "2 9 * * *" script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_ ============小火箭========= 京东资产变动通知 = type=cron,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_change.js, cronexpr="2 9 * * *", timeout=3600, enable=true */ -const $ = new Env('京东资产变动通知'); -const notify = $.isNode() ? require('./sendNotify') : ''; +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("京东资产变动通知"); +const notify = $.isNode() ? require("./sendNotify") : ""; //Node.js用户请在jdCookie.js处填写京东ck; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; -let allMessage = ''; +const jdCookieNode = $.isNode() ? require("./jdCookie.js") : ""; +let allMessage = ""; //IOS等用户直接用NobyDa的jd cookie -let cookiesArr = [], cookie = ''; +let cookiesArr = [], + cookie = ""; if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { - cookiesArr.push(jdCookieNode[item]) - }) - if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => {}; + 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); + cookiesArr = [$.getdata("CookieJD"), $.getdata("CookieJD2"), ...jd_helpers.jsonParse($.getdata("CookiesJD") || "[]").map((item) => item.cookie)].filter((item) => !!item); } !(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"}); + $.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]) + $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]); $.index = i + 1; $.beanCount = 0; $.incomeBean = 0; $.expenseBean = 0; $.todayIncomeBean = 0; - $.errorMsg = ''; + $.errorMsg = ""; $.isLogin = true; - $.nickName = ''; - $.message = ''; + $.nickName = ""; + $.message = ""; $.balance = 0; $.expiredBalance = 0; await TotalBean(); console.log(`\n********开始【京东账号${$.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"}); + $.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 + continue; } await bean(); await showMsg(); @@ -71,22 +76,31 @@ if ($.isNode()) { } if ($.isNode() && allMessage) { - await notify.sendNotify(`${$.name}`, `${allMessage}`, { url: `https://bean.m.jd.com/beanDetail/index.action?resourceValue=bean` }) + await notify.sendNotify(`${$.name}`, `${allMessage}`, { url: `https://bean.m.jd.com/beanDetail/index.action?resourceValue=bean` }); } })() - .catch((e) => { - $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') - }) - .finally(() => { - $.done(); - }) + .catch((e) => { + $.log("", `❌ ${$.name}, 失败! 原因: ${e}!`, ""); + }) + .finally(() => { + $.done(); + }); async function showMsg() { - if ($.errorMsg) return - allMessage += `账号${$.index}:${$.nickName || $.UserName}\n今日收入:${$.todayIncomeBean}京豆 🐶\n昨日收入:${$.incomeBean}京豆 🐶\n昨日支出:${$.expenseBean}京豆 🐶\n当前京豆:${$.beanCount}(今日将过期${$.expirejingdou})京豆 🐶${$.message}${$.index !== cookiesArr.length ? '\n\n' : ''}`; + if ($.errorMsg) return; + allMessage += `账号${$.index}:${$.nickName || $.UserName}\n今日收入:${$.todayIncomeBean}京豆 🐶\n昨日收入:${$.incomeBean}京豆 🐶\n昨日支出:${$.expenseBean}京豆 🐶\n当前京豆:${ + $.beanCount + }(今日将过期${$.expirejingdou})京豆 🐶${$.message}${$.index !== cookiesArr.length ? "\n\n" : ""}`; // if ($.isNode()) { // await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName}`, `账号${$.index}:${$.nickName || $.UserName}\n昨日收入:${$.incomeBean}京豆 🐶\n昨日支出:${$.expenseBean}京豆 🐶\n当前京豆:${$.beanCount}京豆 🐶${$.message}`, { url: `https://bean.m.jd.com/beanDetail/index.action?resourceValue=bean` }) // } - $.msg($.name, '', `账号${$.index}:${$.nickName || $.UserName}\n今日收入:${$.todayIncomeBean}京豆 🐶\n昨日收入:${$.incomeBean}京豆 🐶\n昨日支出:${$.expenseBean}京豆 🐶\n当前京豆:${$.beanCount}(今日将过期${$.expirejingdou})京豆🐶${$.message}`, {"open-url": "https://bean.m.jd.com/beanDetail/index.action?resourceValue=bean"}); + $.msg( + $.name, + "", + `账号${$.index}:${$.nickName || $.UserName}\n今日收入:${$.todayIncomeBean}京豆 🐶\n昨日收入:${$.incomeBean}京豆 🐶\n昨日支出:${$.expenseBean}京豆 🐶\n当前京豆:${$.beanCount}(今日将过期${ + $.expirejingdou + })京豆🐶${$.message}`, + { "open-url": "https://bean.m.jd.com/beanDetail/index.action?resourceValue=bean" } + ); } async function bean() { // console.log(`北京时间零点时间戳:${parseInt((Date.now() + 28800000) / 86400000) * 86400000 - 28800000}`); @@ -94,10 +108,13 @@ async function bean() { // 不管哪个时区。得到都是当前时刻北京时间的时间戳 new Date().getTime() + new Date().getTimezoneOffset()*60*1000 + 8*60*60*1000 //前一天的0:0:0时间戳 - const tm = parseInt((Date.now() + 28800000) / 86400000) * 86400000 - 28800000 - (24 * 60 * 60 * 1000); + const tm = parseInt((Date.now() + 28800000) / 86400000) * 86400000 - 28800000 - 24 * 60 * 60 * 1000; // 今天0:0:0时间戳 const tm1 = parseInt((Date.now() + 28800000) / 86400000) * 86400000 - 28800000; - let page = 1, t = 0, yesterdayArr = [], todayArr = []; + let page = 1, + t = 0, + yesterdayArr = [], + todayArr = []; do { let response = await getJingBeanBalanceDetail(page); // console.log(`第${page}页: ${JSON.stringify(response)}`); @@ -106,10 +123,10 @@ async function bean() { let detailList = response.detailList; if (detailList && detailList.length > 0) { for (let item of detailList) { - const date = item.date.replace(/-/g, '/') + "+08:00"; - if (new Date(date).getTime() >= tm1 && (!item['eventMassage'].includes("退还") && !item['eventMassage'].includes('扣赠'))) { + const date = item.date.replace(/-/g, "/") + "+08:00"; + if (new Date(date).getTime() >= tm1 && !item["eventMassage"].includes("退还") && !item["eventMassage"].includes("扣赠")) { todayArr.push(item); - } else if (tm <= new Date(date).getTime() && new Date(date).getTime() < tm1 && (!item['eventMassage'].includes("退还") && !item['eventMassage'].includes('扣赠'))) { + } else if (tm <= new Date(date).getTime() && new Date(date).getTime() < tm1 && !item["eventMassage"].includes("退还") && !item["eventMassage"].includes("扣赠")) { //昨日的 yesterdayArr.push(item); } else if (tm > new Date(date).getTime()) { @@ -124,11 +141,11 @@ async function bean() { t = 1; } } else if (response && response.code === "3") { - console.log(`cookie已过期,或者填写不规范,跳出`) + console.log(`cookie已过期,或者填写不规范,跳出`); t = 1; } else { console.log(`未知情况:${JSON.stringify(response)}`); - console.log(`未知情况,跳出`) + console.log(`未知情况,跳出`); t = 1; } } while (t === 0); @@ -144,13 +161,13 @@ async function bean() { $.todayIncomeBean += Number(item.amount); } } - await queryexpirejingdou();//过期京豆 - await redPacket();//过期红包 + await queryexpirejingdou(); //过期京豆 + await redPacket(); //过期红包 // console.log(`昨日收入:${$.incomeBean}个京豆 🐶`); // console.log(`昨日支出:${$.expenseBean}个京豆 🐶`) } function TotalBean() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { url: "https://me-api.jd.com/user_new/info/GetJDUserInfoUnion", headers: { @@ -158,210 +175,218 @@ function TotalBean() { Accept: "*/*", Connection: "keep-alive", 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"), + "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", "Accept-Language": "zh-cn", - "Referer": "https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&", - "Accept-Encoding": "gzip, deflate, br" - } - } + Referer: "https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&", + "Accept-Encoding": "gzip, deflate, br", + }, + }; $.get(options, (err, resp, data) => { try { if (err) { - $.logErr(err) + $.logErr(err); } else { if (data) { data = JSON.parse(data); - if (data['retcode'] === "1001") { + if (data["retcode"] === "1001") { $.isLogin = false; //cookie过期 return; } - if (data['retcode'] === "0" && data.data && data.data.hasOwnProperty("userInfo")) { + if (data["retcode"] === "0" && data.data && data.data.hasOwnProperty("userInfo")) { $.nickName = data.data.userInfo.baseInfo.nickname; } - if (data['retcode'] === '0' && data.data && data.data['assetInfo']) { - $.beanCount = data.data && data.data['assetInfo']['beanNum']; + if (data["retcode"] === "0" && data.data && data.data["assetInfo"]) { + $.beanCount = data.data && data.data["assetInfo"]["beanNum"]; } } else { - $.log('京东服务器返回空数据'); + $.log("京东服务器返回空数据"); } } } catch (e) { - $.logErr(e) + $.logErr(e); } finally { resolve(); } - }) - }) + }); + }); } function getJingBeanBalanceDetail(page) { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { - "url": `https://api.m.jd.com/client.action?functionId=getJingBeanBalanceDetail`, - "body": `body=${escape(JSON.stringify({"pageSize": "20", "page": page.toString()}))}&appid=ld`, - "headers": { - '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', - 'Cookie': cookie, - } - } + url: `https://api.m.jd.com/client.action?functionId=getJingBeanBalanceDetail`, + body: `body=${escape(JSON.stringify({ pageSize: "20", page: page.toString() }))}&appid=ld`, + headers: { + "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", + Cookie: cookie, + }, + }; $.post(options, (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { if (data) { data = JSON.parse(data); // console.log(data) } else { - console.log(`京东服务器返回空数据`) + console.log(`京东服务器返回空数据`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function queryexpirejingdou() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { - "url": `https://wq.jd.com/activep3/singjd/queryexpirejingdou?_=${Date.now()}&g_login_type=1&sceneval=2`, - "headers": { - "Accept": "*/*", + url: `https://wq.jd.com/activep3/singjd/queryexpirejingdou?_=${Date.now()}&g_login_type=1&sceneval=2`, + headers: { + Accept: "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", - "Connection": "keep-alive", - "Cookie": cookie, - "Host": "wq.jd.com", - "Referer": "https://wqs.jd.com/promote/201801/bean/mybean.html", - "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Mobile/15E148 Safari/604.1" - } - } + Connection: "keep-alive", + Cookie: cookie, + Host: "wq.jd.com", + Referer: "https://wqs.jd.com/promote/201801/bean/mybean.html", + "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Mobile/15E148 Safari/604.1", + }, + }; $.expirejingdou = 0; $.get(options, (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { if (data) { // console.log(data) data = JSON.parse(data.slice(23, -13)); // console.log(data) if (data.ret === 0) { - data['expirejingdou'].map(item => { - console.log(`${timeFormat(item['time'] * 1000)}日过期京豆:${item['expireamount']}\n`); - }) - $.expirejingdou = data['expirejingdou'][0]['expireamount']; + data["expirejingdou"].map((item) => { + console.log(`${timeFormat(item["time"] * 1000)}日过期京豆:${item["expireamount"]}\n`); + }); + $.expirejingdou = data["expirejingdou"][0]["expireamount"]; // if ($.expirejingdou > 0) { // $.message += `\n今日将过期:${$.expirejingdou}京豆 🐶`; // } } } else { - console.log(`京东服务器返回空数据`) + console.log(`京东服务器返回空数据`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } function redPacket() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { - "url": `https://m.jingxi.com/user/info/QueryUserRedEnvelopesV2?type=1&orgFlag=JD_PinGou_New&page=1&cashRedType=1&redBalanceFlag=1&channel=1&_=${+new Date()}&sceneval=2&g_login_type=1&g_ty=ls`, - "headers": { - 'Host': 'm.jingxi.com', - 'Accept': '*/*', - 'Connection': 'keep-alive', - 'Accept-Language': 'zh-cn', - 'Referer': 'https://st.jingxi.com/my/redpacket.shtml?newPg=App&jxsid=16156262265849285961', - 'Accept-Encoding': 'gzip, deflate, br', - "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") - } - } + url: `https://m.jingxi.com/user/info/QueryUserRedEnvelopesV2?type=1&orgFlag=JD_PinGou_New&page=1&cashRedType=1&redBalanceFlag=1&channel=1&_=${+new Date()}&sceneval=2&g_login_type=1&g_ty=ls`, + headers: { + Host: "m.jingxi.com", + Accept: "*/*", + Connection: "keep-alive", + "Accept-Language": "zh-cn", + Referer: "https://st.jingxi.com/my/redpacket.shtml?newPg=App&jxsid=16156262265849285961", + "Accept-Encoding": "gzip, deflate, br", + 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", + }, + }; $.get(options, (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { if (data) { - data = JSON.parse(data).data - $.jxRed = 0, $.jsRed = 0, $.jdRed = 0, $.jdhRed = 0, $.jxRedExpire = 0, $.jsRedExpire = 0, $.jdRedExpire = 0, $.jdhRedExpire = 0; - let t = new Date() - t.setDate(t.getDate() + 1) - t.setHours(0, 0, 0, 0) - t = parseInt((t - 1) / 1000) + data = JSON.parse(data).data; + ($.jxRed = 0), ($.jsRed = 0), ($.jdRed = 0), ($.jdhRed = 0), ($.jxRedExpire = 0), ($.jsRedExpire = 0), ($.jdRedExpire = 0), ($.jdhRedExpire = 0); + let t = new Date(); + t.setDate(t.getDate() + 1); + t.setHours(0, 0, 0, 0); + t = parseInt((t - 1) / 1000); for (let vo of data.useRedInfo.redList || []) { if (vo.orgLimitStr && vo.orgLimitStr.includes("京喜")) { - $.jxRed += parseFloat(vo.balance) - if (vo['endTime'] === t) { - $.jxRedExpire += parseFloat(vo.balance) + $.jxRed += parseFloat(vo.balance); + if (vo["endTime"] === t) { + $.jxRedExpire += parseFloat(vo.balance); } } else if (vo.activityName.includes("极速版")) { - $.jsRed += parseFloat(vo.balance) - if (vo['endTime'] === t) { - $.jsRedExpire += parseFloat(vo.balance) + $.jsRed += parseFloat(vo.balance); + if (vo["endTime"] === t) { + $.jsRedExpire += parseFloat(vo.balance); } } else if (vo.orgLimitStr && vo.orgLimitStr.includes("京东健康")) { - $.jdhRed += parseFloat(vo.balance) - if (vo['endTime'] === t) { - $.jdhRedExpire += parseFloat(vo.balance) + $.jdhRed += parseFloat(vo.balance); + if (vo["endTime"] === t) { + $.jdhRedExpire += parseFloat(vo.balance); } } else { - $.jdRed += parseFloat(vo.balance) - if (vo['endTime'] === t) { - $.jdRedExpire += parseFloat(vo.balance) + $.jdRed += parseFloat(vo.balance); + if (vo["endTime"] === t) { + $.jdRedExpire += parseFloat(vo.balance); } } } - $.jxRed = $.jxRed.toFixed(2) - $.jsRed = $.jsRed.toFixed(2) - $.jdRed = $.jdRed.toFixed(2) - $.jdhRed = $.jdhRed.toFixed(2) - $.balance = data.balance - $.expiredBalance = ($.jxRedExpire + $.jsRedExpire + $.jdRedExpire).toFixed(2) - $.message += `\n当前总红包:${$.balance}(今日总过期${$.expiredBalance})元 🧧\n京喜红包:${$.jxRed}(今日将过期${$.jxRedExpire.toFixed(2)})元 🧧\n极速红包:${$.jsRed}(今日将过期${$.jsRedExpire.toFixed(2)})元 🧧\n京东红包:${$.jdRed}(今日将过期${$.jdRedExpire.toFixed(2)})元 🧧\n健康红包:${$.jdhRed}(今日将过期${$.jdhRedExpire.toFixed(2)})元 🧧`; + $.jxRed = $.jxRed.toFixed(2); + $.jsRed = $.jsRed.toFixed(2); + $.jdRed = $.jdRed.toFixed(2); + $.jdhRed = $.jdhRed.toFixed(2); + $.balance = data.balance; + $.expiredBalance = ($.jxRedExpire + $.jsRedExpire + $.jdRedExpire).toFixed(2); + $.message += `\n当前总红包:${$.balance}(今日总过期${$.expiredBalance})元 🧧\n京喜红包:${$.jxRed}(今日将过期${$.jxRedExpire.toFixed(2)})元 🧧\n极速红包:${ + $.jsRed + }(今日将过期${$.jsRedExpire.toFixed(2)})元 🧧\n京东红包:${$.jdRed}(今日将过期${$.jdRedExpire.toFixed(2)})元 🧧\n健康红包:${$.jdhRed}(今日将过期${$.jdhRedExpire.toFixed(2)})元 🧧`; } else { - console.log(`京东服务器返回空数据`) + console.log(`京东服务器返回空数据`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) -} -function jsonParse(str) { - if (typeof str == "string") { - try { - return JSON.parse(str); - } catch (e) { - console.log(e); - $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') - return []; - } - } + }); + }); } + function timeFormat(time) { let date; if (time) { - date = new Date(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()); -} -// 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)} \ No newline at end of file + return date.getFullYear() + "-" + (date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1)) + "-" + (date.getDate() >= 10 ? date.getDate() : "0" + date.getDate()); +} \ No newline at end of file diff --git a/jd_bean_home.js b/jd_bean_home.js index 14ccd35..b9c3471 100755 --- a/jd_bean_home.js +++ b/jd_bean_home.js @@ -1,136 +1,482 @@ /* 领京豆额外奖励&抢京豆 -脚本自带助力码,介意者可将 29行 helpAuthor 变量设置为 false 活动入口:京东APP首页-领京豆 -更新地址:https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js +更新地址:jd_bean_home.js 已支持IOS双京东账号, Node.js支持N个京东账号 脚本兼容: QuantumultX, Surge, Loon, 小火箭,JSBox, Node.js ============Quantumultx=============== [task_local] #领京豆额外奖励 -10 7 * * * https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, tag=领京豆额外奖励, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jd_bean_home.png, enabled=true - +23 1,12,22 * * * jd_bean_home.js, tag=领京豆额外奖励, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jd_bean_home.png, enabled=true ================Loon============== [Script] -cron "10 7 * * *" script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, tag=领京豆额外奖励 - +cron "23 1,12,22 * * *" script-path=jd_bean_home.js, tag=领京豆额外奖励 ===============Surge================= -领京豆额外奖励 = type=cron,cronexp="10 7 * * *",wake-system=1,timeout=3600,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js - +领京豆额外奖励 = type=cron,cronexp="23 1,12,22 * * *",wake-system=1,timeout=3600,script-path=jd_bean_home.js ============小火箭========= -领京豆额外奖励 = type=cron,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, cronexpr="10 7 * * *", timeout=3600, enable=true +领京豆额外奖励 = type=cron,script-path=jd_bean_home.js, cronexpr="23 1,12,22 * * *", timeout=3600, enable=true */ -const $ = new Env('领京豆额外奖励'); +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("领京豆额外奖励"); -const notify = $.isNode() ? require('./sendNotify') : ''; +const notify = $.isNode() ? require("./sendNotify") : ""; //Node.js用户请在jdCookie.js处填写京东ck; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; -let jdNotify = true;//是否关闭通知,false打开通知推送,true关闭通知推送 +const jdCookieNode = $.isNode() ? require("./jdCookie.js") : ""; +let jdNotify = true; //是否关闭通知,false打开通知推送,true关闭通知推送 const helpAuthor = true; // 是否帮助作者助力,false打开通知推送,true关闭通知推送 +const qjd = false; // 抢京豆开关,默认开 //IOS等用户直接用NobyDa的jd cookie -let cookiesArr = [], cookie = '', message; +let cookiesArr = [], + cookie = "", + uuid = "", + message; if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { - cookiesArr.push(jdCookieNode[item]) - }) - if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => { - }; + 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); + cookiesArr = [ + $.getdata("CookieJD"), + $.getdata("CookieJD2"), + ...jsonParse($.getdata("CookiesJD") || "[]").map((item) => item.cookie), + ].filter((item) => !!item); } -const JD_API_HOST = 'https://api.m.jd.com/'; +const JD_API_HOST = "https://api.m.jd.com/"; !(async () => { - $.newShareCodes = [] - // await getAuthorShareCode(); - // await getAuthorShareCode2(); + $.newShareCodes = []; + $.authorCode = []; 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"}); + $.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]) + $.UserName = decodeURIComponent( + cookie.match(/pt_pin=([^; ]+)(?=;?)/) && + cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1] + ); $.index = i + 1; $.isLogin = true; - $.nickName = ''; - message = ''; + $.nickName = ""; + message = ""; + uuid = randomString(); await TotalBean(); - console.log(`\n******开始【京东账号${$.index}】${$.nickName || $.UserName}*********\n`); + console.log( + `\n******开始【京东账号${$.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"}); + $.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`); + await notify.sendNotify( + `${$.name}cookie已失效 - ${$.UserName}`, + `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie` + ); } - continue + continue; } await jdBeanHome(); } } - // for (let i = 0; i < cookiesArr.length; i++) { - // $.index = i + 1; - // if (cookiesArr[i]) { - // $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]) - // cookie = cookiesArr[i]; - // if ($.newShareCodes.length > 1) { - // console.log(`\n【抢京豆】 ${$.UserName} 去助力排名第一的cookie`); - // // let code = $.newShareCodes[(i + 1) % $.newShareCodes.length] - // // await help(code[0], code[1]) - // let code = $.newShareCodes[0]; - // await help(code[0], code[1]); - // } - // if (helpAuthor && $.authorCode) { - // console.log(`\n【抢京豆】${$.UserName} 去帮助作者`) - // for (let code of $.authorCode) { - // const helpRes = await help(code.shareCode, code.groupCode); - // if (helpRes && helpRes.data.respCode === 'SG209') { - // break; - // } - // } - // } - // if (helpAuthor && $.authorCode2) { - // for (let code of $.authorCode2) { - // const helpRes = await help(code.shareCode, code.groupCode); - // if (helpRes && helpRes.data.respCode === 'SG209') { - // break; - // } - // } - // } - // for (let j = 1; j < $.newShareCodes.length; j++) { - // console.log(`【抢京豆】${$.UserName} 去助力账号 ${j + 1}`) - // let code = $.newShareCodes[j]; - // await help(code[0], code[1]) - // } - // } - // } + if (qjd) { + for (let i = 0; i < cookiesArr.length; i++) { + $.index = i + 1; + if (cookiesArr[i]) { + cookie = cookiesArr[i]; + $.canHelp = true; + $.UserName = decodeURIComponent( + cookie.match(/pt_pin=([^; ]+)(?=;?)/) && + cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1] + ); + if ($.newShareCodes.length > 1) { + console.log(`\n【抢京豆】 ${$.UserName} 去助力排名第一的cookie`); + // let code = $.newShareCodes[(i + 1) % $.newShareCodes.length] + // await help(code[0], code[1]) + let code = $.newShareCodes[0]; + if (code[2] && code[2] === $.UserName) { + //不助力自己 + } else { + await help(code[0], code[1]); + } + } + if (helpAuthor && $.authorCode && $.canHelp) { + console.log(`\n【抢京豆】${$.UserName} 去帮助作者`); + for (let code of $.authorCode) { + const helpRes = await help(code.shareCode, code.groupCode); + if (helpRes && helpRes["code"] === "0") { + if ( + helpRes && + helpRes.data && + helpRes.data.respCode === "SG209" + ) { + console.log(`${helpRes.data.helpToast}\n`); + break; + } + } else { + console.log(`助力异常:${JSON.stringify(helpRes)}\n`); + } + } + } + for (let j = 1; j < $.newShareCodes.length && $.canHelp; j++) { + let code = $.newShareCodes[j]; + if (code[2] && code[2] === $.UserName) { + //不助力自己 + } else { + console.log(`【抢京豆】${$.UserName} 去助力账号 ${j + 1}`); + await help(code[0], code[1]); + await $.wait(2000); + } + } + } + } + } })() .catch((e) => { - $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') + $.log("", `❌ ${$.name}, 失败! 原因: ${e}!`, ""); }) .finally(() => { $.done(); - }) + }); async function jdBeanHome() { - $.doneState = false - // for (let i = 0; i < 3; ++i) { - // await doTask2() - // await $.wait(1000) - // if ($.doneState) break - // } - do { - await doTask2() - await $.wait(3000) - } while (!$.doneState) - await $.wait(1000) - await award("feeds") - await $.wait(1000) - await getUserInfo() - await $.wait(1000) - await getTaskList(); - await receiveJd2(); - await showMsg(); + try { + $.doneState = false; + // for (let i = 0; i < 3; ++i) { + // await doTask2() + // await $.wait(1000) + // if ($.doneState) break + // } + do { + await doTask2(); + await $.wait(3000); + } while (!$.doneState); + await $.wait(1000); + await award("feeds"); + await $.wait(1000); + await getUserInfo(); + await $.wait(1000); + await getTaskList(); + await receiveJd2(); + + await morningGetBean(); + await $.wait(1000); + + await beanTaskList(1); + await $.wait(1000); + await queryCouponInfo(); + $.doneState = false; + do { + await $.wait(2000); + await beanTaskList(2); + } while (!$.doneState); + await $.wait(2000); + if ($.doneState) await beanTaskList(3); + + await showMsg(); + } catch (e) { + $.logErr(e); + } +} + +// 早起福利 +function morningGetBean() { + return new Promise((resolve) => { + $.post( + taskBeanUrl("morningGetBean", { + fp: "-1", + shshshfp: "-1", + shshshfpa: "-1", + referUrl: "-1", + userAgent: "-1", + jda: "-1", + rnVersion: "3.9", + }), + (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} morningGetBean API请求失败,请检查网路重试`); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (data.data.awardResultFlag === "1") { + console.log(`早起福利领取成功:${data.data.bizMsg}`); + } else if (data.data.awardResultFlag === "2") { + console.log(`早起福利领取失败:${data.data.bizMsg}`); + } else { + console.log(`早起福利领取失败:${data.data.bizMsg}`); + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + } + ); + }); +} + +// 升级领京豆任务 +async function beanTaskList(type) { + return new Promise((resolve) => { + $.post( + taskBeanUrl("beanTaskList", { viewChannel: "myjd" }), + async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} beanTaskList API请求失败,请检查网路重试`); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + switch (type) { + case 1: + console.log( + `当前等级:${data.data.curLevel} 下一级可领取:${ + data.data.nextLevelBeanNum || 0 + }京豆` + ); + if (!data.data.viewAppHome.takenTask) { + console.log(`去做[${data.data.viewAppHome.mainTitle}]`); + await beanHomeIconDoTask({ + flag: "0", + viewChannel: "myjd", + }); + } + await $.wait(2000); + if (!data.data.viewAppHome.doneTask) { + console.log(`去领奖[${data.data.viewAppHome.mainTitle}]`); + await beanHomeIconDoTask({ + flag: "1", + viewChannel: "AppHome", + }); + } else { + console.log(`[${data.data.viewAppHome.mainTitle}]已做完`); + } + break; + case 2: + $.doneState = true; + let taskInfos = data.data.taskInfos; + for (let key of Object.keys(taskInfos)) { + let vo = taskInfos[key]; + if (vo.times < vo.maxTimes) { + for (let key of Object.keys(vo.subTaskVOS)) { + let taskList = vo.subTaskVOS[key]; + if (taskList.status === 1) { + $.doneState = false; + console.log(`去做[${vo.taskName}]${taskList.title}`); + await $.wait(2000); + await beanDoTask( + { + actionType: 1, + taskToken: `${taskList.taskToken}`, + }, + vo.taskType + ); + if (vo.taskType === 9) { + await $.wait(3000); + await beanDoTask( + { + actionType: 0, + taskToken: `${taskList.taskToken}`, + }, + vo.taskType + ); + } + } + } + } + } + break; + case 3: + let taskInfos3 = data.data.taskInfos; + for (let key of Object.keys(taskInfos3)) { + let vo = taskInfos3[key]; + if (vo.times === vo.maxTimes) { + console.log(`[${vo.taskName}]已做完`); + } + } + default: + break; + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + } + ); + }); +} +function beanDoTask(body, taskType) { + return new Promise((resolve) => { + $.post(taskBeanUrl("beanDoTask", body), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} beanDoTask API请求失败,请检查网路重试`); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (body.actionType === 1 && taskType !== 9) { + if (data.code === "0" && data.data.bizCode === "0") { + console.log(`完成任务,获得+${data.data.score}成长值`); + } else { + console.log(`完成任务失败:${data}`); + } + } + if (body.actionType === 0) { + if (data.code === "0" && data.data.bizCode === "0") { + console.log(data.data.bizMsg); + } else { + console.log(`完成任务失败:${data}`); + } + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }); + }); +} +function beanHomeIconDoTask(body) { + return new Promise((resolve) => { + $.post(taskBeanUrl("beanHomeIconDoTask", body), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log( + `${$.name} beanHomeIconDoTask API请求失败,请检查网路重试` + ); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (body.flag === "0" && data.data.taskResult) { + console.log(data.data.remindMsg); + } + if (body.flag === "1" && data.data.taskResult) { + console.log(data.data.remindMsg); + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(data); + } + }); + }); +} +async function queryCouponInfo() { + return new Promise(async (resolve) => { + $.get( + taskBeanUrl("queryCouponInfo", { + rnVersion: "4.7", + fp: "-1", + shshshfp: "-1", + shshshfpa: "-1", + referUrl: "-1", + userAgent: "-1", + jda: "-1", + }), + async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log( + `${$.name} queryCouponInfo API请求失败,请检查网路重试` + ); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (data.data && data.data.couponTaskInfo) { + if (!data.data.couponTaskInfo.awardFlag) { + console.log(`去做[${data.data.couponTaskInfo.taskName}]`); + await sceneGetCoupon(); + } else { + console.log(`[${data.data.couponTaskInfo.taskName}]已做完`); + } + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + } + ); + }); +} +function sceneGetCoupon() { + return new Promise((resolve) => { + $.get( + taskBeanUrl("sceneGetCoupon", { + rnVersion: "4.7", + fp: "-1", + shshshfp: "-1", + shshshfpa: "-1", + referUrl: "-1", + userAgent: "-1", + jda: "-1", + }), + (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} sceneGetCoupon API请求失败,请检查网路重试`); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (data.code === "0" && data.data && data.data.bizMsg) { + console.log(data.data.bizMsg); + } else { + console.log(`完成任务失败:${data}`); + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + } + ); + }); +} +function randomString() { + return ( + Math.random().toString(16).slice(2, 10) + + Math.random().toString(16).slice(2, 10) + + Math.random().toString(16).slice(2, 10) + + Math.random().toString(16).slice(2, 10) + + Math.random().toString(16).slice(2, 10) + ); } function getRandomInt(min, max) { @@ -139,338 +485,381 @@ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function doTask2() { - return new Promise(resolve => { - const body = {"awardFlag": false, "skuId": `${getRandomInt(10000000,20000000)}`, "source": "feeds", "type": '1'}; - $.post(taskUrl('beanHomeTask', body), (err, resp, data) => { + return new Promise((resolve) => { + const body = { + awardFlag: false, + skuId: `${getRandomInt(10000000, 20000000)}`, + source: "feeds", + type: "1", + }; + $.post(taskUrl("beanHomeTask", body), (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); + } else { + if (jd_helpers.safeGet(data)) { + data = JSON.parse(data); + if (data.code === "0" && data.data) { + console.log( + `任务完成进度:${data.data.taskProgress}/${data.data.taskThreshold}` + ); + if (data.data.taskProgress === data.data.taskThreshold) + $.doneState = true; + } else if (data.code === "0" && data.errorCode === "HT201") { + $.doneState = true; + } else { + //HT304风控用户 + $.doneState = true; + console.log(`做任务异常:${JSON.stringify(data)}`); + } + } + } + } catch (e) { + $.logErr(e, resp); + } finally { + resolve(); + } + }); + }); +} +function getUserInfo() { + return new Promise((resolve) => { + $.post( + taskUrl("signBeanGroupStageIndex", "body"), + async (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - if (data.code === '0' && data.data){ - console.log(`任务完成进度:${data.data.taskProgress} / ${data.data.taskThreshold}`) - if(data.data.taskProgress === data.data.taskThreshold) - $.doneState = true - } else if (data.code === '0' && data.errorCode === 'HT201') { - $.doneState = true - } else { - //HT304风控用户 - $.doneState = true - console.log(`做任务异常:${JSON.stringify(data)}`) + if (data.data.jklInfo) { + $.actId = data.data.jklInfo.keyId; + let { shareCode, groupCode } = data.data; + if (!shareCode) { + console.log(`未获取到助力码,去开团`); + await hitGroup(); + } else { + console.log(shareCode, groupCode); + // 去做逛会场任务 + if ( + data.data.beanActivityVisitVenue && + data.data.beanActivityVisitVenue.taskStatus === "0" + ) { + await help(shareCode, groupCode, 1); + } + console.log( + `\n京东账号${$.index} ${ + $.nickName || $.UserName + } 抢京豆邀请码:${shareCode}\n` + ); + $.newShareCodes.push([shareCode, groupCode, $.UserName]); + } } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) -} - -function getAuthorShareCode() { - return new Promise(resolve => { - $.get({url: "https://a.nz.lu/bean.json",headers:{ - "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/87.0.4280.88" - }}, async (err, resp, data) => { - try { - if (err) { - } else { - $.authorCode = JSON.parse(data); - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(); } - }) - }) -} -function getAuthorShareCode2() { - return new Promise(resolve => { - $.get({url: "https://cdn.jsdelivr.net/gh/gitupdate/updateTeam@master/shareCodes/jd_updateBeanHome.json",headers:{ - "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/87.0.4280.88" - }}, async (err, resp, data) => { - try { - if (err) { - } else { - if (safeGet(data)) { - $.authorCode2 = JSON.parse(data); - } - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(); - } - }) - }) -} -function getUserInfo() { - return new Promise(resolve => { - $.post(taskUrl('signBeanGroupStageIndex', 'body'), async (err, resp, data) => { - try { - if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) - } else { - if (safeGet(data)) { - data = JSON.parse(data); - if(data.data.jklInfo) { - $.actId = data.data.jklInfo.keyId - let {shareCode, groupCode} = data.data - if (!shareCode) { - console.log(`未获取到助力码,去开团`) - await hitGroup() - } else { - console.log(shareCode, groupCode) - // 去做逛会场任务 - if (data.data.beanActivityVisitVenue && data.data.beanActivityVisitVenue.taskStatus === '0') { - await help(shareCode, groupCode, 1) - } - console.log(`\n京东账号${$.index} ${$.nickName || $.UserName} 抢京豆邀请码:${shareCode}\n`); - $.newShareCodes.push([shareCode, groupCode]) - } - } - } - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(); - } - }) - }) + ); + }); } function hitGroup() { - return new Promise(resolve => { - const body = {"activeType": 2,}; - $.get(taskGetUrl('signGroupHit', body), async (err, resp, data) => { + return new Promise((resolve) => { + const body = { activeType: 2 }; + $.get(taskGetUrl("signGroupHit", body), async (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data.respCode === "SG150") { - let {shareCode, groupCode} = data.data.signGroupMain + let { shareCode, groupCode } = data.data.signGroupMain; if (shareCode) { - $.newShareCodes.push([shareCode, groupCode]) - console.log('开团成功') - console.log(`\n京东账号${$.index} ${$.nickName || $.UserName} 抢京豆邀请码:${shareCode}\n`); - await help(shareCode, groupCode, 1) + $.newShareCodes.push([shareCode, groupCode, $.UserName]); + console.log("开团成功"); + console.log( + `\n京东账号${$.index} ${ + $.nickName || $.UserName + } 抢京豆邀请码:${shareCode}\n` + ); + await help(shareCode, groupCode, 1); } else { - console.log(`为获取到助力码,错误信息${JSON.stringify(data.data)}`) + console.log( + `为获取到助力码,错误信息${JSON.stringify(data.data)}` + ); } } else { - console.log(`开团失败,错误信息${JSON.stringify(data.data)}`) + console.log(`开团失败,错误信息${JSON.stringify(data.data)}`); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } function help(shareCode, groupCode, isTask = 0) { - return new Promise(resolve => { + return new Promise((resolve) => { const body = { - "activeType": 2, - "groupCode": groupCode, - "shareCode": shareCode, - "activeId": $.actId, + activeType: 2, + groupCode: groupCode, + shareCode: shareCode, + activeId: $.actId, }; if (isTask) { - console.log(`【抢京豆】做任务获取助力`) - body['isTask'] = "1" + console.log(`【抢京豆】做任务获取助力`); + body["isTask"] = "1"; } else { - console.log(`【抢京豆】去助力好友${shareCode}`) - body['source'] = "guest" + console.log(`【抢京豆】去助力好友${shareCode}`); + body["source"] = "guest"; } - $.get(taskGetUrl('signGroupHelp', body), async (err, resp, data) => { + $.get(taskGetUrl("signGroupHelp", body), async (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`【抢京豆】${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`【抢京豆】${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - console.log(`【抢京豆】${data.data.helpToast}`) + if (data.code === "0") { + console.log(`【抢京豆】${data.data.helpToast}`); + } + if ( + data.code === "0" && + data.data && + data.data.respCode === "SG209" + ) { + $.canHelp = false; + } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function showMsg() { - return new Promise(resolve => { - if (message) $.msg($.name, '', `【京东账号${$.index}】${$.nickName}\n${message}`); - resolve() - }) + return new Promise((resolve) => { + if (message) + $.msg($.name, "", `【京东账号${$.index}】${$.nickName}\n${message}`); + resolve(); + }); } function getTaskList() { - return new Promise(resolve => { - const body = {"rnVersion": "4.7", "rnClient": "2", "source": "AppHome"}; - $.post(taskUrl('findBeanHome', body), async (err, resp, data) => { + return new Promise((resolve) => { + const body = { rnVersion: "4.7", rnClient: "2", source: "AppHome" }; + $.post(taskUrl("findBeanHome", body), async (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - let beanTask = data.data.floorList.filter(vo => vo.floorName === "种豆得豆定制化场景")[0] + let beanTask = data.data.floorList.filter( + (vo) => vo.floorName === "种豆得豆定制化场景" + )[0]; if (!beanTask.viewed) { - await receiveTask() - await $.wait(3000) + await receiveTask(); + await $.wait(3000); } - let tasks = data.data.floorList.filter(vo => vo.floorName === "赚京豆")[0]['stageList'] + let tasks = data.data.floorList.filter( + (vo) => vo.floorName === "赚京豆" + )[0]["stageList"]; for (let i = 0; i < tasks.length; ++i) { - const vo = tasks[i] - if (vo.viewed) continue - await receiveTask(vo.stageId, `4_${vo.stageId}`) - await $.wait(3000) + const vo = tasks[i]; + if (vo.viewed) continue; + await receiveTask(vo.stageId, `4_${vo.stageId}`); + await $.wait(3000); } - await award() + await award(); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } function receiveTask(itemId = "zddd", type = "3") { - return new Promise(resolve => { - const body = {"awardFlag": false, "itemId": itemId, "source": "home", "type": type}; - $.post(taskUrl('beanHomeTask', body), (err, resp, data) => { + return new Promise((resolve) => { + const body = { + awardFlag: false, + itemId: itemId, + source: "home", + type: type, + }; + $.post(taskUrl("beanHomeTask", body), (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data) { - console.log(`完成任务成功,进度${data.data.taskProgress}/${data.data.taskThreshold}`) + console.log( + `完成任务成功,进度${data.data.taskProgress}/${data.data.taskThreshold}` + ); } else { - console.log(`完成任务失败,${data.errorMessage}`) + console.log(`完成任务失败,${data.errorMessage}`); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } - -function award(source="home") { - return new Promise(resolve => { - const body = {"awardFlag": true, "source": source}; - $.post(taskUrl('beanHomeTask', body), (err, resp, data) => { +function award(source = "home") { + return new Promise((resolve) => { + const body = { awardFlag: true, source: source }; + $.post(taskUrl("beanHomeTask", body), (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data) { - console.log(`领奖成功,获得 ${data.data.beanNum} 个京豆`) - message += `领奖成功,获得 ${data.data.beanNum} 个京豆\n` + console.log(`领奖成功,获得 ${data.data.beanNum} 个京豆`); + message += `领奖成功,获得 ${data.data.beanNum} 个京豆\n`; } else { - console.log(`领奖失败,${data.errorMessage}`) + console.log(`领奖失败,${data.errorMessage}`); // message += `领奖失败,${data.errorMessage}\n` } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } function receiveJd2() { var headers = { - 'Host': 'api.m.jd.com', - 'content-type': 'application/x-www-form-urlencoded', - 'accept': '*/*', - 'user-agent': 'JD4iPhone/167515 (iPhone; iOS 14.2; Scale/3.00)', - 'accept-language': 'zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6', - 'Cookie': cookie + Host: "api.m.jd.com", + "content-type": "application/x-www-form-urlencoded", + accept: "*/*", + "user-agent": "JD4iPhone/167515 (iPhone; iOS 14.2; Scale/3.00)", + "accept-language": + "zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6", + Cookie: cookie, }; - var dataString = 'body=%7B%7D&build=167576&client=apple&clientVersion=9.4.3&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&osVersion=14.2&partner=TF&rfs=0000&scope=10&screen=1242%2A2208&sign=19c33b5b9ad4f02c53b6040fc8527119&st=1614701322170&sv=122' + var dataString = + "body=%7B%7D&build=167576&client=apple&clientVersion=9.4.3&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&osVersion=14.2&partner=TF&rfs=0000&scope=10&screen=1242%2A2208&sign=19c33b5b9ad4f02c53b6040fc8527119&st=1614701322170&sv=122"; var options = { - url: 'https://api.m.jd.com/client.action?functionId=sceneInitialize', + url: "https://api.m.jd.com/client.action?functionId=sceneInitialize", headers: headers, - body: dataString + body: dataString, }; - return new Promise(resolve => { + return new Promise((resolve) => { $.post(options, (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - if (data['code'] === '0' && data['data']) { - console.log(`强制开启新版领京豆成功,获得${data['data']['sceneLevelConfig']['beanNum']}京豆\n`); - $.msg($.name, '', `强制开启新版领京豆成功\n获得${data['data']['sceneLevelConfig']['beanNum']}京豆`); + if (data["code"] === "0" && data["data"]) { + console.log( + `强制开启新版领京豆成功,获得${data["data"]["sceneLevelConfig"]["beanNum"]}京豆\n` + ); + $.msg( + $.name, + "", + `强制开启新版领京豆成功\n获得${data["data"]["sceneLevelConfig"]["beanNum"]}京豆` + ); } else { - console.log(`强制开启新版领京豆结果:${JSON.stringify(data)}\n`) + console.log(`强制开启新版领京豆结果:${JSON.stringify(data)}\n`); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } function taskGetUrl(function_id, body) { return { - url: `${JD_API_HOST}client.action?functionId=${function_id}&body=${escape(JSON.stringify(body))}&appid=ld&clientVersion=9.2.0`, + url: `${JD_API_HOST}client.action?functionId=${function_id}&body=${escape( + JSON.stringify(body) + )}&appid=ld&clientVersion=9.2.0`, headers: { - 'Cookie': cookie, - 'Host': 'api.m.jd.com', - 'Accept': '*/*', - 'Connection': 'keep-alive', - '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"), - 'Accept-Language': 'zh-Hans-CN;q=1,en-CN;q=0.9', - 'Accept-Encoding': 'gzip, deflate, br', - 'Content-Type': "application/x-www-form-urlencoded" - } - } + Cookie: cookie, + Host: "api.m.jd.com", + Accept: "*/*", + Connection: "keep-alive", + "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", + "Accept-Language": "zh-Hans-CN;q=1,en-CN;q=0.9", + "Accept-Encoding": "gzip, deflate, br", + "Content-Type": "application/x-www-form-urlencoded", + }, + }; } +function taskBeanUrl(function_id, body = {}) { + return { + url: `${JD_API_HOST}client.action?functionId=${function_id}&body=${escape( + JSON.stringify(body) + )}&appid=ld&client=apple&clientVersion=10.0.8&uuid=${uuid}&openudid=${uuid}`, + headers: { + Cookie: cookie, + Host: "api.m.jd.com", + Accept: "*/*", + Connection: "keep-alive", + "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", + "Accept-Language": "zh-cn", + "Accept-Encoding": "gzip, deflate, br", + Referer: "https://h5.m.jd.com/", + }, + }; +} function taskUrl(function_id, body) { body["version"] = "9.0.0.1"; @@ -478,86 +867,77 @@ function taskUrl(function_id, body) { body["monitor_refer"] = ""; return { url: JD_API_HOST, - body: `functionId=${function_id}&body=${escape(JSON.stringify(body))}&appid=ld&client=apple&area=5_274_49707_49973&build=167283&clientVersion=9.1.0`, + body: `functionId=${function_id}&body=${escape( + JSON.stringify(body) + )}&appid=ld&client=apple&area=5_274_49707_49973&build=167283&clientVersion=9.1.0`, headers: { - 'Cookie': cookie, - 'Host': 'api.m.jd.com', - 'Accept': '*/*', - 'Connection': 'keep-alive', - '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"), - 'Accept-Language': 'zh-Hans-CN;q=1,en-CN;q=0.9', - 'Accept-Encoding': 'gzip, deflate, br', - 'Content-Type': "application/x-www-form-urlencoded" - } - } + Cookie: cookie, + Host: "api.m.jd.com", + Accept: "*/*", + Connection: "keep-alive", + "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", + "Accept-Language": "zh-Hans-CN;q=1,en-CN;q=0.9", + "Accept-Encoding": "gzip, deflate, br", + "Content-Type": "application/x-www-form-urlencoded", + }, + }; } function TotalBean() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { - "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, - "headers": { - "Accept": "application/json,text/plain, */*", + 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") - } - } + 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请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { if (data) { data = JSON.parse(data); - if (data['retcode'] === 13) { + if (data["retcode"] === 13) { $.isLogin = false; //cookie过期 - return + return; } - if (data['retcode'] === 0) { - $.nickName = (data['base'] && data['base'].nickname) || $.UserName; + if (data["retcode"] === 0) { + $.nickName = + (data["base"] && data["base"].nickname) || $.UserName; } else { - $.nickName = $.UserName + $.nickName = $.UserName; } } else { - console.log(`京东服务器返回空数据`) + console.log(`京东服务器返回空数据`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } -function safeGet(data) { - try { - if (typeof JSON.parse(data) == "object") { - return true; - } - } catch (e) { - console.log(e); - console.log(`京东服务器访问数据为空,请检查自身设备网络情况`); - return false; - } -} -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)} \ No newline at end of file diff --git a/jd_bean_sign.js b/jd_bean_sign.js index bcdf4b1..5187b72 100755 --- a/jd_bean_sign.js +++ b/jd_bean_sign.js @@ -3,140 +3,219 @@ 活动入口:各处的签到汇总 Node.JS专用 IOS软件用户请使用 https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js -更新时间:2021-8-1 +更新时间:2021-6-18 +推送通知默认简洁模式(多账号只发送一次)。如需详细通知,设置环境变量 JD_BEAN_SIGN_NOTIFY_SIMPLE 为false即可(N账号推送N次通知)。 +Modified From github https://github.com/ruicky/jd_sign_bot */ -const $ = new Env('京东多合一签到SCF') -// const vm = require('vm') -let sendNotify -if ($.isNode()){ - sendNotify = require('./sendNotify.js').sendNotify -} +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("京东多合一签到"); +const notify = $.isNode() ? require('./sendNotify') : ''; //Node.js用户请在jdCookie.js处填写京东ck; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : '' -let cookiesArr = [] +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 = "./utils/JD_DailyBonus.js"; +let outPutUrl = './utils'; +let NodeSet = 'CookieSet.json'; +let cookiesArr = [], cookie = '', allMessage = '', jrbody = ''; +let jrbodies = getJDJrbody(); if ($.isNode()) { Object.keys(jdCookieNode).forEach((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); } !(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; } - const cks = [] - for (let i =0; i < cookiesArr.length; i++) { - const cookie = cookiesArr[i] - cks.push(await TotalBean(cookie)) - if (!cks[i]){ - const UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]) - const msg = `${$.name}cookie已失效 - ${UserName} 京东账号${i} ${UserName}\n请重新登录获取cookie` - $.msg(msg) - if ($.isNode()) { - await sendNotify(`${$.name}cookie已失效`,msg); - } - } - } - cookiesArr = cookiesArr.filter((_, index) => cks[index]) - cookiesArr = cookiesArr.map(cookie => { - return {'cookie':cookie} - }) - if (!cookiesArr[0]) { - $.msg($.name, '【提示】无可用cookie,结束'); - return; - } + process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE = process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE ? process.env.JD_BEAN_SIGN_NOTIFY_SIMPLE : 'true'; + await requireConfig(); // 下载最新代码 - const content = await download() - if(! content){ - console.error("JD_DailyBonus.js 没有成功加载") - $.done() + // await downFile(); + if (!await fs.existsSync(JD_DailyBonusPath)) { + console.log(`\nJD_DailyBonus.js 文件不存在,停止执行${$.name}\n`); + await notify.sendNotify($.name, `本次执行${$.name}失败,JD_DailyBonus.js 文件下载异常,详情请查看日志`) return } - console.log(`*****************开始${$.name}*******************\n`) - const originalLog = console.log - let notifyContent = '' - console.log = (...args) => { - if(args[0].includes("【签到号")){ - notifyContent += args[0].split('\n\n')[1] + '\n' - // originalLog('catch notifyContent:'+notifyContent) + const content = await fs.readFileSync(JD_DailyBonusPath, 'utf8') + for (let i =0; i < cookiesArr.length; i++) { + cookie = cookiesArr[i]; + if (Array.isArray(jrbodies) && jrbodies.length > 0 && i < jrbodies.length) { + jrbody = jrbodies[i]; } - originalLog.apply( - console, - [...args] - ) - if (args[0].includes('签到用时')){ - console.log = originalLog - if ($.isNode() && notifyContent.length != 0) { - $.msg($.name, '', notifyContent) - sendNotify($.name, notifyContent).then(() => { - console.log('send Notify finish') - $.done() - }) - }else{ - $.done() + 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 } + await changeFile(content); + await execSign(); } } - - eval(changeFile(content,JSON.stringify(cookiesArr))) - // new vm.Script('console.log("start");\n'+changeFile(content,JSON.stringify(cookiesArr))+'\nconsole.log("end");').runInThisContext() - // new vm.Script(changeFile(content,JSON.stringify(cookiesArr))).runInContext(new vm.createContext({ - // console: console, - // require: require, - // setTimeout:setTimeout - // })) + //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()) - -function changeFile (content,cookie) { - console.log(`开始替换变量`) - let newContent = content.replace(/var OtherKey = '.*'/, `var OtherKey = '${cookie}'`); - // 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}'`) + .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); + } + } + } + } + //不管哪个时区,这里得到的都是北京时间的时间戳; + 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 + console.log(`\n\n*****************${new Date(new Date().getTime()).toLocaleString('zh', {hour12: false})} 京东账号${$.index} ${$.nickName || $.UserName} ${$.name}完成*******************\n\n`); + } catch (e) { + console.log("京东签到脚本执行异常:" + e); } - const zone = new Date().getTimezoneOffset() - if (zone === 0) { - //此处针对UTC-0时区用户做的 - newContent = newContent.replace(/tm\s=.*/, `tm = new Date(new Date().toLocaleDateString()).getTime() - 28800000;`) +} +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); } - return newContent } -function TotalBean(cookie) { +async function changeFile (content) { + console.log(`开始替换变量`) + let newContent = content.replace(/var Key = '.*'/, `var Key = '${cookie}'`); + newContent = newContent.replace(/var jrBody = ".*"/, `var 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://me-api.jd.com/user_new/info/GetJDUserInfoUnion", - headers: { - Host: "me-api.jd.com", - Accept: "*/*", - Connection: "keep-alive", - 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"), + "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", - "Referer": "https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&", - "Accept-Encoding": "gzip, deflate, br" - } + "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请求失败,请检查网路重试`) - resolve() } else { if (data) { data = JSON.parse(data); - if (data['retcode'] === "1001") { - resolve(); //cookie过期 + if (data['retcode'] === 13) { + $.isLogin = false; //cookie过期 return } - resolve(true) + if (data['retcode'] === 0) { + $.nickName = (data['base'] && data['base'].nickname) || $.UserName; + } else { + $.nickName = $.UserName + } } else { console.log(`京东服务器返回空数据`) } @@ -144,14 +223,14 @@ function TotalBean(cookie) { } catch (e) { $.logErr(e, resp) } finally { - resolve() + resolve(); } }) }) } -async function download() { +function downloadUrl(url = 'https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js') { return new Promise(resolve => { - const options = { 'url':'https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js', "timeout": 10000 }; + const options = { url, "timeout": 10000 }; if ($.isNode() && process.env.TG_PROXY_HOST && process.env.TG_PROXY_PORT) { const tunnel = require("tunnel"); const agent = { @@ -165,37 +244,66 @@ async function download() { Object.assign(options, { agent }) } $.get(options, async (err, resp, data) => { - if (err) { - console.log(`raw download err:${JSON.stringify(err)}`) - console.log(`检测到您当前网络环境不能访问外网,将使用jsdelivr CDN下载JD_DailyBonus.js文件`); - options['url'] = 'https://purge.jsdelivr.net/gh/NobyDa/Script@master/JD-DailyBonus/JD_DailyBonus.js' - await $.http.get(options).then((resp) => { - if (resp.statusCode === 200) { - // console.log(`resp:${JSON.stringify(resp)}`) - let { body } = resp; - body = JSON.parse(body); - if (body['success']) { - console.log(`JD_DailyBonus.js文件 CDN刷新成功`) - } else { - console.log(`JD_DailyBonus.js文件 CDN刷新失败`) + 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刷新失败`) + } } - } - }) - options['url'] = 'https://cdn.jsdelivr.net/gh/NobyDa/Script@master/JD-DailyBonus/JD_DailyBonus.js' - await $.get(options, async (err, resp, data) => { - if (err) { - console.error(`CDN download err:${JSON.stringify(err)}`) - resolve() - }else{ - console.log('JD_DailyBonus.js文件 下载成功(CDN)') - resolve(data) - } - }) - } else { - console.log(`JD_DailyBonus.js文件 下载成功(raw)`) - resolve(data) + }); + } else { + $.body = data; + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(); } }) }) } -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)} \ No newline at end of file +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 getJDJrbody() { + let jrbody = []; + + if (process.env.JD_JRBODY) { + return process.env.JD_JRBODY.split(';').filter(item => item != '') + } + + return jrbody; +} \ No newline at end of file diff --git a/jd_beauty.js b/jd_beauty.js index 2532f2e..38523fb 100755 --- a/jd_beauty.js +++ b/jd_beauty.js @@ -6,7 +6,10 @@ 脚本兼容: Node.js cron 1 7,12,19 * * * jd_beauty.js */ -const $ = new Env('美丽研究院'); + +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("美丽研究院"); const notify = $.isNode() ? require('./sendNotify') : ''; //Node.js用户请在jdCookie.js处填写京东ck; const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; @@ -19,20 +22,14 @@ $.init = false; // const bean = 1; //兑换多少豆,默认是500 //IOS等用户直接用NobyDa的jd cookie let cookiesArr = [], cookie = '', message, helpInfo, ADD_CART = false; -function oc(fn, defaultVal) {//optioanl chaining - try { - return fn() - } catch (e) { - return undefined - } -} + if ($.isNode()) { Object.keys(jdCookieNode).forEach((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); + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jd_helpers.jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); } const JD_API_HOST = 'https://api.m.jd.com/client.action'; !(async () => { @@ -96,7 +93,7 @@ async function accountCheck() { } let client = new WebSocket(`wss://xinruimz-isv.isvjcloud.com/wss/?token=${$.token}`, null, { headers: { - 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "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") : ($.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"), + 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;10.0.2;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"), } }); client.onopen = async () => { @@ -106,7 +103,7 @@ async function accountCheck() { client.send(`{"msg":{"type":"action","args":{"source":1},"action":"get_user"}}`); }; client.onmessage = async function (e) { - if (e.data !== 'pong' && e.data && safeGet(e.data)) { + if (e.data !== 'pong' && e.data && jd_helpers.safeGet(e.data)) { let vo = JSON.parse(e.data); if (vo.action === "_init_") { let vo = JSON.parse(e.data); @@ -157,7 +154,7 @@ async function mr() { $.needs = [] let client = new WebSocket(`wss://xinruimz-isv.isvjcloud.com/wss/?token=${$.token}`,null,{ headers:{ - 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "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") : ($.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"), + 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;10.0.2;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"), } }) console.log(`wss://xinruimz-isv.isvjcloud.com/wss/?token=${$.token}`) @@ -214,7 +211,7 @@ async function mr() { } }; client.onmessage = async function (e) { - if (e.data !== 'pong' && e.data && safeGet(e.data)) { + if (e.data !== 'pong' && e.data && jd_helpers.safeGet(e.data)) { let vo = JSON.parse(e.data); await $.wait(Math.random()*2000+500); console.log(`\n开始任务:"${JSON.stringify(vo.action)}`); @@ -325,17 +322,17 @@ async function mr() { } break case "produce_position_info_v2": - // console.log(`${Boolean(oc(() => vo.data))};${oc(() => vo.data.material_name) !== ''}`); + // console.log(`${Boolean(vo?.data)};${vo?.data?.material_name !== ''}`); if (vo.data && vo.data.material_name !== '') { - console.log(`【${oc(() => vo.data.position)}】上正在生产【${oc(() => vo.data.material_name)}】,可收取 ${vo.data.produce_num} 份`) + console.log(`【${vo?.data?.position}】上正在生产【${vo?.data?.material_name}】,可收取 ${vo.data.produce_num} 份`) if (new Date().getTime() > vo.data.procedure.end_at) { - console.log(`去收取${oc(() => vo.data.material_name)}`) - client.send(`{"msg":{"type":"action","args":{"position":"${oc(() => vo.data.position)}","replace_material":false},"action":"material_fetch_v2"}}`) + console.log(`去收取${vo?.data?.material_name}`) + client.send(`{"msg":{"type":"action","args":{"position":"${vo?.data?.position}","replace_material":false},"action":"material_fetch_v2"}}`) client.send(`{"msg":{"type":"action","args":{},"action":"to_employee"}}`) - $.pos.push(oc(() => vo.data.position)) + $.pos.push(vo?.data?.position) } } else { - if (oc(() => vo.data) && vo.data.valid_electric > 0) { + if (vo?.data && vo.data.valid_electric > 0) { console.log(`【${vo.data.position}】上尚未开始生产`) let ma console.log(`$.needs:${JSON.stringify($.needs)}`); @@ -364,13 +361,9 @@ async function mr() { } break case "material_produce_v2": - console.log(`【${oc(() => vo.data.position)}】上开始生产${oc(() => vo.data.material_name)}`) + console.log(`【${vo?.data?.position}】上开始生产${vo?.data?.material_name}`) client.send(`{"msg":{"type":"action","args":{},"action":"to_employee"}}`) - if(oc(() => vo.data.position)){ - $.pos.push(vo.data.position) - }else{ - console.log(`not exist:${oc(() => vo.data)}`) - } + $.pos.push(vo.data.position) break case "material_fetch_v2": if (vo.code === '200' || vo.code === 200) { @@ -456,6 +449,7 @@ async function mr() { } break case "product_producing": + // console.log('product_producing', vo); if (vo.code === '200' || vo.code === 200) { for (let product of vo.data) { if (product.num === product.produce_num) { @@ -507,22 +501,20 @@ async function mr() { } break case "to_exchange": - if(oc(() => vo.data.coins)){ - console.log(`兑换${vo.data.coins/-100}京豆成功;${JSON.stringify(vo)}`) - }else{ - console.log(`vo.data.coins not exist:${oc(() => vo.data)}`) + if (vo?.data) { + console.log(`兑换${vo?.data?.coins/-100}京豆成功;${JSON.stringify(vo)}`) + } else { + console.log(`兑换京豆失败:${JSON.stringify(vo)}`) } + await $.wait(2000) break case "get_produce_material": + console.log('get_produce_material', vo?.msg); $.material = vo.data break case "to_employee": - console.log(`雇佣助力码【${oc(() => vo.data.token)}】`) - if(oc(() => vo.data.token)){ - $.tokens.push(vo.data.token) - }else{ - console.log(`not exist:${oc(() => vo.data)}`) - } + console.log(`雇佣助力码【${vo.data.token}】`) + $.tokens.push(vo.data.token) break case "employee": console.log(`${vo.msg}`) @@ -539,7 +531,7 @@ function getIsvToken() { headers: { 'Host': 'api.m.jd.com', 'accept': '*/*', - 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "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") : ($.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"), + 'user-agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', 'accept-language': 'zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6', 'content-type': 'application/x-www-form-urlencoded', 'Cookie': cookie @@ -552,7 +544,7 @@ function getIsvToken() { console.log(`${$.name} API请求失败,请检查网路重试`); console.log(`${JSON.stringify(err)}`) } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); $.isvToken = data['tokenKey']; console.log(`isvToken:${$.isvToken}`); @@ -574,7 +566,7 @@ function getIsvToken2() { headers: { 'Host': 'api.m.jd.com', 'accept': '*/*', - 'user-agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "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") : ($.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"), + 'user-agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', 'accept-language': 'zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6', 'content-type': 'application/x-www-form-urlencoded', 'Cookie': cookie @@ -587,7 +579,7 @@ function getIsvToken2() { console.log(`${JSON.stringify(err)}`) console.log(`${$.name} API请求失败,请检查网路重试`) } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); $.token2 = data['token'] console.log(`token2:${$.token2}`); @@ -613,7 +605,7 @@ function getToken() { 'Accept-Language': 'zh-cn', 'Content-Type': 'application/json;charset=utf-8', 'Origin': 'https://xinruimz-isv.isvjcloud.com', - 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "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") : ($.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"), + 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;10.0.2;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"), 'Referer': 'https://xinruimz-isv.isvjcloud.com/logined_jd/', 'Authorization': 'Bearer undefined', 'Cookie': `IsvToken=${$.isvToken};` @@ -626,10 +618,10 @@ function getToken() { console.log(`${JSON.stringify(err)}`) console.log(`${$.name} API请求失败,请检查网路重试`) } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); $.token = data.access_token - console.log(`$.token ${$.token}`) + console.log(`【$.token】 ${$.token}`) } } } catch (e) { @@ -661,7 +653,7 @@ function TotalBean() { "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 : "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") : ($.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") + "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;10.0.2;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) => { @@ -692,31 +684,4 @@ function TotalBean() { } }) }) -} - -function safeGet(data) { - try { - if (typeof JSON.parse(data) == "object") { - return true; - } - } catch (e) { - console.log(e); - console.log(`京东服务器访问数据为空,请检查自身设备网络情况`); - return false; - } -} - -function jsonParse(str) { - if (typeof str == "string") { - try { - return JSON.parse(str); - } catch (e) { - console.log(e); - $.msg($.name, '', '不要在BoxJS手动复制粘贴修改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)} \ No newline at end of file +} \ No newline at end of file diff --git a/jd_blueCoin.js b/jd_blueCoin.js index cc03e84..b23c3f4 100755 --- a/jd_blueCoin.js +++ b/jd_blueCoin.js @@ -1,6 +1,5 @@ -// @grant require /* -东东超市兑换奖品 脚本地址:https://raw.githubusercontent.com/Aaron-lv/sync/jd_scripts/jd_blueCoin.js +东东超市兑换奖品 脚本地址:jd_blueCoin.js 感谢@yangtingxiao提供PR 更新时间:2021-6-7 活动入口:京东APP我的-更多工具-东东超市 @@ -9,19 +8,18 @@ ============QuantumultX============== [task_local] #东东超市兑换奖品 -59 23 * * * https://raw.githubusercontent.com/Aaron-lv/sync/jd_scripts/jd_blueCoin.js, tag=东东超市兑换奖品, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jxc.png, enabled=true - +59 23 * * * jd_blueCoin.js, tag=东东超市兑换奖品, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jxc.png, enabled=true ====================Loon================= [Script] -cron "59 23 * * *" script-path=https://raw.githubusercontent.com/Aaron-lv/sync/jd_scripts/jd_blueCoin.js,tag=东东超市兑换奖品 - +cron "59 23 * * *" script-path=jd_blueCoin.js,tag=东东超市兑换奖品 ===================Surge================== -东东超市兑换奖品 = type=cron,cronexp="59 23 * * *",wake-system=1,timeout=3600,script-path=https://raw.githubusercontent.com/Aaron-lv/sync/jd_scripts/jd_blueCoin.js - +东东超市兑换奖品 = type=cron,cronexp="59 23 * * *",wake-system=1,timeout=3600,script-path=jd_blueCoin.js ============小火箭========= -东东超市兑换奖品 = type=cron,script-path=https://raw.githubusercontent.com/Aaron-lv/sync/jd_scripts/jd_blueCoin.js, cronexpr="59 23 * * *", timeout=3600, enable=true +东东超市兑换奖品 = type=cron,script-path=jd_blueCoin.js, cronexpr="59 23 * * *", timeout=3600, enable=true */ -const $ = new Env('东东超市兑换奖品'); +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +const $ = jd_env.env("东东超市兑换奖品"); const notify = $.isNode() ? require('./sendNotify') : ''; let allMessage = ''; //Node.js用户请在jdCookie.js处填写京东ck; @@ -36,7 +34,7 @@ if ($.isNode()) { }) 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); + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jd_helpers.jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); } const JD_API_HOST = `https://api.m.jd.com/api?appid=jdsupermarket`; @@ -109,8 +107,8 @@ Date.prototype.Format = function (fmt) { //author: meizz await notify.sendNotify(`${$.name}`, `${allMessage}`) } })() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) + .catch((e) => $.logErr(e)) + .finally(() => $.done()) async function PrizeIndex() { let nowtime = new Date().Format("s.S") @@ -253,7 +251,7 @@ function smtg_materialPrizeIndex(timeout = 0) { } $.post(url, async (err, resp, data) => { try { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data.bizCode !== 0) { $.beanerr = `${data.data.bizMsg}`; @@ -290,7 +288,7 @@ function smtg_queryPrize(timeout = 0){ } $.post(url, async (err, resp, data) => { try { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); // $.queryPrizeData = data; if (data.data.bizCode !== 0) { @@ -355,7 +353,7 @@ function smtg_obtainPrize(prizeId, timeout = 0, functionId = 'smt_exchangePrize' $.post(url, async (err, resp, data) => { try { console.log(`兑换结果:${data}`); - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); $.data = data; if ($.data.data.bizCode !== 0 && $.data.data.bizCode !== 400) { @@ -402,7 +400,7 @@ function smtgHome() { console.log('\n东东超市兑换奖品: API查询请求失败 ‼️‼️') console.log(JSON.stringify(err)); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); // console.log(data) if (data.data.bizCode === 0) { @@ -490,17 +488,7 @@ function TotalBean() { }) }) } -function safeGet(data) { - try { - if (typeof JSON.parse(data) == "object") { - return true; - } - } catch (e) { - console.log(e); - console.log(`京东服务器访问数据为空,请检查自身设备网络情况`); - return false; - } -} + function taskUrl(function_id, body = {}) { return { url: `${JD_API_HOST}&functionId=${function_id}&clientVersion=8.0.0&client=m&body=${escape(JSON.stringify(body))}&t=${Date.now()}`, @@ -512,16 +500,4 @@ function taskUrl(function_id, body = {}) { 'Origin': 'https://jdsupermarket.jd.com', } } -} -function jsonParse(str) { - if (typeof str == "string") { - try { - return JSON.parse(str); - } catch (e) { - console.log(e); - $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') - return []; - } - } -} -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)} \ No newline at end of file +} \ No newline at end of file diff --git a/jd_bookshop.js b/jd_bookshop.js index 526d4c2..142cbcc 100755 --- a/jd_bookshop.js +++ b/jd_bookshop.js @@ -1,355 +1,343 @@ /* 口袋书店 -更新时间:2021-06-26 -加了一个码,修复需要手动打开的问题 活动入口:京东app首页-京东图书-右侧口袋书店 已支持IOS双京东账号,Node.js支持N个京东账号 脚本兼容: QuantumultX, Surge, Loon, JSBox, Node.js ============Quantumultx=============== [task_local] #口袋书店 -1 8,12,18 * * * https://raw.githubusercontent.com/Wenmoux/scripts/wen/jd/chinnkarahoi_jd_bookshop.js, tag=口袋书店, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jd.png, enabled=true +1 8,12,18 * * * https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bookshop.js, tag=口袋书店, img-url=https://raw.githubusercontent.com/Orz-3/mini/master/Color/jd.png, enabled=true ================Loon============== [Script] -cron "1 8,12,18 * * *" script-path= https://raw.githubusercontent.com/Wenmoux/scripts/wen/jd/chinnkarahoi_jd_bookshop.js,tag=口袋书店 +cron "1 8,12,18 * * *" script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bookshop.js,tag=口袋书店 ===============Surge================= -口袋书店 = type=cron,cronexp="1 8,12,18 * * *",wake-system=1,timeout=3600,script-path= https://raw.githubusercontent.com/Wenmoux/scripts/wen/jd/chinnkarahoi_jd_bookshop.js +口袋书店 = type=cron,cronexp="1 8,12,18 * * *",wake-system=1,timeout=3600,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bookshop.js ============小火箭========= -口袋书店 = type=cron,script-path= https://raw.githubusercontent.com/Wenmoux/scripts/wen/jd/chinnkarahoi_jd_bookshop.js, cronexpr="1 8,12,18* * *", timeout=3600, enable=true +口袋书店 = type=cron,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bookshop.js, cronexpr="1 8,12,18* * *", timeout=3600, enable=true */ -const $ = new Env('口袋书店'); -const notify = $.isNode() ? require('./sendNotify') : ''; -const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +const jd_shopping_cart = require("./utils/JDShoppingCart"); +const jd_helpers = require("./utils/JDHelpers.js"); +const jd_env = require("./utils/JDEnv.js"); +let $ = jd_env.env("口袋书店"); +const notify = $.isNode() ? require("./sendNotify") : ""; +const jdCookieNode = $.isNode() ? require("./jdCookie.js") : ""; //Node.js用户请在jdCookie.js处填写京东ck; //IOS等用户直接用NobyDa的jd cookie -let cookiesArr = [], cookie = '', message; -const ACT_ID = 'dz2010100034444201', shareUuid = '28a699ac78d74aa3b31f7103597f8927' -let ADD_CART = false -ADD_CART = $.isNode() ? (process.env.PURCHASE_SHOPS ? process.env.PURCHASE_SHOPS : ADD_CART) : ($.getdata("ADD_CART") ? $.getdata("ADD_CART") : ADD_CART); +let cookiesArr = [], + cookie = "", + message; +const ACT_ID = "dz2010100034444201", + shareUuid = "7c9c696bdd2140e0959fd83d6fbae69e"; +let ADD_CART = false; +ADD_CART = $.isNode() ? (process.env.PURCHASE_SHOPS ? process.env.PURCHASE_SHOPS : ADD_CART) : $.getdata("ADD_CART") ? $.getdata("ADD_CART") : ADD_CART; // 加入购物车开关,与东东小窝共享 let inviteCodes = [ - '4dd98623868f4292b5432822389fe3e9@daf75e50044144c68b2aff47de57fe49@e341962809ae42c5b8d2d61995bbb5a4@77f08ad1aea04b73acd4542f7fd1dac6@fe5536751f89403d87bad635a87bd956@7cac62f390074868949f72c18cc8469c', - '4dd98623868f4292b5432822389fe3e9@daf75e50044144c68b2aff47de57fe49@e341962809ae42c5b8d2d61995bbb5a4@77f08ad1aea04b73acd4542f7fd1dac6@fe5536751f89403d87bad635a87bd956@7cac62f390074868949f72c18cc8469c' -] + //"f5e7d8ca8664449ab0828fae8a481d6d@7c9c696bdd2140e0959fd83d6fbae69e@6522e60f38de45fb83c982acd866dcf6@ad1810abcced49faaf6f98c5b1898fb9@94514ed63c1546afb68e4798c6925e3e@591f04167afb4c95ad7e97c82bd3f3a6@6329bfc583ef47cc8138ea042a82265f@c1528406464947a2a1c98936bcfd7152", + //"f5e7d8ca8664449ab0828fae8a481d6d@7c9c696bdd2140e0959fd83d6fbae69e@6522e60f38de45fb83c982acd866dcf6@ad1810abcced49faaf6f98c5b1898fb9@94514ed63c1546afb68e4798c6925e3e@591f04167afb4c95ad7e97c82bd3f3a6@6329bfc583ef47cc8138ea042a82265f@c1528406464947a2a1c98936bcfd7152", +]; if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { - cookiesArr.push(jdCookieNode[item]) - }) - if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => { - }; + 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); + cookiesArr = [$.getdata("CookieJD"), $.getdata("CookieJD2"), ...jd_helpers.jsonParse($.getdata("CookiesJD") || "[]").map((item) => item.cookie)].filter((item) => !!item); } !(async () => { if (!cookiesArr[0]) { - $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', {"open-url": "https://bean.m.jd.com/"}); + $.msg($.name, "【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取", "https://bean.m.jd.com/", { "open-url": "https://bean.m.jd.com/" }); return; } - $.shareCodesArr = [] - await requireConfig() + $.shareCodesArr = []; + await requireConfig(); 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]) + $.UserName = decodeURIComponent(cookie.match(/pt_pin=(.+?);/) && cookie.match(/pt_pin=(.+?);/)[1]); $.index = i + 1; $.isLogin = true; - $.nickName = ''; - message = ''; - $.exit = false; + $.nickName = ""; + $.skuIds = []; + message = ""; 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/"}); + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/`, { "open-url": "https://bean.m.jd.com/" }); if ($.isNode()) { await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); } - continue + continue; } - await shareCodesFormat() - await jdBeauty() + // await shareCodesFormat(); + await jdBookShop(); } } })() .catch((e) => { - $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') + $.log("", `❌ ${$.name}, 失败! 原因: ${e}!`, ""); }) .finally(() => { $.done(); - }) + }); -async function jdBeauty() { - $.score = 0 - await getIsvToken() - await getIsvToken2() - await getActCk() - await getActInfo() - await getToken() - await accessLogWithAD() - await getUserInfo() - await getActContent(false, shareUuid) - if ($.exit) return - await doHelpList() - await getAllBook() - await getMyBook() - await getActContent(true) +async function jdBookShop() { + $.score = 0; + await getIsvToken(); + await getIsvToken2(); + await getActCk(); + await getActInfo(); + await getToken(); + await getUserInfo(); + await getActContent(false, shareUuid); + if ($.exit) return; + await doHelpList(); + await getAllBook(); + await getMyBook(); + await getActContent(true); if ($.gold > 800) { - console.log(`金币大于800,去抽奖`) - while ($.gold >= 800) { - await draw() - await $.wait(1000) - $.gold -= 800 + console.log(`金币大于800,去抽奖`); + let i = 0; + date = new Date(); + hour = date.getHours() + while ($.gold >= 800 && i < 3 && hour == 12) { + await draw(); + await $.wait(1000); + $.gold -= 800; + i++; } } - if($.userInfo.storeGold) await chargeGold() - await helpFriends() - // await showMsg(); + if ($.userInfo.storeGold) await chargeGold(); + // 删除加购物品 + await jd_shopping_cart.getCarts($).then(function ($this) { + $ = $this; + }); + await jd_shopping_cart.unsubscribeCartsFun($); + await helpFriends(); + await showMsg(); } async function helpFriends() { + if (!Array.isArray($.newShareCodes)) { + return; + } + for (let code of $.newShareCodes) { - if (!code) continue - console.log(`去助力好友${code}`) - await getActContent(true, code) - await $.wait(500) + if (!code) continue; + console.log(`去助力好友${code}`); + await getActContent(true, code); + await $.wait(500); } } // 获得IsvToken function getIsvToken() { - return new Promise(resolve => { - let body = 'body=%7B%22to%22%3A%22https%3A%5C%2F%5C%2Flzdz-isv.isvjcloud.com%5C%2Fdingzhi%5C%2Fbook%5C%2Fdevelop%5C%2Factivity%3FactivityId%3Ddz2010100034444201%22%2C%22action%22%3A%22to%22%7D&build=167490&client=apple&clientVersion=9.3.2&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&sign=f3eb9660e798c20372734baf63ab55f2&st=1610267023622&sv=111' - $.post(jdUrl('genToken', body), async (err, resp, data) => { + return new Promise((resolve) => { + let body = + "body=%7B%22to%22%3A%22https%3A%5C%2F%5C%2Flzdz-isv.isvjcloud.com%5C%2Fdingzhi%5C%2Fbook%5C%2Fdevelop%5C%2Factivity%3FactivityId%3Ddz2010100034444201%22%2C%22action%22%3A%22to%22%7D&build=167490&client=apple&clientVersion=9.3.2&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&sign=f3eb9660e798c20372734baf63ab55f2&st=1610267023622&sv=111"; + $.post(jdUrl("genToken", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - $.isvToken = data['tokenKey'] + $.isvToken = data["tokenKey"]; } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得对应游戏的访问Token function getIsvToken2() { - return new Promise(resolve => { - let body = 'body=%7B%22url%22%3A%22https%3A%5C%2F%5C%2Flzdz-isv.isvjcloud.com%22%2C%22id%22%3A%22%22%7D&build=167490&client=apple&clientVersion=9.3.2&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&sign=6050f8b81f4ba562b357e49762a8f4b0&st=1610267024346&sv=121' - $.post(jdUrl('isvObfuscator', body), async (err, resp, data) => { + return new Promise((resolve) => { + let body = + "body=%7B%22url%22%3A%22https%3A%5C%2F%5C%2Flzdz-isv.isvjcloud.com%22%2C%22id%22%3A%22%22%7D&build=167490&client=apple&clientVersion=9.3.2&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&sign=6050f8b81f4ba562b357e49762a8f4b0&st=1610267024346&sv=121"; + $.post(jdUrl("isvObfuscator", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - $.token2 = data['token'] + $.token2 = data["token"]; } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得游戏的Cookie function getActCk() { - return new Promise(resolve => { + return new Promise((resolve) => { $.get(taskUrl("dingzhi/book/develop/activity", `activityId=${ACT_ID}`), (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if($.isNode()) - for (let ck of resp['headers']['set-cookie']) { - cookie = `${cookie}; ${ck.split(";")[0]};` + if ($.isNode()) + for (let ck of resp["headers"]["set-cookie"]) { + cookie = `${cookie}; ${ck.split(";")[0]};`; } - else{ - for (let ck of resp['headers']['Set-Cookie'].split(',')) { - cookie = `${cookie}; ${ck.split(";")[0]};` + else { + for (let ck of resp["headers"]["Set-Cookie"].split(",")) { + cookie = `${cookie}; ${ck.split(";")[0]};`; } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得游戏信息 function getActInfo() { - return new Promise(resolve => { - $.post(taskPostUrl('dz/common/getSimpleActInfoVo', `activityId=${ACT_ID}`), async (err, resp, data) => { + return new Promise((resolve) => { + $.post(taskPostUrl("dz/common/getSimpleActInfoVo", `activityId=${ACT_ID}`), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result) { - $.shopId = data.data.shopId + $.shopId = data.data.shopId; } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得游戏的Token function getToken() { - return new Promise(resolve => { - let body = `userId=${$.shopId}&token=${$.token2}&fromType=APP` - $.post(taskPostUrl('customer/getMyPing', body), async (err, resp, data) => { + return new Promise((resolve) => { + let body = `userId=${$.shopId}&token=${$.token2}&fromType=APP`; + $.post(taskPostUrl("customer/getMyPing", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - $.token = data.data.secretPin + $.token = data.data.secretPin; } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得用户信息 function getUserInfo() { - return new Promise(resolve => { - let body = `pin=${encodeURIComponent($.token)}` - $.post(taskPostUrl('wxActionCommon/getUserInfo', body), async (err, resp, data) => { + return new Promise((resolve) => { + let body = `pin=${encodeURIComponent($.token)}`; + $.post(taskPostUrl("wxActionCommon/getUserInfo", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data) { - console.log(`用户【${data.data.nickname}】信息获取成功`) - $.userId = data.data.id - $.pinImg = data.data.yunMidImageUrl - $.nick = data.data.nickname + console.log(`用户【${data.data.nickname}】信息获取成功`); + $.userId = data.data.id; + $.pinImg = data.data.yunMidImageUrl; + $.nick = data.data.nickname; } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) -} -// 获得用户信息 -function accessLogWithAD() { - return new Promise(resolve => { - let body = `venderId=${ $.shopId}&code=99&pin=${encodeURIComponent($.token)}&activityId=${ACT_ID}&pageUrl=https%3A%2F%2Flzdz-isv.isvjcloud.com%2Fdingzhi%2Fbook%2Fdevelop%2Factivity%3FactivityId%3Ddz2010100034444201%26lng%3D107.146945%26lat%3D33.255267%26sid%3Dcad74d1c843bd47422ae20cadf6fe5aw%26un_area%3D27_2442_2444_31912&subType=app&adSource=` - $.post(taskPostUrl('common/accessLogWithAD', body), async (err, resp, data) => { - try { - if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) - } else { - // if (safeGet(data)) { - if($.isNode()) - for (let ck of resp['headers']['set-cookie']) { - cookie = `${cookie}; ${ck.split(";")[0]};` - } - else{ - for (let ck of resp['headers']['Set-Cookie'].split(',')) { - cookie = `${cookie}; ${ck.split(";")[0]};` - } - } - // } - } - } catch (e) { - $.logErr(e, resp) - } finally { - resolve(data); - } - }) - }) + }); + }); } + // 获得游戏信息 -function getActContent(info = false, shareUuid = '') { - return new Promise(resolve => { - let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&pinImg=${$.pinImg}&nick=${$.nick}&cjyxPin=&cjhyPin=&shareUuid=${shareUuid}` - $.post(taskPostUrl('dingzhi/book/develop/activityContent', body), async (err, resp, data) => { +function getActContent(info = false, shareUuid = "") { + return new Promise((resolve) => { + let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&pinImg=${$.pinImg}&nick=${$.nick}&cjyxPin=&cjhyPin=&shareUuid=${shareUuid}`; + $.post(taskPostUrl("dingzhi/book/develop/activityContent", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - // console.log(data) - if (data && safeGet(data)) { + if (data && jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.data) { - $.userInfo = data.data + $.userInfo = data.data; if (!$.userInfo.bookStore) { - $.exit = true - console.log(`京东账号${$.index}尚未开启口袋书店,请手动开启`) - console.log('\n提示:从五月份开始,需要手动进入一下活动页面。不然即使是开启了这个活动。跑脚本也提示未开启活动\n') - return + $.exit = true; + console.log(`京东账号${$.index}尚未开启口袋书店,请手动开启`); + return; } - $.actorUuid = $.userInfo.actorUuid + $.actorUuid = $.userInfo.actorUuid; // if(!info) console.log(`您的好友助力码为${$.actorUuid}`) - if(!info) console.log(`\n【京东账号${$.index}(${$.UserName})的${$.name}好友互助码】${$.actorUuid}\n`); - $.gold = $.userInfo.bookStore.hasStoreGold + if (!info) console.log(`\n【京东账号${$.index}(${$.UserName})的${$.name}好友互助码】${$.actorUuid}\n`); + $.gold = $.userInfo.bookStore.hasStoreGold; if (!info) { - const tasks = data.data.settingVo + const tasks = data.data.settingVo; for (let task of tasks) { - if (['关注店铺'].includes(task.title)) { + if (["关注店铺"].includes(task.title)) { if (task.okNum < task.dayMaxNum) { - console.log(`去做${task.title}任务`) - await doTask(task.settings[0].type, task.settings[0].value) + console.log(`去做${task.title}任务`); + await doTask(task.settings[0].type, task.settings[0].value); } - } else if (['逛会场', '浏览店铺', '浏览商品'].includes(task.title)) { + } else if (["逛会场", "浏览店铺", "浏览商品"].includes(task.title)) { if (task.okNum < task.dayMaxNum) { - console.log(`去做${task.title}任务`) - for (let set of task.settings.filter(vo => vo.status === 0)) { - await doTask(set.type, set.value) - await $.wait(500) + console.log(`去做${task.title}任务`); + for (let set of task.settings.filter((vo) => vo.status === 0)) { + await doTask(set.type, set.value); + await $.wait(500); } } - } else if(task.title === '每日签到'){ - const hour = new Date().getUTCHours() + 8 - if (8 <= hour && hour < 10 || 12 <= hour && hour < 14 || 18 <= hour && hour < 20) { - console.log(`去做${task.title}任务`) - for (let set of task.settings.filter(vo => vo.status === 0)) { - let res = await doTask(set.type, set.value) - if (res.result) break - await $.wait(500) + } else if (task.title === "每日签到") { + const hour = new Date().getUTCHours() + 8; + if ((8 <= hour && hour < 10) || (12 <= hour && hour < 14) || (18 <= hour && hour < 20)) { + console.log(`去做${task.title}任务`); + for (let set of task.settings.filter((vo) => vo.status === 0)) { + let res = await doTask(set.type, set.value); + if (res.result) break; + await $.wait(500); } } - } else if (ADD_CART && ['加购商品'].includes(task.title)) { + } else if (ADD_CART && ["加购商品"].includes(task.title)) { + $.skuIds = task.settings.map(current_task => current_task.value); if (task.okNum < task.dayMaxNum) { - console.log(`去做${task.title}任务`) - await doTask(task.settings[0].type, task.settings[0].value) + console.log(`去做${task.title}任务`); + await doTask(task.settings[0].type, task.settings[0].value); } } } @@ -358,240 +346,235 @@ function getActContent(info = false, shareUuid = '') { } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function doHelpList(taskType, value) { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&num=0&sortStatus=1` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/taskact/common/getDayShareRecord', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&num=0&sortStatus=1`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/taskact/common/getDayShareRecord", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); - console.log(`今日助力情况${data.data.length}/10`) + console.log(`今日助力情况${data.data.length}/10`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) - + }); + }); } // 做任务 function doTask(taskType, value) { - let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&actorUuid=${$.actorUuid}&taskType=${taskType}&taskValue=${value}` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/saveTask', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&actorUuid=${$.actorUuid}&taskType=${taskType}&taskValue=${value}`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/saveTask", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { - console.log(`任务完成成功,获得${data.data.addScore}积分`) - $.score += data.data.addScore + console.log(`任务完成成功,获得${data.data.addScore}积分`); + $.score += data.data.addScore; } else { - console.log(`任务完成失败,错误信息:${data.errorMessage}`) + console.log(`任务完成失败,错误信息:${data.errorMessage}`); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) - + }); + }); } // 抽奖 function draw() { - let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&actorUuid=${$.actorUuid}` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/startDraw', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&pin=${encodeURIComponent($.token)}&actorUuid=${$.actorUuid}`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/startDraw", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (data && safeGet(data)) { + if (data && jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { if (data.data.name) { - console.log(`抽奖成功,获得奖品:${data.data.name}`) - message += `抽奖成功,获得奖品:${data.data.name}\n` + console.log(`抽奖成功,获得奖品:${data.data.name}`); + message += `抽奖成功,获得奖品:${data.data.name}\n`; } else { - console.log(`抽奖成功,获得空气`) - message += `抽奖成功,获得空气` + console.log(`抽奖成功,获得空气`); + message += `抽奖成功,获得空气`; } } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 获得图书 function getAllBook() { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/getAllBook', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/getAllBook", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { - - const book = data.data.bookConfigList[0] - let num = Math.trunc(data.data.haveScore / book.buyBookScore) - console.log(`拥有${data.data.haveScore}积分,可购买${num}本`) + const book = data.data.bookConfigList[0]; + let num = Math.trunc(data.data.haveScore / book.buyBookScore); + console.log(`拥有${data.data.haveScore}积分,可购买${num}本`); if (num > 0) { - await buyBook(book.uuid, num) + await buyBook(book.uuid, num); } } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } // 购买图书 function buyBook(bookUuid, num) { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&bookUuid=${bookUuid}&buyNum=${num}` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/buyBook', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&bookUuid=${bookUuid}&buyNum=${num}`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/buyBook", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { - console.log(`购买【${data.data.BookIncome.bookName}】成功`) + console.log(`购买【${data.data.BookIncome.bookName}】成功`); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function getMyBook() { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&type1=1&type2=1&type3=1&type=1` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/getMyBook', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&type1=1&type2=1&type3=1&type=1`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/getMyBook", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { for (let book of data.data.myBookList) { if (book.isPutOn !== 1 && book.inventory > 0) { - console.log(`去上架【${book.bookName}】`) - await upBook(book.bookUuid) + console.log(`去上架【${book.bookName}】`); + await upBook(book.bookUuid); } } } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function upBook(bookUuid) { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&bookUuid=${bookUuid}&isPutOn=1&position=1` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/upBook', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}&bookUuid=${bookUuid}&isPutOn=1&position=1`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/upBook", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { - console.log(`上架成功`) + console.log(`上架成功`); } else { - console.log(data) + console.log(data); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function chargeGold() { - let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}` - return new Promise(resolve => { - $.post(taskPostUrl('dingzhi/book/develop/chargeGold', body), async (err, resp, data) => { + let body = `activityId=${ACT_ID}&actorUuid=${$.actorUuid}&pin=${encodeURIComponent($.token)}`; + return new Promise((resolve) => { + $.post(taskPostUrl("dingzhi/book/develop/chargeGold", body), async (err, resp, data) => { try { if (err) { - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${$.name} API请求失败,请检查网路重试`); } else { - if (safeGet(data)) { + if (jd_helpers.safeGet(data)) { data = JSON.parse(data); if (data.result && data.data) { - console.log(`金币收获成功,获得${data.data.chargeGold}`) + console.log(`金币收获成功,获得${data.data.chargeGold}`); } else { - console.log(data.errorMessage) + console.log(data.errorMessage); } } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(data); } - }) - }) + }); + }); } function showMsg() { - return new Promise(resolve => { - if ($.score) { - message += `本次运行获得积分${$.score}`; - $.msg($.name, '', `京东账号${$.index}${$.nickName}\n${message}`); - } - resolve() - }) + return new Promise((resolve) => { + message += `本次运行获得积分${$.score}`; + $.msg($.name, "", `京东账号${$.index}${$.nickName}\n${message}`); + resolve(); + }); } function jdUrl(functionId, body) { @@ -599,31 +582,31 @@ function jdUrl(functionId, body) { url: `https://api.m.jd.com/client.action?functionId=${functionId}`, body: body, headers: { - 'Host': 'api.m.jd.com', - 'accept': '*/*', - 'user-agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', - 'accept-language': 'zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6', - 'content-type': 'application/x-www-form-urlencoded', - 'Cookie': cookie - } - } + Host: "api.m.jd.com", + accept: "*/*", + "user-agent": "JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)", + "accept-language": "zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6", + "content-type": "application/x-www-form-urlencoded", + Cookie: cookie, + }, + }; } function taskUrl(function_id, body) { return { url: `https://lzdz-isv.isvjcloud.com/${function_id}?${body}`, headers: { - 'Host': 'lzdz-isv.isvjcloud.com', - 'Accept': 'application/x.jd-school-island.v1+json', - 'Source': '02', - 'Accept-Language': 'zh-cn', - 'Content-Type': 'application/json;charset=utf-8', - 'Origin': 'https://lzdz-isv.isvjcloud.com', - 'User-Agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', - 'Referer': `https://lzdz-isv.isvjcloud.com/dingzhi/book/develop/activity?activityId=${ACT_ID}`, - 'Cookie': `${cookie} IsvToken=${$.isvToken};` - } - } + Host: "lzdz-isv.isvjcloud.com", + Accept: "application/x.jd-school-island.v1+json", + Source: "02", + "Accept-Language": "zh-cn", + "Content-Type": "application/json;charset=utf-8", + Origin: "https://lzdz-isv.isvjcloud.com", + "User-Agent": "JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)", + Referer: `https://lzdz-isv.isvjcloud.com/dingzhi/book/develop/activity?activityId=${ACT_ID}`, + Cookie: `${cookie} IsvToken=${$.isvToken};`, + }, + }; } function taskPostUrl(function_id, body) { @@ -631,132 +614,112 @@ function taskPostUrl(function_id, body) { url: `https://lzdz-isv.isvjcloud.com/${function_id}`, body: body, headers: { - 'Host': 'lzdz-isv.isvjcloud.com', - 'Accept': 'application/json', - 'Accept-Language': 'zh-cn', - 'Content-Type': 'application/x-www-form-urlencoded', - 'Origin': 'https://lzdz-isv.isvjcloud.com', - 'User-Agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', - 'Referer': `https://lzdz-isv.isvjcloud.com/dingzhi/book/develop/activity?activityId=${ACT_ID}`, - 'Cookie': `${cookie} isvToken=${$.isvToken};` - } - } + Host: "lzdz-isv.isvjcloud.com", + Accept: "application/json", + "Accept-Language": "zh-cn", + "Content-Type": "application/x-www-form-urlencoded", + Origin: "https://lzdz-isv.isvjcloud.com", + "User-Agent": "JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)", + Referer: `https://lzdz-isv.isvjcloud.com/dingzhi/book/develop/activity?activityId=${ACT_ID}`, + Cookie: `${cookie} isvToken=${$.isvToken};`, + }, + }; } function TotalBean() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const options = { - "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, - "headers": { - "Accept": "application/json,text/plain, */*", + 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") - } - } + 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.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0", + }, + }; $.post(options, (err, resp, data) => { try { if (err) { - console.log(`${JSON.stringify(err)}`) - console.log(`${$.name} API请求失败,请检查网路重试`) + console.log(`${JSON.stringify(err)}`); + console.log(`${$.name} API请求失败,请检查网路重试`); } else { if (data) { data = JSON.parse(data); - if (data['retcode'] === 13) { + if (data["retcode"] === 13) { $.isLogin = false; //cookie过期 - return + return; } - if (data['retcode'] === 0) { - $.nickName = (data['base'] && data['base'].nickname) || $.UserName; + if (data["retcode"] === 0) { + $.nickName = (data["base"] && data["base"].nickname) || $.UserName; } else { - $.nickName = $.UserName + $.nickName = $.UserName; } } else { - console.log(`京东服务器返回空数据`) + console.log(`京东服务器返回空数据`); } } } catch (e) { - $.logErr(e, resp) + $.logErr(e, resp); } finally { resolve(); } - }) - }) + }); + }); } //格式化助力码 function shareCodesFormat() { - return new Promise(async resolve => { + return new Promise(async (resolve) => { // console.log(`第${$.index}个京东账号的助力码:::${$.shareCodesArr[$.index - 1]}`) $.newShareCodes = []; if ($.shareCodesArr[$.index - 1]) { - $.newShareCodes = $.shareCodesArr[$.index - 1].split('@'); + $.newShareCodes = $.shareCodesArr[$.index - 1].split("@"); } else { - console.log(`由于您第${$.index}个京东账号未提供shareCode,将采纳本脚本自带的助力码\n`) - const tempIndex = $.index > inviteCodes.length ? (inviteCodes.length - 1) : ($.index - 1); - $.newShareCodes = inviteCodes[tempIndex].split('@'); + console.log(`由于您第${$.index}个京东账号未提供shareCode,将采纳本脚本自带的助力码\n`); + const tempIndex = $.index > inviteCodes.length ? inviteCodes.length - 1 : $.index - 1; + $.newShareCodes = inviteCodes[tempIndex].split("@"); } - // const readShareCodeRes = await readShareCode(); - // if (readShareCodeRes && readShareCodeRes.code === 200) { - // $.newShareCodes = [...new Set([...$.newShareCodes, ...(readShareCodeRes.data || [])])]; - // } - console.log(`第${$.index}个京东账号将要助力的好友${JSON.stringify($.newShareCodes)}`) + const readShareCodeRes = null; //await readShareCode(); + if (readShareCodeRes && readShareCodeRes.code === 200) { + $.newShareCodes = [...new Set([...$.newShareCodes, ...(readShareCodeRes.data || [])])]; + } + console.log(`第${$.index}个京东账号将要助力的好友${JSON.stringify($.newShareCodes)}`); resolve(); - }) + }); } function requireConfig() { - return new Promise(resolve => { + return new Promise((resolve) => { console.log(`开始获取${$.name}配置文件\n`); //Node.js用户请在jdCookie.js处填写京东ck; - let shareCodes = [] + let shareCodes = []; console.log(`共${cookiesArr.length}个京东账号\n`); $.shareCodesArr = []; if ($.isNode()) { //自定义助力码 if (process.env.BOOKSHOP_SHARECODES) { - if (process.env.BOOKSHOP_SHARECODES.indexOf('\n') > -1) { - shareCodes = process.env.BOOKSHOP_SHARECODES.split('\n'); + if (process.env.BOOKSHOP_SHARECODES.indexOf("\n") > -1) { + shareCodes = process.env.BOOKSHOP_SHARECODES.split("\n"); } else { - shareCodes = process.env.BOOKSHOP_SHARECODES.split('&'); + shareCodes = process.env.BOOKSHOP_SHARECODES.split("&"); } } Object.keys(shareCodes).forEach((item) => { if (shareCodes[item]) { - $.shareCodesArr.push(shareCodes[item]) + $.shareCodesArr.push(shareCodes[item]); } - }) + }); } console.log(`您提供了${$.shareCodesArr.length}个账号的${$.name}助力码\n`); - resolve() - }) -} - -function safeGet(data) { - try { - if (typeof JSON.parse(data) == "object") { - return true; - } - } catch (e) { - console.log(e); - console.log(`京东服务器访问数据为空,请检查自身设备网络情况`); - return false; - } -} - -function jsonParse(str) { - if (typeof str == "string") { - try { - return JSON.parse(str); - } catch (e) { - console.log(e); - $.msg($.name, '', '不要在BoxJS手动复制粘贴修改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)} \ No newline at end of file + resolve(); + }); +} \ No newline at end of file