From 6c75d57adbd19fbc4755540772db87775f83a37c Mon Sep 17 00:00:00 2001 From: shanmite Date: Fri, 21 Jun 2024 16:55:12 +0800 Subject: [PATCH] lint: eslint --- .eslintrc.json | 10 +- env.example.js | 76 ++++----- lib/account.js | 12 +- lib/check.js | 74 ++++----- lib/clear.js | 56 +++---- lib/core/monitor.js | 298 +++++++++++++++++------------------ lib/core/searcher.js | 306 ++++++++++++++++++------------------ lib/data/config.js | 26 +-- lib/data/env.js | 18 +-- lib/data/global_var.js | 46 +++--- lib/helper/d_storage.js | 32 ++-- lib/helper/event_bus.js | 4 +- lib/helper/notify.js | 248 ++++++++++++++--------------- lib/helper/randomDynamic.js | 24 +-- lib/index.js | 14 +- lib/login.js | 18 +-- lib/lottery.js | 14 +- lib/net/api.bili.js | 10 +- lib/net/bili.js | 230 +++++++++++++-------------- lib/net/http.js | 48 +++--- lib/update.js | 54 +++---- lib/utils.js | 166 +++++++++---------- main.js | 86 +++++----- my_config.example.js | 24 +-- package.json | 4 +- test/api.test.js | 32 ++-- test/article.test.js | 10 +- test/dynamic_card.test.js | 60 +++---- test/index.js | 14 +- test/ocr.test.js | 8 +- test/util.js | 4 +- 31 files changed, 1018 insertions(+), 1008 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 3a28b3ef20..339d795e7b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -9,5 +9,13 @@ "ecmaVersion": "latest" }, "rules": { + "quotes": [ + "error", + "single" + ], + "semi": [ + "error", + "always" + ] } -} +} \ No newline at end of file diff --git a/env.example.js b/env.example.js index 7cba177b6d..f237ed1e75 100644 --- a/env.example.js +++ b/env.example.js @@ -23,19 +23,19 @@ module.exports = Object.freeze({ * **按顺序依次执行, 防止访问频繁封禁IP** */ account_parm: { - COOKIE: "", - NOTE: "", + COOKIE: '', + NOTE: '', NUMBER: 1, CLEAR: true, - ACCOUNT_UA: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36", + ACCOUNT_UA: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', ENABLE_CHAT_CAPTCHA_OCR: false, - CHAT_CAPTCHA_OCR_URL: "http://127.0.0.1:9898/ocr/url/text", + CHAT_CAPTCHA_OCR_URL: 'http://127.0.0.1:9898/ocr/url/text', ENABLE_MULTIPLE_ACCOUNT: false, - MULTIPLE_ACCOUNT_PARM: "", + MULTIPLE_ACCOUNT_PARM: '', LOTTERY_LOG_LEVEL: 3, - NOT_GO_LOTTERY: "" + NOT_GO_LOTTERY: '' }, /** @@ -59,12 +59,12 @@ module.exports = Object.freeze({ */ multiple_account_parm: [ { - COOKIE: "", - NOTE: "", + COOKIE: '', + NOTE: '', NUMBER: 1, CLEAR: true, WAIT: 60 * 1000, - ACCOUNT_UA: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" + ACCOUNT_UA: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' } ], @@ -72,33 +72,33 @@ module.exports = Object.freeze({ * 推送相关参数 */ push_parm: { - SCKEY: "", - SENDKEY: "", - QQ_SKEY: "", - QQ_MODE: "", - BARK_PUSH: "", - BARK_SOUND: "", - PUSHDEER_URL: "", - PUSHDEER_PUSHKEY: "", - TG_BOT_TOKEN: "", - TG_USER_ID: "", - TG_PROXY_HOST: "", - TG_PROXY_PORT: "", - DD_BOT_TOKEN: "", - DD_BOT_SECRET: "", - QYWX_AM: "", - QYWX_KEY: "", - IGOT_PUSH_KEY: "", - PUSH_PLUS_TOKEN: "", - PUSH_PLUS_USER: "", - QMSG_KEY: "", - QMSG_QQ: "", - SMTP_HOST: "", - SMTP_PORT: "", - SMTP_USER: "", - SMTP_PASS: "", - SMTP_TO_USER: "", - GOTIFY_URL: "", - GOTIFY_APPKEY: "" + SCKEY: '', + SENDKEY: '', + QQ_SKEY: '', + QQ_MODE: '', + BARK_PUSH: '', + BARK_SOUND: '', + PUSHDEER_URL: '', + PUSHDEER_PUSHKEY: '', + TG_BOT_TOKEN: '', + TG_USER_ID: '', + TG_PROXY_HOST: '', + TG_PROXY_PORT: '', + DD_BOT_TOKEN: '', + DD_BOT_SECRET: '', + QYWX_AM: '', + QYWX_KEY: '', + IGOT_PUSH_KEY: '', + PUSH_PLUS_TOKEN: '', + PUSH_PLUS_USER: '', + QMSG_KEY: '', + QMSG_QQ: '', + SMTP_HOST: '', + SMTP_PORT: '', + SMTP_USER: '', + SMTP_PASS: '', + SMTP_TO_USER: '', + GOTIFY_URL: '', + GOTIFY_APPKEY: '' } -}) +}); diff --git a/lib/account.js b/lib/account.js index f7b8d11d16..c7f81d4e4d 100644 --- a/lib/account.js +++ b/lib/account.js @@ -1,15 +1,15 @@ -const bili = require('./net/bili') -const { log } = require('./utils') +const bili = require('./net/bili'); +const { log } = require('./utils'); async function account() { const my_info = await bili.getMyinfo(); const stat = await bili.getStat(); if (my_info && stat) { - log.info("帐号信息", `${my_info.name} Lv${my_info.level} ${my_info.silence ? "已封禁" : "未封禁"} 升级还需${my_info.level_exp.next_exp - my_info.level_exp.current_exp}经验`) - log.info("帐号信息", `当前关注数:${stat.following} 粉丝数:${stat.follower} 动态数量:${stat.dynamic_count}`) + log.info('帐号信息', `${my_info.name} Lv${my_info.level} ${my_info.silence ? '已封禁' : '未封禁'} 升级还需${my_info.level_exp.next_exp - my_info.level_exp.current_exp}经验`); + log.info('帐号信息', `当前关注数:${stat.following} 粉丝数:${stat.follower} 动态数量:${stat.dynamic_count}`); } else { - log.error("帐号信息", "获取失败"); + log.error('帐号信息', '获取失败'); } } -module.exports = { account } \ No newline at end of file +module.exports = { account }; \ No newline at end of file diff --git a/lib/check.js b/lib/check.js index 853fde8253..ba7e73a39d 100644 --- a/lib/check.js +++ b/lib/check.js @@ -1,8 +1,8 @@ -const { log, delay, infiniteNumber, judge } = require('./utils') -const { sendNotify } = require('./helper/notify') -const config = require('./data/config') -const global_var = require('./data/global_var') -const bili = require('./net/bili') +const { log, delay, infiniteNumber, judge } = require('./utils'); +const { sendNotify } = require('./helper/notify'); +const config = require('./data/config'); +const global_var = require('./data/global_var'); +const bili = require('./net/bili'); /** * 是否中奖 @@ -21,14 +21,14 @@ async function isMe(num) { MyAtInfo .slice(0, unread_at_num) .forEach(({ at_time, up_uname, business, source_content, url }) => { - desp += '## [at]检测结果\n\n' - desp += '- - - -\n\n' - desp += `发生时间: ${new Date(at_time * 1000).toLocaleString()}\n\n` - desp += `用户: ${up_uname}\n\n` - desp += `在${business}中@了[你](https://space.bilibili.com/${global_var.get("myUID")})\n\n` - desp += `原内容为: ${source_content}\n\n` - desp += `[直达链接](${url})\n\n` - desp += '- - - -\n\n' + desp += '## [at]检测结果\n\n'; + desp += '- - - -\n\n'; + desp += `发生时间: ${new Date(at_time * 1000).toLocaleString()}\n\n`; + desp += `用户: ${up_uname}\n\n`; + desp += `在${business}中@了[你](https://space.bilibili.com/${global_var.get('myUID')})\n\n`; + desp += `原内容为: ${source_content}\n\n`; + desp += `[直达链接](${url})\n\n`; + desp += '- - - -\n\n'; }); log.info('中奖检测', '--> OK'); } @@ -39,22 +39,22 @@ async function isMe(num) { .slice(0, unread_reply_num) .forEach(({ nickname, uri, source, timestamp }) => { if (judge(source, notice_key_words)) { - desp += '## 回复检测结果\n\n' - desp += '- - - -\n\n' - desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()}\n\n` - desp += `用户: ${nickname}\n\n` - desp += `回复[你](https://space.bilibili.com/${global_var.get("myUID")})说:\n${source}\n\n` - desp += `[直达链接](${uri})\n\n` - desp += '- - - -\n\n' + desp += '## 回复检测结果\n\n'; + desp += '- - - -\n\n'; + desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()}\n\n`; + desp += `用户: ${nickname}\n\n`; + desp += `回复[你](https://space.bilibili.com/${global_var.get('myUID')})说:\n${source}\n\n`; + desp += `[直达链接](${uri})\n\n`; + desp += '- - - -\n\n'; } - }) + }); log.info('中奖检测', '--> OK'); } if (follow_unread + unfollow_unread > 0) { const check = async (type) => { let session_t = ''; - let MySession = await bili.getSessionInfo(type) - log.info("准备检查私信", check_session_pages + "页") + let MySession = await bili.getSessionInfo(type); + log.info('准备检查私信', check_session_pages + '页'); for (const index of infiniteNumber()) { for (const Session of MySession.data) { const { sender_uid, session_ts, timestamp, unread_count, talker_id, msg_seqno } = Session; @@ -62,13 +62,13 @@ async function isMe(num) { if (unread_count) { const content = await bili.fetch_session_msgs(talker_id, unread_count); if (judge(content, notice_key_words)) { - desp += '## 私信检测结果\n\n' - desp += '- - - -\n\n' - desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()}\n\n` - desp += `用户: ${sender_uid}\n\n` - desp += `私信[你](https://space.bilibili.com/${global_var.get("myUID")})说:\n${content}\n\n` - desp += `[直达链接](https://message.bilibili.com/#/whisper/mid${sender_uid})\n\n` - desp += '- - - -\n\n' + desp += '## 私信检测结果\n\n'; + desp += '- - - -\n\n'; + desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()}\n\n`; + desp += `用户: ${sender_uid}\n\n`; + desp += `私信[你](https://space.bilibili.com/${global_var.get('myUID')})说:\n${content}\n\n`; + desp += `[直达链接](https://message.bilibili.com/#/whisper/mid${sender_uid})\n\n`; + desp += '- - - -\n\n'; } await bili.updateSessionStatus(talker_id, type, msg_seqno); await delay(update_session_wait); @@ -76,26 +76,26 @@ async function isMe(num) { } if (MySession.has_more && index < check_session_pages) { await delay(get_session_wait); - MySession = await bili.getSessionInfo(type, session_t) + MySession = await bili.getSessionInfo(type, session_t); } else { - break + break; } } - } + }; if (follow_unread) { - log.info('中奖检测', '<-- 正在检查已关注者的私信') + log.info('中奖检测', '<-- 正在检查已关注者的私信'); } if (unfollow_unread) { - log.info('中奖检测', '<-- 正在检查未关注者的私信') + log.info('中奖检测', '<-- 正在检查未关注者的私信'); } - await check("1") + await check('1'); log.info('中奖检测', '--> OK'); } if (desp) { log.info('可能中奖了', desp); await sendNotify(`帐号${num}可能中奖了`, desp); } else { - log.info('中奖检测', "暂未中奖"); + log.info('中奖检测', '暂未中奖'); } return; } diff --git a/lib/clear.js b/lib/clear.js index 882dcbc9a7..2b7b4c1530 100644 --- a/lib/clear.js +++ b/lib/clear.js @@ -1,8 +1,8 @@ -const { log, delay, infiniteNumber, retryfn } = require("./utils"); -const bili = require("./net/bili"); -const { Searcher } = require("./core/searcher"); +const { log, delay, infiniteNumber, retryfn } = require('./utils'); +const bili = require('./net/bili'); +const { Searcher } = require('./core/searcher'); const global_var = require('./data/global_var'); -const config = require("./data/config"); +const config = require('./data/config'); /** * 获取关注分区里的uid @@ -16,13 +16,13 @@ async function getFollowList(partition) { let rmup = []; if (typeof tagid === 'undefined') { log.info('获取关注列表', '未能成功获取关注分区id'); - return rmup + return rmup; } for (let index = 1; index < 100; index++) { const uids = await bili.getPartitionUID(tagid, index); await delay(get_partition_wait); if (!uids.length) break; - rmup.push(...uids) + rmup.push(...uids); } return clear_white_list.length ? rmup.filter(uid => clear_white_list.split(',').indexOf(String(uid)) === -1) @@ -37,24 +37,24 @@ async function clear() { let success = true; const uid_list = (await Promise.all(clear_partition.split(',').map(getFollowList))).flat(); if (!uid_list.length) { - log.info('清理关注', `关注为空`) + log.info('清理关注', '关注为空'); } else { - log.info('清理关注', `共有${uid_list.length}个关注`) + log.info('清理关注', `共有${uid_list.length}个关注`); } if (clear_quick_remove_attention) { - log.info('清理关注', '进入只清理关注模式') + log.info('清理关注', '进入只清理关注模式'); /* 专清关注 */ for (const [index, uid] of uid_list.entries()) { const fannumber = await bili.getUserInfo(uid); - log.info('清理关注', `粉丝数${fannumber}`) + log.info('清理关注', `粉丝数${fannumber}`); if (fannumber !== -1 && fannumber < clear_quick_remove_attention_fans_number_smallest) { - log.info('清理关注', `(${index}) (${uid})`) + log.info('清理关注', `(${index}) (${uid})`); /* 取消关注 */ if (await retryfn(3, [false], () => bili.cancelAttention(uid))) { - log.info('清理关注', '成功') + log.info('清理关注', '成功'); } else { - log.error('清理关注', '失败') - break + log.error('清理关注', '失败'); + break; } } /* 延时 */ @@ -77,7 +77,7 @@ async function clear() { )) || { allModifyDynamicResArray: [], offset: '0' }; next_offset = offset; for (const [index, dyinfo] of allModifyDynamicResArray.entries()) { - log.info('清理动态', `第${page + 1}页中的第${index + 1}个动态`) + log.info('清理动态', `第${page + 1}页中的第${index + 1}个动态`); const { type, dynamic_id, create_time, origin_uid } = dyinfo || {}; if (typeof type !== 'undefined' && clear_dynamic_type instanceof Array @@ -87,12 +87,12 @@ async function clear() { const days_ago = (Now - create_time) / 86400; if (days_ago > clear_max_day) { - log.debug('清理动态', `当前UID保护列表:\n${before_separate.join(',')}\n`) + log.debug('清理动态', `当前UID保护列表:\n${before_separate.join(',')}\n`); /* 移除动态 */ if (dynamic_id && clear_remove_dynamic && !(new RegExp(dynamic_id).test(clear_white_list))) { - success = await retryfn(3, [false], () => bili.rmDynamic(dynamic_id)) + success = await retryfn(3, [false], () => bili.rmDynamic(dynamic_id)); } /* 取消关注 */ @@ -101,38 +101,38 @@ async function clear() { && clear_remove_attention && before_separate.indexOf(origin_uid) === -1 && uid_list.indexOf(origin_uid) > -1) { - success = await retryfn(3, [false], () => bili.cancelAttention(origin_uid)) + success = await retryfn(3, [false], () => bili.cancelAttention(origin_uid)); } if (!success) { - log.error("清理失败", "出现错误") - break + log.error('清理失败', '出现错误'); + break; } /* 延时 */ await delay(clear_remove_delay); } else { - log.info('清理动态', `已设置跳过${clear_max_day}天 当前动态(${dynamic_id})发布时间: ${~~days_ago}天前`) + log.info('清理动态', `已设置跳过${clear_max_day}天 当前动态(${dynamic_id})发布时间: ${~~days_ago}天前`); if (origin_uid) { - log.info('清理动态', `储存用户(${origin_uid})防止误删`) - before_separate.push(origin_uid) + log.info('清理动态', `储存用户(${origin_uid})防止误删`); + before_separate.push(origin_uid); } else { - log.info('清理动态', `非转发动态`) + log.info('清理动态', '非转发动态'); } } } else { - log.info('清理动态', `此动态类型为${type} != 要清理的动态类型${clear_dynamic_type}`) + log.info('清理动态', `此动态类型为${type} != 要清理的动态类型${clear_dynamic_type}`); } } /* 延时 */ await delay(clear_remove_delay); - log.info('清理动态', `第${page + 1}页(${allModifyDynamicResArray.length})中的转发动态与关注全部处理成功`) + log.info('清理动态', `第${page + 1}页(${allModifyDynamicResArray.length})中的转发动态与关注全部处理成功`); if (next_offset === '0' || !success) break; } } - return + return; } -module.exports = { clear } +module.exports = { clear }; diff --git a/lib/core/monitor.js b/lib/core/monitor.js index 61d19db061..ad44b2a4c5 100644 --- a/lib/core/monitor.js +++ b/lib/core/monitor.js @@ -3,10 +3,10 @@ const { send } = require('../net/http'); const bili = require('../net/bili'); const { sendNotify } = require('../helper/notify'); const event_bus = require('../helper/event_bus'); -const { randomDynamic } = require('../helper/randomDynamic') +const { randomDynamic } = require('../helper/randomDynamic'); const { Searcher } = require('./searcher'); -const global_var = require("../data/global_var"); -const config = require("../data/config"); +const global_var = require('../data/global_var'); +const config = require('../data/config'); const d_storage = require('../helper/d_storage'); /** @@ -19,7 +19,7 @@ class Monitor extends Searcher { */ constructor(lottery_param) { super(); - this.lottery_param = lottery_param + this.lottery_param = lottery_param; this.tagid = config.partition_id; /* tagid初始化 */ this.attentionList = ''; /* 转为字符串的所有关注的up主uid */ this.LotteryInfoMap = new Map([ @@ -35,68 +35,68 @@ class Monitor extends Searcher { */ async init() { if (config.model === '00') { - event_bus.emit('Turn_off_the_Monitor', '已关闭所有转发行为') - return + event_bus.emit('Turn_off_the_Monitor', '已关闭所有转发行为'); + return; } if (!this.tagid && config.is_not_create_partition !== true) { - this.tagid = await bili.checkMyPartition() /* 检查关注分区 */ + this.tagid = await bili.checkMyPartition(); /* 检查关注分区 */ if (!this.tagid) { - event_bus.emit('Turn_off_the_Monitor', '分区获取失败') - return + event_bus.emit('Turn_off_the_Monitor', '分区获取失败'); + return; } } /** 关注列表初始化 */ - this.attentionList = await bili.getAttentionList(global_var.get("myUID")); + this.attentionList = await bili.getAttentionList(global_var.get('myUID')); const status = await this.startLottery(); switch (status) { case 0: - event_bus.emit('Turn_on_the_Monitor') + event_bus.emit('Turn_on_the_Monitor'); break; case 1001: - event_bus.emit('Turn_off_the_Monitor', '评论失败') + event_bus.emit('Turn_off_the_Monitor', '评论失败'); break; case 1010: - event_bus.emit('Turn_off_the_Monitor', '已掉号') + event_bus.emit('Turn_off_the_Monitor', '已掉号'); break; case 1004: - event_bus.emit('Turn_off_the_Monitor', '需要输入验证码') - break + event_bus.emit('Turn_off_the_Monitor', '需要输入验证码'); + break; case 2001: - event_bus.emit('Turn_off_the_Monitor', '关注出错') + event_bus.emit('Turn_off_the_Monitor', '关注出错'); break; case 3001: - event_bus.emit('Turn_off_the_Monitor', '分区移动出错 可于设置处关闭移动分区') + event_bus.emit('Turn_off_the_Monitor', '分区移动出错 可于设置处关闭移动分区'); break; case 2004: case 4005: - log.warn(`账号异常${status}`, `UID(${global_var.get('myUID')})异常号只会对部分UP出现异常`) + log.warn(`账号异常${status}`, `UID(${global_var.get('myUID')})异常号只会对部分UP出现异常`); if (!config.is_exception) { await sendNotify( `[动态抽奖]账号异常${status}通知`, `UID: ${global_var.get('myUID')}\n异常号只会对部分UP出现异常\n可在设置中令is_exception为true关闭此推送\n${log._cache.filter(it => /Error|\s抽奖信息\]/.test(it)).join('\n')}` - ) + ); } config.is_exception = true; - event_bus.emit('Turn_on_the_Monitor') - break + event_bus.emit('Turn_on_the_Monitor'); + break; case 2005: - log.warn('关注已达上限', `UID(${global_var.get('myUID')})关注已达上限,已临时进入只转已关注模式`) + log.warn('关注已达上限', `UID(${global_var.get('myUID')})关注已达上限,已临时进入只转已关注模式`); if (!config.is_outof_maxfollow) { await sendNotify( '[动态抽奖]关注已达上限', `UID: ${global_var.get('myUID')}\n关注已达上限,已临时进入只转已关注模式\n可在设置中令is_outof_maxfollow为true关闭此推送\n${log._cache.filter(it => /Error|\s抽奖信息\]/.test(it)).join('\n')}` - ) + ); } config.is_outof_maxfollow = true; config.only_followed = true; - event_bus.emit('Turn_on_the_Monitor') - break + event_bus.emit('Turn_on_the_Monitor'); + break; case 5001: - event_bus.emit('Turn_off_the_Monitor', '转发失败') - break + event_bus.emit('Turn_off_the_Monitor', '转发失败'); + break; default: - event_bus.emit('Turn_off_the_Monitor', `??? 未知错误: ${status}`) + event_bus.emit('Turn_off_the_Monitor', `??? 未知错误: ${status}`); break; } } @@ -126,53 +126,53 @@ class Monitor extends Searcher { && lottery.uid.length && (new RegExp(lottery.uid.join('|'))).test(this.attentionList) ) { - log.info('过滤', `已关注(${lottery.uid.join(',')})`) - continue + log.info('过滤', `已关注(${lottery.uid.join(',')})`); + continue; } if (lottery.isOfficialLottery) { let { ts } = await bili.getLotteryNotice(lottery.dyid); const ts_10 = Date.now() / 1000; if (ts === -1) { - log.warn('过滤', '无法判断开奖时间') - await delay(filter_wait) - continue + log.warn('过滤', '无法判断开奖时间'); + await delay(filter_wait); + continue; } if (ts === -9999) { - log.info('过滤', '已撤销抽奖') - d_storage.updateDyid(lottery.dyid) - await delay(filter_wait) - continue + log.info('过滤', '已撤销抽奖'); + d_storage.updateDyid(lottery.dyid); + await delay(filter_wait); + continue; } if (ts < ts_10) { - log.info('过滤', '已过开奖时间') - d_storage.updateDyid(lottery.dyid) - await delay(filter_wait) - continue + log.info('过滤', '已过开奖时间'); + d_storage.updateDyid(lottery.dyid); + await delay(filter_wait); + continue; } if (ts > ts_10 + config.maxday * 86400) { - log.info('过滤', '超过指定开奖时间') - d_storage.updateDyid(lottery.dyid) - await delay(filter_wait) - continue + log.info('过滤', '超过指定开奖时间'); + d_storage.updateDyid(lottery.dyid); + await delay(filter_wait); + continue; } } else if (lottery.uid[0]) { - const { minfollower } = config + const { minfollower } = config; if (minfollower > 0) { const followerNum = await bili.getUserInfo(lottery.uid[0]); if (followerNum === -1) { - log.warn('过滤', `粉丝数(${followerNum})获取失败`) - await delay(filter_wait) - continue + log.warn('过滤', `粉丝数(${followerNum})获取失败`); + await delay(filter_wait); + continue; } if (followerNum < minfollower) { - log.info('过滤', `粉丝数(${followerNum})小于指定数量`) - d_storage.updateDyid(lottery.dyid) - await delay(filter_wait) - continue + log.info('过滤', `粉丝数(${followerNum})小于指定数量`); + d_storage.updateDyid(lottery.dyid); + await delay(filter_wait); + continue; } } else { - log.info('过滤', "不过滤粉丝数") + log.info('过滤', '不过滤粉丝数'); } } @@ -182,13 +182,13 @@ class Monitor extends Searcher { && index % getRandomOne(create_dy_mode[0]) === 0 ) { const number = getRandomOne(create_dy_mode[1]) || 0; - randomDynamic(number) + randomDynamic(number); } - status = await this.go(lottery) + status = await this.go(lottery); switch (status) { case 0: - relayed_nums += 1 + relayed_nums += 1; break; case 1002: case 1003: @@ -207,16 +207,16 @@ class Monitor extends Searcher { case 5002: case 5003: case 5004: - status = 0 + status = 0; break; case 2004: - is_exception = 2004 + is_exception = 2004; break; case 4005: - is_exception = 4005 + is_exception = 4005; break; case 2005: - is_outof_maxfollow = 2005 + is_outof_maxfollow = 2005; break; case 1001: case 1010: @@ -224,25 +224,25 @@ class Monitor extends Searcher { case 2001: case 3001: case 5001: - is_shutdown = true + is_shutdown = true; break; default: break; } - if (is_shutdown) break + if (is_shutdown) break; - d_storage.updateDyid(lottery.dyid) + d_storage.updateDyid(lottery.dyid); await delay(wait * (Math.random() + 0.5)); } log.info('抽奖', `本轮共处理${total_nums}条,成功参与${relayed_nums}条`); return is_exception || is_outof_maxfollow - || status + || status; } else { log.info('抽奖', '无未转发抽奖'); - return 0 + return 0; } } @@ -295,10 +295,10 @@ class Monitor extends Searcher { /**去重 */ protoLotteryInfo = protoLotteryInfo.filter(({ dyid }) => { if (dyids_map.has(dyid)) { - return false + return false; } dyids_map.set(dyid, false); - return true + return true; }); log.info('筛选动态', `去重后(${protoLotteryInfo.length})`); @@ -311,35 +311,35 @@ class Monitor extends Searcher { .searchDyid(it) .then(hasIt => dyids_map.set(it, hasIt)) ) - ) - log.info('筛选动态', `并发查询本地dyid完毕`); + ); + log.info('筛选动态', '并发查询本地dyid完毕'); } - if (lottery_param[0] !== "APIs" && save_lottery_info_to_file && protoLotteryInfo.length) { - log.info("保存抽奖信息", "保存开始") - await appendLotteryInfoFile(lottery_param[1].toString(), protoLotteryInfo) + if (lottery_param[0] !== 'APIs' && save_lottery_info_to_file && protoLotteryInfo.length) { + log.info('保存抽奖信息', '保存开始'); + await appendLotteryInfoFile(lottery_param[1].toString(), protoLotteryInfo); } - if (lottery_param[0] !== "APIs" && set_lottery_info_url && protoLotteryInfo.length) { - log.info("上传抽奖信息", "上传开始") + if (lottery_param[0] !== 'APIs' && set_lottery_info_url && protoLotteryInfo.length) { + log.info('上传抽奖信息', '上传开始'); await new Promise((resolve) => { send({ url: set_lottery_info_url, - method: "POST", + method: 'POST', headers: { - "content-type": "application/json" + 'content-type': 'application/json' }, contents: protoLotteryInfo, success: ({ body }) => { - log.info("发送获取到的动态数据", body) - resolve() + log.info('发送获取到的动态数据', body); + resolve(); }, failure: err => { - log.error("发送获取到的动态数据", err) - resolve() + log.error('发送获取到的动态数据', err); + resolve(); } - }) - }) + }); + }); } /* 检查动态是否满足要求 */ @@ -357,27 +357,27 @@ class Monitor extends Searcher { log.debug('正在筛选的动态信息', lottery_info); if (lottery_info_type.startsWith('sneak') && sneaktower) { - log.info("筛选动态", `偷塔模式不检查是否已转发(https://t.bilibili.com/${dyid})`) + log.info('筛选动态', `偷塔模式不检查是否已转发(https://t.bilibili.com/${dyid})`); } else { /* 遇到转发过就退出 */ if ( ((!check_if_duplicated || check_if_duplicated >= 2) && is_liked) || ((check_if_duplicated >= 1) && dyids_map.get(dyid)) ) { - log.info("筛选动态", `已转发(https://t.bilibili.com/${dyid})`) - return false + log.info('筛选动态', `已转发(https://t.bilibili.com/${dyid})`); + return false; } } /* 超过指定时间退出 */ if (create_time && now_ts - create_time > max_create_time * 86400) { - log.info("筛选动态", `过时动态(https://t.bilibili.com/${dyid})`) - return false + log.info('筛选动态', `过时动态(https://t.bilibili.com/${dyid})`); + return false; } if (is_charge_lottery) { - log.info("筛选动态", `充电抽奖(https://t.bilibili.com/${dyid})`) - return false + log.info('筛选动态', `充电抽奖(https://t.bilibili.com/${dyid})`); + return false; } const @@ -403,61 +403,61 @@ class Monitor extends Searcher { || (!hasOfficialLottery && chatmodel[1] === '1'), keys = [dyid, m_uid, ori_uid]; - log.debug("筛选动态", { real_uid, mIsFollowed, oriIsFollowed, realIsFollowed, needAt, needTopic, type, isRelayDynamic, key_words, has_key_words, blockword, isBlock, isLottery, isSendChat }) + log.debug('筛选动态', { real_uid, mIsFollowed, oriIsFollowed, realIsFollowed, needAt, needTopic, type, isRelayDynamic, key_words, has_key_words, blockword, isBlock, isLottery, isSendChat }); if ( blacklist.split(',').some(id => keys.some(key => { if (key + '' === id) { - log.info("筛选动态", `黑名单匹配(${id})(https://t.bilibili.com/${dyid})`) - return true + log.info('筛选动态', `黑名单匹配(${id})(https://t.bilibili.com/${dyid})`); + return true; } else { - return false + return false; } })) ) { - return false + return false; } if (block_dynamic_type.includes(type)) { - log.warn("筛选动态", `屏蔽动态类型 ${type}`) - return false + log.warn('筛选动态', `屏蔽动态类型 ${type}`); + return false; } /**屏蔽词 */ if (isBlock) { - log.info("筛选动态", `包含屏蔽词(https://t.bilibili.com/${dyid})`) - return false + log.info('筛选动态', `包含屏蔽词(https://t.bilibili.com/${dyid})`); + return false; } if (reserve_id) { if (disable_reserve_lottery) { - log.info("已关闭预约抽奖功能") + log.info('已关闭预约抽奖功能'); } else { - log.info("预约抽奖", "开始"); - log.info("预约抽奖", `奖品: ${reserve_lottery_text}`); + log.info('预约抽奖', '开始'); + log.info('预约抽奖', `奖品: ${reserve_lottery_text}`); if (hasEnv('NOT_GO_LOTTERY')) { log.info('NOT_GO_LOTTERY', 'ON'); } else { await delay(reserve_lottery_wait); - await bili.reserve_lottery(reserve_id) + await bili.reserve_lottery(reserve_id); } } if (is_not_relay_reserve_lottery === true) { - log.info("预约抽奖", "已关闭预约抽奖转关功能"); - return false + log.info('预约抽奖', '已关闭预约抽奖转关功能'); + return false; } } if (!hasOfficialLottery && model[1] === '1' && !has_key_words && description) { - log.warn("筛选动态", `无关键词动态的描述: ${description}\n\n考虑是否修改设置key_words:\n${key_words.join('\n且满足: ')}`) + log.warn('筛选动态', `无关键词动态的描述: ${description}\n\n考虑是否修改设置key_words:\n${key_words.join('\n且满足: ')}`); } /**若勾选只转已关注 */ if (only_followed && (!mIsFollowed || !oriIsFollowed) ) { - log.info("筛选动态", `只转已关注(https://t.bilibili.com/${dyid})`) - return false + log.info('筛选动态', `只转已关注(https://t.bilibili.com/${dyid})`); + return false; } if (isLottery) { @@ -466,7 +466,7 @@ class Monitor extends Searcher { onelotteryinfo.isOfficialLottery = hasOfficialLottery; /**初始化待关注列表 */ - onelotteryinfo.uid = [] + onelotteryinfo.uid = []; if (!realIsFollowed) { onelotteryinfo.uid.push(real_uid); @@ -476,14 +476,14 @@ class Monitor extends Searcher { let /**转发评语 */ - RandomStr = (getRandomOne(relays) || "!!!") + RandomStr = (getRandomOne(relays) || '!!!') .replace(/\$\{uname\}/g, uname), /**控制字段 */ new_ctrl = []; /* 是否需要带话题 */ if (needTopic) { - RandomStr += needTopic + RandomStr += needTopic; } /* 是否需要@ */ @@ -494,9 +494,9 @@ class Monitor extends Searcher { location: RandomStr.length, length: it[0].length + 1, type: 1 - }) - RandomStr += '@' + it[0] - }) + }); + RandomStr += '@' + it[0]; + }); } /* 是否是转发的动态 */ @@ -509,11 +509,11 @@ class Monitor extends Searcher { location: RandomStr.length + 2, length: uname.length + 1, type: 1 - }) + }); ctrl.map(item => { item.location += addlength; return item; - }).forEach(it => new_ctrl.push(it)) + }).forEach(it => new_ctrl.push(it)); if (!oriIsFollowed) { onelotteryinfo.uid.push(ori_uid); } @@ -528,16 +528,16 @@ class Monitor extends Searcher { /* 是否评论 */ if (isSendChat) { - onelotteryinfo.rid = rid - onelotteryinfo.chat = (getRandomOne(chats) || "!!!") - .replace(/\$\{uname\}/g, uname) + onelotteryinfo.rid = rid; + onelotteryinfo.chat = (getRandomOne(chats) || '!!!') + .replace(/\$\{uname\}/g, uname); } alllotteryinfo.push(onelotteryinfo); } else { - log.info("筛选动态", `非抽奖动态(https://t.bilibili.com/${dyid})`) + log.info('筛选动态', `非抽奖动态(https://t.bilibili.com/${dyid})`); } - }) + }); return alllotteryinfo; } @@ -577,7 +577,7 @@ class Monitor extends Searcher { log.debug('正在转发的动态信息', option); if (hasEnv('NOT_GO_LOTTERY')) { log.info('NOT_GO_LOTTERY', 'ON'); - return 0 + return 0; } let @@ -591,14 +591,14 @@ class Monitor extends Searcher { const copy_chat = getRandomOne( (await bili.getChat(rid, chat_type)) .filter(it => !(new RegExp(copy_blockword.join('|')).test(it[1]))) - ) || [";;;;;;;;;", chat || "!!!"]; + ) || [';;;;;;;;;', chat || '!!!']; chat = copy_chat[1] .replace( new RegExp(copy_chat[0], 'g'), - global_var.get("myUNAME") || '') + global_var.get('myUNAME') || ''); } else { if (is_repost_then_chat) { - chat = chat + relay_chat + chat = chat + relay_chat; } } @@ -610,50 +610,50 @@ class Monitor extends Searcher { chat, chat_type ) - ) + ); if (status === 8 || status === 9) { status = await bili.sendChatWithOcr( rid, - "[doge][doge][doge][doge][doge]", + '[doge][doge][doge][doge][doge]', chat_type - ) + ); } if (status) { - log.warn("抽奖信息", `dyid: ${dyid}, rid: ${rid}, chat_type: ${chat_type}`) - return 1000 + status + log.warn('抽奖信息', `dyid: ${dyid}, rid: ${rid}, chat_type: ${chat_type}`); + return 1000 + status; } } /* 关注 */ if (uid.length) { await try_for_each(uid, async (u) => { - status = await bili.autoAttention(u) + status = await bili.autoAttention(u); if (status === 6) { status = 0; - return false + return false; } if (status) { - log.warn("抽奖信息", `dyid: ${dyid}, uid: ${u}`) - return true + log.warn('抽奖信息', `dyid: ${dyid}, uid: ${u}`); + return true; } else { if (is_not_create_partition !== true) { if (await bili.movePartition(u, this.tagid)) { - log.warn("抽奖信息", `dyid: ${dyid}, uid: ${u} tagid: ${this.tagid}`) + log.warn('抽奖信息', `dyid: ${dyid}, uid: ${u} tagid: ${this.tagid}`); /* 3000系错误 */ - status = 1001 - return true + status = 1001; + return true; } else { - return false + return false; } } else { - return false + return false; } } - }) - if (status) return 2000 + status + }); + if (status) return 2000 + status; } /* 点赞 */ @@ -662,11 +662,11 @@ class Monitor extends Searcher { 5, [3], () => bili.autolike(dyid) - ) + ); if (status) { - log.warn("抽奖信息", `dyid: ${dyid}`) - return 4000 + status + log.warn('抽奖信息', `dyid: ${dyid}`); + return 4000 + status; } } @@ -676,19 +676,19 @@ class Monitor extends Searcher { 5, [3, 4], () => bili.autoRelay( - global_var.get("myUID"), + global_var.get('myUID'), dyid, relay_chat, ctrl) - ) + ); if (status) { - log.warn("抽奖信息", `dyid: ${dyid}`) - return 5000 + status + log.warn('抽奖信息', `dyid: ${dyid}`); + return 5000 + status; } } - return status + return status; } } diff --git a/lib/core/searcher.js b/lib/core/searcher.js index e00ee5e97b..adcad27235 100644 --- a/lib/core/searcher.js +++ b/lib/core/searcher.js @@ -1,10 +1,10 @@ const utils = require('../utils'); const bili = require('../net/bili'); -const { send } = require("../net/http"); -const { check_if_duplicated, article_scan_page, article_create_time, not_check_article, get_dynamic_detail_wait, uid_scan_page, search_wait, tag_scan_page } = require("../data/config"); -const d_storage = require("../helper/d_storage") +const { send } = require('../net/http'); +const { check_if_duplicated, article_scan_page, article_create_time, not_check_article, get_dynamic_detail_wait, uid_scan_page, search_wait, tag_scan_page } = require('../data/config'); +const d_storage = require('../helper/d_storage'); -const { log } = utils +const { log } = utils; /** * 解析dynamic_detail_card @@ -60,125 +60,125 @@ const { log } = utils */ function parseDynamicCard(data) { if (data?.card?.desc?.uid) { - return oldParseDynamicCard(data?.card) + return oldParseDynamicCard(data?.card); } let ditem = data?.item; /**临时储存单个动态中的信息 */ let obj = {}; try { const dy_typeenum2num = new Map([ - ["DYNAMIC_TYPE_FORWARD", 1], - ["DYNAMIC_TYPE_DRAW", 2], - ["DYNAMIC_TYPE_WORD", 4], - ["DYNAMIC_TYPE_AV", 8], - ["DYNAMIC_TYPE_ARTICLE", 64] + ['DYNAMIC_TYPE_FORWARD', 1], + ['DYNAMIC_TYPE_DRAW', 2], + ['DYNAMIC_TYPE_WORD', 4], + ['DYNAMIC_TYPE_AV', 8], + ['DYNAMIC_TYPE_ARTICLE', 64] ]); const dy_type2chat_type = new Map([ - ["DYNAMIC_TYPE_FORWARD", 17], - ["DYNAMIC_TYPE_DRAW", 11], - ["DYNAMIC_TYPE_WORD", 17], - ["DYNAMIC_TYPE_AV", 1], - ["DYNAMIC_TYPE_ARTICLE", 12] + ['DYNAMIC_TYPE_FORWARD', 17], + ['DYNAMIC_TYPE_DRAW', 11], + ['DYNAMIC_TYPE_WORD', 17], + ['DYNAMIC_TYPE_AV', 1], + ['DYNAMIC_TYPE_ARTICLE', 12] ]); /* 转发者的UID */ - obj.uid = ditem?.modules?.module_author?.mid || 0 + obj.uid = ditem?.modules?.module_author?.mid || 0; /* 转发者的name */ - obj.uname = ditem?.modules?.module_author?.name || '' + obj.uname = ditem?.modules?.module_author?.name || ''; /* 动态是否点过赞 */ - obj.is_liked = ditem?.modules?.module_stat?.like?.status || false + obj.is_liked = ditem?.modules?.module_stat?.like?.status || false; /* 动态的ts10 */ - obj.create_time = ditem?.modules?.module_author?.pub_ts || 0 + obj.create_time = ditem?.modules?.module_author?.pub_ts || 0; /* 动态类型 */ - obj.type = dy_typeenum2num.get(ditem?.type) || 0 + obj.type = dy_typeenum2num.get(ditem?.type) || 0; /* 用于发送评论 */ - obj.rid_str = ditem?.basic?.comment_id_str || "" + obj.rid_str = ditem?.basic?.comment_id_str || ''; /* 用于发送评论 */ - obj.chat_type = ditem?.basic?.comment_type || 0 + obj.chat_type = ditem?.basic?.comment_type || 0; /* 转发者的动态ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */ - obj.dynamic_id = ditem?.id_str || "" + obj.dynamic_id = ditem?.id_str || ''; /* 定位@信息 */ obj.ctrl = []; /* 是否有官方抽奖 */ - obj.hasOfficialLottery = false + obj.hasOfficialLottery = false; /* 转发描述 */ - obj.description = "" + obj.description = ''; let _total_len = 0; ditem?.modules?.module_dynamic?.desc?.rich_text_nodes.forEach(node => { - if (node.type === "RICH_TEXT_NODE_TYPE_AT") { + if (node.type === 'RICH_TEXT_NODE_TYPE_AT') { obj.ctrl.push({ data: node.rid, location: _total_len, length: node.text.length, type: 1 - }) + }); } /* 是否有官方抽奖 */ - if (node.type === "RICH_TEXT_NODE_TYPE_LOTTERY") { - obj.hasOfficialLottery = true + if (node.type === 'RICH_TEXT_NODE_TYPE_LOTTERY') { + obj.hasOfficialLottery = true; } - obj.description += node.orig_text - _total_len += node.text.length - }) + obj.description += node.orig_text; + _total_len += node.text.length; + }); /* 预约抽奖信息 */ - obj.reserve_id = ditem?.modules?.module_dynamic?.additional?.reserve?.rid || 0 - obj.reserve_lottery_text = ditem?.modules?.module_dynamic?.additional?.reserve?.title || "信息丢失" + obj.reserve_id = ditem?.modules?.module_dynamic?.additional?.reserve?.rid || 0; + obj.reserve_lottery_text = ditem?.modules?.module_dynamic?.additional?.reserve?.title || '信息丢失'; /* 充电抽奖 */ - if (ditem?.modules?.module_dynamic?.additional?.type === "ADDITIONAL_TYPE_UPOWER_LOTTERY") { - obj.is_charge_lottery = true + if (ditem?.modules?.module_dynamic?.additional?.type === 'ADDITIONAL_TYPE_UPOWER_LOTTERY') { + obj.is_charge_lottery = true; } /* 转发 */ if (obj.type === 1) { /* 被转发者的UID */ - obj.origin_uid = ditem?.orig?.modules?.module_author?.mid || 0 + obj.origin_uid = ditem?.orig?.modules?.module_author?.mid || 0; /* 被转发者的name */ - obj.origin_uname = ditem?.orig?.modules?.module_author?.name || '' + obj.origin_uname = ditem?.orig?.modules?.module_author?.name || ''; /* 源动态的ts10 */ - obj.origin_create_time = ditem?.orig?.modules?.module_author?.pub_ts || 0 + obj.origin_create_time = ditem?.orig?.modules?.module_author?.pub_ts || 0; /* 源动态类型 */ - obj.origin_type = dy_typeenum2num.get(ditem?.orig?.type) || 0 + obj.origin_type = dy_typeenum2num.get(ditem?.orig?.type) || 0; /* 被转发者的rid(用于发评论) */ switch (ditem?.orig?.type) { - case "DYNAMIC_TYPE_DRAW": - obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.draw?.id?.toString() || "" + case 'DYNAMIC_TYPE_DRAW': + obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.draw?.id?.toString() || ''; break; - case "DYNAMIC_TYPE_AV": - obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.archive?.aid || "" + case 'DYNAMIC_TYPE_AV': + obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.archive?.aid || ''; break; - case "DYNAMIC_TYPE_ARTICLE": - obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.article?.id?.toString() || "" + case 'DYNAMIC_TYPE_ARTICLE': + obj.origin_rid_str = ditem?.orig?.modules?.module_dynamic?.major?.article?.id?.toString() || ''; break; default: - obj.origin_rid_str = ditem?.orig?.id_str || "" + obj.origin_rid_str = ditem?.orig?.id_str || ''; break; } /* 用于发送评论 */ - obj.origin_chat_type = dy_type2chat_type.get(ditem?.orig?.type) || 0 + obj.origin_chat_type = dy_type2chat_type.get(ditem?.orig?.type) || 0; /* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */ - obj.origin_dynamic_id = ditem?.orig?.id_str || "" + obj.origin_dynamic_id = ditem?.orig?.id_str || ''; /* 预约抽奖信息 */ - obj.origin_reserve_id = ditem?.orig?.modules?.module_dynamic?.additional?.reserve?.rid || 0 - obj.origin_reserve_lottery_text = ditem?.orig?.modules?.module_dynamic?.additional?.reserve?.title || "信息丢失" + obj.origin_reserve_id = ditem?.orig?.modules?.module_dynamic?.additional?.reserve?.rid || 0; + obj.origin_reserve_lottery_text = ditem?.orig?.modules?.module_dynamic?.additional?.reserve?.title || '信息丢失'; /* 充电抽奖 */ - if (ditem?.orig?.modules?.module_dynamic?.additional?.type === "ADDITIONAL_TYPE_UPOWER_LOTTERY") { - obj.origin_is_charge_lottery = true + if (ditem?.orig?.modules?.module_dynamic?.additional?.type === 'ADDITIONAL_TYPE_UPOWER_LOTTERY') { + obj.origin_is_charge_lottery = true; } /* 是否有官方抽奖 */ - obj.origin_hasOfficialLottery = false + obj.origin_hasOfficialLottery = false; /* 转发描述 */ - obj.origin_description = "" + obj.origin_description = ''; ditem?.orig?.modules?.module_dynamic?.desc?.rich_text_nodes.forEach(node => { /* 是否有官方抽奖 */ - if (node.type === "RICH_TEXT_NODE_TYPE_LOTTERY") { - obj.origin_hasOfficialLottery = true + if (node.type === 'RICH_TEXT_NODE_TYPE_LOTTERY') { + obj.origin_hasOfficialLottery = true; } - obj.origin_description += node.orig_text - }) + obj.origin_description += node.orig_text; + }); } } catch (e) { - log.error("动态卡片解析", e) + log.error('动态卡片解析', e); } - return obj + return obj; } /** @@ -190,7 +190,7 @@ function oldParseDynamicCard(dynamic_detail_card) { /**临时储存单个动态中的信息 */ let obj = {}; try { - const { desc, card, extension, extend_json = "{}", display = {} } = dynamic_detail_card + const { desc, card, extension, extend_json = '{}', display = {} } = dynamic_detail_card , { is_liked = 1, user_profile = {} } = desc , { info = {} } = user_profile || {} , cardToJson = strToJson(card) @@ -199,15 +199,15 @@ function oldParseDynamicCard(dynamic_detail_card) { , { item } = cardToJson; const dy_type2chat_type = new Map([[1, 17], [2, 11], [4, 17], [8, 1], [64, 12]]); /* 转发者的UID */ - obj.uid = desc.uid + obj.uid = desc.uid; /* 转发者的name */ - obj.uname = info.uname || '' + obj.uname = info.uname || ''; /* 动态是否点过赞 */ - obj.is_liked = is_liked > 0 + obj.is_liked = is_liked > 0; /* 动态的ts10 */ - obj.create_time = desc.timestamp + obj.create_time = desc.timestamp; /* 动态类型 */ - obj.type = desc.type + obj.type = desc.type; /* 用于发送评论 */ obj.rid_str = desc.rid_str.length > 12 ? desc.dynamic_id_str : desc.rid_str; /* 用于发送评论 */ @@ -231,16 +231,16 @@ function oldParseDynamicCard(dynamic_detail_card) { obj.reserve_lottery_text = text; } } - if (extendjsonToJson[""]) { - let r = extendjsonToJson[""].reserve || {}; + if (extendjsonToJson['']) { + let r = extendjsonToJson[''].reserve || {}; let { reserve_id, reserve_lottery } = r; if (reserve_lottery === 1) { - obj.reserve_id = reserve_id + ""; - obj.reserve_lottery_text = "信息丢失"; + obj.reserve_id = reserve_id + ''; + obj.reserve_lottery_text = '信息丢失'; } } if (extend_json.match(/"":\{"lottery/)) { - obj.is_charge_lottery = true + obj.is_charge_lottery = true; } /* 是否有官方抽奖 */ obj.hasOfficialLottery = extension && extension.lott && true; @@ -255,7 +255,7 @@ function oldParseDynamicCard(dynamic_detail_card) { || ''; /* 转发 */ if (obj.type === 1) { - const { origin_extension, origin, origin_extend_json = "{}" } = cardToJson + const { origin_extension, origin, origin_extend_json = '{}' } = cardToJson , originToJson = strToJson(origin) , { add_on_card_info = [] } = display.origin || {} , originExtendjsonToJson = strToJson(origin_extend_json) @@ -265,11 +265,11 @@ function oldParseDynamicCard(dynamic_detail_card) { /* 被转发者的UID */ obj.origin_uid = desc.origin.uid; /* 源动态类型 */ - obj.origin_type = desc.orig_type + obj.origin_type = desc.orig_type; /* 被转发者的rid(用于发评论) */ obj.origin_rid_str = desc.origin.rid_str.length > 12 ? desc.origin.dynamic_id_str : desc.origin.rid_str; /* 用于发送评论 */ - obj.origin_chat_type = dy_type2chat_type.get(obj.origin_type) || 0 + obj.origin_chat_type = dy_type2chat_type.get(obj.origin_type) || 0; /* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */ obj.origin_dynamic_id = desc.orig_dy_id_str; /* 预约抽奖信息 */ @@ -287,16 +287,16 @@ function oldParseDynamicCard(dynamic_detail_card) { obj.origin_reserve_lottery_text = text; } } - if (originExtendjsonToJson[""]) { - let r = originExtendjsonToJson[""].reserve || {}; + if (originExtendjsonToJson['']) { + let r = originExtendjsonToJson[''].reserve || {}; let { reserve_id, reserve_lottery } = r; if (reserve_lottery === 1) { - obj.origin_reserve_id = reserve_id + ""; - obj.origin_reserve_lottery_text = "信息丢失"; + obj.origin_reserve_id = reserve_id + ''; + obj.origin_reserve_lottery_text = '信息丢失'; } } if (origin_extend_json.match(/"":\{"lottery/)) { - obj.origin_is_charge_lottery = true + obj.origin_is_charge_lottery = true; } /* 是否有官方抽奖 */ obj.origin_hasOfficialLottery = origin_extension && origin_extension.lott; @@ -309,10 +309,10 @@ function oldParseDynamicCard(dynamic_detail_card) { || ''; } } catch (e) { - log.error("动态卡片解析", e) + log.error('动态卡片解析', e); } - return obj + return obj; } /** @@ -331,11 +331,11 @@ function modifyDynamicRes(res) { } if (cards == null || !cards || !cards.length) { - log.warn('处理动态数据', '未找到任何动态信息') + log.warn('处理动态数据', '未找到任何动态信息'); } - if (typeof has_more === "undefined" - && typeof offset === "undefined") { + if (typeof has_more === 'undefined' + && typeof offset === 'undefined') { log.error('处理动态数据', '该功能已失效'); return null; } @@ -355,14 +355,14 @@ function modifyDynamicRes(res) { */ array = next.has_more === 0 ? [] - : cards.map(oldParseDynamicCard) + : cards.map(oldParseDynamicCard); log.info('处理动态数据', `动态数据读取完毕(${cards.length})(${next.has_more})`); return { modifyDynamicResArray: array, nextinfo: next - } + }; } /** @@ -405,7 +405,7 @@ class Searcher { mDRdata = modifyDynamicRes(OneDynamicInfo); if (mDRdata === null) { - return null + return null; } const @@ -417,7 +417,7 @@ class Searcher { if (nextinfo.has_more === 0) { offset = nextinfo.next_offset; - log.info('检查所有动态', `已经是最后一页了故无法读取更多`); + log.info('检查所有动态', '已经是最后一页了故无法读取更多'); break; } else { /**合并 */ @@ -428,7 +428,7 @@ class Searcher { await utils.delay(time); } - log.info('检查所有动态', `${pages}页信息读取完成`) + log.info('检查所有动态', `${pages}页信息读取完成`); return ({ allModifyDynamicResArray, offset }); } @@ -443,7 +443,7 @@ class Searcher { log.info('获取动态', `开始获取用户${UID}的动态信息`); const AllDynamic = await Searcher.checkAllDynamic(UID, uid_scan_page, search_wait); - if (AllDynamic === null) return null + if (AllDynamic === null) return null; let { allModifyDynamicResArray } = AllDynamic, { length } = allModifyDynamicResArray; @@ -453,10 +453,10 @@ class Searcher { const fomatdata = await allModifyDynamicResArray .filter(d => { if (d.type === 1) { - return true + return true; } else { - length-- - return false + length--; + return false; } }) .reduce(async (pre, cur) => { @@ -466,12 +466,12 @@ class Searcher { is_liked = false; if (!check_if_duplicated || check_if_duplicated >= 2) { - const card = await bili.getOneDynamicByDyid(origin_dynamic_id) - log.info('获取动态', `查看源动态(${origin_dynamic_id})是否点赞 (${length--})`) + const card = await bili.getOneDynamicByDyid(origin_dynamic_id); + log.info('获取动态', `查看源动态(${origin_dynamic_id})是否点赞 (${length--})`); if (card) { - ({ is_liked } = parseDynamicCard(card)) + ({ is_liked } = parseDynamicCard(card)); } - await utils.delay(get_dynamic_detail_wait) + await utils.delay(get_dynamic_detail_wait); } results.push({ @@ -490,10 +490,10 @@ class Searcher { des: cur.origin_description, type: cur.origin_type, hasOfficialLottery: cur.origin_hasOfficialLottery - }) + }); - return results - }, Promise.resolve([])) + return results; + }, Promise.resolve([])); log.info('获取动态', `成功获取用户${UID}的动态信息`); @@ -555,10 +555,10 @@ class Searcher { type: o.type, hasOfficialLottery: o.hasOfficialLottery }; - }) + }); log.info('获取动态', `成功获取带话题#${tag_name}#的动态信息`); - return fomatdata + return fomatdata; } /** @@ -576,11 +576,11 @@ class Searcher { for (const { id, pub_time } of cvs) { let now_time = Math.floor(Date.now() / 1000); if ((now_time - pub_time) / 86400 > article_create_time) { - log.warn("获取动态", `该专栏(${id})创建时间大于设定天数(${article_create_time}天)`) - continue + log.warn('获取动态', `该专栏(${id})创建时间大于设定天数(${article_create_time}天)`); + continue; } const - content = (await bili.getOneArticleByCv(id) || "").split("推荐文章")[0], + content = (await bili.getOneArticleByCv(id) || '').split('推荐文章')[0], dyids = content.match(/[0-9]{18}/g) || [], short_ids = content.match(/(?<=b23.tv\/)[a-zA-Z0-9]{7}/g) || [], short_id_set = [...new Set(short_ids)], @@ -594,18 +594,18 @@ class Searcher { _weight = 0, /**单个专栏中的dyid */ _dyinfos = []; - log.info('获取动态', `提取专栏(${id})中提及的dyid(${length})`) + log.info('获取动态', `提取专栏(${id})中提及的dyid(${length})`); /**遍历某专栏中的dyids */ for (const dyid of dyid_set) { - if (typeof dyid === "string" + if (typeof dyid === 'string' && dyid.length === utils.dyid_length) { - log.info('获取动态', `查看专栏中所提及动态(${dyid}) (${length--})`) - const card = await bili.getOneDynamicByDyid(dyid) + log.info('获取动态', `查看专栏中所提及动态(${dyid}) (${length--})`); + const card = await bili.getOneDynamicByDyid(dyid); if (card) { - await utils.delay(get_dynamic_detail_wait) + await utils.delay(get_dynamic_detail_wait); const parsed_card = parseDynamicCard(card) , { is_liked } = parsed_card; @@ -616,23 +616,23 @@ class Searcher { || ((check_if_duplicated >= 1) && await d_storage.searchDyid(dyid)) ) { - log.info('获取动态', `动态(${dyid})已转发过`) + log.info('获取动态', `动态(${dyid})已转发过`); _weight += 1; } if (_weight >= weight && !not_check_article) { - log.warn('获取动态', `1/2动态曾经转过,该专栏或已查看,故中止`) - _dyinfos = [] - break + log.warn('获取动态', '1/2动态曾经转过,该专栏或已查看,故中止'); + _dyinfos = []; + break; } _dyinfos.push(parsed_card); } } else { - log.warn('获取动态', `动态(${dyid})无效 (${length--})`) + log.warn('获取动态', `动态(${dyid})无效 (${length--})`); } } - dyinfos.push(..._dyinfos) + dyinfos.push(..._dyinfos); } const fomatdata = dyinfos.map(o => { return { @@ -652,10 +652,10 @@ class Searcher { type: o.type, hasOfficialLottery: o.hasOfficialLottery }; - }) + }); log.info('获取动态', `成功获取含关键词${key_words}的专栏信息`); - return fomatdata + return fomatdata; } /** @@ -667,9 +667,9 @@ class Searcher { return new Promise((resolve) => { if (api) { const { strToJson } = utils; - log.info('获取动态', `开始获取链接(${api})中的抽奖信息`) - if (api.startsWith("file://")) { - utils.readLotteryInfoFile(api.substring(7)).then(resolve) + log.info('获取动态', `开始获取链接(${api})中的抽奖信息`); + if (api.startsWith('file://')) { + utils.readLotteryInfoFile(api.substring(7)).then(resolve); } else { send({ url: api, @@ -679,8 +679,8 @@ class Searcher { method: 'GET', success: ({ body }) => { if (body.err_msg) { - log.error("从API响应数据中获取抽奖信息", body.err_msg) - resolve(null) + log.error('从API响应数据中获取抽奖信息', body.err_msg); + resolve(null); } else { const raw_lottery_info = strToJson(body).lottery_info; @@ -693,46 +693,46 @@ class Searcher { , { dyid } = cur; if (!check_if_duplicated || check_if_duplicated >= 2) { - log.info('获取动态', `查看动态(${dyid})是否点赞 (${length--})`) - const card = await bili.getOneDynamicByDyid(dyid) + log.info('获取动态', `查看动态(${dyid})是否点赞 (${length--})`); + const card = await bili.getOneDynamicByDyid(dyid); if (card) { - await utils.delay(get_dynamic_detail_wait) + await utils.delay(get_dynamic_detail_wait); - const { is_liked } = parseDynamicCard(card) + const { is_liked } = parseDynamicCard(card); if (is_liked) { - log.info('获取动态', `动态(${dyid})已转发过`) + log.info('获取动态', `动态(${dyid})已转发过`); } else { - cur.is_liked = is_liked - results.push(cur) + cur.is_liked = is_liked; + results.push(cur); } } } else { - results.push(cur) + results.push(cur); } - return results + return results; - }, Promise.resolve([])) + }, Promise.resolve([])); - resolve(lottery_info) - return + resolve(lottery_info); + return; } } - log.error("从API响应数据中获取抽奖信息", "非Json数据或没有lottery_info或lottery为空") - resolve(null) + log.error('从API响应数据中获取抽奖信息', '非Json数据或没有lottery_info或lottery为空'); + resolve(null); } }, failure: err => { - log.error("从API响应数据中获取抽奖信息", err) - resolve(null) + log.error('从API响应数据中获取抽奖信息', err); + resolve(null); } - }) + }); } } else { - log.warn('获取动态', `链接为空`) - resolve(null) + log.warn('获取动态', '链接为空'); + resolve(null); } }); } @@ -750,14 +750,14 @@ class Searcher { dyinfos = []; for (const dyid of dyids) { - if (typeof dyid === "string" + if (typeof dyid === 'string' && dyid.length === utils.dyid_length) { - log.info('获取动态', `查看Txt中所提及动态(${dyid}) (${length--})`) - const card = await bili.getOneDynamicByDyid(dyid) + log.info('获取动态', `查看Txt中所提及动态(${dyid}) (${length--})`); + const card = await bili.getOneDynamicByDyid(dyid); if (card) { - await utils.delay(get_dynamic_detail_wait) + await utils.delay(get_dynamic_detail_wait); const parsed_card = parseDynamicCard(card) , { is_liked } = parsed_card; @@ -768,14 +768,14 @@ class Searcher { || ((check_if_duplicated >= 1) && await d_storage.searchDyid(dyid)) ) { - log.info('获取动态', `动态(${dyid})已转发过`) - continue + log.info('获取动态', `动态(${dyid})已转发过`); + continue; } dyinfos.push(parsed_card); } } else { - log.warn('获取动态', `动态(${dyid})无效 (${length--})`) + log.warn('获取动态', `动态(${dyid})无效 (${length--})`); } } const fomatdata = dyinfos.map(o => { @@ -796,10 +796,10 @@ class Searcher { type: o.type, hasOfficialLottery: o.hasOfficialLottery }; - }) - log.info('获取动态', `成功获取txt信息`); + }); + log.info('获取动态', '成功获取txt信息'); - return fomatdata + return fomatdata; } } diff --git a/lib/data/config.js b/lib/data/config.js index d4390c1c7f..dc7e824406 100644 --- a/lib/data/config.js +++ b/lib/data/config.js @@ -75,15 +75,15 @@ const config = { * API发送数据类型 {LotteryInfo[]} * 上传抽奖信息的链接字符串 */ - set_lottery_info_url: "", + set_lottery_info_url: '', /** * 动态中的关键词(表示须同时满足以下条件) * 符合js正则表达式的字符串 */ key_words: [ - "[抽奖送揪]|福利", - "[转关评粉]|参与" + '[抽奖送揪]|福利', + '[转关评粉]|参与' ], /** @@ -308,7 +308,7 @@ const config = { /** * 屏蔽词 */ - blockword: ["脚本", "抽奖号", "钓鱼"], + blockword: ['脚本', '抽奖号', '钓鱼'], /** * 转发并评论 @@ -370,10 +370,10 @@ const config = { * - 优先级递增 */ notice_key_words: [ - "~预约成功|预约主题", - "中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员", - "~你的账号在新设备或平台登录成功", - "~你预约的直播已开始" + '~预约成功|预约主题', + '中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员', + '~你的账号在新设备或平台登录成功', + '~你预约的直播已开始' ], /** @@ -457,23 +457,23 @@ const config = { */ raw_config() { delete require.cache[config_file]; - return require(config_file) + return require(config_file); }, /** * @param {string} n */ updata(n) { - this.init() - this.setObject(this.raw_config()[`config_${n}`]) + this.init(); + this.setObject(this.raw_config()[`config_${n}`]); }, init() { - this.setObject(this.raw_config()["default_config"]) + this.setObject(this.raw_config()['default_config']); }, setObject(o = {}) { - Object.entries(o).forEach(([k, v]) => this[k] = v) + Object.entries(o).forEach(([k, v]) => this[k] = v); } }; diff --git a/lib/data/env.js b/lib/data/env.js index e3e677150e..992898a8d7 100644 --- a/lib/data/env.js +++ b/lib/data/env.js @@ -1,4 +1,4 @@ -const { env_file } = require("../utils"); +const { env_file } = require('../utils'); const env = { /** @@ -7,28 +7,28 @@ const env = { */ raw_env() { delete require.cache[env_file]; - return require(env_file) + return require(env_file); }, init() { - const raw_env = this.raw_env() + const raw_env = this.raw_env(); this.setEnv({ - ...raw_env["account_parm"], - ...raw_env["push_parm"] - }) + ...raw_env['account_parm'], + ...raw_env['push_parm'] + }); }, /** * @returns {Object[]} */ get_multiple_account() { - return this.raw_env()["multiple_account_parm"] + return this.raw_env()['multiple_account_parm']; }, setEnv(o) { process.env = { ...process.env, ...o - } + }; } -} +}; module.exports = env; \ No newline at end of file diff --git a/lib/data/global_var.js b/lib/data/global_var.js index ee45c3b757..b1b0cb5094 100644 --- a/lib/data/global_var.js +++ b/lib/data/global_var.js @@ -1,13 +1,13 @@ -const { getRandomOne, createDir, createFile, dyids_dir } = require("../utils"); -const config = require("../data/config"); +const { getRandomOne, createDir, createFile, dyids_dir } = require('../utils'); +const config = require('../data/config'); let global_var = { inner: {}, get(key) { - return this.inner[key] + return this.inner[key]; }, set(key, value) { - this.inner[key] = value + this.inner[key] = value; }, /** * 全局变量初始化 @@ -22,28 +22,28 @@ let global_var = { ['DedeUserID', 'myUID'], ['bili_jct', 'csrf']]), LotteryOrderMap = new Map([ - [0, "UIDs"], - [1, "TAGs"], - [2, "Articles"], - [3, "APIs"], - [4, "TxT"], + [0, 'UIDs'], + [1, 'TAGs'], + [2, 'Articles'], + [3, 'APIs'], + [4, 'TxT'], ]); config.updata(num); if (!/buvid3/.test(cookie)) { - const charset = "0123456789ABCDEF".split(""); - const buvid3 = "x".repeat(8).split("").map(() => getRandomOne(charset)).join("") - + "-" - + "x".repeat(4).split("").map(() => getRandomOne(charset)).join("") - + "-" - + "x".repeat(4).split("").map(() => getRandomOne(charset)).join("") - + "-" - + "x".repeat(4).split("").map(() => getRandomOne(charset)).join("") - + "-" - + "x".repeat(17).split("").map(() => getRandomOne(charset)).join("") - + "infoc"; - this.set('cookie', cookie + ";" + buvid3); + const charset = '0123456789ABCDEF'.split(''); + const buvid3 = 'x'.repeat(8).split('').map(() => getRandomOne(charset)).join('') + + '-' + + 'x'.repeat(4).split('').map(() => getRandomOne(charset)).join('') + + '-' + + 'x'.repeat(4).split('').map(() => getRandomOne(charset)).join('') + + '-' + + 'x'.repeat(4).split('').map(() => getRandomOne(charset)).join('') + + '-' + + 'x'.repeat(17).split('').map(() => getRandomOne(charset)).join('') + + 'infoc'; + this.set('cookie', cookie + ';' + buvid3); } else { this.set('cookie', cookie); } @@ -58,13 +58,13 @@ let global_var = { this.set('Lottery', LotteryOrder .map(it => LotteryOrderMap.get(it)) - .filter(it => typeof it === "string") + .filter(it => typeof it === 'string') .map(lottery_option => config[lottery_option].map(it => [lottery_option, it])) .flat() ); } await createDir('dyids'); - await createFile(dyids_dir, num < 2 ? 'dyid.txt' : `dyid${num}.txt`, '', 'a') + await createFile(dyids_dir, num < 2 ? 'dyid.txt' : `dyid${num}.txt`, '', 'a'); } }; diff --git a/lib/helper/d_storage.js b/lib/helper/d_storage.js index c57710a44f..46c54faf17 100644 --- a/lib/helper/d_storage.js +++ b/lib/helper/d_storage.js @@ -1,4 +1,4 @@ -const { log, readDyidFile, writeDyidFile, dyid_length } = require("../utils"); +const { log, readDyidFile, writeDyidFile, dyid_length } = require('../utils'); const d_storage = { /** @@ -13,17 +13,17 @@ const d_storage = { let status = false; rs.on('data', chunk => { if (Rdyid.test(chunk)) { - status = true + status = true; } - }) + }); rs.on('end', () => { - resolve(status) - }) + resolve(status); + }); rs.on('error', err => { - log.error('搜索dyid', err) - resolve(status) - }) - }) + log.error('搜索dyid', err); + resolve(status); + }); + }); }, /** * 更新dyid @@ -32,21 +32,21 @@ const d_storage = { updateDyid: (dyid) => { log.info('更新dyid', `写入${dyid}`); if (dyid.length !== dyid_length) { - log.error('更新dyid', `dyid(${dyid})长度不为18 若出现此问题请即时通知开发者`) + log.error('更新dyid', `dyid(${dyid})长度不为18 若出现此问题请即时通知开发者`); } return new Promise((resolve) => { const ws = writeDyidFile(Number(process.env.NUMBER)); ws.write(dyid + ',', () => { ws.destroy(); - resolve() - }) + resolve(); + }); ws.on('error', err => { - log.error('更新dyid', err) - resolve() - }) + log.error('更新dyid', err); + resolve(); + }); }); } -} +}; module.exports = d_storage; \ No newline at end of file diff --git a/lib/helper/event_bus.js b/lib/helper/event_bus.js index 69cf334d0e..af4e8164cc 100644 --- a/lib/helper/event_bus.js +++ b/lib/helper/event_bus.js @@ -15,11 +15,11 @@ const event_bus = { }, flush() { this.event_list.forEach(event => { - this.ee.removeAllListeners(event) + this.ee.removeAllListeners(event); }); this.event_list = []; } -} +}; module.exports = event_bus; diff --git a/lib/helper/notify.js b/lib/helper/notify.js index 23bd753ddf..3ebe504f40 100644 --- a/lib/helper/notify.js +++ b/lib/helper/notify.js @@ -1,6 +1,6 @@ -const { log } = require("../utils"); -const { send } = require("../net/http"); -const { createTransport } = require("nodemailer"); +const { log } = require('../utils'); +const { send } = require('../net/http'); +const { createTransport } = require('nodemailer'); // =======================================微信server酱通知设置区域=========================================== //此处填你申请的SCKEY. @@ -107,24 +107,24 @@ if (process.env.QQ_MODE) { if (process.env.BARK_PUSH) { if (process.env.BARK_PUSH.indexOf('https') > -1 || process.env.BARK_PUSH.indexOf('http') > -1) { //兼容BARK自建用户 - BARK_PUSH = process.env.BARK_PUSH + BARK_PUSH = process.env.BARK_PUSH; } else { - BARK_PUSH = `https://api.day.app/${process.env.BARK_PUSH}` + BARK_PUSH = `https://api.day.app/${process.env.BARK_PUSH}`; } if (process.env.BARK_SOUND) { - BARK_SOUND = process.env.BARK_SOUND + BARK_SOUND = process.env.BARK_SOUND; } } else { if (BARK_PUSH && BARK_PUSH.indexOf('https') === -1 && BARK_PUSH.indexOf('http') === -1) { //兼容BARK本地用户只填写设备码的情况 - BARK_PUSH = `https://api.day.app/${BARK_PUSH}` + BARK_PUSH = `https://api.day.app/${BARK_PUSH}`; } } if (process.env.PUSHDEER_URL) { - PUSHDEER_URL = process.env.PUSHDEER_URL + PUSHDEER_URL = process.env.PUSHDEER_URL; } else { - PUSHDEER_URL = "https://api2.pushdeer.com/message/push"; + PUSHDEER_URL = 'https://api2.pushdeer.com/message/push'; } if (process.env.PUSHDEER_PUSHKEY) { @@ -163,7 +163,7 @@ if (process.env.QYWX_KEY) { } if (process.env.IGOT_PUSH_KEY) { - IGOT_PUSH_KEY = process.env.IGOT_PUSH_KEY + IGOT_PUSH_KEY = process.env.IGOT_PUSH_KEY; } if (process.env.PUSH_PLUS_TOKEN) { @@ -200,7 +200,7 @@ if (process.env.SMTP_TO_USER) { if (process.env.GOTIFY_URL) { GOTIFY_URL = process.env.GOTIFY_URL; if (process.env.GOTIFY_APPKEY) { - GOTIFY_APPKEY = process.env.GOTIFY_APPKEY + GOTIFY_APPKEY = process.env.GOTIFY_APPKEY; } } @@ -208,7 +208,7 @@ if (process.env.GOTIFY_URL) { async function sendNotify(text, desp, params = {}) { if (process.env.NOTE) { - desp = `帐号备注: ${process.env.NOTE}\n${desp}` + desp = `帐号备注: ${process.env.NOTE}\n${desp}`; } //提供多种通知方式 await Promise.all([ @@ -240,7 +240,7 @@ async function sendNotify(text, desp, params = {}) { email(text, desp), // Gotify gotifyNotify(text, desp) - ]) + ]); } function serverNotify(text, desp) { @@ -263,29 +263,29 @@ function serverNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.errno === 0) { - log.info('发送通知', 'server酱发送通知消息成功') + log.info('发送通知', 'server酱发送通知消息成功'); } else if (data.errno === 1024) { // 一分钟内发送相同的内容会触发 - log.error('发送通知', `server酱发送通知消息异常: ${data.errmsg}`) + log.error('发送通知', `server酱发送通知消息异常: ${data.errmsg}`); } else { - log.error('发送通知', `server酱发送通知消息异常\n${JSON.stringify(data)}`) + log.error('发送通知', `server酱发送通知消息异常\n${JSON.stringify(data)}`); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { - log.error('发送通知', 'server酱 发送通知调用API失败!!' + err) - resolve() + log.error('发送通知', 'server酱 发送通知调用API失败!!' + err); + resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供server酱的SCKEY,取消微信推送消息通知'); - resolve() + resolve(); } - }) + }); } function serverNotifyTurbo(text, desp) { @@ -308,26 +308,26 @@ function serverNotifyTurbo(text, desp) { try { const data = JSON.parse(res.body); if (data.code === 0) { - log.info('发送通知', 'server酱(Turbo版)发送通知消息成功') + log.info('发送通知', 'server酱(Turbo版)发送通知消息成功'); } else { - log.error('发送通知', `server酱(Turbo版)发送通知消息异常\n${JSON.stringify(data)}`) + log.error('发送通知', `server酱(Turbo版)发送通知消息异常\n${JSON.stringify(data)}`); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { - log.error('发送通知', 'server酱(Turbo版) 发送通知调用API失败!!' + err) - resolve() + log.error('发送通知', 'server酱(Turbo版) 发送通知调用API失败!!' + err); + resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供server酱(Turbo版)的SCKEY,取消微信推送消息通知'); - resolve() + resolve(); } - }) + }); } function coolPush(text, desp) { @@ -335,18 +335,18 @@ function coolPush(text, desp) { if (QQ_SKEY) { let pushMode = function (t) { switch (t) { - case "send": - return "个人"; - case "group": - return "QQ群"; - case "wx": - return "微信"; - case "ww": - return "企业微信"; + case 'send': + return '个人'; + case 'group': + return 'QQ群'; + case 'wx': + return '微信'; + case 'ww': + return '企业微信'; default: - return "未知方式" + return '未知方式'; } - } + }; send({ method: 'POST', url: `https://push.xuthus.cc/${QQ_MODE}/${QQ_SKEY}`, @@ -356,34 +356,34 @@ function coolPush(text, desp) { }, headers: { accept: 'application/json, text/plain, */*', - "content-type": "text/plain" + 'content-type': 'text/plain' }, success: res => { try { const data = JSON.parse(res.body); if (data.code === 200) { - log.info('发送通知', `酷推发送${pushMode(QQ_MODE)}通知消息成功`) + log.info('发送通知', `酷推发送${pushMode(QQ_MODE)}通知消息成功`); } else if (data.code === 400) { - log.error('发送通知', `QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}`) + log.error('发送通知', `QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}`); } else { log.error('发送通知', `酷推推送异常: ${data.msg}`); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { - log.error('发送通知', `酷推 发送${pushMode(QQ_MODE)}通知调用API失败!!${err}`) - resolve() + log.error('发送通知', `酷推 发送${pushMode(QQ_MODE)}通知调用API失败!!${err}`); + resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供酷推的SKEY,取消QQ推送消息通知'); - resolve() + resolve(); } - }) + }); } function barkNotify(text, desp, params = {}) { @@ -406,26 +406,26 @@ function barkNotify(text, desp, params = {}) { try { const data = JSON.parse(res.body); if (data.code === 200) { - log.info('发送通知', 'Bark APP发送通知消息成功') + log.info('发送通知', 'Bark APP发送通知消息成功'); } else { log.error('发送通知', `${data.message}`); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { log.error('发送通知', 'Bark APP发送通知调用API失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知'); - resolve() + resolve(); } - }) + }); } function pushdeerNotify(text, desp) { @@ -438,7 +438,7 @@ function pushdeerNotify(text, desp) { pushkey: PUSHDEER_PUSHKEY, text, desp, - type: "markdown" + type: 'markdown' }, config: { retry: false @@ -447,26 +447,26 @@ function pushdeerNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.code === 0) { - log.info('发送通知', 'Pushdeer推送发送通知消息成功') + log.info('发送通知', 'Pushdeer推送发送通知消息成功'); } else { - log.error('发送通知', `Pushdeer推送发送通知消息异常\n${JSON.stringify(data)}`) + log.error('发送通知', `Pushdeer推送发送通知消息异常\n${JSON.stringify(data)}`); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { - log.error('发送通知', 'Pushdeer推送发送通知调用API失败!!' + err) - resolve() + log.error('发送通知', 'Pushdeer推送发送通知调用API失败!!' + err); + resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供Pushdeer推送所需的PUSHDEER_URL 和 PUSHDEER_PUSHKEY, 取消Pushdeer推送消息通知'); - resolve() + resolve(); } - }) + }); } function tgBotNotify(text, desp) { @@ -492,35 +492,35 @@ function tgBotNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.ok) { - log.info('发送通知', 'Telegram发送通知消息完成。') + log.info('发送通知', 'Telegram发送通知消息完成。'); } else if (data.error_code === 400) { - log.error('发送通知', '请主动给bot发送一条消息并检查接收用户ID是否正确。') + log.error('发送通知', '请主动给bot发送一条消息并检查接收用户ID是否正确。'); } else if (data.error_code === 401) { - log.error('发送通知', 'Telegram bot token 填写错误。') + log.error('发送通知', 'Telegram bot token 填写错误。'); } } catch (error) { log.error('发送通知', error); } finally { - resolve() + resolve(); } }, failure: err => { - log.error('发送通知', 'telegram发送通知消息失败!!' + err) - resolve() + log.error('发送通知', 'telegram发送通知消息失败!!' + err); + resolve(); } - } + }; if (TG_PROXY_HOST && TG_PROXY_PORT) { options.proxy = { - url: "http://" + TG_PROXY_HOST + ":" + TG_PROXY_PORT, + url: 'http://' + TG_PROXY_HOST + ':' + TG_PROXY_PORT, auth_headers: [] - } + }; } - send(options) + send(options); } else { log.debug('发送通知', '您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知'); - resolve() + resolve(); } - }) + }); } function ddBotNotify(text, desp) { @@ -533,7 +533,7 @@ function ddBotNotify(text, desp) { const result = encodeURIComponent(hmac.digest().toString('base64')); send({ method: 'POST', - url: `https://oapi.dingtalk.com/robot/send`, + url: 'https://oapi.dingtalk.com/robot/send', query: { access_token: DD_BOT_TOKEN, timestamp: dateNow, @@ -543,7 +543,7 @@ function ddBotNotify(text, desp) { retry: false }, contents: { - msgtype: "text", + msgtype: 'text', text: { content: `${text}\n\n${desp}` } @@ -556,9 +556,9 @@ function ddBotNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.errcode === 0) { - log.info('发送通知', '钉钉发送通知消息完成。') + log.info('发送通知', '钉钉发送通知消息完成。'); } else { - log.error('发送通知', `${data.errmsg}`) + log.error('发送通知', `${data.errmsg}`); } } catch (e) { log.error('发送通知', e); @@ -567,14 +567,14 @@ function ddBotNotify(text, desp) { } }, failure: err => { - log.error('发送通知', '钉钉发送通知消息失败!!' + err) - resolve() + log.error('发送通知', '钉钉发送通知消息失败!!' + err); + resolve(); } - }) + }); } else if (DD_BOT_TOKEN) { send({ method: 'POST', - url: `https://oapi.dingtalk.com/robot/send`, + url: 'https://oapi.dingtalk.com/robot/send', query: { access_token: DD_BOT_TOKEN }, @@ -582,7 +582,7 @@ function ddBotNotify(text, desp) { retry: false }, contents: { - msgtype: "text", + msgtype: 'text', text: { content: `${text}\n\n${desp}` } @@ -595,9 +595,9 @@ function ddBotNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.errcode === 0) { - log.info('发送通知', '钉钉发送通知消息完成。') + log.info('发送通知', '钉钉发送通知消息完成。'); } else { - log.error('发送通知', `${data.errmsg}`) + log.error('发送通知', `${data.errmsg}`); } } catch (e) { log.error('发送通知', e); @@ -609,12 +609,12 @@ function ddBotNotify(text, desp) { log.error('发送通知', '钉钉发送通知消息失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知'); - resolve() + resolve(); } - }) + }); } function qywxAmNotify(text, desp) { @@ -623,7 +623,7 @@ function qywxAmNotify(text, desp) { const QYWX_AM_AY = QYWX_AM.split(','); send({ method: 'POST', - url: `https://qyapi.weixin.qq.com/cgi-bin/gettoken`, + url: 'https://qyapi.weixin.qq.com/cgi-bin/gettoken', contents: { corpid: `${QYWX_AM_AY[0]}`, corpsecret: `${QYWX_AM_AY[1]}`, @@ -676,7 +676,7 @@ function qywxAmNotify(text, desp) { log.error('发送通知', '企业微信应用发送通知消息失败!!' + err); resolve(); } - }) + }); } catch (e) { log.error('发送通知', e); } finally { @@ -687,7 +687,7 @@ function qywxAmNotify(text, desp) { log.error('发送通知', '企业微信应用发送通知消息失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供企业微信应用所需的QYWX_AM,取消企业微信应用推送消息通知'); resolve(); @@ -732,7 +732,7 @@ function qywxBotNotify(text, desp) { log.error('发送通知', '企业微信发送通知消息失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知'); resolve(); @@ -744,11 +744,11 @@ function iGotNotify(text, desp, params = {}) { return new Promise(resolve => { if (IGOT_PUSH_KEY) { // 校验传入的IGOT_PUSH_KEY是否有效 - const IGOT_PUSH_KEY_REGX = new RegExp("^[a-zA-Z0-9]{24}$") + const IGOT_PUSH_KEY_REGX = new RegExp('^[a-zA-Z0-9]{24}$'); if (!IGOT_PUSH_KEY_REGX.test(IGOT_PUSH_KEY)) { - log.error('发送通知', '您所提供的IGOT_PUSH_KEY无效') - resolve() - return + log.error('发送通知', '您所提供的IGOT_PUSH_KEY无效'); + resolve(); + return; } send({ method: 'POST', @@ -769,9 +769,9 @@ function iGotNotify(text, desp, params = {}) { try { const data = JSON.parse(res.body); if (data.ret === 0) { - log.info('发送通知', 'iGot发送通知消息成功') + log.info('发送通知', 'iGot发送通知消息成功'); } else { - log.error('发送通知', `iGot发送通知消息失败:${data.errMsg}`) + log.error('发送通知', `iGot发送通知消息失败:${data.errMsg}`); } } catch (e) { log.error('发送通知', e); @@ -780,15 +780,15 @@ function iGotNotify(text, desp, params = {}) { } }, failure: err => { - log.error('发送通知', 'iGot 发送通知调用API失败!!' + err) + log.error('发送通知', 'iGot 发送通知调用API失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知'); - resolve() + resolve(); } - }) + }); } function pushPlusNotify(text, desp) { @@ -814,9 +814,9 @@ function pushPlusNotify(text, desp) { try { const data = JSON.parse(res.body); if (data.code === 200) { - log.info('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息完成。`) + log.info('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息完成。`); } else { - log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}`) + log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}`); } } catch (e) { log.error('发送通知', e); @@ -825,15 +825,15 @@ function pushPlusNotify(text, desp) { } }, failure: err => { - log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败!!${err}`) + log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败!!${err}`); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知'); - resolve() + resolve(); } - }) + }); } function gotifyNotify(text, desp) { @@ -856,19 +856,19 @@ function gotifyNotify(text, desp) { }, success: () => { // HTTP 响应码 200 就说明成功了 - log.info('发送通知', 'Gotify 发送通知消息成功') + log.info('发送通知', 'Gotify 发送通知消息成功'); resolve(); }, failure: err => { - log.error('发送通知', 'Gotify 发送通知调用API失败!!' + err) + log.error('发送通知', 'Gotify 发送通知调用API失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供Gotify推送所需的GOTIFY_APPKEY,取消Gotify推送消息通知'); - resolve() + resolve(); } - }) + }); } async function qmsg(text, desp) { @@ -878,7 +878,7 @@ async function qmsg(text, desp) { method: 'POST', url: 'https://qmsg.zendee.cn/send/' + QMSG_KEY, contents: { - msg: text + "\n\n" + desp, + msg: text + '\n\n' + desp, qq: QMSG_QQ }, config: { @@ -892,9 +892,9 @@ async function qmsg(text, desp) { try { const data = JSON.parse(res.body); if (data.code === 200) { - log.info('发送通知', `qmsg发送通知消息完成。`) + log.info('发送通知', 'qmsg发送通知消息完成。'); } else { - log.error('发送通知', `qmsg通知消息失败: ${data.reason}`) + log.error('发送通知', `qmsg通知消息失败: ${data.reason}`); } } catch (e) { log.error('发送通知', e); @@ -903,15 +903,15 @@ async function qmsg(text, desp) { } }, failure: err => { - log.error('发送通知', `qmsg通知消息失败!!` + err) + log.error('发送通知', 'qmsg通知消息失败!!' + err); resolve(); } - }) + }); } else { log.debug('发送通知', '您未提供qmsg推送所需的QMSG_KEY,取消qmsg推送消息通知'); - resolve() + resolve(); } - }) + }); } async function email(text, desp) { @@ -929,10 +929,10 @@ async function email(text, desp) { to: SMTP_TO_USER, subject: text, text: desp, - }) + }); } catch (e) { log.error('发送通知', `email发送失败 原因: ${e.message}`); - return + return; } log.info('发送通知', 'email发送成功'); } else { @@ -940,4 +940,4 @@ async function email(text, desp) { } } -module.exports = { sendNotify } +module.exports = { sendNotify }; diff --git a/lib/helper/randomDynamic.js b/lib/helper/randomDynamic.js index 2a93bea324..23811aabbd 100644 --- a/lib/helper/randomDynamic.js +++ b/lib/helper/randomDynamic.js @@ -1,6 +1,6 @@ -const config = require("../data/config"); -const bili = require("../net/bili"); -const utils = require("../utils"); +const config = require('../data/config'); +const bili = require('../net/bili'); +const utils = require('../utils'); /** * 随机动态 @@ -8,22 +8,22 @@ const utils = require("../utils"); * @returns */ async function randomDynamic(num) { - let dynamics = [] + let dynamics = []; const { create_dy_type, dy_contents, random_dynamic_wait } = config, hasShareVideo = create_dy_type === -1 || create_dy_type === 1, hasRandomCreate = create_dy_type === -1 || create_dy_type === 0 || typeof create_dy_type === 'undefined'; if (hasShareVideo) { - dynamics = await bili.getTopRcmd() + dynamics = await bili.getTopRcmd(); for (let index = 0; dynamics.length < num; index++) { - dynamics.push(...await bili.getTopRcmd()) + dynamics.push(...await bili.getTopRcmd()); } } if (hasRandomCreate) { for (let index = 0; index < num; index++) { - dynamics.push(utils.getRandomOne(dy_contents)) + dynamics.push(utils.getRandomOne(dy_contents)); } } @@ -31,13 +31,13 @@ async function randomDynamic(num) { utils.shuffle(dynamics).slice(0, num), async (dynamic) => { await utils.delay(random_dynamic_wait); - if (dynamic instanceof Array && dynamic.length === 2 && typeof dynamic[0] === "number") { - await bili.shareVideo(...dynamic) + if (dynamic instanceof Array && dynamic.length === 2 && typeof dynamic[0] === 'number') { + await bili.shareVideo(...dynamic); } else { - await bili.createDynamic(dynamic) + await bili.createDynamic(dynamic); } } - ) + ); } -module.exports = { randomDynamic } \ No newline at end of file +module.exports = { randomDynamic }; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index f345c4fd9b..e672b36ffc 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,10 +2,10 @@ const { login } = require('./login'); const { isMe } = require('./check'); const { clear } = require('./clear'); const { start } = require('./lottery'); -const { account } = require("./account"); -const global_var = require('./data/global_var') -const bili = require('./net/bili') -const { log } = require('./utils') +const { account } = require('./account'); +const global_var = require('./data/global_var'); +const bili = require('./net/bili'); +const { log } = require('./utils'); const { sendNotify } = require('./helper/notify'); /** @@ -13,16 +13,16 @@ const { sendNotify } = require('./helper/notify'); * @param {string} num */ async function checkCookie(num) { - const My_UID = global_var.get("myUID"); + const My_UID = global_var.get('myUID'); if (await bili.getMyinfo()) { log.info('Cookie有效性检测', `成功登录 UID:${My_UID}`); return true; } else { log.error('Cookie有效性检测', `登录失败 COOKIE${num} 已失效 UID:${My_UID}`); - await sendNotify('动态抽奖出错-登录失败', `COOKIE${num} 已失效 UID:${My_UID}`) + await sendNotify('动态抽奖出错-登录失败', `COOKIE${num} 已失效 UID:${My_UID}`); return false; } } -module.exports = { login, start, isMe, clear, checkCookie, account } \ No newline at end of file +module.exports = { login, start, isMe, clear, checkCookie, account }; \ No newline at end of file diff --git a/lib/login.js b/lib/login.js index b55b33102b..784ebd7f18 100644 --- a/lib/login.js +++ b/lib/login.js @@ -1,5 +1,5 @@ const { readFileSync, writeFileSync } = require('fs'); -const { log, env_file } = require("./utils"); +const { log, env_file } = require('./utils'); /** * 扫码登陆 @@ -10,17 +10,17 @@ async function login(num) { const { pcLogin } = require('@catlair/blogin'); const loginInfo = await pcLogin(); if (!loginInfo) { - log.error("扫码登陆", "失败/取消"); + log.error('扫码登陆', '失败/取消'); return; } - log.info("扫码登陆", "登录成功"); + log.info('扫码登陆', '登录成功'); JSON.stringify(loginInfo, null, 2); const uid = `${loginInfo.mid}`; const cookie = `${loginInfo.cookie}`; - log.info("账号UID", uid); - log.info("Cookie", cookie); + log.info('账号UID', uid); + log.info('Cookie', cookie); if (replaceCookie(env_file, uid, cookie)) { - log.info("扫码登陆", `账号${num}已进行cookie自动更新,如未能生效请手动复制在env.js内替换。路径:${env_file}`); + log.info('扫码登陆', `账号${num}已进行cookie自动更新,如未能生效请手动复制在env.js内替换。路径:${env_file}`); } } catch (error) { log.error(error); @@ -41,7 +41,7 @@ function replaceCookie(filePath, uid, oldCK) { const newCK = content.replaceAll(reg, substring => { let quote = substring.at(0) || ''; /['"]/.test(quote) || (quote = ''); - const quote2 = oldCK.includes("'") + const quote2 = oldCK.includes('\'') ? '"' : substring.match(/^['"]?COOKIE['"]?:\s?(['"])/)?.[1] || '"'; return `${quote}COOKIE${quote}: ${quote2}${oldCK}${quote2}`; @@ -50,9 +50,9 @@ function replaceCookie(filePath, uid, oldCK) { writeFileSync(filePath, newCK); return true; } catch (error) { - log.error("扫码登陆", error); + log.error('扫码登陆', error); } return false; } -module.exports = { login } \ No newline at end of file +module.exports = { login }; \ No newline at end of file diff --git a/lib/lottery.js b/lib/lottery.js index b6f5d9cf5f..0d11c1ab16 100644 --- a/lib/lottery.js +++ b/lib/lottery.js @@ -15,11 +15,11 @@ async function createRandomDynamic(num) { { allModifyDynamicResArray } = (await utils.retryfn( 3, [null], - () => Searcher.checkAllDynamic(global_var.get("myUID"), 1) + () => Searcher.checkAllDynamic(global_var.get('myUID'), 1) )) || { allModifyDynamicResArray: [] }, { type, origin_type } = allModifyDynamicResArray[0] || {}; if (type === 1 && origin_type !== 8) { - await randomDynamic(num) + await randomDynamic(num); } else { log.info('随机动态', '已有非抽奖动态故无需创建'); } @@ -36,16 +36,16 @@ function start(num) { let times = utils.counter(); /* 注册事件 */ event_bus.on('Turn_on_the_Monitor', async () => { - const lotterys = global_var.get("Lottery"); + const lotterys = global_var.get('Lottery'); if (lotterys.length === 0) { log.info('抽奖', '抽奖信息为空'); - event_bus.emit('Turn_off_the_Monitor', '抽奖信息为空') + event_bus.emit('Turn_off_the_Monitor', '抽奖信息为空'); return; } if (times.value() === lotterys.length) { log.info('抽奖', '所有动态转发完毕'); times.clear(); - event_bus.emit('Turn_off_the_Monitor', '目前无抽奖信息,过一会儿再来看看吧') + event_bus.emit('Turn_off_the_Monitor', '目前无抽奖信息,过一会儿再来看看吧'); return; } const lottery = lotterys[times.next()]; @@ -63,10 +63,10 @@ function start(num) { await createRandomDynamic(config.create_dy_num); event_bus.flush(); resolve(); - }) + }); event_bus.emit('Turn_on_the_Monitor'); }); } -module.exports = { start } \ No newline at end of file +module.exports = { start }; \ No newline at end of file diff --git a/lib/net/api.bili.js b/lib/net/api.bili.js index f93f8ff665..0133046d3c 100644 --- a/lib/net/api.bili.js +++ b/lib/net/api.bili.js @@ -30,13 +30,13 @@ module.exports = Object.freeze({ SHORTLINK: 'https://b23.tv/{{short_id}}', SPACE_MYINFO: 'https://api.bilibili.com/x/space/myinfo', TAG_INFO: 'https://api.bilibili.com/x/tag/info', - TOP_FEED_RCMD: "https://api.bilibili.com/x/web-interface/index/top/feed/rcmd", - TOP_RCMD: "https://api.bilibili.com/x/web-interface/index/top/rcmd", + TOP_FEED_RCMD: 'https://api.bilibili.com/x/web-interface/index/top/feed/rcmd', + TOP_RCMD: 'https://api.bilibili.com/x/web-interface/index/top/rcmd', TOPIC_SVR_TOPIC_HISTORY: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_history', TOPIC_SVR_TOPIC_NEW: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_new', - V2_REPLAY: "https://api.bilibili.com/x/v2/reply", + V2_REPLAY: 'https://api.bilibili.com/x/v2/reply', WEB_INTERFACE_CARD: 'https://api.bilibili.com/x/web-interface/card', - WEB_INTERFACE_NAV_STAT: "https://api.bilibili.com/x/web-interface/nav/stat", + WEB_INTERFACE_NAV_STAT: 'https://api.bilibili.com/x/web-interface/nav/stat', WEB_INTERFACE_SEARCH_TYPE: 'https://api.bilibili.com/x/web-interface/search/type', X_POLYMER_WEB_DYNAMIC_V1_DETAIL: 'https://api.bilibili.com/x/polymer/web-dynamic/v1/detail', -}) +}); diff --git a/lib/net/bili.js b/lib/net/bili.js index 261da42fac..7273a9f228 100644 --- a/lib/net/bili.js +++ b/lib/net/bili.js @@ -14,15 +14,15 @@ class Line { * @param {(responseText: string) => ResResult} [pub_handler] */ constructor(line_name, requests, pub_handler) { - this.line_name = line_name - this.requests = requests - this.valid_line = 0 - this.switch_times = 0 - if (pub_handler) this.pub_handler = pub_handler + this.line_name = line_name; + this.requests = requests; + this.valid_line = 0; + this.switch_times = 0; + if (pub_handler) this.pub_handler = pub_handler; /** * @type {ResResult} */ - this.res_result = [false, null, ''] + this.res_result = [false, null, '']; } /** @@ -30,13 +30,13 @@ class Line { * @returns {boolean} */ switchLine() { - const { valid_line, requests: { length }, switch_times } = this - this.valid_line = (valid_line + 1) % length - this.switch_times += 1 + const { valid_line, requests: { length }, switch_times } = this; + this.valid_line = (valid_line + 1) % length; + this.switch_times += 1; if (switch_times > length) { - return false + return false; } else { - return true + return true; } } @@ -45,8 +45,8 @@ class Line { * @param {number} line */ storeLine(line) { - this.valid_line = line - this.switch_times = 0 + this.valid_line = line; + this.switch_times = 0; } /** @@ -59,24 +59,24 @@ class Line { { line_name, requests, valid_line } = this, resp = await requests[valid_line](...args); if (typeof resp === 'string') { - this.res_result = this.pub_handler(resp) + this.res_result = this.pub_handler(resp); } else { - this.res_result = resp + this.res_result = resp; } - const [i_switch, value, msg] = this.res_result + const [i_switch, value, msg] = this.res_result; if (!i_switch) { - log.info(line_name, msg) - this.storeLine(valid_line) - return value + log.info(line_name, msg); + this.storeLine(valid_line); + return value; } if (this.switchLine()) { - log.warn(line_name, msg) - log.warn(line_name, `切换线路(${valid_line + 1}/${requests.length})`) - return await this.run() + log.warn(line_name, msg); + log.warn(line_name, `切换线路(${valid_line + 1}/${requests.length})`); + return await this.run(); } else { - log.error(line_name, msg) - log.error(line_name, '所有备用线路均连接失败') - return value + log.error(line_name, msg); + log.error(line_name, '所有备用线路均连接失败'); + return value; } } } @@ -93,15 +93,15 @@ function get({ url, config, contents, query }) { method: 'GET', config, headers: { - "accept": 'application/json, text/plain, */*', - "cookie": GlobalVar.get("cookie") + 'accept': 'application/json, text/plain, */*', + 'cookie': GlobalVar.get('cookie') }, query, contents, success: res => resolve(res.body), failure: err => resolve(err) - }) - }) + }); + }); } /** @@ -116,16 +116,16 @@ function post({ url, config, contents, query }) { method: 'POST', config, headers: { - "accept": 'application/json, text/plain, */*', - "content-type": 'application/x-www-form-urlencoded; charset=UTF-8', - "cookie": GlobalVar.get("cookie") + 'accept': 'application/json, text/plain, */*', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'cookie': GlobalVar.get('cookie') }, query, contents, success: res => resolve(res.body), failure: err => resolve(err) - }) - }) + }); + }); } /** @@ -143,7 +143,7 @@ const bili_client = { }), res = strToJson(responseText); if (res.code === 0) { - GlobalVar.set("myUNAME", res.data.name) + GlobalVar.set('myUNAME', res.data.name); return res.data; } else { return null; @@ -212,7 +212,7 @@ const bili_client = { }), res = strToJson(responseText); if (res.code === 0) { - log.info('获取未读信息', `成功`); + log.info('获取未读信息', '成功'); return res.data; } else { log.error('获取未读信息', `失败\n${responseText}`); @@ -243,11 +243,11 @@ const bili_client = { source: it.item.source_content, uri: it.item.uri, timestamp: it.reply_time - } + }; }); } else { log.error('获取一页回复', '失败'); - return [] + return []; } }, /** @@ -292,7 +292,7 @@ const bili_client = { }); return { has_more, data }; } else if (res.code === 2) { - log.error('获取私信', `API抽风...请再次尝试`); + log.error('获取私信', 'API抽风...请再次尝试'); return { has_more: 0, data: [] }; } else { log.error('获取私信', `失败\n${responseText}`); @@ -316,16 +316,16 @@ const bili_client = { }), res = strToJson(responseText); if (res.code === 0) { - const msgs = res.data.messages + const msgs = res.data.messages; if (msgs instanceof Array) { - log.info('私信细节', `${talker_id}有${size}条未读私信`) - return msgs.filter(it => ![5, 8, 9, 10, 11].includes(it.msg_source)).map(it => it.content).join('\n') + log.info('私信细节', `${talker_id}有${size}条未读私信`); + return msgs.filter(it => ![5, 8, 9, 10, 11].includes(it.msg_source)).map(it => it.content).join('\n'); } else { - log.warn('私信细节', `${talker_id}无私信`) + log.warn('私信细节', `${talker_id}无私信`); } } - log.error('私信细节', `获取失败`) - return '' + log.error('私信细节', '获取失败'); + return ''; }, /** * 获取未读私信数量 @@ -363,8 +363,8 @@ const bili_client = { talker_id, session_type, ack_seqno: msg_seqno, - csrf_token: GlobalVar.get("csrf"), - csrf: GlobalVar.get("csrf") + csrf_token: GlobalVar.get('csrf'), + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -408,9 +408,9 @@ const bili_client = { } }).then(a => { const dyid = (a.match(/[0-9]{18}/) || [])[0]; - log.info("短连接转换", `${short_id} -> ${dyid}`) - return dyid - }) + log.info('短连接转换', `${short_id} -> ${dyid}`); + return dyid; + }); }, _getOneDynamicByDyid: new Line( '获取一个动态的细节', @@ -436,9 +436,9 @@ const bili_client = { { code, data } = res; switch (code) { case 0: - return [false, data, `ok`]; + return [false, data, 'ok']; default: - return [true, undefined, `获取动态数据出错:\n${responseText}`] + return [true, undefined, `获取动态数据出错:\n${responseText}`]; } }), /** @@ -447,7 +447,7 @@ const bili_client = { * @return {Promise} 失败返回undefined */ async getOneDynamicByDyid(dynamic_id) { - return this._getOneDynamicByDyid.run(dynamic_id) + return this._getOneDynamicByDyid.run(dynamic_id); }, /** * 获取一组动态的信息 @@ -460,14 +460,14 @@ const bili_client = { return get({ url: API.DYNAMIC_SVR_SPACE_HISTORY, query: { - visitor_uid: GlobalVar.get("myUID"), + visitor_uid: GlobalVar.get('myUID'), host_uid, offset_dynamic_id, }, config: { retry: false } - }) + }); }, /** * 通过tag名获取tag的id @@ -504,7 +504,7 @@ const bili_client = { query: { topic_id: tagid } - }) + }); }, /** * 获取tag下的最新动态 @@ -522,7 +522,7 @@ const bili_client = { config: { retry: false } - }) + }); }, /** * 搜索专栏 @@ -549,7 +549,7 @@ const bili_client = { return { pub_time: it.pub_time, id: it.id - } + }; }); } catch (error) { log.error('搜索专栏', '失败 原因:\n' + responseText); @@ -569,7 +569,7 @@ const bili_client = { getOneArticleByCv(cv) { return get({ url: API.READ_CV.replace('{{cv}}', cv) - }) + }); }, /** * 获取粉丝数的所有有效方式 @@ -607,7 +607,7 @@ const bili_client = { * @returns {Promise} */ (uid) => get({ - url: "https://tenapi.cn/bilibilifo/", + url: 'https://tenapi.cn/bilibilifo/', query: { uid } @@ -617,7 +617,7 @@ const bili_client = { if (res.code === 0) { return [false, res.data.follower, 'ok']; } else { - return [true, -1, `出错 可能是访问过频繁\n${responseText}`] + return [true, -1, `出错 可能是访问过频繁\n${responseText}`]; } }), /** @@ -626,7 +626,7 @@ const bili_client = { * @returns {Promise} */ getUserInfo(uid) { - return this._getUserInfo.run(uid) + return this._getUserInfo.run(uid); }, /** * 获取开奖信息 @@ -672,7 +672,7 @@ const bili_client = { fid: uid, act: 1, re_src: 0, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), (uid) => post({ @@ -680,7 +680,7 @@ const bili_client = { contents: { type: 1, follow: uid, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), (uid) => post({ @@ -689,26 +689,26 @@ const bili_client = { fids: uid, act: 1, re_src: 1, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }) ], responseText => { const res = strToJson(responseText); switch (res.code) { case 0: - return [false, 0, '关注+1'] + return [false, 0, '关注+1']; case 22002: - return [false, 2, '您已被对方拉入黑名单'] + return [false, 2, '您已被对方拉入黑名单']; case 22003: - return [false, 3, '黑名单用户无法关注'] + return [false, 3, '黑名单用户无法关注']; case 22015: - return [false, 4, '账号异常'] + return [false, 4, '账号异常']; case 22009: - return [false, 5, '关注已达上限'] + return [false, 5, '关注已达上限']; case 22014: - return [false, 6, '已经关注用户,无法重复关注'] + return [false, 6, '已经关注用户,无法重复关注']; default: - return [true, 1, `未知错误\n${responseText}`] + return [true, 1, `未知错误\n${responseText}`]; } }), /** @@ -727,7 +727,7 @@ const bili_client = { * - 已经关注用户 6 */ autoAttention(uid) { - return this._autoAttention.run(uid) + return this._autoAttention.run(uid); }, /** * 移动分区 @@ -743,7 +743,7 @@ const bili_client = { contents: { fids: uid, tagids: tagid, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }); /* 重复移动code also equal 0 */ @@ -771,7 +771,7 @@ const bili_client = { fid: uid, act: 2, re_src: 0, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -799,10 +799,10 @@ const bili_client = { responseText = await post({ url: API.DYNAMIC_LIKE_THUMB, contents: { - uid: GlobalVar.get("myUID"), + uid: GlobalVar.get('myUID'), dynamic_id: dyid, up: 1, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -845,7 +845,7 @@ const bili_client = { async autoRelay(uid, dyid, msg = '转发动态', ctrl = '[]') { const len = msg.length; if (len > 233) { - msg = msg.slice(0, 233 - len) + msg = msg.slice(0, 233 - len); } const responseText = await post({ @@ -858,7 +858,7 @@ const bili_client = { dynamic_id: dyid, content: msg, ctrl, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -890,9 +890,9 @@ const bili_client = { responseText = await post({ url: API.DYNAMIC_MIX_RESERVE_ATTACH_CARD_BUTTON, contents: { - cur_btn_status: "1", + cur_btn_status: '1', reserve_id, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -920,25 +920,25 @@ const bili_client = { async createDynamic(content) { let contents = { - csrf: GlobalVar.get("csrf"), + csrf: GlobalVar.get('csrf'), extension: '{"emoji_type":1,"from":{"emoji_type":1},"flag_cfg":{}}', }, url = ''; if (content instanceof Array) { - url = API.DYNAMIC_SVR_CREATE_DRAW + url = API.DYNAMIC_SVR_CREATE_DRAW; contents = { ...contents, biz: 3, category: 3, pictures: JSON.stringify(content) - } + }; } else { - url = API.DYNAMIC_SVR_CREATE + url = API.DYNAMIC_SVR_CREATE; contents = { ...contents, type: 4, content, - } + }; } const responseText = await post({ url, @@ -946,10 +946,10 @@ const bili_client = { }); if (/^{"code":0/.test(responseText)) { log.info('发布动态', `成功创建一条随机内容的动态\n${JSON.stringify(content)}\n`); - return false + return false; } else { log.error('发布动态', `发布动态失败\n${JSON.stringify(content)}\n${responseText}`); - return true + return true; } }, _getTopRcmd: new Line('获取推荐', [ @@ -964,7 +964,7 @@ const bili_client = { if (res.code === 0) { return [false, res.data.item.map(it => { return [it.owner.mid, it.id]; - }), "成功"]; + }), '成功']; } else { return [true, [], `获取推荐失败\n${responseText}`]; } @@ -974,7 +974,7 @@ const bili_client = { * @returns {Promise>} */ async getTopRcmd() { - return this._getTopRcmd.run() + return this._getTopRcmd.run(); }, /** * 分享视频 @@ -987,26 +987,26 @@ const bili_client = { responseText = await post({ url: API.DYNAMIC_REPOST_SHARE, contents: { - platform: "pc", + platform: 'pc', uid, type: 8, - content: "分享视频", + content: '分享视频', repost_code: 20000, rid: aid, - csrf_token: GlobalVar.get("csrf") + csrf_token: GlobalVar.get('csrf') } }), res = strToJson(responseText); switch (res.code) { case 0: log.info('转发视频', `成功转发视频(av${aid})`); - return false + return false; case 1101015: log.warn('转发视频', `该动态不能转发分享(av${aid})`); - return false + return false; default: log.error('转发视频', `转发失败\n${responseText}`); - return true + return true; } }, /** @@ -1019,7 +1019,7 @@ const bili_client = { url: API.DYNAMIC_SVR_RM_DYNAMIC, contents: { dynamic_id: dyid, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') }, config: { retry: false @@ -1067,7 +1067,7 @@ const bili_client = { type: type, message: msg, code, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), res = strToJson(responseText); @@ -1085,7 +1085,7 @@ const bili_client = { log.error('自动评论', '需要输入验证码'); return res.data.url; case 12035: - log.error('自动评论', `已被对方拉入黑名单`); + log.error('自动评论', '已被对方拉入黑名单'); return 5; case 12053: log.error('自动评论', '黑名单用户无法互动'); @@ -1139,13 +1139,13 @@ const bili_client = { */ async sendChatWithOcr(rid, msg, type) { let need_captcha = false; - let url = ""; + let url = ''; let status = 0; do { if (need_captcha) { const code = await ocr(url); if (code) { - log.info("验证码识别", `${url} -> ${code}`); + log.info('验证码识别', `${url} -> ${code}`); status = await bili_client.sendChat( rid, msg, @@ -1153,11 +1153,11 @@ const bili_client = { code ); if (status === 0) { - need_captcha = false + need_captcha = false; } else if (status === 12) { - need_captcha = true + need_captcha = true; } else { - need_captcha = false + need_captcha = false; } } } else { @@ -1165,12 +1165,12 @@ const bili_client = { rid, msg, type - ) - if (typeof url === "string" - && hasEnv("ENABLE_CHAT_CAPTCHA_OCR")) { - need_captcha = true + ); + if (typeof url === 'string' + && hasEnv('ENABLE_CHAT_CAPTCHA_OCR')) { + need_captcha = true; } else { - status = url + status = url; } } } while (need_captcha); @@ -1194,14 +1194,14 @@ const bili_client = { res = strToJson(responseText); switch (res.code) { case 0: - log.info('查询评论', `成功`); + log.info('查询评论', '成功'); try { const upmid = res.data.upper.mid; return res.data.replies .filter(it => it.mid !== upmid) .map(it => [it.member.uname, it.content.message]); } catch (_) { - return [] + return []; } default: log.error('查询评论', `未知错误\n${responseText}`); @@ -1216,7 +1216,7 @@ const bili_client = { * @returns {Promise} */ async checkMyPartition(name) { - if (!name) name = '此处存放因抽奖临时关注的up' + if (!name) name = '此处存放因抽奖临时关注的up'; const responseText = await get({ url: API.RELATION_TAGS @@ -1256,7 +1256,7 @@ const bili_client = { url: API.RELATION_TAG_CREATE, contents: { tag: partition_name, - csrf: GlobalVar.get("csrf") + csrf: GlobalVar.get('csrf') } }), obj = strToJson(responseText); @@ -1281,7 +1281,7 @@ const bili_client = { responseText = await get({ url: API.RELATION_TAG, query: { - mid: GlobalVar.get("myUID"), + mid: GlobalVar.get('myUID'), tagid: tagid, pn: n, ps: 50 @@ -1303,4 +1303,4 @@ const bili_client = { }; -module.exports = bili_client +module.exports = bili_client; diff --git a/lib/net/http.js b/lib/net/http.js index 9b43559c74..0acd22c5fc 100644 --- a/lib/net/http.js +++ b/lib/net/http.js @@ -69,7 +69,7 @@ function send(detail) { const { method, url, stream, config, proxy, query, contents, headers, success, failure } = detail; const { timeout, wait, retry, redirect, retry_times } = config; const thisURL = new URL(url) - , content = formatContents(headers["content-type"], contents) + , content = formatContents(headers['content-type'], contents) , request = (thisURL.protocol === 'https:') ? https_request : http_request; /** * @type {import("https").RequestOptions} @@ -82,10 +82,10 @@ function send(detail) { path: thisURL.pathname + thisURL.search + thisURL.hash, headers, }; - if (!headers["user-agent"]) options.headers["user-agent"] = DEFAULT_UA; + if (!headers['user-agent']) options.headers['user-agent'] = DEFAULT_UA; if (query) options.path += (thisURL.search ? '&' : '?') + stringify(query); if (content) { - if (!headers["content-type"]) options.headers["content-type"] = DEFAULT_CONTENT_TYPE; + if (!headers['content-type']) options.headers['content-type'] = DEFAULT_CONTENT_TYPE; options.headers['content-length'] = Buffer.byteLength(content, 'utf-8').toString(); } if (proxy) { @@ -93,28 +93,28 @@ function send(detail) { ? new HttpsProxyAgent(proxy.url) : new HttpProxyAgent(proxy.url); for (const ah of proxy.auth_headers) { - options.headers[ah[0]] = ah[1] + options.headers[ah[0]] = ah[1]; } - options.rejectUnauthorized = false + options.rejectUnauthorized = false; } const req = request(options, res => { let protodata = ''; const { statusCode, headers } = res; if (redirect && ~~(statusCode / 100) === 3) { try { - detail.url = new URL(headers.location).href + detail.url = new URL(headers.location).href; } catch (error) { - detail.url = new URL(thisURL.origin + headers.location).href + detail.url = new URL(thisURL.origin + headers.location).href; } console.log(`[重定向]状态码:${statusCode} location:${detail.url}`); - send(detail) - return + send(detail); + return; } if (stream) { - success({ headers: headers, resStream: res }) + success({ headers: headers, resStream: res }); } else { res.setEncoding(DEFAULT_DECODE) - .on('data', chunk => { protodata += chunk }) + .on('data', chunk => { protodata += chunk; }) .on('error', async err => { if (retry && retry_times) { console.log(`[不期待响应]原因:${err.message} 尝试重新请求中...`); @@ -122,18 +122,18 @@ function send(detail) { detail.config.retry_times = retry_times - 1; send(detail); } else { - failure(`[响应错误]${err.message} 响应数据:\n${protodata}`) + failure(`[响应错误]${err.message} 响应数据:\n${protodata}`); } }) .on('end', () => { if (statusCode < 400) { - success({ headers: headers, body: protodata }) + success({ headers: headers, body: protodata }); } else { - res.emit('error', new Error(`HTTP状态码: ${statusCode}`)) + res.emit('error', new Error(`HTTP状态码: ${statusCode}`)); } - }) + }); } - }) + }); req.on('error', async err => { if (retry && retry_times) { console.log(`[请求失败]原因:${err.message} 尝试重新连接中...`); @@ -143,9 +143,9 @@ function send(detail) { } else { failure(`[请求失败]: ${err.message}`); } - }) - req.on('timeout', () => { req.destroy(new Error('请求超时')) }) - req.end(content) + }); + req.on('timeout', () => { req.destroy(new Error('请求超时')); }); + req.end(content); } /** @@ -173,10 +173,10 @@ function setDefault(detail) { stream: false, proxy: '', headers: {}, - success: (res) => { console.log(res.headers) }, - failure: (err) => { console.log(err) }, + success: (res) => { console.log(res.headers); }, + failure: (err) => { console.log(err); }, ...detail - } + }; detail.config = { timeout: DEFAULT_TIMEOUT, wait: DEFAULT_WAIT, @@ -184,7 +184,7 @@ function setDefault(detail) { redirect: DEFAULT_REDIRECT, retry_times: DEFAULT_RETRY_TIMES, ...detail.config - } + }; return detail; } @@ -202,4 +202,4 @@ function delay(time) { } -module.exports = { send } \ No newline at end of file +module.exports = { send }; \ No newline at end of file diff --git a/lib/update.js b/lib/update.js index 65364629df..4932844faf 100644 --- a/lib/update.js +++ b/lib/update.js @@ -1,6 +1,6 @@ -const { send } = require('./net/http') -const { strToJson, download, try_for_each } = require('./utils') -const { version, checkVersion, log } = require('./utils') +const { send } = require('./net/http'); +const { strToJson, download, try_for_each } = require('./utils'); +const { version, checkVersion, log } = require('./utils'); const platform = new Map([ @@ -25,7 +25,7 @@ function getLatestRelease(owner, repo) { send({ url: `https://api.github.com/repos/${owner}/${repo}/releases/latest`, headers: { - "accept": 'application/vnd.github.v3+json' + 'accept': 'application/vnd.github.v3+json' }, config: { retry: false @@ -33,15 +33,15 @@ function getLatestRelease(owner, repo) { success: ({ body }) => { const release = strToJson(body); if (release.tag_name) { - resolve(release) + resolve(release); } else { - reject(body) + reject(body); } }, failure: error => { - reject(error) + reject(error); } - }) + }); }); } @@ -51,7 +51,7 @@ function getLatestRelease(owner, repo) { */ function checkPlatform(releases) { return releases.includes(platform) - && releases.includes(arch) + && releases.includes(arch); } /** @@ -60,40 +60,40 @@ function checkPlatform(releases) { */ async function update(isDdownload) { try { - const { tag_name, assets, body: text } = await getLatestRelease('shanmiteko', 'LotteryAutoScript') + const { tag_name, assets, body: text } = await getLatestRelease('shanmiteko', 'LotteryAutoScript'); if (checkVersion(version) < checkVersion(tag_name)) { const download_url = assets .filter(({ name }) => checkPlatform(name)) - .map(({ browser_download_url }) => browser_download_url) + .map(({ browser_download_url }) => browser_download_url); if (download_url.length) { if (isDdownload) { await try_for_each(download_url.entries(), async ([i, url]) => { - let proxy_url = "https://mirror.ghproxy.com/"; - proxy_url += url - log.warn('自动下载', `切换代理${proxy_url}`) + let proxy_url = 'https://mirror.ghproxy.com/'; + proxy_url += url; + log.warn('自动下载', `切换代理${proxy_url}`); await download(proxy_url, `latest_version${i}.zip`) .catch(async err => { - log.error('自动下载', err) - proxy_url = url - log.warn('自动下载', `使用原始链接${proxy_url}`) - await download(proxy_url, `latest_version${i}.zip`) - }) - return false - }) - log.info('自动下载', '成功下载到当前目录') + log.error('自动下载', err); + proxy_url = url; + log.warn('自动下载', `使用原始链接${proxy_url}`); + await download(proxy_url, `latest_version${i}.zip`); + }); + return false; + }); + log.info('自动下载', '成功下载到当前目录'); log.info('检查更新', '请手动解压替换可执行文件'); } - log.info('更新说明', '\n' + text + '\n') + log.info('更新说明', '\n' + text + '\n'); } else { - throw `未找到能在此平台(${process.platform})-(${process.arch})上运行的版本,建议以源码运行` + throw `未找到能在此平台(${process.platform})-(${process.arch})上运行的版本,建议以源码运行`; } } else { - throw '当前已是最新版本' + throw '当前已是最新版本'; } } catch (error) { - log.warn('更新脚本', error) + log.warn('更新脚本', error); } } -module.exports = { update } \ No newline at end of file +module.exports = { update }; \ No newline at end of file diff --git a/lib/utils.js b/lib/utils.js index d32d4fdfed..5f92b9b944 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,7 +1,7 @@ const chalk = require('chalk'); const fs = require('fs'); const path = require('path'); -const { send } = require("./net/http"); +const { send } = require('./net/http'); const { version } = require('../package.json'); /** @@ -10,15 +10,15 @@ const { version } = require('../package.json'); const utils = { version, /**环境变量设置文件 */ - env_file: path.join(process.cwd(), "env.js"), + env_file: path.join(process.cwd(), 'env.js'), /**配置文件 */ - config_file: path.join(process.cwd(), "my_config.js"), + config_file: path.join(process.cwd(), 'my_config.js'), /**dyids存放目录 */ - dyids_dir: path.join(process.cwd(), "dyids"), + dyids_dir: path.join(process.cwd(), 'dyids'), /**lottery_info存放目录 */ - lottery_info_dir: path.join(process.cwd(), "lottery_info"), + lottery_info_dir: path.join(process.cwd(), 'lottery_info'), /**本地抽奖信息存放目录 */ - lottery_dyids: path.join(process.cwd(), "lottery_dyids"), + lottery_dyids: path.join(process.cwd(), 'lottery_dyids'), /**dyid长度 */ dyid_length: 18, /** @@ -29,7 +29,7 @@ const utils = { * @returns {Number} */ checkVersion(version) { - return (version.match(/\d.*/)[0]).split('.').reduce((a, v, i) => a + (0.01 ** i) * Number(v), 0) + return (version.match(/\d.*/)[0]).split('.').reduce((a, v, i) => a + (0.01 ** i) * Number(v), 0); }, /** * 安全的将JSON字符串转为对象 @@ -43,16 +43,16 @@ const utils = { if (typeof str === 'string') { try { const obj = JSON.parse(str); - return typeof obj === 'object' ? obj : false + return typeof obj === 'object' ? obj : false; } catch (e) { - utils.log.error("json解析", e + "\n" + params) + utils.log.error('json解析', e + '\n' + params); return false; } } else { return false; } })(params); - return isJSON ? isJSON : {} + return isJSON ? isJSON : {}; }, /** * @template T @@ -61,7 +61,7 @@ const utils = { */ async try_for_each(iter, fn) { for (const item of iter) { - if (await fn(item)) break + if (await fn(item)) break; } }, /** @@ -74,12 +74,12 @@ const utils = { async retryfn(max_times, unexpected, fn) { let ret = null; for (let times = 0; times < max_times; times++) { - ret = await fn() + ret = await fn(); if (unexpected.includes(ret)) { - utils.log.warn('自动重试', `将在 ${times + 1} 分钟后再次尝试(${times + 1}/${max_times})`) - await utils.delay(60 * 1000 * (times + 1)) + utils.log.warn('自动重试', `将在 ${times + 1} 分钟后再次尝试(${times + 1}/${max_times})`); + await utils.delay(60 * 1000 * (times + 1)); } else { - break + break; } } return ret; @@ -123,10 +123,10 @@ const utils = { let c = { i: 0, next: () => c.i++, - clear: () => { c.i = 0 }, + clear: () => { c.i = 0; }, value: () => c.i - } - return c + }; + return c; }, /** * 无限序列 @@ -134,7 +134,7 @@ const utils = { */ *infiniteNumber() { for (let index = 0; ; index++) { - yield index + yield index; } }, /** @@ -148,7 +148,7 @@ const utils = { if (Array.isArray(arr) && arr.length) { RandomOne = arr[parseInt(Math.random() * arr.length)]; } - return RandomOne + return RandomOne; }, /** * Fisher–Yates shuffle洗牌 @@ -173,9 +173,9 @@ const utils = { return key_words.reduce((acc, word) => { word.startsWith('~') ? RegExp(word.slice(1)).test(text) && (acc = false) - : RegExp(word).test(text) && (acc = true) - return acc - }, false) + : RegExp(word).test(text) && (acc = true); + return acc; + }, false); }, /** * 是否有指定环境变量 @@ -207,16 +207,16 @@ const utils = { */ proPrint(msg, split = ' ') { if (msg instanceof Array) { - msg = msg.join(split) + msg = msg.join(split); } - console.log(msg) + console.log(msg); }, /** * @param {Array} msg * @returns */ rainbow(msg) { - this.proPrint(msg.map(it => it.split('').map(l => chalk.hex("#89cff0")(l)).join('')), '\n') + this.proPrint(msg.map(it => it.split('').map(l => chalk.hex('#89cff0')(l)).join('')), '\n'); }, /** * @param {number} done @@ -226,55 +226,55 @@ const utils = { progress_bar(done, total, size = 30) { let perc = done >= total ? 1 : done / total, bar = ~~(perc * size), - status_bar = `\r[${"=".repeat(bar) + ">" + " ".repeat(size - bar)}] ${(perc * 100 + ' ').slice(0, 4)}%` - process.stdout.write(status_bar) + status_bar = `\r[${'='.repeat(bar) + '>' + ' '.repeat(size - bar)}] ${(perc * 100 + ' ').slice(0, 4)}%`; + process.stdout.write(status_bar); }, debug(context, msg) { if (this._level > 3) { if (msg instanceof Object) msg = JSON.stringify(msg, null, 4); let color_text_pair = [ [this._colors[0], `[${this._iso_time()}]`], - [this._colors[1], "[Debug]"], - [this._colors[2], `[帐号${process.env["NUMBER"]} ${context}]`], + [this._colors[1], '[Debug]'], + [this._colors[2], `[帐号${process.env['NUMBER']} ${context}]`], [this._colors[3], `[\n${msg}\n]`], ]; - this.proPrint(color_text_pair.map(([color, text]) => color(text))) + this.proPrint(color_text_pair.map(([color, text]) => color(text))); } }, info(context, msg) { if (this._level > 2) { let color_text_pair = [ [this._colors[0], `[${this._iso_time()}]`], - [this._colors[1], "[Info]"], - [this._colors[2], `[帐号${process.env["NUMBER"]} ${context}]`], + [this._colors[1], '[Info]'], + [this._colors[2], `[帐号${process.env['NUMBER']} ${context}]`], [this._colors[4], `[${msg}]`], ]; this._cache.push(color_text_pair.map(it => it[1]).join(' ')); - this.proPrint(color_text_pair.map(([color, text]) => color(text))) + this.proPrint(color_text_pair.map(([color, text]) => color(text))); } }, warn(context, msg) { if (this._level > 1) { let color_text_pair = [ [this._colors[0], `[${this._iso_time()}]`], - [this._colors[1], "[Warn]"], - [this._colors[2], `[帐号${process.env["NUMBER"]} ${context}]`], + [this._colors[1], '[Warn]'], + [this._colors[2], `[帐号${process.env['NUMBER']} ${context}]`], [this._colors[5], `[\n${msg}\n]`], ]; this._cache.push(color_text_pair.map(it => it[1]).join(' ')); - this.proPrint(color_text_pair.map(([color, text]) => color(text))) + this.proPrint(color_text_pair.map(([color, text]) => color(text))); } }, error(context, msg) { if (this._level > 0) { let color_text_pair = [ [this._colors[0], `[${this._iso_time()}]`], - [this._colors[1], "[Error]"], - [this._colors[2], `[帐号${process.env["NUMBER"]} ${context}]`], + [this._colors[1], '[Error]'], + [this._colors[2], `[帐号${process.env['NUMBER']} ${context}]`], [this._colors[6], `[\n${msg}\n]`], ]; this._cache.push(color_text_pair.map(it => it[1]).join(' ')); - this.proPrint(color_text_pair.map(([color, text]) => color(text))) + this.proPrint(color_text_pair.map(([color, text]) => color(text))); } } }, @@ -287,19 +287,19 @@ const utils = { return new Promise((resolve) => { send({ method: 'POST', - url: process.env["CHAT_CAPTCHA_OCR_URL"] || "http://127.0.0.1:9898/ocr/url/text", + url: process.env['CHAT_CAPTCHA_OCR_URL'] || 'http://127.0.0.1:9898/ocr/url/text', headers: { - "content-type": 'application/x-www-form-urlencoded; charset=UTF-8', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', }, contents: { url }, success: res => { - resolve(res.body) + resolve(res.body); }, failure: () => { - resolve() + resolve(); } - }) - }) + }); + }); }, /** * 下载文件 @@ -317,26 +317,26 @@ const utils = { retry: false }, success: ({ headers, resStream }) => { - const total_len = Number(headers["content-length"]) || 16000000; + const total_len = Number(headers['content-length']) || 16000000; let recv_length = 0; const wtbs = fs.createWriteStream(file_name); resStream.on('data', chuck => { - recv_length += chuck.length - utils.log.progress_bar(recv_length, total_len) - }) - resStream.pipe(wtbs) + recv_length += chuck.length; + utils.log.progress_bar(recv_length, total_len); + }); + resStream.pipe(wtbs); wtbs.on('finish', () => { - utils.log.proPrint('下载完成') - resolve() + utils.log.proPrint('下载完成'); + resolve(); }).on('error', error => { - wtbs.destroy() - reject(error) - }) + wtbs.destroy(); + reject(error); + }); }, failure: error => { - reject(error) + reject(error); } - }) + }); }); }, /** @@ -346,11 +346,11 @@ const utils = { */ hasFileOrDir(path) { try { - fs.accessSync(path, fs.constants.F_OK) + fs.accessSync(path, fs.constants.F_OK); } catch (_) { - return false + return false; } - return true + return true; }, /** * 生成文件夹 @@ -361,10 +361,10 @@ const utils = { return new Promise((resolve) => { fs.stat(dirname, (err) => { if (err) { - fs.mkdirSync(dirname) + fs.mkdirSync(dirname); } - resolve() - }) + resolve(); + }); }); }, /** @@ -381,18 +381,18 @@ const utils = { return new Promise((resolve, rejects) => { fs.open(fpath, flag, (err, fd) => { if (err) { - rejects(err) + rejects(err); } else { fs.write(fd, buffer, 0, buffer.length, 0, err => { - fs.close(fd) + fs.close(fd); if (err) { - rejects(err) + rejects(err); } else { resolve(); } - }) + }); } - }) + }); }); }, /** @@ -402,7 +402,7 @@ const utils = { */ readDyidFile(num) { const fpath = num < 2 ? path.join(utils.dyids_dir, 'dyid.txt') : path.join(utils.dyids_dir, `dyid${num}.txt`); - return fs.createReadStream(fpath, { encoding: 'utf8', highWaterMark: (utils.dyid_length + 1) * 1000 }) + return fs.createReadStream(fpath, { encoding: 'utf8', highWaterMark: (utils.dyid_length + 1) * 1000 }); }, /** * 追加dyid @@ -411,7 +411,7 @@ const utils = { */ writeDyidFile(num) { const fpath = num < 2 ? path.join(utils.dyids_dir, 'dyid.txt') : path.join(utils.dyids_dir, `dyid${num}.txt`); - return fs.createWriteStream(fpath, { flags: 'a' }) + return fs.createWriteStream(fpath, { flags: 'a' }); }, /** * 追加lotteryinfo @@ -422,17 +422,17 @@ const utils = { async appendLotteryInfoFile(from, lottery_info) { let all_lottery_info = {}; try { - all_lottery_info = utils.strToJson(fs.readFileSync(path.join(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`)).toString()) + all_lottery_info = utils.strToJson(fs.readFileSync(path.join(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`)).toString()); } catch (_) { - all_lottery_info = {} + all_lottery_info = {}; } await utils.createDir(utils.lottery_info_dir); if (all_lottery_info[from] instanceof Array) { - all_lottery_info[from].push(...lottery_info) + all_lottery_info[from].push(...lottery_info); } else { - all_lottery_info[from] = lottery_info + all_lottery_info[from] = lottery_info; } - await utils.createFile(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`, JSON.stringify(all_lottery_info), "w") + await utils.createFile(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`, JSON.stringify(all_lottery_info), 'w'); }, /** * 读取lottery_info @@ -443,12 +443,12 @@ const utils = { return new Promise((resolve) => { fs.readFile(path.join(utils.lottery_info_dir, filename), (err, data) => { if (err) { - resolve([]) + resolve([]); } else { let all_lottery_info = utils.strToJson(data.toString('utf8')); - resolve(Object.values(all_lottery_info).flat()) + resolve(Object.values(all_lottery_info).flat()); } - }) + }); }); }, /** @@ -456,7 +456,7 @@ const utils = { */ async clearLotteryInfo() { await utils.createDir(utils.lottery_info_dir); - await utils.createFile(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`, "{}", "w") + await utils.createFile(utils.lottery_info_dir, `lottery_info_${Number(process.env.NUMBER)}.json`, '{}', 'w'); }, /** * 获取含抽奖dyids @@ -467,11 +467,11 @@ const utils = { return new Promise((resolve) => { fs.readFile(path.join(utils.lottery_dyids, filename), (err, data) => { if (err) { - resolve([]) + resolve([]); } else { - resolve(data.toString("utf8").split(/[^0123456789]+/)) + resolve(data.toString('utf8').split(/[^0123456789]+/)); } - }) + }); }); } }; diff --git a/main.js b/main.js index 989b5c5b8c..86556234c5 100644 --- a/main.js +++ b/main.js @@ -1,24 +1,24 @@ -const { version: ve, env_file, config_file, log, hasEnv, delay, hasFileOrDir, clearLotteryInfo } = require("./lib/utils"); +const { version: ve, env_file, config_file, log, hasEnv, delay, hasFileOrDir, clearLotteryInfo } = require('./lib/utils'); const metainfo = [ - ` _ _ _ _____ _ _ `, - ` | | | | | | / ____| (_) | | `, - ` | | ___ | |_| |_ ___ _ __ _ _| (___ ___ _ __ _ _ __ | |_ `, - ` | | / _ \\| __| __/ _ \\ '__| | | |\\___ \\ / __| '__| | '_ \\| __|`, - ` | |___| (_) | |_| || __/ | | |_| |____) | (__| | | | |_) | |_ `, - ` |______\\___/ \\__|\\__\\___|_| \\__, |_____/ \\___|_| |_| .__/ \\__|`, - ` __/ | | | `, - ` |___/ |_| `, - ` `, + ' _ _ _ _____ _ _ ', + ' | | | | | | / ____| (_) | | ', + ' | | ___ | |_| |_ ___ _ __ _ _| (___ ___ _ __ _ _ __ | |_ ', + ' | | / _ \\| __| __/ _ \\ \'__| | | |\\___ \\ / __| \'__| | \'_ \\| __|', + ' | |___| (_) | |_| || __/ | | |_| |____) | (__| | | | |_) | |_ ', + ' |______\\___/ \\__|\\__\\___|_| \\__, |_____/ \\___|_| |_| .__/ \\__|', + ' __/ | | | ', + ' |___/ |_| ', + ' ', ` This: v${ve} Nodejs: ${process.version} Written By shanmite`, -] +]; /**多账号存储 */ let multiple_account = []; /**循环等待时间 */ let loop_wait = 0; /**账号状态标记 1正常 -1失效 */ // eslint-disable-next-line no-unused-vars -let ck_flag = 0 +let ck_flag = 0; /** * @returns {Promise} 错误信息 @@ -40,7 +40,7 @@ async function main() { process.env.ACCOUNT_UA = acco.ACCOUNT_UA; const err_msg = await main(); if (err_msg) { - return err_msg + return err_msg; } else { if (ck_flag === 1) { await delay(acco.WAIT); @@ -53,26 +53,26 @@ async function main() { /**多账号状态还原 */ process.env.ENABLE_MULTIPLE_ACCOUNT = ENABLE_MULTIPLE_ACCOUNT; } else if (COOKIE) { - const global_var = require("./lib/data/global_var"); + const global_var = require('./lib/data/global_var'); await global_var.init(COOKIE, NUMBER); /**引入基础功能 */ - const { start, isMe, clear, account, checkCookie, login } = require("./lib/index"); + const { start, isMe, clear, account, checkCookie, login } = require('./lib/index'); log.info('main', '当前为第' + NUMBER + '个账号'); - log._cache.length = 0 + log._cache.length = 0; const mode = process.env.lottery_mode; - const help_msg = "用法: lottery [OPTIONS]\n\nOPTIONS:\n\tstart 启动抽奖\n\tcheck 中奖检查\n\tacount 查看帐号信息\n\tclear 清理动态和关注\n\tlogin 扫码登录更新CK\n\tupdate 检查更新\n\thelp 帮助信息"; + const help_msg = '用法: lottery [OPTIONS]\n\nOPTIONS:\n\tstart 启动抽奖\n\tcheck 中奖检查\n\tacount 查看帐号信息\n\tclear 清理动态和关注\n\tlogin 扫码登录更新CK\n\tupdate 检查更新\n\thelp 帮助信息'; if (await checkCookie(NUMBER)) { - const { lottery_loop_wait, check_loop_wait, clear_loop_wait, save_lottery_info_to_file } = require("./lib/data/config"); + const { lottery_loop_wait, check_loop_wait, clear_loop_wait, save_lottery_info_to_file } = require('./lib/data/config'); ck_flag = 1; switch (mode) { case 'start': log.info('抽奖', '开始运行'); loop_wait = lottery_loop_wait; if (save_lottery_info_to_file) { - await clearLotteryInfo() + await clearLotteryInfo(); } await start(NUMBER); break; @@ -92,27 +92,27 @@ async function main() { log.info('登录状态', '正常,跳过扫码'); break; case 'help': - return help_msg + return help_msg; case 'account': log.info('检查帐号信息', '开始运行'); await account(); break; case undefined: - return "未提供以下参数\n\t[OPTIONS]\n\n" + help_msg + return '未提供以下参数\n\t[OPTIONS]\n\n' + help_msg; default: - return `提供了错误的[OPTIONS] -> ${mode}\n\n` + help_msg + return `提供了错误的[OPTIONS] -> ${mode}\n\n` + help_msg; } } else { - log.error('Cookie已失效', '切换账号时不要点击退出账号而应直接删除Cookie退出') + log.error('Cookie已失效', '切换账号时不要点击退出账号而应直接删除Cookie退出'); ck_flag = -1; - if (mode === "login") { + if (mode === 'login') { log.info('登陆', '开始扫码'); await login(NUMBER); await delay(1000); } } } else { - return '请查看README文件, 在env.js指定位置填入cookie' + return '请查看README文件, 在env.js指定位置填入cookie'; } } @@ -123,7 +123,7 @@ async function main() { function initEnv() { if (hasFileOrDir(env_file)) { const - env = require("./lib/data/env"), + env = require('./lib/data/env'), multiple_account_parm = env.get_multiple_account(); if (multiple_account_parm) { @@ -139,10 +139,10 @@ function initEnv() { } else { log.init(); log.error('环境变量初始化', '未在当前目录下找到env.js文件或者在环境变量中设置所需参数'); - return true + return true; } - return false + return false; } /** @@ -151,32 +151,32 @@ function initEnv() { */ function initConfig() { if (hasFileOrDir(config_file)) { - const config = require("./lib/data/config"); + const config = require('./lib/data/config'); config.init(); log.info('配置文件初始化', '成功加载my_config.js文件'); } else { log.error('配置文件初始化', '未在当前目录下找到my_config.js文件'); - return true + return true; } - return false + return false; } (async function () { - log.rainbow(metainfo) + log.rainbow(metainfo); if (initEnv() || initConfig()) return; /**OPTIONS */ - process.env.lottery_mode = process.argv[2] + process.env.lottery_mode = process.argv[2]; - log.info('检查更新', '开始') + log.info('检查更新', '开始'); - if (process.env.lottery_mode === "update") { - await require("./lib/update").update(true) - return + if (process.env.lottery_mode === 'update') { + await require('./lib/update').update(true); + return; } else { - await require("./lib/update").update(false) + await require('./lib/update').update(false); } const err_msg = await main(); @@ -186,13 +186,13 @@ function initConfig() { await delay(5 * 1000); } else { while (loop_wait) { - log.info('程序休眠', `${loop_wait / 1000}秒后再次启动`) - await delay(loop_wait) + log.info('程序休眠', `${loop_wait / 1000}秒后再次启动`); + await delay(loop_wait); if (initEnv() || initConfig()) return; - await main() + await main(); } - log.info('结束运行', '未在my_config.js中设置休眠时间') + log.info('结束运行', '未在my_config.js中设置休眠时间'); } process.exit(0); -})() \ No newline at end of file +})(); \ No newline at end of file diff --git a/my_config.example.js b/my_config.example.js index f69550d619..d8b727acb4 100644 --- a/my_config.example.js +++ b/my_config.example.js @@ -49,13 +49,13 @@ module.exports = Object.freeze({ * @example * ["file://lottery_info_1.json"] */ - APIs: ["file://lottery_info_1.json"], + APIs: ['file://lottery_info_1.json'], /** * lottery_dyids目录下抽奖动态文件名(如dyids.txt) * 一行一个dyids(非数字字符分割即可) */ - TxT: ["dyids.txt"], + TxT: ['dyids.txt'], /** * 抽奖参与顺序组合 @@ -79,15 +79,15 @@ module.exports = Object.freeze({ * API发送数据类型 {LotteryInfo[]} * 上传抽奖信息的链接字符串 */ - set_lottery_info_url: "", + set_lottery_info_url: '', /** * 动态中的关键词(表示须同时满足以下条件) * 符合js正则表达式的字符串 */ key_words: [ - "[抽奖送揪]|福利", - "[转关评粉]|参与" + '[抽奖送揪]|福利', + '[转关评粉]|参与' ], /** @@ -313,7 +313,7 @@ module.exports = Object.freeze({ /** * 屏蔽词 */ - blockword: ["脚本", "抽奖号", "钓鱼"], + blockword: ['脚本', '抽奖号', '钓鱼'], /** * 转发并评论 @@ -349,7 +349,7 @@ module.exports = Object.freeze({ /** * 热评屏蔽词 */ - copy_blockword: ["三不原则"], + copy_blockword: ['三不原则'], /** * - 抽奖UP用户分组id(网页端点击分区后地址栏中的tagid) @@ -379,10 +379,10 @@ module.exports = Object.freeze({ * - 优先级递增 */ notice_key_words: [ - "~预约成功|预约主题", - "中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员", - "~你的账号在新设备或平台登录成功", - "~你预约的直播已开始" + '~预约成功|预约主题', + '中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员', + '~你的账号在新设备或平台登录成功', + '~你预约的直播已开始' ], /** @@ -490,4 +490,4 @@ module.exports = Object.freeze({ }, config_2: {}, config_3: {} -}) +}); diff --git a/package.json b/package.json index 981e98119e..e1d9989714 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,9 @@ "account": "node main.js account", "help": "node main.js help", "pkg": "bash script/build/pkg.sh", - "changelog": "bash script/build/changelog.sh" + "changelog": "bash script/build/changelog.sh", + "lint": "npx eslint lib/ test/ *.js", + "lint-fix": "npx eslint lib/ test/ *.js --fix" }, "files": [ "lib", diff --git a/test/api.test.js b/test/api.test.js index 074feb5f3e..145a02c8bf 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -1,5 +1,5 @@ const assert = require('assert'); -const bili_client = require("../lib/net/bili"); +const bili_client = require('../lib/net/bili'); const util = require('./util'); const { parseDynamicCard } = require('../lib/core/searcher'); @@ -9,47 +9,47 @@ const { parseDynamicCard } = require('../lib/core/searcher'); await util.par_run([0, 3], [ // 0 async () => { - assert.equal((await bili_client.getTopRcmd()).length, 10) + assert.equal((await bili_client.getTopRcmd()).length, 10); }, // 1 async () => { assert.equal(await bili_client.sendChat( - parseDynamicCard(await bili_client.getOneDynamicByDyid("692193323569381399")).rid_str, - "test", + parseDynamicCard(await bili_client.getOneDynamicByDyid('692193323569381399')).rid_str, + 'test', 11), 7 - ) + ); }, // 2 async () => { assert.equal(await bili_client.sendChat( - parseDynamicCard(await bili_client.getOneDynamicByDyid("11229466874154064")).rid_str, - "test", + parseDynamicCard(await bili_client.getOneDynamicByDyid('11229466874154064')).rid_str, + 'test', 1), 3 - ) + ); }, // 3 async () => { - assert.notEqual((await bili_client.searchArticlesByKeyword("专栏")).length, 0) + assert.notEqual((await bili_client.searchArticlesByKeyword('专栏')).length, 0); }, // 4 async () => { - assert.notEqual(await bili_client.sendChat("703886913053917267", "t", 17), 1) + assert.notEqual(await bili_client.sendChat('703886913053917267', 't', 17), 1); }, // 5 async () => { - assert(!await bili_client.createDynamic("1")) + assert(!await bili_client.createDynamic('1')); }, // 6 async () => { - assert.equal(await bili_client.autolike("761391835139538967"), 4) + assert.equal(await bili_client.autolike('761391835139538967'), 4); }, // 7 async () => { - assert(await bili_client.rmDynamic("835102428771647513")) + assert(await bili_client.rmDynamic('835102428771647513')); }, - ]) + ]); - console.log("api.test ... ok!"); -})() \ No newline at end of file + console.log('api.test ... ok!'); +})(); \ No newline at end of file diff --git a/test/article.test.js b/test/article.test.js index e0691e608f..bff709ea93 100644 --- a/test/article.test.js +++ b/test/article.test.js @@ -1,5 +1,5 @@ const assert = require('assert'); -const bili_client = require("../lib/net/bili"); +const bili_client = require('../lib/net/bili'); const util = require('./util'); (async () => { @@ -8,8 +8,8 @@ const util = require('./util'); async () => { let info = await bili_client.getOneArticleByCv(22112353); let short_ids = [...new Set(info.match(/(?<=b23.tv\/)[a-zA-Z0-9]{7}/g) || [])]; - assert.equal((await Promise.all(short_ids.map(bili_client.shortDynamicIdToDyid)))[0], "767357823884460033"); + assert.equal((await Promise.all(short_ids.map(bili_client.shortDynamicIdToDyid)))[0], '767357823884460033'); }, - ]) - console.log("article.test ... ok!"); -})() \ No newline at end of file + ]); + console.log('article.test ... ok!'); +})(); \ No newline at end of file diff --git a/test/dynamic_card.test.js b/test/dynamic_card.test.js index aec1dd263d..7d37c9beac 100644 --- a/test/dynamic_card.test.js +++ b/test/dynamic_card.test.js @@ -1,33 +1,33 @@ const assert = require('assert'); -const bili_client = require("../lib/net/bili"); -const searcher = require("../lib/core/searcher"); +const bili_client = require('../lib/net/bili'); +const searcher = require('../lib/core/searcher'); const util = require('./util'); (async () => { await util.par_run([0, 1, 2, 3, 4, 5, 6, 7, 8], [ // 0 async () => { - let info = await bili_client.getOneDynamicByDyid("728424890210713624"); + let info = await bili_client.getOneDynamicByDyid('728424890210713624'); assert(searcher.parseDynamicCard(info).is_charge_lottery); }, // 1 async () => { - let info = await bili_client.getOneDynamicByDyid("768874900850999300"); + let info = await bili_client.getOneDynamicByDyid('768874900850999300'); assert(searcher.parseDynamicCard(info).origin_is_charge_lottery); }, // 2 async () => { - let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid("746824225190314008")); - let chats = await bili_client.getChat(card.rid_str, card.chat_type) - assert(chats.length > 0 && typeof chats[0][0] == "string") + let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid('746824225190314008')); + let chats = await bili_client.getChat(card.rid_str, card.chat_type); + assert(chats.length > 0 && typeof chats[0][0] == 'string'); }, // 3 async () => { - let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid("900172162530279445")); - assert.equal(card.chat_type, 11) - card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid("926978638295859236")); - assert.equal(card.chat_type, 17) - assert.equal(card.origin_chat_type, 11) + let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid('900172162530279445')); + assert.equal(card.chat_type, 11); + card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid('926978638295859236')); + assert.equal(card.chat_type, 17); + assert.equal(card.origin_chat_type, 11); }, // 4 async () => { @@ -37,32 +37,32 @@ const util = require('./util'); }, // 5 async () => { - let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid("762591475338838053")); - let chats = await bili_client.getChat(card.rid_str, card.chat_type) - assert.equal(chats.length, 19) - card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid("762502724122050647")); - chats = await bili_client.getChat(card.rid_str, card.chat_type) - assert.equal(chats.filter(it => it[0] === '六的月').length, 0) + let card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid('762591475338838053')); + let chats = await bili_client.getChat(card.rid_str, card.chat_type); + assert.equal(chats.length, 19); + card = searcher.parseDynamicCard(await bili_client.getOneDynamicByDyid('762502724122050647')); + chats = await bili_client.getChat(card.rid_str, card.chat_type); + assert.equal(chats.filter(it => it[0] === '六的月').length, 0); }, // 6 async () => { - const dy = await bili_client.getOneDynamicByDyid("774973685666676768"); - const card = searcher.parseDynamicCard(dy) - assert.notEqual(card.description + "", undefined + ""); + const dy = await bili_client.getOneDynamicByDyid('774973685666676768'); + const card = searcher.parseDynamicCard(dy); + assert.notEqual(card.description + '', undefined + ''); }, // 7 async () => { - const dy = await bili_client.getOneDynamicByDyid("924676093465591832"); - const card = searcher.parseDynamicCard(dy) - assert.equal(card.reserve_id, "3715576"); + const dy = await bili_client.getOneDynamicByDyid('924676093465591832'); + const card = searcher.parseDynamicCard(dy); + assert.equal(card.reserve_id, '3715576'); }, // 8 async () => { - const dy = await bili_client.getOneDynamicByDyid("925061227481137187"); - const card = searcher.parseDynamicCard(dy) - assert.equal(card.origin_reserve_id, "3715576"); + const dy = await bili_client.getOneDynamicByDyid('925061227481137187'); + const card = searcher.parseDynamicCard(dy); + assert.equal(card.origin_reserve_id, '3715576'); }, - ]) + ]); - console.log("dynamic_card.test ... ok!"); -})() \ No newline at end of file + console.log('dynamic_card.test ... ok!'); +})(); \ No newline at end of file diff --git a/test/index.js b/test/index.js index 29d3210464..e9ce9be1c3 100644 --- a/test/index.js +++ b/test/index.js @@ -1,12 +1,12 @@ -const env = require("../lib/data/env"); -const global_var = require("../lib/data/global_var"); +const env = require('../lib/data/env'); +const global_var = require('../lib/data/global_var'); const { log } = require('../lib/utils'); const fs = require('fs'); -log._level = 4 -env.init() -global_var.init(process.env["COOKIE"], 1) +log._level = 4; +env.init(); +global_var.init(process.env['COOKIE'], 1); fs.readdirSync(module.path) - .filter(file => file.endsWith(".test.js")) - .forEach(file => require(`${module.path}/${file}`)) \ No newline at end of file + .filter(file => file.endsWith('.test.js')) + .forEach(file => require(`${module.path}/${file}`)); \ No newline at end of file diff --git a/test/ocr.test.js b/test/ocr.test.js index 91e460684a..d2fcde2387 100644 --- a/test/ocr.test.js +++ b/test/ocr.test.js @@ -1,5 +1,5 @@ const assert = require('assert'); -const bili_client = require("../lib/net/bili"); +const bili_client = require('../lib/net/bili'); const util = require('./util'); const { parseDynamicCard } = require('../lib/core/searcher'); @@ -9,7 +9,7 @@ const { parseDynamicCard } = require('../lib/core/searcher'); async () => { assert.notEqual(await bili_client.getMyinfo(), null); - const rid = parseDynamicCard(await bili_client.getOneDynamicByDyid("551416252543796684")).rid_str; + const rid = parseDynamicCard(await bili_client.getOneDynamicByDyid('551416252543796684')).rid_str; for (let index = 0; index < 100; index++) { console.log(index); @@ -17,7 +17,7 @@ const { parseDynamicCard } = require('../lib/core/searcher'); rid, Date.now().toString(), 17, - ) + ); } },]); -})() +})(); diff --git a/test/util.js b/test/util.js index 9b10195ffe..861c362ada 100644 --- a/test/util.js +++ b/test/util.js @@ -5,9 +5,9 @@ function par_run(nums, fns) { return Promise.all( nums.map(num => fns[num]()) - ) + ); } module.exports = { par_run -} \ No newline at end of file +}; \ No newline at end of file