From 10db0bcbab515e9da8a6d18b3f752cb6984dd51e Mon Sep 17 00:00:00 2001 From: HCLonely Date: Mon, 2 Aug 2021 16:26:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=BD=E5=89=A7=E5=8A=9F?= =?UTF-8?q?=E8=83=BD(#56)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .history/package_20210311103859.json | 49 ---- .history/src/index_20210217103151.js | 137 ----------- .history/src/index_20210217103853.js | 137 ----------- .history/src/index_20210217104038.js | 137 ----------- README.md | 48 ++-- index.js | 351 ++++----------------------- lib/bangumi-generator.js | 67 +++-- lib/get-bili-data.js | 314 ++++++++++++++++++++++++ lib/templates/bangumi.ejs | 6 +- lib/templates/template.ejs | 4 +- package-lock.json | 220 +---------------- package.json | 4 +- src/index.js | 121 +++------ src/lib/bangumi-generator.js | 40 +-- src/lib/get-bili-data.js | 98 ++++++++ 15 files changed, 586 insertions(+), 1147 deletions(-) delete mode 100644 .history/package_20210311103859.json delete mode 100644 .history/src/index_20210217103151.js delete mode 100644 .history/src/index_20210217103853.js delete mode 100644 .history/src/index_20210217104038.js create mode 100644 lib/get-bili-data.js create mode 100644 src/lib/get-bili-data.js diff --git a/.history/package_20210311103859.json b/.history/package_20210311103859.json deleted file mode 100644 index 28212a2..0000000 --- a/.history/package_20210311103859.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "hexo-bilibili-bangumi", - "version": "1.5.3", - "description": "hexo bilibili番剧页", - "main": "index.js", - "scripts": { - "test": "standard --fix", - "build": "babel src/index.js --out-file index.js && babel src/lib/util.js --out-file lib/util.js && babel src/lib/bangumi-generator.js --out-file lib/bangumi-generator.js && babel src/lib/templates/index.js --out-file lib/templates/index.js --presets minify && babel src/lib/templates/pagination.js --out-file lib/templates/pagination.js --presets minify && cleancss src/lib/templates/index.css -O2 -o lib/templates/index.css" - }, - "author": "HCLonely ", - "license": "Apache Licence 2.0", - "keywords": [ - "generator", - "plugin", - "bilibili", - "bangumi", - "hexo", - "anime" - ], - "dependencies": { - "@babel/runtime": "^7.9.6", - "axios": "^0.21.1", - "ejs": "2.5.6", - "hexo-fs": "^0.2.2", - "hexo-i18n": "^0.2.1", - "hexo-log": "^0.2.0", - "path": "^0.12.7", - "progress": "^2.0.3" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/HCLonely/hexo-bilibili-bangumi.git" - }, - "devDependencies": { - "@babel/cli": "^7.8.4", - "@babel/core": "^7.9.6", - "@babel/plugin-transform-runtime": "^7.9.6", - "@babel/preset-env": "^7.9.6", - "babel-preset-minify": "^0.5.1", - "clean-css-cli": "^4.3.0", - "standard": "^14.3.4" - }, - "standard": { - "ignore": [ - "index.js", - "lib/*" - ] - } -} diff --git a/.history/src/index_20210217103151.js b/.history/src/index_20210217103151.js deleted file mode 100644 index ace155f..0000000 --- a/.history/src/index_20210217103151.js +++ /dev/null @@ -1,137 +0,0 @@ -/* global hexo */ -'use strict' -const fs = require('hexo-fs') -const path = require('path') -const axios = require('axios') -const log = require('hexo-log')({ - debug: false, - silent: false -}) -const ProgressBar = require('progress') - -if (typeof URL !== 'function') var { URL } = require('url') - -const options = { - options: [ - { name: '-u, --update', desc: 'Update bangumi data' }, - { name: '-d, --delete', desc: 'Delete bangumi data' } - ] -} -hexo.extend.generator.register('bangumis', function (locals) { - if (!this?.config?.bangumi?.enable) { - return - } - return require('./lib/bangumi-generator').call(this, locals) -}) -hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { - if (args.d) { - if (fs.existsSync(path.join(this.source_dir, '/_data/'))) { - fs.rmdirSync(path.join(this.source_dir, '/_data/')) - log.info('Bangumis data has been deleted') - } - } else if (args.u) { - if (!this?.config?.bangumi) { - log.info('Please add config to _config.yml') - return - } - if (!this.config.bangumi.enable) { - return - } - if (!this.config.bangumi.vmid) { - log.info('Please add vmid to _config.yml') - return - } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress ?? true, this.source_dir) - } else { - log.info('Unknown command, please use "hexo bangumi -h" to see the available commands') - } -}) - -async function getBangumiPage (vmid, status) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=1&pn=1`) - if (response?.data?.code === 0 && response?.data?.message === '0' && response?.data?.data && typeof response?.data?.data?.total !== 'undefined') { - return { success: true, data: Math.ceil(response.data.data.total / 30) + 1 } - } else if (response && response.data && response.data.message !== '0') { - return { success: false, data: response.data.message } - } else if (response && response.data) { - return { success: false, data: response.data } - } else { - return { success: false, data: response } - } -} -async function getBangumi (vmid, status, webp, pn) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) - const $data = [] - if (response?.data?.code === 0) { - const data = response?.data?.data - const list = data?.list || [] - for (const bangumi of list) { - let cover = bangumi?.cover - if (cover) { - const href = new URL(cover) - href.protocol = 'https' - if (webp) href.pathname += '@220w_280h.webp' - cover = href.href - } - $data.push({ - title: bangumi?.title, - type: bangumi?.season_type_name, - area: bangumi?.areas?.[0]?.name, - cover: cover, - totalCount: total(bangumi?.total_count), - id: bangumi?.media_id, - follow: count(bangumi?.stat?.follow), - view: count(bangumi?.stat?.view), - danmaku: count(bangumi?.stat?.danmaku), - coin: count(bangumi.stat.coin), - score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', - des: bangumi?.evaluate - }) - } - return $data - } -} -function count (e) { - return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-' -} -function total (e) { - return e ? (e === -1 ? '未完结' : `全${e}话`) : '-' -} -async function biliBangumi (vmid, status, webp, progress) { - const page = await getBangumiPage(vmid, status, webp) - if (page?.success) { - const list = [] - let bar = null - if (progress) bar = new ProgressBar(`正在获取 ${status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]'} 番剧 [:bar] :percent :elapseds`, { total: page.data - 1, complete: '█' }) - for (let i = 1; i < page.data; i++) { - if (progress) bar.tick() - const data = await getBangumi(vmid, status, webp, i) - list.push(...data) - } - return list - } else { - console.log('Get bangumi data error:', page?.data) - return [] - } -} -async function saveBangumiData(vmid, webp = true, progress, sourceDir) { - log.info('Getting bilibili bangumis, please wait...') - const startTime = new Date().getTime() - const wantWatch = await biliBangumi(vmid, 1, webp, progress) - const watching = await biliBangumi(vmid, 2, webp, progress) - const watched = await biliBangumi(vmid, 3, webp, progress) - const endTime = new Date().getTime() - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms') - const bangumis = { wantWatch, watching, watched } - if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { - fs.mkdirsSync(path.join(sourceDir, '/_data/')) - } - fs.writeFile(path.join(sourceDir, '/_data/bangumis.json'), JSON.stringify(bangumis), err => { - if (err) { - log.info('Failed to write data to bangumis.json') - console.error(err) - } else { - log.info('Bilibili bangumis data has been saved') - } - }) -} diff --git a/.history/src/index_20210217103853.js b/.history/src/index_20210217103853.js deleted file mode 100644 index e2a8d9d..0000000 --- a/.history/src/index_20210217103853.js +++ /dev/null @@ -1,137 +0,0 @@ -/* global hexo */ -'use strict' -const fs = require('hexo-fs') -const path = require('path') -const axios = require('axios') -const log = require('hexo-log')({ - debug: false, - silent: false -}) -const ProgressBar = require('progress') - -if (typeof URL !== 'function') var { URL } = require('url') - -const options = { - options: [ - { name: '-u, --update', desc: 'Update bangumi data' }, - { name: '-d, --delete', desc: 'Delete bangumi data' } - ] -} -hexo.extend.generator.register('bangumis', function (locals) { - if (!this?.config?.bangumi?.enable) { - return - } - return require('./lib/bangumi-generator').call(this, locals) -}) -hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { - if (args.d) { - if (fs.existsSync(path.join(this.source_dir, '/_data/bangumis.json'))) { - fs.rmdirSync(path.join(this.source_dir, '/_data/bangumis.json')) - log.info('Bangumis data has been deleted') - } - } else if (args.u) { - if (!this?.config?.bangumi) { - log.info('Please add config to _config.yml') - return - } - if (!this.config.bangumi.enable) { - return - } - if (!this.config.bangumi.vmid) { - log.info('Please add vmid to _config.yml') - return - } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress ?? true, this.source_dir) - } else { - log.info('Unknown command, please use "hexo bangumi -h" to see the available commands') - } -}) - -async function getBangumiPage (vmid, status) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=1&pn=1`) - if (response?.data?.code === 0 && response?.data?.message === '0' && response?.data?.data && typeof response?.data?.data?.total !== 'undefined') { - return { success: true, data: Math.ceil(response.data.data.total / 30) + 1 } - } else if (response && response.data && response.data.message !== '0') { - return { success: false, data: response.data.message } - } else if (response && response.data) { - return { success: false, data: response.data } - } else { - return { success: false, data: response } - } -} -async function getBangumi (vmid, status, webp, pn) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) - const $data = [] - if (response?.data?.code === 0) { - const data = response?.data?.data - const list = data?.list || [] - for (const bangumi of list) { - let cover = bangumi?.cover - if (cover) { - const href = new URL(cover) - href.protocol = 'https' - if (webp) href.pathname += '@220w_280h.webp' - cover = href.href - } - $data.push({ - title: bangumi?.title, - type: bangumi?.season_type_name, - area: bangumi?.areas?.[0]?.name, - cover: cover, - totalCount: total(bangumi?.total_count), - id: bangumi?.media_id, - follow: count(bangumi?.stat?.follow), - view: count(bangumi?.stat?.view), - danmaku: count(bangumi?.stat?.danmaku), - coin: count(bangumi.stat.coin), - score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', - des: bangumi?.evaluate - }) - } - return $data - } -} -function count (e) { - return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-' -} -function total (e) { - return e ? (e === -1 ? '未完结' : `全${e}话`) : '-' -} -async function biliBangumi (vmid, status, webp, progress) { - const page = await getBangumiPage(vmid, status, webp) - if (page?.success) { - const list = [] - let bar = null - if (progress) bar = new ProgressBar(`正在获取 ${status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]'} 番剧 [:bar] :percent :elapseds`, { total: page.data - 1, complete: '█' }) - for (let i = 1; i < page.data; i++) { - if (progress) bar.tick() - const data = await getBangumi(vmid, status, webp, i) - list.push(...data) - } - return list - } else { - console.log('Get bangumi data error:', page?.data) - return [] - } -} -async function saveBangumiData(vmid, webp = true, progress, sourceDir) { - log.info('Getting bilibili bangumis, please wait...') - const startTime = new Date().getTime() - const wantWatch = await biliBangumi(vmid, 1, webp, progress) - const watching = await biliBangumi(vmid, 2, webp, progress) - const watched = await biliBangumi(vmid, 3, webp, progress) - const endTime = new Date().getTime() - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms') - const bangumis = { wantWatch, watching, watched } - if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { - fs.mkdirsSync(path.join(sourceDir, '/_data/')) - } - fs.writeFile(path.join(sourceDir, '/_data/bangumis.json'), JSON.stringify(bangumis), err => { - if (err) { - log.info('Failed to write data to bangumis.json') - console.error(err) - } else { - log.info('Bilibili bangumis data has been saved') - } - }) -} diff --git a/.history/src/index_20210217104038.js b/.history/src/index_20210217104038.js deleted file mode 100644 index 0fcf6ac..0000000 --- a/.history/src/index_20210217104038.js +++ /dev/null @@ -1,137 +0,0 @@ -/* global hexo */ -'use strict' -const fs = require('hexo-fs') -const path = require('path') -const axios = require('axios') -const log = require('hexo-log')({ - debug: false, - silent: false -}) -const ProgressBar = require('progress') - -if (typeof URL !== 'function') var { URL } = require('url') - -const options = { - options: [ - { name: '-u, --update', desc: 'Update bangumi data' }, - { name: '-d, --delete', desc: 'Delete bangumi data' } - ] -} -hexo.extend.generator.register('bangumis', function (locals) { - if (!this?.config?.bangumi?.enable) { - return - } - return require('./lib/bangumi-generator').call(this, locals) -}) -hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { - if (args.d) { - if (fs.existsSync(path.join(this.source_dir, '/_data/bangumis.json'))) { - fs.unlinkSync(path.join(this.source_dir, '/_data/bangumis.json')) - log.info('Bangumis data has been deleted') - } - } else if (args.u) { - if (!this?.config?.bangumi) { - log.info('Please add config to _config.yml') - return - } - if (!this.config.bangumi.enable) { - return - } - if (!this.config.bangumi.vmid) { - log.info('Please add vmid to _config.yml') - return - } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress ?? true, this.source_dir) - } else { - log.info('Unknown command, please use "hexo bangumi -h" to see the available commands') - } -}) - -async function getBangumiPage (vmid, status) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=1&pn=1`) - if (response?.data?.code === 0 && response?.data?.message === '0' && response?.data?.data && typeof response?.data?.data?.total !== 'undefined') { - return { success: true, data: Math.ceil(response.data.data.total / 30) + 1 } - } else if (response && response.data && response.data.message !== '0') { - return { success: false, data: response.data.message } - } else if (response && response.data) { - return { success: false, data: response.data } - } else { - return { success: false, data: response } - } -} -async function getBangumi (vmid, status, webp, pn) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) - const $data = [] - if (response?.data?.code === 0) { - const data = response?.data?.data - const list = data?.list || [] - for (const bangumi of list) { - let cover = bangumi?.cover - if (cover) { - const href = new URL(cover) - href.protocol = 'https' - if (webp) href.pathname += '@220w_280h.webp' - cover = href.href - } - $data.push({ - title: bangumi?.title, - type: bangumi?.season_type_name, - area: bangumi?.areas?.[0]?.name, - cover: cover, - totalCount: total(bangumi?.total_count), - id: bangumi?.media_id, - follow: count(bangumi?.stat?.follow), - view: count(bangumi?.stat?.view), - danmaku: count(bangumi?.stat?.danmaku), - coin: count(bangumi.stat.coin), - score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', - des: bangumi?.evaluate - }) - } - return $data - } -} -function count (e) { - return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-' -} -function total (e) { - return e ? (e === -1 ? '未完结' : `全${e}话`) : '-' -} -async function biliBangumi (vmid, status, webp, progress) { - const page = await getBangumiPage(vmid, status, webp) - if (page?.success) { - const list = [] - let bar = null - if (progress) bar = new ProgressBar(`正在获取 ${status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]'} 番剧 [:bar] :percent :elapseds`, { total: page.data - 1, complete: '█' }) - for (let i = 1; i < page.data; i++) { - if (progress) bar.tick() - const data = await getBangumi(vmid, status, webp, i) - list.push(...data) - } - return list - } else { - console.log('Get bangumi data error:', page?.data) - return [] - } -} -async function saveBangumiData(vmid, webp = true, progress, sourceDir) { - log.info('Getting bilibili bangumis, please wait...') - const startTime = new Date().getTime() - const wantWatch = await biliBangumi(vmid, 1, webp, progress) - const watching = await biliBangumi(vmid, 2, webp, progress) - const watched = await biliBangumi(vmid, 3, webp, progress) - const endTime = new Date().getTime() - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms') - const bangumis = { wantWatch, watching, watched } - if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { - fs.mkdirsSync(path.join(sourceDir, '/_data/')) - } - fs.writeFile(path.join(sourceDir, '/_data/bangumis.json'), JSON.stringify(bangumis), err => { - if (err) { - log.info('Failed to write data to bangumis.json') - console.error(err) - } else { - log.info('Bilibili bangumis data has been saved') - } - }) -} diff --git a/README.md b/README.md index abba1b0..896bc7e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ## 介绍 -**为 Hexo 添加哔哩哔哩番剧页面,参考自[hexo-douban](https://github.com/mythsman/hexo-douban)**. +**为 Hexo 添加哔哩哔哩追番/追剧页面,参考自[hexo-douban](https://github.com/mythsman/hexo-douban)**. [Demo](https://demo.hclonely.com/bangumis/) @@ -21,7 +21,19 @@ $ npm install hexo-bilibili-bangumi --save 将下面的配置写入站点的配置文件 `_config.yml` 里(不是主题的配置文件). ``` yaml -bangumi: +bangumi: # 追番设置 + enable: true + path: + vmid: + title: '追番列表' + quote: '生命不息,追番不止!' + show: 1 + loading: + metaColor: + color: + webp: + progress: +cinema: # 追剧设置 enable: true path: vmid: @@ -36,8 +48,8 @@ bangumi: ``` - **enable**: 是否启用 -- **path**: 番剧页面路径,默认`bangumis/index.html` -- **vmid**: 哔哩哔哩番剧页面的 `vmid(uid)`,[如何获取?](#获取uid) +- **path**: 页面路径,默认`bangumis/index.html`, `cinemas/index.html` +- **vmid**: 哔哩哔哩的 `vmid(uid)`,[如何获取?](#获取uid) - **title**: 该页面的标题 - **quote**: 写在页面开头的一段话,支持 html 语法,可留空。 - **show**: 初始显示页面:`0: 想看`, `1: 在看`, `2: 看过`,默认为`1` @@ -49,8 +61,8 @@ bangumi: ## 使用 -1. 在`hexo generate`或`hexo deploy`之前使用`hexo bangumi -u`命令更新番剧数据! -2. 删除数据命令:`hexo bangumi -d` +1. 在`hexo generate`或`hexo deploy`之前使用`hexo bangumi -u`命令更新追番数据,使用`hexo cinema -u`命令更新追剧数据! +2. 删除数据命令:`hexo bangumi -d`/`hexo cinema -d` ## 获取 uid @@ -62,25 +74,25 @@ bangumi: ![示例图片](https://github.com/HCLonely/hexo-bilibili-bangumi/raw/master/example.png) -## 手动添加番剧数据 +## 手动添加番剧/追剧数据 因为某些番剧在哔哩哔哩上没有,但是又想在hexo中展示,怎么办呢?现在支持手动添加番剧数据了! -在 `sources/_data/` 目录下新建文件,命名为 `extra_bangumis.json` ,并添加以如下内容: +在 `sources/_data/` 目录下新建文件,命名为 `extra_bangumis.json`(追番数据)或`extra_cinemas.json`(追剧数据) ,并添加以如下内容: ```json { "watchedExtra": [ { - "title": "缘之空", - "type": "番剧", - "area": "日本", - "cover": "https://cdn.jsdelivr.net/gh/mmdjiji/bangumis@main/Yosuga-no-Sora/cover.jpg", - "totalCount": "全12话", + "title": "缘之空", + "type": "番剧", + "area": "日本", + "cover": "https://cdn.jsdelivr.net/gh/mmdjiji/bangumis@main/Yosuga-no-Sora/cover.jpg", + "totalCount": "全12话", "id": 0, - "follow": "不可用", - "view": "不可用", - "danmaku": "不可用", - "coin": "不可用", - "score": "不可用", + "follow": "不可用", + "view": "不可用", + "danmaku": "不可用", + "coin": "不可用", + "score": "不可用", "des": "远离都市的田园小镇,奥木染。春日野悠带着妹妹穹,来到了这座城镇。坐落在这里的是,儿时暑假经常造访的充满回忆的已故祖父的家。双亲因意外事故而丧生,变得无依无靠..." } ] diff --git a/index.js b/index.js index 1b92b6b..3d5e177 100644 --- a/index.js +++ b/index.js @@ -1,42 +1,27 @@ /* global hexo */ 'use strict'; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); - -var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); - -var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); - -var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); - -function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - var fs = require('hexo-fs'); var path = require('path'); -var axios = require('axios'); - var log = require('hexo-log')({ debug: false, silent: false }); -var ProgressBar = require('progress'); +var _require = require('./lib/get-bili-data'), + getBiliData = _require.getBiliData; -if (typeof URL !== 'function') var _require = require('url'), - URL = _require.URL; +if (typeof URL !== 'function') var _require2 = require('url'), + URL = _require2.URL; var options = { options: [{ name: '-u, --update', - desc: 'Update bangumi data' + desc: 'Update bilibili data' }, { name: '-d, --delete', - desc: 'Delete bangumi data' + desc: 'Delete bilibili data' }] }; hexo.extend.generator.register('bangumis', function (locals) { @@ -46,7 +31,16 @@ hexo.extend.generator.register('bangumis', function (locals) { return; } - return require('./lib/bangumi-generator').call(this, locals); + return require('./lib/bangumi-generator').call(this, locals, 'bangumi'); +}); +hexo.extend.generator.register('cinemas', function (locals) { + var _this$config2, _this$config2$cinema; + + if (!(this !== null && this !== void 0 && (_this$config2 = this.config) !== null && _this$config2 !== void 0 && (_this$config2$cinema = _this$config2.cinema) !== null && _this$config2$cinema !== void 0 && _this$config2$cinema.enable)) { + return; + } + + return require('./lib/bangumi-generator').call(this, locals, 'cinema'); }); hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { if (args.d) { @@ -55,9 +49,9 @@ hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for log.info('Bangumis data has been deleted'); } } else if (args.u) { - var _this$config2, _this$config$bangumi$; + var _this$config3, _this$config$bangumi$; - if (!(this !== null && this !== void 0 && (_this$config2 = this.config) !== null && _this$config2 !== void 0 && _this$config2.bangumi)) { + if (!(this !== null && this !== void 0 && (_this$config3 = this.config) !== null && _this$config3 !== void 0 && _this$config3.bangumi)) { log.info('Please add config to _config.yml'); return; } @@ -71,295 +65,36 @@ hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for return; } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, (_this$config$bangumi$ = this.config.bangumi.progress) !== null && _this$config$bangumi$ !== void 0 ? _this$config$bangumi$ : true, this.source_dir); + getBiliData(this.config.bangumi.vmid, 'bangumi', (_this$config$bangumi$ = this.config.bangumi.progress) !== null && _this$config$bangumi$ !== void 0 ? _this$config$bangumi$ : true, this.source_dir, this.config.bangumi.webp); } else { log.info('Unknown command, please use "hexo bangumi -h" to see the available commands'); } }); +hexo.extend.console.register('cinema', 'Generate pages of bilibili cinemas for Hexo', options, function (args) { + if (args.d) { + if (fs.existsSync(path.join(this.source_dir, '/_data/cinemas.json'))) { + fs.unlinkSync(path.join(this.source_dir, '/_data/cinemas.json')); + log.info('Cinemas data has been deleted'); + } + } else if (args.u) { + var _this$config4, _this$config$cinema$p; -function getBangumiPage(_x, _x2) { - return _getBangumiPage.apply(this, arguments); -} - -function _getBangumiPage() { - _getBangumiPage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(vmid, status) { - var _response$data, _response$data2, _response$data3, _response$data4, _response$data4$data; - - var response; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return axios.get("https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=".concat(status, "&vmid=").concat(vmid, "&ps=1&pn=1")); - - case 2: - response = _context.sent; - - if (!((response === null || response === void 0 ? void 0 : (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.code) === 0 && (response === null || response === void 0 ? void 0 : (_response$data2 = response.data) === null || _response$data2 === void 0 ? void 0 : _response$data2.message) === '0' && response !== null && response !== void 0 && (_response$data3 = response.data) !== null && _response$data3 !== void 0 && _response$data3.data && typeof (response === null || response === void 0 ? void 0 : (_response$data4 = response.data) === null || _response$data4 === void 0 ? void 0 : (_response$data4$data = _response$data4.data) === null || _response$data4$data === void 0 ? void 0 : _response$data4$data.total) !== 'undefined')) { - _context.next = 7; - break; - } - - return _context.abrupt("return", { - success: true, - data: Math.ceil(response.data.data.total / 30) + 1 - }); - - case 7: - if (!(response && response.data && response.data.message !== '0')) { - _context.next = 11; - break; - } - - return _context.abrupt("return", { - success: false, - data: response.data.message - }); - - case 11: - if (!(response && response.data)) { - _context.next = 15; - break; - } - - return _context.abrupt("return", { - success: false, - data: response.data - }); - - case 15: - return _context.abrupt("return", { - success: false, - data: response - }); - - case 16: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _getBangumiPage.apply(this, arguments); -} - -function getBangumi(_x3, _x4, _x5, _x6) { - return _getBangumi.apply(this, arguments); -} - -function _getBangumi() { - _getBangumi = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(vmid, status, webp, pn) { - var _response$data5; - - var response, $data, _response$data6, data, list, _iterator, _step, _bangumi$areas, _bangumi$areas$, _bangumi$stat, _bangumi$stat2, _bangumi$stat3, _bangumi$rating, bangumi, cover, href; - - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return axios.get("https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=".concat(status, "&vmid=").concat(vmid, "&ps=30&pn=").concat(pn)); - - case 2: - response = _context2.sent; - $data = []; - - if (!((response === null || response === void 0 ? void 0 : (_response$data5 = response.data) === null || _response$data5 === void 0 ? void 0 : _response$data5.code) === 0)) { - _context2.next = 10; - break; - } - - data = response === null || response === void 0 ? void 0 : (_response$data6 = response.data) === null || _response$data6 === void 0 ? void 0 : _response$data6.data; - list = (data === null || data === void 0 ? void 0 : data.list) || []; - _iterator = _createForOfIteratorHelper(list); - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - bangumi = _step.value; - cover = bangumi === null || bangumi === void 0 ? void 0 : bangumi.cover; - - if (cover) { - href = new URL(cover); - href.protocol = 'https'; - if (webp) href.pathname += '@220w_280h.webp'; - cover = href.href; - } - - $data.push({ - title: bangumi === null || bangumi === void 0 ? void 0 : bangumi.title, - type: bangumi === null || bangumi === void 0 ? void 0 : bangumi.season_type_name, - area: bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$areas = bangumi.areas) === null || _bangumi$areas === void 0 ? void 0 : (_bangumi$areas$ = _bangumi$areas[0]) === null || _bangumi$areas$ === void 0 ? void 0 : _bangumi$areas$.name, - cover: cover, - totalCount: total(bangumi === null || bangumi === void 0 ? void 0 : bangumi.total_count), - id: bangumi === null || bangumi === void 0 ? void 0 : bangumi.media_id, - follow: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat = bangumi.stat) === null || _bangumi$stat === void 0 ? void 0 : _bangumi$stat.follow), - view: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat2 = bangumi.stat) === null || _bangumi$stat2 === void 0 ? void 0 : _bangumi$stat2.view), - danmaku: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat3 = bangumi.stat) === null || _bangumi$stat3 === void 0 ? void 0 : _bangumi$stat3.danmaku), - coin: count(bangumi.stat.coin), - score: bangumi !== null && bangumi !== void 0 && bangumi.rating ? bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$rating = bangumi.rating) === null || _bangumi$rating === void 0 ? void 0 : _bangumi$rating.score : '暂无评分', - des: bangumi === null || bangumi === void 0 ? void 0 : bangumi.evaluate - }); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return _context2.abrupt("return", $data); - - case 10: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - return _getBangumi.apply(this, arguments); -} - -function count(e) { - return e ? e > 10000 && e < 100000000 ? "".concat((e / 10000).toFixed(1), " \u4E07") : e > 100000000 ? "".concat((e / 100000000).toFixed(1), " \u4EBF") : e : '-'; -} - -function total(e) { - return e ? e === -1 ? '未完结' : "\u5168".concat(e, "\u8BDD") : '-'; -} - -function biliBangumi(_x7, _x8, _x9, _x10) { - return _biliBangumi.apply(this, arguments); -} - -function _biliBangumi() { - _biliBangumi = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(vmid, status, webp, progress) { - var page, list, bar, i, data; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getBangumiPage(vmid, status, webp); - - case 2: - page = _context3.sent; - - if (!(page !== null && page !== void 0 && page.success)) { - _context3.next = 20; - break; - } - - list = []; - bar = null; - if (progress) bar = new ProgressBar("\u6B63\u5728\u83B7\u53D6 ".concat(status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]', " \u756A\u5267 [:bar] :percent :elapseds"), { - total: page.data - 1, - complete: '█' - }); - i = 1; - - case 8: - if (!(i < page.data)) { - _context3.next = 17; - break; - } - - if (progress) bar.tick(); - _context3.next = 12; - return getBangumi(vmid, status, webp, i); - - case 12: - data = _context3.sent; - list.push.apply(list, (0, _toConsumableArray2["default"])(data)); - - case 14: - i++; - _context3.next = 8; - break; - - case 17: - return _context3.abrupt("return", list); - - case 20: - console.log('Get bangumi data error:', page === null || page === void 0 ? void 0 : page.data); - return _context3.abrupt("return", []); - - case 22: - case "end": - return _context3.stop(); - } - } - }, _callee3); - })); - return _biliBangumi.apply(this, arguments); -} - -function saveBangumiData(_x11) { - return _saveBangumiData.apply(this, arguments); -} - -function _saveBangumiData() { - _saveBangumiData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(vmid) { - var webp, - progress, - sourceDir, - startTime, - wantWatch, - watching, - watched, - endTime, - bangumis, - _args4 = arguments; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - webp = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : true; - progress = _args4.length > 2 ? _args4[2] : undefined; - sourceDir = _args4.length > 3 ? _args4[3] : undefined; - log.info('Getting bilibili bangumis, please wait...'); - startTime = new Date().getTime(); - _context4.next = 7; - return biliBangumi(vmid, 1, webp, progress); - - case 7: - wantWatch = _context4.sent; - _context4.next = 10; - return biliBangumi(vmid, 2, webp, progress); - - case 10: - watching = _context4.sent; - _context4.next = 13; - return biliBangumi(vmid, 3, webp, progress); - - case 13: - watched = _context4.sent; - endTime = new Date().getTime(); - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms'); - bangumis = { - wantWatch: wantWatch, - watching: watching, - watched: watched - }; + if (!(this !== null && this !== void 0 && (_this$config4 = this.config) !== null && _this$config4 !== void 0 && _this$config4.cinema)) { + log.info('Please add config to _config.yml'); + return; + } - if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { - fs.mkdirsSync(path.join(sourceDir, '/_data/')); - } + if (!this.config.cinema.enable) { + return; + } - fs.writeFile(path.join(sourceDir, '/_data/bangumis.json'), JSON.stringify(bangumis), function (err) { - if (err) { - log.info('Failed to write data to bangumis.json'); - console.error(err); - } else { - log.info('Bilibili bangumis data has been saved'); - } - }); + if (!this.config.cinema.vmid) { + log.info('Please add vmid to _config.yml'); + return; + } - case 19: - case "end": - return _context4.stop(); - } - } - }, _callee4); - })); - return _saveBangumiData.apply(this, arguments); -} + getBiliData(this.config.cinema.vmid, 'cinema', (_this$config$cinema$p = this.config.cinema.progress) !== null && _this$config$cinema$p !== void 0 ? _this$config$cinema$p : true, this.source_dir, this.config.cinema.webp); + } else { + log.info('Unknown command, please use "hexo cinema -h" to see the available commands'); + } +}); diff --git a/lib/bangumi-generator.js b/lib/bangumi-generator.js index cad4c86..a02bb21 100644 --- a/lib/bangumi-generator.js +++ b/lib/bangumi-generator.js @@ -21,24 +21,39 @@ var log = require('hexo-log')({ module.exports = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(locals) { - var _config$bangumi; - - var config, root, wantWatch, watching, watched, _JSON$parse, wantWatchExtra, watchingExtra, watchedExtra, _JSON$parse2, __, contents; + var _config$type; + + var type, + config, + root, + wantWatch, + watching, + watched, + _JSON$parse, + wantWatchExtra, + watchingExtra, + watchedExtra, + _JSON$parse2, + __, + contents, + customPath, + _args = arguments; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: + type = _args.length > 1 && _args[1] !== undefined ? _args[1] : 'bangumi'; config = this.config; - if (config !== null && config !== void 0 && (_config$bangumi = config.bangumi) !== null && _config$bangumi !== void 0 && _config$bangumi.enable) { - _context.next = 3; + if (config !== null && config !== void 0 && (_config$type = config[type]) !== null && _config$type !== void 0 && _config$type.enable) { + _context.next = 4; break; } return _context.abrupt("return"); - case 3: + case 4: root = config.root; if (root.endsWith('/')) { @@ -49,22 +64,22 @@ module.exports = /*#__PURE__*/function () { watching = []; watched = []; // console.log(path.join(this.source_dir, '/_data/bangumis.json')) - if (!fs.existsSync(path.join(this.source_dir, '/_data/bangumis.json'))) { - log.info('Can\'t find bilibili bangumi data, please use \'hexo bangumi -u\' command to get data'); + if (!fs.existsSync(path.join(this.source_dir, '/_data/' + type + 's.json'))) { + log.info('Can\'t find bilibili ' + type + ' data, please use \'hexo ' + type + ' -u\' command to get data'); } else { - _JSON$parse = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/bangumis.json'))); + _JSON$parse = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/' + type + 's.json'))); wantWatch = _JSON$parse.wantWatch; watching = _JSON$parse.watching; watched = _JSON$parse.watched; - // extra bangumis - console.log(path.join(this.source_dir, '/_data/extra_bangumis.json')); - if (fs.existsSync(path.join(this.source_dir, '/_data/extra_bangumis.json'))) { - log.info('Found extra bangumi data'); + // extra bangumis + // console.log(path.join(this.source_dir, '/_data/extra_' + type + 's.json')) + if (fs.existsSync(path.join(this.source_dir, '/_data/extra_' + type + 's.json'))) { + log.info('Found extra ' + type + 's data'); wantWatchExtra = []; watchingExtra = []; watchedExtra = []; - _JSON$parse2 = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/extra_bangumis.json'))); + _JSON$parse2 = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/extra_' + type + 's.json'))); wantWatchExtra = _JSON$parse2.wantWatchExtra; watchingExtra = _JSON$parse2.watchingExtra; watchedExtra = _JSON$parse2.watchedExtra; @@ -82,38 +97,40 @@ module.exports = /*#__PURE__*/function () { } } - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded'); + log.info(wantWatch.length + watching.length + watched.length + ' ' + type + 's have been loaded'); } __ = i18n.__(config.language); - _context.next = 12; + _context.next = 13; return ejs.renderFile(path.join(__dirname, 'templates/bangumi.ejs'), { - quote: config.bangumi.quote, - show: config.bangumi.show || 1, - loading: config.bangumi.loading, - metaColor: config.bangumi.metaColor ? "style=\"color:".concat(config.bangumi.metaColor, "\"") : '', - color: config.bangumi.color ? "style=\"color:".concat(config.bangumi.color, "\"") : '', + quote: config[type].quote, + show: config[type].show || 1, + loading: config[type].loading, + metaColor: config[type].metaColor ? "style=\"color:".concat(config[type].metaColor, "\"") : '', + color: config[type].color ? "style=\"color:".concat(config[type].color, "\"") : '', wantWatch: wantWatch, watched: watched, watching: watching, + type: type, __: __, root: root }, { async: false }); - case 12: + case 13: contents = _context.sent; + customPath = config[type].path; return _context.abrupt("return", { - path: config.bangumi.path || 'bangumis/index.html', + path: customPath || type + 's/index.html', data: { - title: config.bangumi.title, + title: config[type].title, content: contents }, layout: ['page', 'post'] }); - case 14: + case 16: case "end": return _context.stop(); } diff --git a/lib/get-bili-data.js b/lib/get-bili-data.js new file mode 100644 index 0000000..f86722a --- /dev/null +++ b/lib/get-bili-data.js @@ -0,0 +1,314 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +var fs = require('hexo-fs'); + +var path = require('path'); + +var axios = require('axios'); + +var log = require('hexo-log')({ + debug: false, + silent: false +}); + +var ProgressBar = require('progress'); + +function getDataPage(_x, _x2, _x3) { + return _getDataPage.apply(this, arguments); +} + +function _getDataPage() { + _getDataPage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(vmid, status, typeNum) { + var _response$data, _response$data2, _response$data3, _response$data4, _response$data4$data; + + var response; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return axios.get("https://api.bilibili.com/x/space/bangumi/follow/list?type=".concat(typeNum, "&follow_status=").concat(status, "&vmid=").concat(vmid, "&ps=1&pn=1")); + + case 2: + response = _context2.sent; + + if (!((response === null || response === void 0 ? void 0 : (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.code) === 0 && (response === null || response === void 0 ? void 0 : (_response$data2 = response.data) === null || _response$data2 === void 0 ? void 0 : _response$data2.message) === '0' && response !== null && response !== void 0 && (_response$data3 = response.data) !== null && _response$data3 !== void 0 && _response$data3.data && typeof (response === null || response === void 0 ? void 0 : (_response$data4 = response.data) === null || _response$data4 === void 0 ? void 0 : (_response$data4$data = _response$data4.data) === null || _response$data4$data === void 0 ? void 0 : _response$data4$data.total) !== 'undefined')) { + _context2.next = 7; + break; + } + + return _context2.abrupt("return", { + success: true, + data: Math.ceil(response.data.data.total / 30) + 1 + }); + + case 7: + if (!(response && response.data && response.data.message !== '0')) { + _context2.next = 11; + break; + } + + return _context2.abrupt("return", { + success: false, + data: response.data.message + }); + + case 11: + if (!(response && response.data)) { + _context2.next = 15; + break; + } + + return _context2.abrupt("return", { + success: false, + data: response.data + }); + + case 15: + return _context2.abrupt("return", { + success: false, + data: response + }); + + case 16: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getDataPage.apply(this, arguments); +} + +function getData(_x4, _x5, _x6, _x7, _x8) { + return _getData.apply(this, arguments); +} + +function _getData() { + _getData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(vmid, status, useWebp, typeNum, pn) { + var _response$data5; + + var response, $data, _response$data6, data, list, _iterator, _step, _bangumi$areas, _bangumi$areas$, _bangumi$stat, _bangumi$stat2, _bangumi$stat3, _bangumi$rating, bangumi, cover, href; + + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return axios.get("https://api.bilibili.com/x/space/bangumi/follow/list?type=".concat(typeNum, "&follow_status=").concat(status, "&vmid=").concat(vmid, "&ps=30&pn=").concat(pn)); + + case 2: + response = _context3.sent; + $data = []; + + if (!((response === null || response === void 0 ? void 0 : (_response$data5 = response.data) === null || _response$data5 === void 0 ? void 0 : _response$data5.code) === 0)) { + _context3.next = 10; + break; + } + + data = response === null || response === void 0 ? void 0 : (_response$data6 = response.data) === null || _response$data6 === void 0 ? void 0 : _response$data6.data; + list = (data === null || data === void 0 ? void 0 : data.list) || []; + _iterator = _createForOfIteratorHelper(list); + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + bangumi = _step.value; + cover = bangumi === null || bangumi === void 0 ? void 0 : bangumi.cover; + + if (cover) { + href = new URL(cover); + href.protocol = 'https'; + if (useWebp) href.pathname += '@220w_280h.webp'; + cover = href.href; + } + + $data.push({ + title: bangumi === null || bangumi === void 0 ? void 0 : bangumi.title, + type: bangumi === null || bangumi === void 0 ? void 0 : bangumi.season_type_name, + area: bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$areas = bangumi.areas) === null || _bangumi$areas === void 0 ? void 0 : (_bangumi$areas$ = _bangumi$areas[0]) === null || _bangumi$areas$ === void 0 ? void 0 : _bangumi$areas$.name, + cover: cover, + totalCount: total(bangumi === null || bangumi === void 0 ? void 0 : bangumi.total_count, typeNum), + id: bangumi === null || bangumi === void 0 ? void 0 : bangumi.media_id, + follow: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat = bangumi.stat) === null || _bangumi$stat === void 0 ? void 0 : _bangumi$stat.follow), + view: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat2 = bangumi.stat) === null || _bangumi$stat2 === void 0 ? void 0 : _bangumi$stat2.view), + danmaku: count(bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$stat3 = bangumi.stat) === null || _bangumi$stat3 === void 0 ? void 0 : _bangumi$stat3.danmaku), + coin: count(bangumi.stat.coin), + score: bangumi !== null && bangumi !== void 0 && bangumi.rating ? bangumi === null || bangumi === void 0 ? void 0 : (_bangumi$rating = bangumi.rating) === null || _bangumi$rating === void 0 ? void 0 : _bangumi$rating.score : '暂无评分', + des: bangumi === null || bangumi === void 0 ? void 0 : bangumi.evaluate + }); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return _context3.abrupt("return", $data); + + case 10: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _getData.apply(this, arguments); +} + +function count(e) { + return e ? e > 10000 && e < 100000000 ? "".concat((e / 10000).toFixed(1), " \u4E07") : e > 100000000 ? "".concat((e / 100000000).toFixed(1), " \u4EBF") : e : '-'; +} + +function total(e, typeNum) { + return e ? e === -1 ? '未完结' : "\u5168".concat(e).concat(typeNum === 1 ? '话' : '集') : '-'; +} + +function processData(_x9, _x10, _x11, _x12, _x13) { + return _processData.apply(this, arguments); +} + +function _processData() { + _processData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(vmid, status, useWebp, showProgress, typeNum) { + var page, list, bar, i, data; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return getDataPage(vmid, status, typeNum); + + case 2: + page = _context4.sent; + + if (!(page !== null && page !== void 0 && page.success)) { + _context4.next = 20; + break; + } + + list = []; + bar = null; + if (showProgress) bar = new ProgressBar("\u6B63\u5728\u83B7\u53D6 ".concat(status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]', " ").concat(typeNum === 1 ? '番剧' : '追剧', " [:bar] :percent :elapseds"), { + total: page.data - 1, + complete: '█' + }); + i = 1; + + case 8: + if (!(i < page.data)) { + _context4.next = 17; + break; + } + + if (showProgress) bar.tick(); + _context4.next = 12; + return getData(vmid, status, useWebp, typeNum, i); + + case 12: + data = _context4.sent; + list.push.apply(list, (0, _toConsumableArray2["default"])(data)); + + case 14: + i++; + _context4.next = 8; + break; + + case 17: + return _context4.abrupt("return", list); + + case 20: + console.log('Get ' + (typeNum === 1 ? 'bangumi' : 'cinema') + ' data error:', page === null || page === void 0 ? void 0 : page.data); + return _context4.abrupt("return", []); + + case 22: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _processData.apply(this, arguments); +} + +module.exports.getBiliData = /*#__PURE__*/function () { + var _getBiliData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(vmid, type, showProgress, sourceDir) { + var useWebp, + typeNum, + startTime, + wantWatch, + watching, + watched, + endTime, + bangumis, + _args = arguments; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + useWebp = _args.length > 4 && _args[4] !== undefined ? _args[4] : true; + typeNum = type === 'cinema' ? 2 : 1; + log.info('Getting bilibili ' + type + ', please wait...'); + startTime = new Date().getTime(); + _context.next = 6; + return processData(vmid, 1, useWebp, showProgress, typeNum); + + case 6: + wantWatch = _context.sent; + _context.next = 9; + return processData(vmid, 2, useWebp, showProgress, typeNum); + + case 9: + watching = _context.sent; + _context.next = 12; + return processData(vmid, 3, useWebp, showProgress, typeNum); + + case 12: + watched = _context.sent; + endTime = new Date().getTime(); + log.info(wantWatch.length + watching.length + watched.length + ' ' + type + 's have been loaded in ' + (endTime - startTime) + ' ms'); + bangumis = { + wantWatch: wantWatch, + watching: watching, + watched: watched + }; + + if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { + fs.mkdirsSync(path.join(sourceDir, '/_data/')); + } + + fs.writeFile(path.join(sourceDir, '/_data/' + type + 's.json'), JSON.stringify(bangumis), function (err) { + if (err) { + log.info('Failed to write data to ' + type + 's.json'); + console.error(err); + } else { + log.info('Bilibili ' + type + 's data has been saved'); + } + }); + + case 18: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + function getBiliData(_x14, _x15, _x16, _x17) { + return _getBiliData.apply(this, arguments); + } + + return getBiliData; +}(); diff --git a/lib/templates/bangumi.ejs b/lib/templates/bangumi.ejs index be5c7f5..9c9740b 100644 --- a/lib/templates/bangumi.ejs +++ b/lib/templates/bangumi.ejs @@ -20,19 +20,19 @@
<% wantWatch.forEach(function(item){ %> - <%- include('template.ejs', {item,loading,metaColor}) %> + <%- include('template.ejs', {item,loading,metaColor,type}) %> <% }); %> <%- include('pagination.ejs', {__: __}) %>
<% watching.forEach(function(item){ %> - <%- include('template.ejs', {item,loading,metaColor}) %> + <%- include('template.ejs', {item,loading,metaColor,type}) %> <% }); %> <%- include('pagination.ejs', {__: __}) %>
<% watched.forEach(function(item){ %> - <%- include('template.ejs', {item,loading,metaColor}) %> + <%- include('template.ejs', {item,loading,metaColor,type}) %> <% }); %> <%- include('pagination.ejs', {__: __}) %>
diff --git a/lib/templates/template.ejs b/lib/templates/template.ejs index fd6e2a4..a758f70 100644 --- a/lib/templates/template.ejs +++ b/lib/templates/template.ejs @@ -22,7 +22,7 @@ 总播放 <%= item.view || "-" %> - 追番人数 <%= item.follow || "-" %> + <%= type === 'bangumi' ? '追番人数' : '追剧人数' %> <%= item.follow || "-" %> 硬币数 <%= item.coin || "-" %> @@ -35,6 +35,6 @@
-
>
简介:<%= item.des || "暂无简介" %>
+
>

简介:<%= item.des || "暂无简介" %>

diff --git a/package-lock.json b/package-lock.json index 0cebc84..91998ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "hexo-bilibili-bangumi", - "version": "1.5.4", + "version": "1.6.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -597,30 +597,6 @@ "regexpu-core": "^4.7.1" } }, - "@babel/helper-define-polyfill-provider": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.2.0.tgz", - "integrity": "sha512-JT8tHuFjKBo8NnaUbblz7mIu1nnvUDiHVjXXkulZULyidvo/7P6TY7+YqpV37IfF+KUFxmlK04elKtGKXaiVgw==", - "dev": true, - "requires": { - "@babel/helper-compilation-targets": "^7.13.0", - "@babel/helper-module-imports": "^7.12.13", - "@babel/helper-plugin-utils": "^7.13.0", - "@babel/traverse": "^7.13.0", - "debug": "^4.1.1", - "lodash.debounce": "^4.0.8", - "resolve": "^1.14.2", - "semver": "^6.1.2" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, "@babel/helper-explode-assignable-expression": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.14.5.tgz", @@ -695,28 +671,6 @@ } } }, - "@babel/helper-member-expression-to-functions": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", - "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", - "dev": true, - "requires": { - "@babel/types": "^7.13.12" - }, - "dependencies": { - "@babel/types": { - "version": "7.13.13", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.13.tgz", - "integrity": "sha512-kt+EpC6qDfIaqlP+DIbIJOclYy/A1YXs9dAf/ljbi+39Bcbc073H6jKVpXEr/EoIh5anGn5xq/yRVzKl+uIc9w==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.12.11", - "lodash": "^4.17.19", - "to-fast-properties": "^2.0.0" - } - } - } - }, "@babel/helper-module-imports": { "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", @@ -744,93 +698,6 @@ } } }, - "@babel/helper-module-transforms": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.14.2.tgz", - "integrity": "sha512-OznJUda/soKXv0XhpvzGWDnml4Qnwp16GN+D/kZIdLsWoHj05kyu8Rm5kXmMef+rVJZ0+4pSGLkeixdqNUATDA==", - "dev": true, - "requires": { - "@babel/helper-module-imports": "^7.13.12", - "@babel/helper-replace-supers": "^7.13.12", - "@babel/helper-simple-access": "^7.13.12", - "@babel/helper-split-export-declaration": "^7.12.13", - "@babel/helper-validator-identifier": "^7.14.0", - "@babel/template": "^7.12.13", - "@babel/traverse": "^7.14.2", - "@babel/types": "^7.14.2" - }, - "dependencies": { - "@babel/generator": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.14.2.tgz", - "integrity": "sha512-OnADYbKrffDVai5qcpkMxQ7caomHOoEwjkouqnN2QhydAjowFAZcsdecFIRUBdb+ZcruwYE4ythYmF1UBZU5xQ==", - "dev": true, - "requires": { - "@babel/types": "^7.14.2", - "jsesc": "^2.5.1", - "source-map": "^0.5.0" - } - }, - "@babel/helper-function-name": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.2.tgz", - "integrity": "sha512-NYZlkZRydxw+YT56IlhIcS8PAhb+FEUiOzuhFTfqDyPmzAhRge6ua0dQYT/Uh0t/EDHq05/i+e5M2d4XvjgarQ==", - "dev": true, - "requires": { - "@babel/helper-get-function-arity": "^7.12.13", - "@babel/template": "^7.12.13", - "@babel/types": "^7.14.2" - } - }, - "@babel/helper-validator-identifier": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz", - "integrity": "sha512-V3ts7zMSu5lfiwWDVWzRDGIN+lnCEUdaXgtVHJgLb1rGaA6jMrtB9EmE7L18foXJIE8Un/A/h6NJfGQp/e1J4A==", - "dev": true - }, - "@babel/parser": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.14.2.tgz", - "integrity": "sha512-IoVDIHpsgE/fu7eXBeRWt8zLbDrSvD7H1gpomOkPpBoEN8KCruCqSDdqo8dddwQQrui30KSvQBaMUOJiuFu6QQ==", - "dev": true - }, - "@babel/traverse": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.14.2.tgz", - "integrity": "sha512-TsdRgvBFHMyHOOzcP9S6QU0QQtjxlRpEYOy3mcCO5RgmC305ki42aSAmfZEMSSYBla2oZ9BMqYlncBaKmD/7iA==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.12.13", - "@babel/generator": "^7.14.2", - "@babel/helper-function-name": "^7.14.2", - "@babel/helper-split-export-declaration": "^7.12.13", - "@babel/parser": "^7.14.2", - "@babel/types": "^7.14.2", - "debug": "^4.1.0", - "globals": "^11.1.0" - } - }, - "@babel/types": { - "version": "7.14.2", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.14.2.tgz", - "integrity": "sha512-SdjAG/3DikRHpUOjxZgnkbR11xUlyDMUFJdvnIgZEE16mqmY0BINMmc4//JMJglEmn6i7sq6p+mGrFWyZ98EEw==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.14.0", - "to-fast-properties": "^2.0.0" - } - } - } - }, - "@babel/helper-optimise-call-expression": { - "version": "7.12.13", - "resolved": "https://registry.npm.taobao.org/@babel/helper-optimise-call-expression/download/@babel/helper-optimise-call-expression-7.12.13.tgz?cache=0&sync_timestamp=1612314687212&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40babel%2Fhelper-optimise-call-expression%2Fdownload%2F%40babel%2Fhelper-optimise-call-expression-7.12.13.tgz", - "integrity": "sha1-XALRcbTIYVsecWP4iMHIHDCiquo=", - "dev": true, - "requires": { - "@babel/types": "^7.12.13" - } - }, "@babel/helper-plugin-utils": { "version": "7.13.0", "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.13.0.tgz", @@ -866,53 +733,6 @@ } } }, - "@babel/helper-replace-supers": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.13.12.tgz", - "integrity": "sha512-Gz1eiX+4yDO8mT+heB94aLVNCL+rbuT2xy4YfyNqu8F+OI6vMvJK891qGBTqL9Uc8wxEvRW92Id6G7sDen3fFw==", - "dev": true, - "requires": { - "@babel/helper-member-expression-to-functions": "^7.13.12", - "@babel/helper-optimise-call-expression": "^7.12.13", - "@babel/traverse": "^7.13.0", - "@babel/types": "^7.13.12" - }, - "dependencies": { - "@babel/types": { - "version": "7.13.13", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.13.tgz", - "integrity": "sha512-kt+EpC6qDfIaqlP+DIbIJOclYy/A1YXs9dAf/ljbi+39Bcbc073H6jKVpXEr/EoIh5anGn5xq/yRVzKl+uIc9w==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.12.11", - "lodash": "^4.17.19", - "to-fast-properties": "^2.0.0" - } - } - } - }, - "@babel/helper-simple-access": { - "version": "7.13.12", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", - "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", - "dev": true, - "requires": { - "@babel/types": "^7.13.12" - }, - "dependencies": { - "@babel/types": { - "version": "7.13.13", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.13.tgz", - "integrity": "sha512-kt+EpC6qDfIaqlP+DIbIJOclYy/A1YXs9dAf/ljbi+39Bcbc073H6jKVpXEr/EoIh5anGn5xq/yRVzKl+uIc9w==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.12.11", - "lodash": "^4.17.19", - "to-fast-properties": "^2.0.0" - } - } - } - }, "@babel/helper-skip-transparent-expression-wrappers": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.14.5.tgz", @@ -4521,44 +4341,6 @@ "babel-helper-is-void-0": "^0.4.3" } }, - "babel-plugin-polyfill-corejs2": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.2.0.tgz", - "integrity": "sha512-9bNwiR0dS881c5SHnzCmmGlMkJLl0OUZvxrxHo9w/iNoRuqaPjqlvBf4HrovXtQs/au5yKkpcdgfT1cC5PAZwg==", - "dev": true, - "requires": { - "@babel/compat-data": "^7.13.11", - "@babel/helper-define-polyfill-provider": "^0.2.0", - "semver": "^6.1.1" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "babel-plugin-polyfill-corejs3": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.2.0.tgz", - "integrity": "sha512-zZyi7p3BCUyzNxLx8KV61zTINkkV65zVkDAFNZmrTCRVhjo1jAS+YLvDJ9Jgd/w2tsAviCwFHReYfxO3Iql8Yg==", - "dev": true, - "requires": { - "@babel/helper-define-polyfill-provider": "^0.2.0", - "core-js-compat": "^3.9.1" - } - }, - "babel-plugin-polyfill-regenerator": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.2.0.tgz", - "integrity": "sha512-J7vKbCuD2Xi/eEHxquHN14bXAW9CXtecwuLrOIDJtcZzTaPzV1VdEfoUf9AzcRBMolKUQKM9/GVojeh0hFiqMg==", - "dev": true, - "requires": { - "@babel/helper-define-polyfill-provider": "^0.2.0" - } - }, "babel-plugin-transform-inline-consecutive-adds": { "version": "0.4.3", "resolved": "https://registry.npm.taobao.org/babel-plugin-transform-inline-consecutive-adds/download/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz", diff --git a/package.json b/package.json index 43ab3b7..f376ff1 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "hexo-bilibili-bangumi", - "version": "1.5.4", + "version": "1.6.0", "description": "hexo bilibili番剧页", "main": "index.js", "scripts": { "test": "standard --fix && ejslint lib/templates/*.ejs", - "build": "babel src/index.js --out-file index.js && babel src/lib/util.js --out-file lib/util.js && babel src/lib/bangumi-generator.js --out-file lib/bangumi-generator.js && babel src/lib/templates/index.js --out-file lib/templates/index.js --presets minify && babel src/lib/templates/pagination.js --out-file lib/templates/pagination.js --presets minify && cleancss src/lib/templates/index.css -O2 -o lib/templates/index.css", + "build": "babel src/index.js --out-file index.js && babel src/lib/util.js --out-file lib/util.js && babel src/lib/get-bili-data.js --out-file lib/get-bili-data.js && babel src/lib/bangumi-generator.js --out-file lib/bangumi-generator.js && babel src/lib/templates/index.js --out-file lib/templates/index.js --presets minify && babel src/lib/templates/pagination.js --out-file lib/templates/pagination.js --presets minify && cleancss src/lib/templates/index.css -O2 -o lib/templates/index.css", "ejslint": "ejslint lib/templates/*.ejs" }, "author": "HCLonely ", diff --git a/src/index.js b/src/index.js index 0fcf6ac..afac057 100644 --- a/src/index.js +++ b/src/index.js @@ -2,26 +2,31 @@ 'use strict' const fs = require('hexo-fs') const path = require('path') -const axios = require('axios') const log = require('hexo-log')({ debug: false, silent: false }) -const ProgressBar = require('progress') +const { getBiliData } = require('./lib/get-bili-data') if (typeof URL !== 'function') var { URL } = require('url') const options = { options: [ - { name: '-u, --update', desc: 'Update bangumi data' }, - { name: '-d, --delete', desc: 'Delete bangumi data' } + { name: '-u, --update', desc: 'Update bilibili data' }, + { name: '-d, --delete', desc: 'Delete bilibili data' } ] } hexo.extend.generator.register('bangumis', function (locals) { if (!this?.config?.bangumi?.enable) { return } - return require('./lib/bangumi-generator').call(this, locals) + return require('./lib/bangumi-generator').call(this, locals, 'bangumi') +}) +hexo.extend.generator.register('cinemas', function (locals) { + if (!this?.config?.cinema?.enable) { + return + } + return require('./lib/bangumi-generator').call(this, locals, 'cinema') }) hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { if (args.d) { @@ -41,97 +46,31 @@ hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for log.info('Please add vmid to _config.yml') return } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress ?? true, this.source_dir) + getBiliData(this.config.bangumi.vmid, 'bangumi', this.config.bangumi.progress ?? true, this.source_dir, this.config.bangumi.webp) } else { log.info('Unknown command, please use "hexo bangumi -h" to see the available commands') } }) - -async function getBangumiPage (vmid, status) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=1&pn=1`) - if (response?.data?.code === 0 && response?.data?.message === '0' && response?.data?.data && typeof response?.data?.data?.total !== 'undefined') { - return { success: true, data: Math.ceil(response.data.data.total / 30) + 1 } - } else if (response && response.data && response.data.message !== '0') { - return { success: false, data: response.data.message } - } else if (response && response.data) { - return { success: false, data: response.data } - } else { - return { success: false, data: response } - } -} -async function getBangumi (vmid, status, webp, pn) { - const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) - const $data = [] - if (response?.data?.code === 0) { - const data = response?.data?.data - const list = data?.list || [] - for (const bangumi of list) { - let cover = bangumi?.cover - if (cover) { - const href = new URL(cover) - href.protocol = 'https' - if (webp) href.pathname += '@220w_280h.webp' - cover = href.href - } - $data.push({ - title: bangumi?.title, - type: bangumi?.season_type_name, - area: bangumi?.areas?.[0]?.name, - cover: cover, - totalCount: total(bangumi?.total_count), - id: bangumi?.media_id, - follow: count(bangumi?.stat?.follow), - view: count(bangumi?.stat?.view), - danmaku: count(bangumi?.stat?.danmaku), - coin: count(bangumi.stat.coin), - score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', - des: bangumi?.evaluate - }) +hexo.extend.console.register('cinema', 'Generate pages of bilibili cinemas for Hexo', options, function (args) { + if (args.d) { + if (fs.existsSync(path.join(this.source_dir, '/_data/cinemas.json'))) { + fs.unlinkSync(path.join(this.source_dir, '/_data/cinemas.json')) + log.info('Cinemas data has been deleted') } - return $data - } -} -function count (e) { - return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-' -} -function total (e) { - return e ? (e === -1 ? '未完结' : `全${e}话`) : '-' -} -async function biliBangumi (vmid, status, webp, progress) { - const page = await getBangumiPage(vmid, status, webp) - if (page?.success) { - const list = [] - let bar = null - if (progress) bar = new ProgressBar(`正在获取 ${status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]'} 番剧 [:bar] :percent :elapseds`, { total: page.data - 1, complete: '█' }) - for (let i = 1; i < page.data; i++) { - if (progress) bar.tick() - const data = await getBangumi(vmid, status, webp, i) - list.push(...data) + } else if (args.u) { + if (!this?.config?.cinema) { + log.info('Please add config to _config.yml') + return + } + if (!this.config.cinema.enable) { + return + } + if (!this.config.cinema.vmid) { + log.info('Please add vmid to _config.yml') + return } - return list + getBiliData(this.config.cinema.vmid, 'cinema', this.config.cinema.progress ?? true, this.source_dir, this.config.cinema.webp) } else { - console.log('Get bangumi data error:', page?.data) - return [] - } -} -async function saveBangumiData(vmid, webp = true, progress, sourceDir) { - log.info('Getting bilibili bangumis, please wait...') - const startTime = new Date().getTime() - const wantWatch = await biliBangumi(vmid, 1, webp, progress) - const watching = await biliBangumi(vmid, 2, webp, progress) - const watched = await biliBangumi(vmid, 3, webp, progress) - const endTime = new Date().getTime() - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms') - const bangumis = { wantWatch, watching, watched } - if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { - fs.mkdirsSync(path.join(sourceDir, '/_data/')) + log.info('Unknown command, please use "hexo cinema -h" to see the available commands') } - fs.writeFile(path.join(sourceDir, '/_data/bangumis.json'), JSON.stringify(bangumis), err => { - if (err) { - log.info('Failed to write data to bangumis.json') - console.error(err) - } else { - log.info('Bilibili bangumis data has been saved') - } - }) -} +}) diff --git a/src/lib/bangumi-generator.js b/src/lib/bangumi-generator.js index e1e08e3..be197af 100644 --- a/src/lib/bangumi-generator.js +++ b/src/lib/bangumi-generator.js @@ -9,9 +9,9 @@ const log = require('hexo-log')({ silent: false }) -module.exports = async function (locals) { +module.exports = async function (locals, type = 'bangumi') { const config = this.config - if (!config?.bangumi?.enable) { + if (!config?.[type]?.enable) { return } @@ -19,19 +19,19 @@ module.exports = async function (locals) { if (root.endsWith('/')) { root = root.slice(0, root.length - 1) } - let wantWatch = []; let watching = []; let watched = []; + let wantWatch = []; let watching = []; let watched = [] // console.log(path.join(this.source_dir, '/_data/bangumis.json')) - if (!fs.existsSync(path.join(this.source_dir, '/_data/bangumis.json'))) { - log.info('Can\'t find bilibili bangumi data, please use \'hexo bangumi -u\' command to get data') + if (!fs.existsSync(path.join(this.source_dir, '/_data/' + type + 's.json'))) { + log.info('Can\'t find bilibili ' + type + ' data, please use \'hexo ' + type + ' -u\' command to get data') } else { - ({ wantWatch, watching, watched } = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/bangumis.json')))) + ({ wantWatch, watching, watched } = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/' + type + 's.json')))) // extra bangumis - console.log(path.join(this.source_dir, '/_data/extra_bangumis.json')) - if (fs.existsSync(path.join(this.source_dir, '/_data/extra_bangumis.json'))) { - log.info('Found extra bangumi data'); + // console.log(path.join(this.source_dir, '/_data/extra_' + type + 's.json')) + if (fs.existsSync(path.join(this.source_dir, '/_data/extra_' + type + 's.json'))) { + log.info('Found extra ' + type + 's data') let wantWatchExtra = []; let watchingExtra = []; let watchedExtra = []; - ({ wantWatchExtra, watchingExtra, watchedExtra } = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/extra_bangumis.json')))) + ({ wantWatchExtra, watchingExtra, watchedExtra } = JSON.parse(fs.readFileSync(path.join(this.source_dir, '/_data/extra_' + type + 's.json')))) if (wantWatchExtra) { wantWatch = wantWatch.concat(wantWatchExtra) } @@ -43,28 +43,30 @@ module.exports = async function (locals) { } } - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded') + log.info(wantWatch.length + watching.length + watched.length + ' ' + type + 's have been loaded') } const __ = i18n.__(config.language) const contents = await ejs.renderFile(path.join(__dirname, 'templates/bangumi.ejs'), { - quote: config.bangumi.quote, - show: config.bangumi.show || 1, - loading: config.bangumi.loading, - metaColor: config.bangumi.metaColor ? `style="color:${config.bangumi.metaColor}"` : '', - color: config.bangumi.color ? `style="color:${config.bangumi.color}"` : '', + quote: config[type].quote, + show: config[type].show || 1, + loading: config[type].loading, + metaColor: config[type].metaColor ? `style="color:${config[type].metaColor}"` : '', + color: config[type].color ? `style="color:${config[type].color}"` : '', wantWatch: wantWatch, watched: watched, watching: watching, + type: type, __: __, root: root - },{ async: false }) + }, { async: false }) + const customPath = config[type].path return { - path: config.bangumi.path || 'bangumis/index.html', + path: customPath || (type + 's/index.html'), data: { - title: config.bangumi.title, + title: config[type].title, content: contents }, layout: ['page', 'post'] diff --git a/src/lib/get-bili-data.js b/src/lib/get-bili-data.js new file mode 100644 index 0000000..dcab655 --- /dev/null +++ b/src/lib/get-bili-data.js @@ -0,0 +1,98 @@ +const fs = require('hexo-fs') +const path = require('path') +const axios = require('axios') +const log = require('hexo-log')({ + debug: false, + silent: false +}) +const ProgressBar = require('progress') + +async function getDataPage (vmid, status, typeNum) { + const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=${typeNum}&follow_status=${status}&vmid=${vmid}&ps=1&pn=1`) + if (response?.data?.code === 0 && response?.data?.message === '0' && response?.data?.data && typeof response?.data?.data?.total !== 'undefined') { + return { success: true, data: Math.ceil(response.data.data.total / 30) + 1 } + } else if (response && response.data && response.data.message !== '0') { + return { success: false, data: response.data.message } + } else if (response && response.data) { + return { success: false, data: response.data } + } else { + return { success: false, data: response } + } +} +async function getData (vmid, status, useWebp, typeNum, pn) { + const response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=${typeNum}&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) + const $data = [] + if (response?.data?.code === 0) { + const data = response?.data?.data + const list = data?.list || [] + for (const bangumi of list) { + let cover = bangumi?.cover + if (cover) { + const href = new URL(cover) + href.protocol = 'https' + if (useWebp) href.pathname += '@220w_280h.webp' + cover = href.href + } + $data.push({ + title: bangumi?.title, + type: bangumi?.season_type_name, + area: bangumi?.areas?.[0]?.name, + cover: cover, + totalCount: total(bangumi?.total_count, typeNum), + id: bangumi?.media_id, + follow: count(bangumi?.stat?.follow), + view: count(bangumi?.stat?.view), + danmaku: count(bangumi?.stat?.danmaku), + coin: count(bangumi.stat.coin), + score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', + des: bangumi?.evaluate + }) + } + return $data + } +} +function count (e) { + return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-' +} +function total (e, typeNum) { + return e ? (e === -1 ? '未完结' : `全${e}${typeNum === 1 ? '话' : '集'}`) : '-' +} +async function processData (vmid, status, useWebp, showProgress, typeNum) { + const page = await getDataPage(vmid, status, typeNum) + if (page?.success) { + const list = [] + let bar = null + if (showProgress) bar = new ProgressBar(`正在获取 ${status === 1 ? '[想看]' : status === 2 ? '[在看]' : '[已看]'} ${typeNum === 1 ? '番剧' : '追剧'} [:bar] :percent :elapseds`, { total: page.data - 1, complete: '█' }) + for (let i = 1; i < page.data; i++) { + if (showProgress) bar.tick() + const data = await getData(vmid, status, useWebp, typeNum, i) + list.push(...data) + } + return list + } else { + console.log('Get ' + (typeNum === 1 ? 'bangumi' : 'cinema') + ' data error:', page?.data) + return [] + } +} +module.exports.getBiliData = async function getBiliData (vmid, type, showProgress, sourceDir, useWebp = true) { + const typeNum = type === 'cinema' ? 2 : 1 + log.info('Getting bilibili ' + type + ', please wait...') + const startTime = new Date().getTime() + const wantWatch = await processData(vmid, 1, useWebp, showProgress, typeNum) + const watching = await processData(vmid, 2, useWebp, showProgress, typeNum) + const watched = await processData(vmid, 3, useWebp, showProgress, typeNum) + const endTime = new Date().getTime() + log.info(wantWatch.length + watching.length + watched.length + ' ' + type + 's have been loaded in ' + (endTime - startTime) + ' ms') + const bangumis = { wantWatch, watching, watched } + if (!fs.existsSync(path.join(sourceDir, '/_data/'))) { + fs.mkdirsSync(path.join(sourceDir, '/_data/')) + } + fs.writeFile(path.join(sourceDir, '/_data/' + type + 's.json'), JSON.stringify(bangumis), err => { + if (err) { + log.info('Failed to write data to ' + type + 's.json') + console.error(err) + } else { + log.info('Bilibili ' + type + 's data has been saved') + } + }) +}