From 8e79ae5609b23fb8d8b500a92f582700cb9ca583 Mon Sep 17 00:00:00 2001 From: HCLonely Date: Tue, 4 Aug 2020 16:25:33 +0800 Subject: [PATCH] =?UTF-8?q?=E8=8E=B7=E5=8F=96=E7=95=AA=E5=89=A7=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E6=97=B6=E6=B7=BB=E5=8A=A0=E8=BF=9B=E5=BA=A6=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 +-- index.js | 96 +++++++++++--------- lib/bangumi-generator.js | 28 +++--- lib/templates/index.js | 2 +- lib/templates/pagination.js | 2 +- package.json | 18 ++-- src/index.js | 150 ++++++++++++++++---------------- src/lib/bangumi-generator.js | 97 ++++++++++----------- src/lib/templates/index.js | 58 ++++++------ src/lib/templates/pagination.js | 109 ++++++++++++----------- src/lib/util.js | 76 ++++++++-------- 11 files changed, 336 insertions(+), 313 deletions(-) diff --git a/README.md b/README.md index d1af055..68946f1 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/) @@ -38,19 +38,20 @@ bangumi: - **path**: 番剧页面路径,默认`bangumis/index.html` - **vmid**: 哔哩哔哩番剧页面的 `vmid(uid)`,[如何获取?](#获取uid) - **title**: 该页面的标题 -- **quote**: 写在页面开头的一段话,支持html语法 +- **quote**: 写在页面开头的一段话,支持 html 语法,可留空。 - **show**: 初始显示页面:`0: 想看`, `1: 在看`, `2: 看过`,默认为`1` -- **loading**: 图片加载完成前的loading图片 -- **metaColor**: meta部分(简介上方)字体颜色 +- **loading**: 图片加载完成前的 loading 图片 +- **metaColor**: meta 部分(简介上方)字体颜色 - **color**: 简介字体颜色 -- **webp**: 番剧封面使用`webp`格式(此格式在`safari`浏览器下不显示,但是图片大小可以缩小100倍左右), 默认`true` +- **webp**: 番剧封面使用`webp`格式(此格式在`safari`浏览器下不显示,但是图片大小可以缩小 100 倍左右), 默认`true` +- **progress**: 获取番剧数据时是否显示进度条,默认`true` ## 使用 1. 在`hexo generate`或`hexo deploy`之前使用`hexo bangumi -u`命令更新番剧数据! 2. 删除数据命令:`hexo bangumi -d` -## 获取uid +## 获取 uid 登录哔哩哔哩后前往[https://space.bilibili.com/](https://space.bilibili.com/)页面,网址最后的一串数字就是 `uid` diff --git a/index.js b/index.js index 496f9f1..27767a5 100644 --- a/index.js +++ b/index.js @@ -19,13 +19,15 @@ var fs = require('hexo-fs'); var path = require('path'); -var axios = require("axios"); +var axios = require('axios'); var log = require('hexo-log')({ debug: false, silent: false }); +var ProgressBar = require('progress'); + if (typeof URL !== 'function') var _require = require('url'), URL = _require.URL; var options = { @@ -48,15 +50,15 @@ hexo.extend.generator.register('bangumis', function (locals) { }); hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for Hexo', options, function (args) { if (args.d) { - if (fs.existsSync(path.join(__dirname, "/data/"))) { - fs.rmdirSync(path.join(__dirname, "/data/")); + if (fs.existsSync(path.join(__dirname, '/data/'))) { + fs.rmdirSync(path.join(__dirname, '/data/')); log.info('Bangumis data has been deleted'); } } else if (args.u) { var _this$config2; if (!(this === null || this === void 0 ? void 0 : (_this$config2 = this.config) === null || _this$config2 === void 0 ? void 0 : _this$config2.bangumi)) { - log.info("Please add config to _config.yml"); + log.info('Please add config to _config.yml'); return; } @@ -65,13 +67,13 @@ hexo.extend.console.register('bangumi', 'Generate pages of bilibili bangumis for } if (!this.config.bangumi.vmid) { - log.info("Please add vmid to _config.yml"); + log.info('Please add vmid to _config.yml'); return; } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp); + saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress); } else { - log.info("Unknown command, please use \"hexo bangumi -h\" to see the available commands"); + log.info('Unknown command, please use "hexo bangumi -h" to see the available commands'); } }); @@ -94,7 +96,7 @@ function _getBangumiPage() { 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 ? void 0 : (_response$data3 = response.data) === null || _response$data3 === void 0 ? 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")) { + 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 ? void 0 : (_response$data3 = response.data) === null || _response$data3 === void 0 ? 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; } @@ -105,7 +107,7 @@ function _getBangumiPage() { }); case 7: - if (!(response && response.data && response.data.message !== "0")) { + if (!(response && response.data && response.data.message !== '0')) { _context.next = 11; break; } @@ -195,7 +197,7 @@ function _getBangumi() { 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 ? 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 : "暂无评分", + score: (bangumi === null || bangumi === void 0 ? 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 }); } @@ -222,16 +224,16 @@ function count(e) { } function total(e) { - return e ? e === -1 ? "\u672A\u5B8C\u7ED3" : "\u5168".concat(e, "\u8BDD") : '-'; + return e ? e === -1 ? '未完结' : "\u5168".concat(e, "\u8BDD") : '-'; } -function biliBangumi(_x7, _x8, _x9) { +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) { - var page, list, i, data; + _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) { @@ -243,39 +245,45 @@ function _biliBangumi() { page = _context3.sent; if (!(page === null || page === void 0 ? void 0 : page.success)) { - _context3.next = 17; + _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 6: + case 8: if (!(i < page.data)) { - _context3.next = 14; + _context3.next = 17; break; } - _context3.next = 9; + if (progress) bar.tick(); + _context3.next = 12; return getBangumi(vmid, status, webp, i); - case 9: + case 12: data = _context3.sent; list.push.apply(list, (0, _toConsumableArray2["default"])(data)); - case 11: + case 14: i++; - _context3.next = 6; + _context3.next = 8; break; - case 14: + case 17: return _context3.abrupt("return", list); - case 17: - console.log("Get bangumi data error:", page === null || page === void 0 ? void 0 : page.data); + case 20: + console.log('Get bangumi data error:', page === null || page === void 0 ? void 0 : page.data); return _context3.abrupt("return", []); - case 19: + case 22: case "end": return _context3.stop(); } @@ -285,13 +293,14 @@ function _biliBangumi() { return _biliBangumi.apply(this, arguments); } -function saveBangumiData(_x10) { +function saveBangumiData(_x11) { return _saveBangumiData.apply(this, arguments); } function _saveBangumiData() { _saveBangumiData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(vmid) { var webp, + progress, startTime, wantWatch, watching, @@ -304,45 +313,46 @@ function _saveBangumiData() { switch (_context4.prev = _context4.next) { case 0: webp = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : true; - log.info("Getting bilibili bangumis, please wait..."); + progress = _args4.length > 2 ? _args4[2] : undefined; + log.info('Getting bilibili bangumis, please wait...'); startTime = new Date().getTime(); - _context4.next = 5; - return biliBangumi(vmid, 1, webp); + _context4.next = 6; + return biliBangumi(vmid, 1, webp, progress); - case 5: + case 6: wantWatch = _context4.sent; - _context4.next = 8; - return biliBangumi(vmid, 2, webp); + _context4.next = 9; + return biliBangumi(vmid, 2, webp, progress); - case 8: + case 9: watching = _context4.sent; - _context4.next = 11; - return biliBangumi(vmid, 3, webp); + _context4.next = 12; + return biliBangumi(vmid, 3, webp, progress); - case 11: + case 12: watched = _context4.sent; endTime = new Date().getTime(); - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + " ms"); + log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + ' ms'); bangumis = { wantWatch: wantWatch, watching: watching, watched: watched }; - if (!fs.existsSync(path.join(__dirname, "/data/"))) { - fs.mkdirsSync(path.join(__dirname, "/data/")); + if (!fs.existsSync(path.join(__dirname, '/data/'))) { + fs.mkdirsSync(path.join(__dirname, '/data/')); } - fs.writeFile(path.join(__dirname, "/data/bangumis.json"), JSON.stringify(bangumis), function (err) { + fs.writeFile(path.join(__dirname, '/data/bangumis.json'), JSON.stringify(bangumis), function (err) { if (err) { - log.info("Failed to write data to bangumis.json"); + log.info('Failed to write data to bangumis.json'); console.error(err); } else { - log.info("Bilibili bangumis data has been saved"); + log.info('Bilibili bangumis data has been saved'); } }); - case 17: + case 18: case "end": return _context4.stop(); } diff --git a/lib/bangumi-generator.js b/lib/bangumi-generator.js index 3fe1563..60d2810 100644 --- a/lib/bangumi-generator.js +++ b/lib/bangumi-generator.js @@ -45,10 +45,12 @@ module.exports = /*#__PURE__*/function () { root = root.slice(0, root.length - 1); } - wantWatch = [], watching = [], watched = []; + wantWatch = []; + watching = []; + watched = []; if (!fs.existsSync(path.resolve(__dirname, '../data/bangumis.json'))) { - log.info("Can't find bilibili bangumi data, please use 'hexo bangumi -u' command to get data"); + log.info('Can\'t find bilibili bangumi data, please use \'hexo bangumi -u\' command to get data'); } else { _JSON$parse = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../data/bangumis.json'))); wantWatch = _JSON$parse.wantWatch; @@ -59,16 +61,16 @@ module.exports = /*#__PURE__*/function () { __ = i18n.__(config.language); contents = 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, "\"") : "", - 'wantWatch': wantWatch, - 'watched': watched, - 'watching': watching, - '__': __, - 'root': root + 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, "\"") : '', + wantWatch: wantWatch, + watched: watched, + watching: watching, + __: __, + root: root }, function (err, result) { if (err) console.log(err); return result; @@ -82,7 +84,7 @@ module.exports = /*#__PURE__*/function () { layout: ['page', 'post'] }); - case 10: + case 12: case "end": return _context.stop(); } diff --git a/lib/templates/index.js b/lib/templates/index.js index 001c501..e89f015 100644 --- a/lib/templates/index.js +++ b/lib/templates/index.js @@ -1,2 +1,2 @@ -"use strict";Element.prototype.siblings=function(){for(var a=[],b=this.parentNode.children,c=0;c", "license": "Apache Licence 2.0", "keywords": [ "generator", @@ -24,7 +24,8 @@ "hexo-fs": "^0.2.2", "hexo-i18n": "^0.2.1", "hexo-log": "^0.2.0", - "path": "^0.12.7" + "path": "^0.12.7", + "progress": "^2.0.3" }, "repository": { "type": "git", @@ -36,6 +37,13 @@ "@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" + "clean-css-cli": "^4.3.0", + "standard": "^14.3.4" + }, + "standard":{ + "ignore": [ + "index.js", + "lib/*" + ] } } diff --git a/src/index.js b/src/index.js index 94ab39d..32fe750 100644 --- a/src/index.js +++ b/src/index.js @@ -1,75 +1,76 @@ /* global hexo */ -'use strict'; -const fs = require('hexo-fs'); -const path = require('path'); -const axios = require("axios"); +'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') -let options = { +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 } - return require('./lib/bangumi-generator').call(this, locals); -}); + 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(__dirname, "/data/"))) { - fs.rmdirSync(path.join(__dirname, "/data/")); - log.info('Bangumis data has been deleted'); + if (fs.existsSync(path.join(__dirname, '/data/'))) { + fs.rmdirSync(path.join(__dirname, '/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; + log.info('Please add config to _config.yml') + return } if (!this.config.bangumi.enable) { - return; + return } if (!this.config.bangumi.vmid) { - log.info("Please add vmid to _config.yml"); - return; + log.info('Please add vmid to _config.yml') + return } - saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp); + saveBangumiData(this.config.bangumi.vmid, this.config.bangumi.webp, this.config.bangumi.progress) } else { - log.info("Unknown command, please use \"hexo bangumi -h\" to see the available commands") + log.info('Unknown command, please use "hexo bangumi -h" to see the available commands') } -}); +}) -async function getBangumiPage(vmid, status) { - let 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 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) { - let response = await axios.get(`https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${status}&vmid=${vmid}&ps=30&pn=${pn}`) - let $data = []; +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) { - let data = response?.data?.data; - let list = data?.list || []; - for (let bangumi of list) { + const data = response?.data?.data + const list = data?.list || [] + for (const bangumi of list) { let cover = bangumi?.cover - if (cover){ - let href = new URL(cover) + if (cover) { + const href = new URL(cover) href.protocol = 'https' - if(webp) href.pathname += '@220w_280h.webp' + if (webp) href.pathname += '@220w_280h.webp' cover = href.href } $data.push({ @@ -83,51 +84,54 @@ async function getBangumi(vmid, status, webp, pn) { view: count(bangumi?.stat?.view), danmaku: count(bangumi?.stat?.danmaku), coin: count(bangumi.stat.coin), - score: bangumi?.rating ? bangumi?.rating?.score : "暂无评分", + score: bangumi?.rating ? bangumi?.rating?.score : '暂无评分', des: bangumi?.evaluate - }); + }) } - return $data; + return $data } } -function count(e) { - return e ? (e > 10000 && e < 100000000 ? `${(e / 10000).toFixed(1)} 万` : e > 100000000 ? `${(e / 100000000).toFixed(1)} 亿` : e) : '-'; +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}话`) : '-'; +function total (e) { + return e ? (e === -1 ? '未完结' : `全${e}话`) : '-' } -async function biliBangumi(vmid, status, webp) { - let page = await getBangumiPage(vmid, status, webp); - if(page?.success){ - let list = []; +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++) { - let data = await getBangumi(vmid, status, webp, i); - list.push(...data); + 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 []; + return list + } else { + console.log('Get bangumi data error:', page?.data) + return [] } } -async function saveBangumiData(vmid, webp = true) { - log.info("Getting bilibili bangumis, please wait..."); - let startTime = new Date().getTime(); - let wantWatch = await biliBangumi(vmid, 1, webp); - let watching = await biliBangumi(vmid, 2, webp); - let watched = await biliBangumi(vmid, 3, webp); - let endTime = new Date().getTime(); - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded in ' + (endTime - startTime) + " ms"); - let bangumis = { wantWatch, watching, watched }; - if (!fs.existsSync(path.join(__dirname, "/data/"))) { - fs.mkdirsSync(path.join(__dirname, "/data/")); +async function saveBangumiData (vmid, webp = true, progress) { + 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(__dirname, '/data/'))) { + fs.mkdirsSync(path.join(__dirname, '/data/')) } - fs.writeFile(path.join(__dirname, "/data/bangumis.json"), JSON.stringify(bangumis), err => { + fs.writeFile(path.join(__dirname, '/data/bangumis.json'), JSON.stringify(bangumis), err => { if (err) { - log.info("Failed to write data to bangumis.json"); - console.error(err); + log.info('Failed to write data to bangumis.json') + console.error(err) } else { - log.info("Bilibili bangumis data has been saved"); + log.info('Bilibili bangumis data has been saved') } - }); + }) } diff --git a/src/lib/bangumi-generator.js b/src/lib/bangumi-generator.js index dc368fb..0d0d552 100644 --- a/src/lib/bangumi-generator.js +++ b/src/lib/bangumi-generator.js @@ -1,58 +1,57 @@ -'use strict'; +'use strict' -const ejs = require('ejs'); -const path = require('path'); -const i18n = require('./util').i18n; -const fs = require('hexo-fs'); +const ejs = require('ejs') +const path = require('path') +const i18n = require('./util').i18n +const fs = require('hexo-fs') const log = require('hexo-log')({ - debug: false, - silent: false -}); + debug: false, + silent: false +}) module.exports = async function (locals) { + const config = this.config + if (!config?.bangumi?.enable) { + return + } - let config = this.config; - if (!config?.bangumi?.enable) { - return; - } + let root = config.root + if (root.endsWith('/')) { + root = root.slice(0, root.length - 1) + } + let wantWatch = []; let watching = []; let watched = [] + if (!fs.existsSync(path.resolve(__dirname, '../data/bangumis.json'))) { + log.info('Can\'t find bilibili bangumi data, please use \'hexo bangumi -u\' command to get data') + } else { + ({ wantWatch, watching, watched } = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../data/bangumis.json')))) + log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded') + } - let root = config.root; - if (root.endsWith('/')) { - root = root.slice(0, root.length - 1); - } - let wantWatch=[], watching=[], watched=[]; - if(!fs.existsSync(path.resolve(__dirname, '../data/bangumis.json'))){ - log.info(`Can't find bilibili bangumi data, please use 'hexo bangumi -u' command to get data`); - }else{ - ({ wantWatch, watching, watched } = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../data/bangumis.json')))); - log.info(wantWatch.length + watching.length + watched.length + ' bangumis have been loaded'); - } + const __ = i18n.__(config.language) - let __ = i18n.__(config.language); + const contents = 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}"` : '', + wantWatch: wantWatch, + watched: watched, + watching: watching, + __: __, + root: root + }, + function (err, result) { + if (err) console.log(err) + return result + }) - let contents = 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}"` : "", - 'wantWatch': wantWatch, - 'watched': watched, - 'watching': watching, - '__': __, - 'root': root + return { + path: config.bangumi.path || 'bangumis/index.html', + data: { + title: config.bangumi.title, + content: contents }, - function (err, result) { - if (err) console.log(err); - return result; - }); - - return { - path: config.bangumi.path || 'bangumis/index.html', - data: { - title: config.bangumi.title, - content: contents - }, - layout: ['page', 'post'] - }; -}; + layout: ['page', 'post'] + } +} diff --git a/src/lib/templates/index.js b/src/lib/templates/index.js index df9cb1a..9c9e0f3 100644 --- a/src/lib/templates/index.js +++ b/src/lib/templates/index.js @@ -1,33 +1,33 @@ Element.prototype.siblings = function () { - let siblingElement = []; - let sibs = this.parentNode.children; - for (let i = 0; i < sibs.length; i++) { - if (sibs[i] !== this) { - siblingElement.push(sibs[i]); - } - } - return siblingElement; -}; -function tabClick() { - //修改标签样式 - this.classList.add('bangumi-active'); - let sibs = this.siblings(); - for (let j = 0; j < sibs.length; j++) { - sibs[j].classList.remove('bangumi-active'); - } - //显示对应板块 - let itemId = this.id.replace('tab', 'item'); - let target = document.getElementById(itemId); - target.classList.remove('bangumi-hide'); - target.classList.add('bangumi-show'); - sibs = document.getElementById(itemId).siblings(); - for (let k = 0; k < sibs.length; k++) { - sibs[k].classList.remove('bangumi-show'); - sibs[k].classList.add('bangumi-hide'); + const siblingElement = [] + const sibs = this.parentNode.children + for (let i = 0; i < sibs.length; i++) { + if (sibs[i] !== this) { + siblingElement.push(sibs[i]) } + } + return siblingElement } -let tabs = document.getElementsByClassName("bangumi-tab"); +function tabClick () { + // 修改标签样式 + this.classList.add('bangumi-active') + let sibs = this.siblings() + for (let j = 0; j < sibs.length; j++) { + sibs[j].classList.remove('bangumi-active') + } + // 显示对应板块 + const itemId = this.id.replace('tab', 'item') + const target = document.getElementById(itemId) + target.classList.remove('bangumi-hide') + target.classList.add('bangumi-show') + sibs = document.getElementById(itemId).siblings() + for (let k = 0; k < sibs.length; k++) { + sibs[k].classList.remove('bangumi-show') + sibs[k].classList.add('bangumi-hide') + } +} +const tabs = document.getElementsByClassName('bangumi-tab') for (let i = 0; i < tabs.length; i++) { - tabs[i].onclick = tabClick; - tabs[i].onclick.apply(tabs[i]); -} \ No newline at end of file + tabs[i].onclick = tabClick + tabs[i].onclick.apply(tabs[i]) +} diff --git a/src/lib/templates/pagination.js b/src/lib/templates/pagination.js index d32ea31..dd09b68 100644 --- a/src/lib/templates/pagination.js +++ b/src/lib/templates/pagination.js @@ -1,71 +1,70 @@ -var firstpages = document.getElementsByClassName("bangumi-firstpage"); -var previouspages = document.getElementsByClassName("bangumi-previouspage"); -var nextpages = document.getElementsByClassName("bangumi-nextpage"); -var lastpages = document.getElementsByClassName("bangumi-lastpage"); -var pagenums = document.getElementsByClassName("bangumi-pagenum"); +var firstpages = document.getElementsByClassName('bangumi-firstpage') +var previouspages = document.getElementsByClassName('bangumi-previouspage') +var nextpages = document.getElementsByClassName('bangumi-nextpage') +var lastpages = document.getElementsByClassName('bangumi-lastpage') +var pagenums = document.getElementsByClassName('bangumi-pagenum') -function makePageNum(num, arr) { - return (num + 1) + ' / ' + (Math.ceil(arr.length / 10 === 0 ? 1 : Math.ceil(arr.length / 10))); +function makePageNum (num, arr) { + return (num + 1) + ' / ' + (Math.ceil(arr.length / 10 === 0 ? 1 : Math.ceil(arr.length / 10))) } -function firstBtn() { - var sibs = this.parentNode.siblings(); - displayPage(sibs, 0); - this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(0, sibs); +function firstBtn () { + var sibs = this.parentNode.siblings() + displayPage(sibs, 0) + this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(0, sibs) } -function previousBtn() { - var sibs = this.parentNode.siblings(); - var currNum = this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText; - currNum = currNum.substr(0, currNum.indexOf('/') - 1); - currNum = parseInt(currNum, 10) - 1; - if (currNum > 0) { - currNum--; - } - displayPage(sibs, currNum); - this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(currNum, sibs); +function previousBtn () { + var sibs = this.parentNode.siblings() + var currNum = this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText + currNum = currNum.substr(0, currNum.indexOf('/') - 1) + currNum = parseInt(currNum, 10) - 1 + if (currNum > 0) { + currNum-- + } + displayPage(sibs, currNum) + this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(currNum, sibs) } -function nextBtn() { - var sibs = this.parentNode.siblings(); - var currNum = this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText; - currNum = currNum.substr(0, currNum.indexOf('/') - 1); - currNum = parseInt(currNum, 10) - 1; - if (currNum < Math.ceil(sibs.length / 10) - 1) { - currNum++; - } - displayPage(sibs, currNum); - this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(currNum, sibs); +function nextBtn () { + var sibs = this.parentNode.siblings() + var currNum = this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText + currNum = currNum.substr(0, currNum.indexOf('/') - 1) + currNum = parseInt(currNum, 10) - 1 + if (currNum < Math.ceil(sibs.length / 10) - 1) { + currNum++ + } + displayPage(sibs, currNum) + this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(currNum, sibs) } -function lastBtn() { - var sibs = this.parentNode.siblings(); - displayPage(sibs, Math.ceil(sibs.length / 10) - 1); - this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(Math.ceil(sibs.length / 10) - 1 === -1 ? 0 : Math.ceil(sibs.length / 10) - 1, sibs); +function lastBtn () { + var sibs = this.parentNode.siblings() + displayPage(sibs, Math.ceil(sibs.length / 10) - 1) + this.parentNode.getElementsByClassName('bangumi-pagenum')[0].innerText = makePageNum(Math.ceil(sibs.length / 10) - 1 === -1 ? 0 : Math.ceil(sibs.length / 10) - 1, sibs) } -function displayPage(arr, num) { - for (var i = 0; i < arr.length; i++) { - if (Math.floor(i / 10) === num) { - arr[i].classList.remove('bangumi-hide'); - var img = arr[i].getElementsByTagName('img')[0]; - img.src = img.getAttribute('data-src'); - } else { - arr[i].classList.add('bangumi-hide'); - } +function displayPage (arr, num) { + for (var i = 0; i < arr.length; i++) { + if (Math.floor(i / 10) === num) { + arr[i].classList.remove('bangumi-hide') + var img = arr[i].getElementsByTagName('img')[0] + img.src = img.getAttribute('data-src') + } else { + arr[i].classList.add('bangumi-hide') } + } } for (var i = 0; i < firstpages.length; i++) { + // add listener + firstpages[i].onclick = firstBtn + previouspages[i].onclick = previousBtn + nextpages[i].onclick = nextBtn + lastpages[i].onclick = lastBtn - //add listener - firstpages[i].onclick = firstBtn; - previouspages[i].onclick = previousBtn; - nextpages[i].onclick = nextBtn; - lastpages[i].onclick = lastBtn; - - //set page num - var size = pagenums[i].parentNode.siblings().length; - pagenums[i].innerText = '1 / ' + (Math.ceil(size / 10) === 0 ? 1 : Math.ceil(size / 10)); - firstpages[i].click(); -} \ No newline at end of file + // set page num + var size = pagenums[i].parentNode.siblings().length + pagenums[i].innerText = '1 / ' + (Math.ceil(size / 10) === 0 ? 1 : Math.ceil(size / 10)) + firstpages[i].click() +} diff --git a/src/lib/util.js b/src/lib/util.js index 6d26b28..24ed6cf 100644 --- a/src/lib/util.js +++ b/src/lib/util.js @@ -1,49 +1,49 @@ -'use strict'; +'use strict' -const I18N = require('hexo-i18n'); +const I18N = require('hexo-i18n') -let i18n = new I18N({ - languages: ['zh-CN', 'zh-TW', 'en'] -}); +const i18n = new I18N({ + languages: ['zh-CN', 'zh-TW', 'en'] +}) i18n.set('en', { - wantWatch: 'Wish', - watched: 'Watched', - watching: 'Watching', - prev: 'Prev', - next: 'Next', - top: 'Top', - end: 'End' -}); + wantWatch: 'Wish', + watched: 'Watched', + watching: 'Watching', + prev: 'Prev', + next: 'Next', + top: 'Top', + end: 'End' +}) i18n.set('zh-TW', { - wantWatch: '想看', - watched: '看过', - watching: '在看', - prev: '上一頁', - next: '下一頁', - top: '首頁', - end: '尾頁' -}); + wantWatch: '想看', + watched: '看过', + watching: '在看', + prev: '上一頁', + next: '下一頁', + top: '首頁', + end: '尾頁' +}) i18n.set('zh-Hans', { - wantWatch: '想看', - watched: '看过', - watching: '在看', - prev: '上一页', - next: '下一页', - top: '首页', - end: '尾页' -}); + wantWatch: '想看', + watched: '看过', + watching: '在看', + prev: '上一页', + next: '下一页', + top: '首页', + end: '尾页' +}) i18n.set('zh-CN', { - wantWatch: '想看', - watched: '已看', - watching: '在看', - prev: '上一页', - next: '下一页', - top: '首页', - end: '尾页' -}); + wantWatch: '想看', + watched: '已看', + watching: '在看', + prev: '上一页', + next: '下一页', + top: '首页', + end: '尾页' +}) -module.exports.i18n = i18n; \ No newline at end of file +module.exports.i18n = i18n