diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 121cf61..904e53d 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -17,7 +17,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -33,7 +33,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -49,7 +49,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -65,7 +65,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -81,7 +81,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: diff --git a/.github/workflows/clear.yml b/.github/workflows/clear.yml index 1b02fc8..eb4a601 100644 --- a/.github/workflows/clear.yml +++ b/.github/workflows/clear.yml @@ -18,7 +18,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -34,7 +34,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -50,7 +50,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -66,7 +66,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -82,7 +82,7 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 5e05642..5d343ee 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -14,6 +14,7 @@ env: SCKEY: ${{ secrets.SCKEY }} MY_CONFIG: ${{ secrets.MY_CONFIG }} PUSH_PLUS_TOKEN: ${{ secrets.PUSH_PLUS_TOKEN }} + PAT: ${{ secrets.PAT }} jobs: lottery_1: runs-on: ubuntu-latest @@ -23,14 +24,20 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: NUMBER: 1 COOKIE: ${{ secrets.COOKIE }} run: + npm install npm start + - name: 'Upload dyid to artifact' + uses: actions/upload-artifact@v2 + with: + name: dyid.txt + path: lib/dyid.txt lottery_2: runs-on: ubuntu-latest steps: @@ -39,14 +46,20 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: NUMBER: 2 COOKIE: ${{ secrets.COOKIE2 }} run: + npm install npm start + - name: 'Upload dyid to artifact' + uses: actions/upload-artifact@v2 + with: + name: dyid.txt + path: lib/dyid.txt lottery_3: runs-on: ubuntu-latest steps: @@ -55,14 +68,20 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: NUMBER: 3 COOKIE: ${{ secrets.COOKIE3 }} run: + npm install npm start + - name: 'Upload dyid to artifact' + uses: actions/upload-artifact@v2 + with: + name: dyid.txt + path: lib/dyid.txt lottery_4: runs-on: ubuntu-latest steps: @@ -71,14 +90,20 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: NUMBER: 4 COOKIE: ${{ secrets.COOKIE4 }} run: + npm install npm start + - name: 'Upload dyid to artifact' + uses: actions/upload-artifact@v2 + with: + name: dyid.txt + path: lib/dyid.txt lottery_5: runs-on: ubuntu-latest steps: @@ -87,11 +112,17 @@ jobs: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: NUMBER: 5 COOKIE: ${{ secrets.COOKIE5 }} run: + npm install npm start + - name: 'Upload dyid to artifact' + uses: actions/upload-artifact@v2 + with: + name: dyid.txt + path: lib/dyid.txt diff --git a/.github/workflows/sync.yml b/.github/workflows/sync.yml index 98afdb6..098b341 100644 --- a/.github/workflows/sync.yml +++ b/.github/workflows/sync.yml @@ -10,14 +10,13 @@ on: jobs: repo-sync: env: - PAT: ${{ github.event.client_payload.PAT || secrets.PAT }} #此处PAT需要申请,教程详见:https://www.jianshu.com/p/bb82b3ad1d11 + PAT: ${{ github.event.client_payload.PAT || secrets.PAT }} runs-on: ubuntu-latest if: github.event.repository.owner.id == github.event.sender.id steps: - uses: actions/checkout@v2 with: persist-credentials: false - - name: 开始自动同步 uses: repo-sync/github-sync@v2 if: env.PAT diff --git a/.vscode/httpRequest.code-snippets b/.vscode/httpRequest.code-snippets index b0c8ab6..8a203ec 100644 --- a/.vscode/httpRequest.code-snippets +++ b/.vscode/httpRequest.code-snippets @@ -10,7 +10,6 @@ " $2", " },", " headers: {", - " 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',", " Accept: 'application/json, text/plain, */*',", " Cookie: '$3',", " },", @@ -35,7 +34,6 @@ " $2", " },", " headers: {", - " 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',", " Accept: 'application/json, text/plain, */*',", " 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',", " Cookie: '$3',", diff --git a/README.md b/README.md index 2b8e57b..ccd57b0 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ - [操作步骤](#操作步骤) - [Fork本仓库](#fork本仓库) - [填入COOKIE](#填入cookie) + - [防重复转发](#防重复转发) - [检测中奖](#检测中奖) - [手动检查](#手动检查) - [微信推送(可选)](#微信推送可选) @@ -53,7 +54,8 @@ > [Actions官方文档](https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-syntax-for-github-actions) -此脚本将在B站专栏草稿中储存转发过的动态id以防止重复转发 +~~此脚本将在B站专栏草稿中储存转发过的动态id以防止重复转发~~ +动态id已储存在本地和GitHub构件中 --- @@ -108,6 +110,20 @@ Chrome浏览器: ↓↓ +### 防重复转发 +转发过的动态上传至构件 +为了能够从构件中下载文件,需要access token权限 + +1. 点我创建 [`授权令牌`](https://github.com/settings/tokens/new) + +2. 如图,勾选前两项即可: + +![如图,勾选前两项即可:](.github/create_pat.png) + +3. 将 令牌 复制(注意,先复制,一旦关闭网页就不能查看了),再新建`Secrets`,键名 填入 `PAT` + +↓↓ + ### 检测中奖 每两个小时检测一次 通过`@`信息判断 @@ -187,15 +203,9 @@ Chrome浏览器: > This will force sync ALL branches to match source repo. Branches that are created only in the destination repo will not be affected but all the other branches will be hard reset to match source repo. > ⚠️ This does mean if upstream ever creates a branch that shares the name, your changes will be gone. -1. 点我创建 [`授权令牌`](https://github.com/settings/tokens/new) +每天与主仓库自动同步一次! -2. 如图,勾选前两项即可: - -![如图,勾选前两项即可:](.github/create_pat.png) - -3. 将 令牌 复制(注意,先复制,一旦关闭网页就不能查看了),再新建`Secrets`,键名 填入 `PAT` - -4. 每天与主仓库自动同步一次! +如需关闭请手动关闭 或者使用[GitHub App Pull](https://github.com/apps/pull)自动同步 @@ -226,7 +236,7 @@ steps: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -248,7 +258,7 @@ lottery_*: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: @@ -268,7 +278,7 @@ lottery_*: - name: 'Use Node.js' uses: actions/setup-node@v1 with: - node-version: '12.18.3' + node-version: '14.15.5' - name: 'Run in Nodejs' shell: bash env: diff --git a/lib/Base.js b/lib/Base.js index ef1daad..db40f1a 100644 --- a/lib/Base.js +++ b/lib/Base.js @@ -1,3 +1,5 @@ +const fs = require('fs'); +const path = require('path'); const { HttpRequest } = require("./HttpRequest"); /** @@ -193,7 +195,48 @@ const Base = { * @param {string} ts 13位时间戳 * @param {number} zoneOffset 东时区记做正数 */ - transformTimeZone: (ts, zoneOffset) => new Date(new Date(ts).getTime() + zoneOffset * 60 * 60 * 1000).toLocaleString() + transformTimeZone: (ts, zoneOffset) => new Date(new Date(ts).getTime() + zoneOffset * 60 * 60 * 1000).toLocaleString(), + /** + * ifNotExistCreateFile + * @param {string} filepath 相对于lib的文件路径 + * @param {string} [defaultValue] 写入默认值 + * @returns {Promise} + */ + ifNotExistCreateFile: (filepath, defaultValue = '') => { + const fpath = path.join('./lib', filepath); + const buffer = Buffer.from(defaultValue); + return new Promise((resolve, rejects) => { + fs.open(fpath, 'wx', (err, fd) => { + if (err) { + resolve(); + } else { + fs.write(fd, buffer, 0, buffer.length, 0, err => { + if (err) { + rejects(err) + } else { + resolve(); + } + }) + } + }) + }); + }, + /** + * 读取dyid文件 + * @returns {string} + */ + readDyidFile: () => { + const fpath = path.join('./lib', 'dyid.txt'); + return fs.readFileSync(fpath).toString() + }, + /** + * 追加dyid + * @param {string} dyid + */ + writeDyidFile: (dyid) => { + const fpath = path.join('./lib', 'dyid.txt'); + return fs.writeFileSync(fpath, dyid, { flag: 'a' }) + } }; module.exports = Base; \ No newline at end of file diff --git a/lib/BiliAPI.js b/lib/BiliAPI.js index e1bee38..c89470f 100644 --- a/lib/BiliAPI.js +++ b/lib/BiliAPI.js @@ -644,99 +644,6 @@ const BiliAPI = { } }) }); - }, - /** - * 获取草稿列表 - * @typedef Page - * @property {number} pn - * @typedef Draft - * @property {number} id - * @property {string} title - * @typedef DraftList - * @property {Array} drafts - * @property {Page} page - * @param {number} pn 页数 - * @returns {Promise} - * 错误返回 {} - */ - showDraftList: (pn) => { - return new Promise((resolve) => { - Ajax.get({ - url: 'https://member.bilibili.com/x/web/draft/list', - queryStringsObj: { - pn - }, - hasCookies: true, - success: responseText => { - const { artlist } = Base.strToJson(responseText); - if (typeof artlist === 'object' && artlist !== null) { - const { drafts, page } = artlist; - resolve({ drafts, page }) - } else { - resolve({}); - } - } - }) - }); - }, - /** - * - * @param {number} aid 专栏的id - * @param {string} text - * @returns {Promise} - */ - addDraft: (text, aid = '') => { - return new Promise((resolve) => { - Ajax.post({ - url: 'https://api.bilibili.com/x/article/creative/draft/addupdate', - hasCookies: true, - dataType: 'application/x-www-form-urlencoded', - data: { - title: '转发过的动态', - content: `

${text}

`, - summary: '此处存放转发过的动态的id', - csrf: GlobalVar.csrf, - aid - }, - success: responseText => { - const { code, data } = Base.strToJson(responseText); - if (code === 0) { - console.log('[更新专栏]成功'); - resolve(data.aid); - } else { - console.log('[更新专栏]失败'); - resolve(-1); - } - } - }) - }); - }, - /** - * 获取专栏内容 - * @param {number} aid 专栏id - * @returns {Promise} - */ - getDraftView: (aid) => { - return new Promise((resolve) => { - Ajax.get({ - url: 'https://api.bilibili.com/x/article/creative/draft/view', - queryStringsObj: { - aid - }, - hasCookies: true, - success: responseText => { - const { code, data } = Base.strToJson(responseText); - if (code === 0) { - console.log('[获取专栏草稿]成功'); - const { content = '

' } = data; - resolve(content.slice(3, -4)); - } else { - console.log('[获取专栏草稿]失败'); - resolve(''); - } - } - }) - }); } }; diff --git a/lib/GithubAPI.js b/lib/GithubAPI.js new file mode 100644 index 0000000..87b7ab4 --- /dev/null +++ b/lib/GithubAPI.js @@ -0,0 +1,96 @@ +const { createReadStream, createWriteStream } = require('fs') +const unzip = require('unzipper'); +const { strToJson } = require("./Base") +const { HttpRequest } = require("./HttpRequest") +const GlobalVar = require('./GlobalVar.json') + +const { GITHUB_REPOSITORY } = process.env; + + +const GihubAPI = { + /** + * 列出第一个构件 + * @returns {Promise<{id: number, size_in_bytes: number}>} + */ + listArtifacts: () => { + return new Promise((resolve) => { + HttpRequest({ + method: 'GET', + url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts`, + config: { + retry: false + }, + query: { + page: 1, + per_page: 5 + }, + headers: { + Accept: 'application/json, text/plain, */*', + }, + success: res => { + const data = strToJson(res.body); + if (data.total_count) { + resolve(data.artifacts[0]) + } else { + resolve({}) + console.log('之前无构件'); + } + }, + failure: err => { + console.log(err); + resolve({}) + } + }) + }); + }, + /** + * + * @param {number} id + * @param {number} size + * @returns {Promise} success: true + */ + downloadArtifacts: (id, size) => { + return new Promise((resolve) => { + HttpRequest({ + method: 'GET', + url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts/${id}/zip`, + headers: { + accept: 'application/vnd.github.v3+json', + Authorization: `token ${GlobalVar.PAT}` + }, + config: { + redirect: true, + }, + stream: true, + success: res => { + const total_length = size; + let recv_length = 0; + const wtbs = createWriteStream('dyid.zip'); + res.resStream.on('data', chuck => { + recv_length += chuck.length + console.log(((recv_length / total_length) * 100).toFixed(1) + '%') + }) + res.resStream.pipe(wtbs) + wtbs.on('finish', () => { + console.log('下载完成开始解压') + createReadStream('dyid.zip').pipe(unzip.Extract({ + path: 'lib' + }).on('close', () => { + console.log('解压完成') + resolve(true) + })) + }).on('error', () => { + wtbs.close() + resolve(false) + }) + }, + failure: err => { + console.log(err); + resolve(false) + } + }) + }); + } +} + +module.exports = GihubAPI; \ No newline at end of file diff --git a/lib/HttpRequest.js b/lib/HttpRequest.js index 4d27eec..5cc8691 100644 --- a/lib/HttpRequest.js +++ b/lib/HttpRequest.js @@ -4,7 +4,8 @@ * * @typedef {object} Respond 返回的响应 * @property {HttpHeaders} headers 响应头 - * @property {string} body 响应体 + * @property {string} [body] UTF8编码响应 + * @property {import("http").IncomingMessage} [resStream] 可读流式响应体 * * @callback SuccessCb 成功回调 * @param {Respond} res @@ -22,11 +23,13 @@ * @property {number} [timeout] 超时 * @property {number} [wait] 错误等待 * @property {boolean} [retry] 是否重传 + * @property {boolean} [redirect] 是否重定向 * @property {number} [retry_times] 重试次数 * * @typedef {object} RequestOptions Http请求选项 * @property {string} method 请求方法 * @property {string} url 完整链接 + * @property {boolean} stream 是否流式数据 * @property {RequestConfig} [config] 设置 * @property {Proxy} [proxy] 代理 * @property {Object.} [query] 查询选项 @@ -40,12 +43,16 @@ const { request: http_request } = require('http'); const { request: https_request } = require('https'); const { stringify } = require('querystring'); +/**默认编码 */ +const DEFAULT_DECODE = 'utf8'; /**超时时间 */ const DEFAULT_TIMEOUT = 20000; /**出错等待时间 */ const DEFAULT_WAIT = 10000; -/**是否重传 */ +/**默认重传 */ const DEFAULT_RETRY = true; +/**默认不重定向 */ +const DEFAULT_REDIRECT = false; /**错误尝试次数 */ const DEFAULT_RETRY_TIMES = 6; /**Google Chrome */ @@ -57,8 +64,8 @@ const DEFAULT_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 * @returns {void} */ function HttpRequest(detail) { - const { method, url, config = {}, proxy, query, contents, headers = {}, success, failure } = detail; - let { timeout = DEFAULT_TIMEOUT, wait = DEFAULT_WAIT, retry = DEFAULT_RETRY, retry_times = DEFAULT_RETRY_TIMES } = config; + const { method, url, stream = false, config = {}, proxy, query, contents, headers = {}, success, failure } = detail; + let { timeout = DEFAULT_TIMEOUT, wait = DEFAULT_WAIT, retry = DEFAULT_RETRY, redirect = DEFAULT_REDIRECT, retry_times = DEFAULT_RETRY_TIMES } = config; const thisURL = new URL(url) , content = formatContents(headers["content-type"], contents) , request = thisURL.protocol === 'https:' ? https_request : http_request; @@ -66,11 +73,11 @@ function HttpRequest(detail) { timeout, method: method.toUpperCase(), host: thisURL.host, - path: thisURL.pathname + thisURL.hash, + path: thisURL.pathname + thisURL.search + thisURL.hash, headers, }; if (!headers["user-agent"]) headers["user-agent"] = DEFAULT_UA; - if (query) options.path += '?' + stringify(query); + if (query) options.path += (thisURL.search ? '&' : '?') + stringify(query); if (contents) options.headers['content-length'] = Buffer.byteLength(content, 'utf-8').toString(); if (proxy) { options.headers.host = thisURL.host; @@ -81,28 +88,42 @@ function HttpRequest(detail) { const req = request(options, res => { let protodata = ''; const { statusCode, headers } = res; - res.setEncoding('utf8') - .on('data', chunk => { protodata += chunk }) - .on('error', async err => { - if (retry && retry_times--) { - console.log('[不期待响应]尝试重新请求中...'); - await delay(wait); - HttpRequest(detail); - } else { - failure(`[响应错误]${err.message} 响应数据:\n${protodata}`) - } - }) - .on('end', () => { - if (statusCode < 400) { - success({ headers: headers, body: protodata }) - } else { - res.emit('error', new Error(`HTTP状态码: ${statusCode}`)) - } - }) + if (redirect && ~~(statusCode / 100) === 3) { + try { + detail.url = new URL(headers.location).href + } catch (error) { + detail.url = new URL(thisURL.origin + headers.location).href + } + console.log(`[重定向]状态码:${statusCode} location:${detail.url}`); + HttpRequest(detail) + return + } + if (stream) { + success({ headers: headers, resStream: res }) + } else { + res.setEncoding(DEFAULT_DECODE) + .on('data', chunk => { protodata += chunk }) + .on('error', async err => { + if (retry && retry_times--) { + console.log(`[不期待响应]原因:${err.message} 尝试重新请求中...`); + await delay(wait); + HttpRequest(detail); + } else { + failure(`[响应错误]${err.message} 响应数据:\n${protodata}`) + } + }) + .on('end', () => { + if (statusCode < 400) { + success({ headers: headers, body: protodata }) + } else { + res.emit('error', new Error(`HTTP状态码: ${statusCode}`)) + } + }) + } }) req.on('error', async err => { if (retry && retry_times--) { - console.log('[请求失败]尝试重新连接中...'); + console.log(`[请求失败]原因:${err.message} 尝试重新连接中...`); await delay(wait); HttpRequest(detail); } else { diff --git a/lib/MyStorage.js b/lib/MyStorage.js index 4e9b9d8..7c27113 100644 --- a/lib/MyStorage.js +++ b/lib/MyStorage.js @@ -1,72 +1,47 @@ -const BiliAPI = require("./BiliAPI"); - -/**@type {number} */ -let aid; - -/** - * 获取草稿的id - * @param {number} pn - * @returns {Promise} - */ -async function getDraftid(pn = 1) { - if (typeof aid === 'number') return aid; - const list = await BiliAPI.showDraftList(pn); - if (Object.keys(list).length === 0) { - aid = await BiliAPI.addDraft(''); - return aid; - } else { - const { drafts, page } = list; - const { pn } = page; - for (let index = 0; index < drafts.length; index++) { - const draft = drafts[index]; - if (draft.title === '转发过的动态') { - aid = draft.id; - break; - } - } - if (typeof aid === 'number') return aid; - await getDraftid(pn + 1); - } -} - -/** - * 获取dyid - * @returns {Promise} - */ -async function getDyid() { - const draftId = await getDraftid(); - console.log(`[获取专栏草稿]id:${draftId}`); - return await BiliAPI.getDraftView(draftId); -} - -/** - * 更新dyid - * @param {string} dyid - * @returns - */ -async function updateDyid(dyid) { - if (typeof aid === 'number' && aid !== -1) { - if (dyid === '') return; - console.log(`[更新专栏草稿]id:${aid}`); - return await BiliAPI.addDraft(dyid, aid); - } -} - -/** - * 清空dyid - * @param {string} dyid - * @returns - */ -async function clearDyid() { - const draftId = await getDraftid(); - console.log(`[清空专栏草稿]id:${draftId}`); - await BiliAPI.addDraft('', draftId); -} +const Base = require("./Base"); +const { ifNotExistCreateFile } = require("./Base"); +const GihubAPI = require("./GithubAPI"); const MyStorage = { - getDyid, - updateDyid, - clearDyid -}; + /** + * 初始化dyid.txt + */ + init: () => { + return new Promise((resolve) => { + GihubAPI.listArtifacts().then(async artifact => { + const { id, size_in_bytes } = artifact; + if (size_in_bytes) { + GihubAPI.downloadArtifacts(id, size_in_bytes).then(async status => { + if (status) { + console.log('存储初始化成功'); + } else { + console.log('存储初始化失败'); + await ifNotExistCreateFile('dyid.txt') + } + resolve() + }) + } else { + await ifNotExistCreateFile('dyid.txt') + resolve() + } + }) + }); + }, + /** + * 获取dyid + */ + getDyid: () => { + console.log('获取已转发过的动态信息'); + return Base.readDyidFile() + }, + /** + * 更新dyid + * @param {string} dyid + */ + updateDyid: (dyid) => { + console.log('更新已转发过的动态信息'); + return Base.writeDyidFile(dyid) + } +} module.exports = MyStorage; \ No newline at end of file diff --git a/lib/clear.js b/lib/clear.js index 72fc805..0518e2c 100644 --- a/lib/clear.js +++ b/lib/clear.js @@ -3,7 +3,6 @@ const { checkMyPartition } = require("./BiliAPI"); const BiliAPI = require("./BiliAPI"); const Public = require("./Public"); const GlobalVar = require('./GlobalVar.json'); -const { clearDyid } = require("./MyStorage"); const { followWhiteList } = require("./config"); let offset = '0'; @@ -60,7 +59,6 @@ async function unFollow () { async function clear () { await delDynamic(); await unFollow(); - await clearDyid(); return; } diff --git a/lib/setCookie.js b/lib/setCookie.js deleted file mode 100644 index 0d3f528..0000000 --- a/lib/setCookie.js +++ /dev/null @@ -1,65 +0,0 @@ -const Script = require("./Script"); -const fs = require('fs'); -const path = require('path'); -const { getRemoteConfig } = require("./Base"); - -/** - * - * @param {string} filepath 相对于根目录的文件路径 - * @param {string} [defaultValue] 写入默认值 - * @returns {Promise} - */ -function ifNotExistCreateFile(filepath, defaultValue = '') { - const fpath = path.join('./lib', filepath); - const buffer = Buffer.from(defaultValue); - return new Promise((resolve, rejects) => { - fs.open(fpath, 'wx', (err, fd) => { - if (err) { - resolve(); - } else { - fs.write(fd, buffer, 0, buffer.length, 0, err => { - if (err) { - rejects(err) - } else { - resolve(); - } - }) - } - }) - }); -} - -let GlobalVar = { - cookie: '', - /**自己的UID*/ - myUID: '', - /**防跨站请求伪造*/ - csrf: '', - /** - * 抽奖信息 - * @type {(string|number)[]} - */ - Lottery: [...Script.UIDs, ...Script.TAGs], - SCKEY: '', - remoteconfig: {}, -} -/** - * 生成全局变量文件 - * @param {string} cookie - * @param {string} [SCKEY] - */ -module.exports = async function setGlobalVar(cookie, SCKEY = '', PUSH_PLUS_TOKEN = '') { - const key = ['DedeUserID','bili_jct'] - GlobalVar.cookie = cookie; - GlobalVar.SCKEY = SCKEY; - GlobalVar.PUSH_PLUS_TOKEN = PUSH_PLUS_TOKEN; - cookie.split(/\s*;\s*/).forEach(item=>{ - const _item = item.split('='); - if (key.indexOf(_item[0]) !== -1) GlobalVar[_item[0]] = _item[1]; - }) - GlobalVar.csrf = GlobalVar.bili_jct; - GlobalVar.myUID = GlobalVar.DedeUserID; - GlobalVar.remoteconfig = await getRemoteConfig(); - await ifNotExistCreateFile('GlobalVar.json',JSON.stringify(GlobalVar)); - return -} diff --git a/lib/setVariable.js b/lib/setVariable.js new file mode 100644 index 0000000..6843a31 --- /dev/null +++ b/lib/setVariable.js @@ -0,0 +1,45 @@ +const Script = require("./Script"); +const { getRemoteConfig } = require("./Base"); +const MyStorage = require("./MyStorage"); +const Base = require("./Base"); + +let GlobalVar = { + cookie: '', + /**自己的UID*/ + myUID: '', + /**防跨站请求伪造*/ + csrf: '', + /** + * 抽奖信息 + * @type {(string|number)[]} + */ + Lottery: [...Script.UIDs, ...Script.TAGs], + SCKEY: '', + remoteconfig: {}, +} +/** + * 生成全局变量文件 + * @param {string} cookie + * @param {string} [PAT] + * @param {string} [SCKEY] + * @param {string} [PUSH_PLUS_TOKEN] + */ +async function setVariable(cookie, PAT = '', SCKEY = '', PUSH_PLUS_TOKEN = '') { + const key = ['DedeUserID','bili_jct'] + GlobalVar.cookie = cookie; + GlobalVar.SCKEY = SCKEY; + GlobalVar.PAT = PAT; + GlobalVar.PUSH_PLUS_TOKEN = PUSH_PLUS_TOKEN; + cookie.split(/\s*;\s*/).forEach(item=>{ + const _item = item.split('='); + if (key.indexOf(_item[0]) !== -1) GlobalVar[_item[0]] = _item[1]; + }) + GlobalVar.csrf = GlobalVar.bili_jct; + GlobalVar.myUID = GlobalVar.DedeUserID; + GlobalVar.remoteconfig = await getRemoteConfig(); + await Base.ifNotExistCreateFile('GlobalVar.json',JSON.stringify(GlobalVar)); + await MyStorage.init() + return +} + +module.exports = { setVariable }; \ No newline at end of file diff --git a/main.js b/main.js index 48ba076..e573a00 100644 --- a/main.js +++ b/main.js @@ -1,10 +1,10 @@ -const setGlobalVar = require("./lib/setCookie"); +const { setVariable } = require("./lib/setVariable"); -const { NUMBER, CLEAR, COOKIE, SCKEY, PUSH_PLUS_TOKEN } = process.env; +const { NUMBER, CLEAR, COOKIE, PAT, SCKEY, PUSH_PLUS_TOKEN } = process.env; ((async () => { if (typeof COOKIE === 'string' && COOKIE.length > 10) { - await setGlobalVar(COOKIE, SCKEY, PUSH_PLUS_TOKEN); + await setVariable(COOKIE, PAT, SCKEY, PUSH_PLUS_TOKEN); const { start, isMe, checkCookie } = require("./lib/lottery-in-nodejs"); const { clear } = require("./lib/clear"); const isRight = await checkCookie(NUMBER); diff --git a/package-lock.json b/package-lock.json index 96ce9a9..695f6e4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -124,25 +124,60 @@ "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "big-integer": { + "version": "1.6.48", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.48.tgz", + "integrity": "sha512-j51egjPa7/i+RdiRuJbPdJ2FIUYYPhvYLjzoYbcMMm62ooO6F94fETG4MTs46zPAF9Brs04OajboA/qTGuz78w==" + }, + "binary": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", + "integrity": "sha1-n2BVO8XOjDOG87VTz/R0Yq3sqnk=", + "requires": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + } + }, + "bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha1-9y12C+Cbf3bQjtj66Ysomo0F+rM=" }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, + "buffer-indexof-polyfill": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", + "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==" + }, + "buffers": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", + "integrity": "sha1-skV5w77U1tOWru5tmorn9Ugqt7s=" + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true }, + "chainsaw": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", + "integrity": "sha1-XqtQsor+WAdNDVgpE4iCi15fvJg=", + "requires": { + "traverse": ">=0.3.0 <0.4" + } + }, "chalk": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", @@ -212,8 +247,12 @@ "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, "cross-spawn": { "version": "7.0.3", @@ -250,6 +289,14 @@ "esutils": "^2.0.2" } }, + "duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha1-ixLauHjA1p4+eJEFFmKjL8a93ME=", + "requires": { + "readable-stream": "^2.0.2" + } + }, "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -466,8 +513,28 @@ "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "requires": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "dependencies": { + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "requires": { + "glob": "^7.1.3" + } + } + } }, "functional-red-black-tree": { "version": "1.0.1", @@ -479,7 +546,6 @@ "version": "7.1.6", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -507,6 +573,11 @@ "type-fest": "^0.8.1" } }, + "graceful-fs": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", + "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==" + }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -539,7 +610,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "requires": { "once": "^1.3.0", "wrappy": "1" @@ -548,8 +618,7 @@ "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "is-extglob": { "version": "2.1.1", @@ -572,6 +641,11 @@ "is-extglob": "^2.1.1" } }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -616,6 +690,11 @@ "type-check": "~0.4.0" } }, + "listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha1-hMinKrWcRyUyFIDJdeZQg0LnCTc=" + }, "lodash": { "version": "4.17.20", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", @@ -635,11 +714,23 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + }, + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "requires": { + "minimist": "^1.2.5" + } + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -656,7 +747,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, "requires": { "wrappy": "1" } @@ -687,8 +777,7 @@ "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { "version": "3.1.1", @@ -702,6 +791,11 @@ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, "progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", @@ -714,6 +808,20 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, "regexpp": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", @@ -741,6 +849,11 @@ "glob": "^7.1.3" } }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, "semver": { "version": "7.3.4", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.4.tgz", @@ -750,6 +863,11 @@ "lru-cache": "^6.0.0" } }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=" + }, "shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -819,6 +937,14 @@ "strip-ansi": "^6.0.0" } }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", @@ -881,6 +1007,11 @@ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, + "traverse": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", + "integrity": "sha1-cXuPIgzAu3tE5AUUwisui7xw2Lk=" + }, "type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -896,6 +1027,23 @@ "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true }, + "unzipper": { + "version": "0.10.11", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.11.tgz", + "integrity": "sha512-+BrAq2oFqWod5IESRjL3S8baohbevGcVA+teAIOYWM3pDVdseogqbzhhvvmiyQrUNKFUnDMtELW3X8ykbyDCJw==", + "requires": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "graceful-fs": "^4.2.2", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, "uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -905,6 +1053,11 @@ "punycode": "^2.1.0" } }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, "v8-compile-cache": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.2.0.tgz", @@ -929,8 +1082,7 @@ "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "yallist": { "version": "4.0.0", diff --git a/package.json b/package.json index cdb5721..1933692 100644 --- a/package.json +++ b/package.json @@ -27,5 +27,8 @@ "homepage": "https://github.com/shanmite/AutoScript#readme", "devDependencies": { "eslint": "^7.17.0" + }, + "dependencies": { + "unzipper": "^0.10.11" } }