diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..1739bcf --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +/http/res/* \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..da93825 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,27 @@ +{ + "env": { + "es6": true, + "browser": false, + "node": true + }, + "rules": { + "curly": 0, + "comma-dangle": [2, "always-multiline"], + "comma-spacing": 0, + "eqeqeq": [2, "allow-null"], + "key-spacing": 0, + "no-underscore-dangle": 0, + "no-unused-expressions": 0, + "no-shadow": 0, + "no-shadow-restricted-names": 0, + "no-extend-native": 0, + "no-var": 2, + "new-cap": 0, + "quotes": 0, + "semi-spacing": 0, + "space-unary-ops": 0, + "space-infix-ops": 0, + "consistent-return": 0, + "strict": 0 + } +} \ No newline at end of file diff --git a/lib/database/csv.js b/lib/database/csv.js index 89fe2fa..520d100 100644 --- a/lib/database/csv.js +++ b/lib/database/csv.js @@ -2,20 +2,21 @@ /* global config */ /* global log */ /* global coordinator */ -var fs = require("fs"); -var path = require("path"); +'use strict'; +let fs = require("fs"); +let path = require("path"); function formatContent(content) { return '"' + content.toString().replace(/"/g, '""') + '"'; } module.exports = {}; module.exports.init = function (callback) { - var savePath = path.resolve(config.database.savedir); + let savePath = path.resolve(config.database.savedir); log.log("保存位置:" + savePath); callback(null); - coordinator.on("gotDanmu", function (data) { - var date = new Date(); - var joinArray = []; + coordinator.on("gotDanmu", (data) => { + let date = new Date(); + let joinArray = []; joinArray.push(formatContent(Math.round(new Date().getTime() / 1000))); joinArray.push(formatContent(data.hash)); joinArray.push(formatContent(data.ip)); @@ -25,7 +26,7 @@ module.exports.init = function (callback) { fs.appendFile(path.resolve(savePath, data.room + '.csv'), joinArray.join(",")); }); - coordinator.on("searchDanmu", function (data) { + coordinator.on("searchDanmu", (data) => { coordinator.emit("gotSearchDanmu", '[{"user": "ERROR", "text": "Not yet supported", "publish": ""}]'); }); }; diff --git a/lib/database/index.js b/lib/database/index.js index db43d0b..fcbf3e2 100644 --- a/lib/database/index.js +++ b/lib/database/index.js @@ -1,8 +1,9 @@ /* global config */ +'use strict'; module.exports = { init: function (callback) { require("./" + config.database.type + ".js").init(function () { callback.apply(this, arguments); }); - } + }, }; diff --git a/lib/database/mongo.js b/lib/database/mongo.js index ee85ec7..f28f881 100644 --- a/lib/database/mongo.js +++ b/lib/database/mongo.js @@ -2,18 +2,18 @@ /* global config */ /* global log */ /* global coordinator */ -var SECONDS_IN_DAY = 24 * 60 * 60 * 1000; -var mongodb = require('mongodb'); -var server = new mongodb.Server(config.database.server, config.database.port, { - auto_reconnect: true +const SECONDS_IN_DAY = 24 * 60 * 60 * 1000; +let mongodb = require('mongodb'); +let server = new mongodb.Server(config.database.server, config.database.port, { + auto_reconnect: true, }); -var db = null; -var errorCounter = 0; -var firstErrorTime = new Date(); +let db = null; +let errorCounter = 0; +let firstErrorTime = new Date(); -var getConnection = function (callback) { +let getConnection = function (callback) { db = new mongodb.Db(config.database.db, server, { - w: 1 + w: 1, }); db.open(function (err) { if (err !== null) { @@ -44,13 +44,13 @@ module.exports = { coordinator.on("gotDanmu", function (data) { - var room = data.room; + let room = data.room; db.collection(config.rooms[room].table).insert({ user: data.hash, text: data.text, publish: Math.round(new Date().getTime() / 1000), ip: data.ip, - ua: data.ua + ua: data.ua, }, function (err, results) { if (err !== null) { log.log("数据库写入出错"); @@ -62,11 +62,11 @@ module.exports = { coordinator.on("searchDanmu", function (data) { - var room = data.room; + let room = data.room; db.collection(config.rooms[room].table).find({ text: { - $regex: ".*?" + preg_quote(data.key) + ".*?" - } + $regex: ".*?" + preg_quote(data.key) + ".*?", + }, }, null, null).toArray(function (err, results) { if (err === null) { results.map(function (object) { @@ -83,7 +83,7 @@ module.exports = { }); - } + }, }; diff --git a/lib/database/mysql.js b/lib/database/mysql.js index 47595db..5118cf7 100644 --- a/lib/database/mysql.js +++ b/lib/database/mysql.js @@ -2,14 +2,15 @@ /* global config */ /* global log */ /* global coordinator */ -var SECONDS_IN_DAY = 24 * 60 * 60 * 1000; -var mysql = require("mysql"); -var pool = null; -var connection = null; -var errorCounter = 0; -var firstErrorTime = new Date(); +'use strict'; +const SECONDS_IN_DAY = 24 * 60 * 60 * 1000; +let mysql = require("mysql"); +let pool = null; +let connection = null; +let errorCounter = 0; +let firstErrorTime = new Date(); -var createTableSql = [ +let createTableSql = [ "CREATE TABLE IF NOT EXISTS `%table%` (", "danmu_id int(11) NOT NULL AUTO_INCREMENT,", "danmu_user varchar(255) NOT NULL DEFAULT '',", @@ -19,11 +20,11 @@ var createTableSql = [ "danmu_useragent text NOT NULL,", "PRIMARY KEY (danmu_id),", "KEY danmu_TPISC (danmu_publish)", - ") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;" + ") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;", ].join("\n"); -var createDatabase = function (callbackOrig) { - var asyncList = Object.keys(config.rooms); +let createDatabase = function (callbackOrig) { + let asyncList = Object.keys(config.rooms); async.each(asyncList, function (room, callback) { connection.query('SELECT MAX(danmu_id) FROM `' + config.rooms[room].table + '`', function (err, rows) { if (err !== null) { @@ -40,7 +41,7 @@ var createDatabase = function (callbackOrig) { }); }; -var dbErrorHandler = function (err) { +let dbErrorHandler = function (err) { if (err !== null) { if (err.errno !== "ECONNRESET") { // 部分MySQL会自动超时,此时要重连但不计errorCounter if (errorCounter === 0 || new Date() - firstErrorTime >= SECONDS_IN_DAY) { @@ -62,8 +63,8 @@ var dbErrorHandler = function (err) { } }; -var getConnection = function (callback) { - var called = false; +let getConnection = function (callback) { + let called = false; pool.getConnection(function (err, privateConnection) { connection = privateConnection; if (err) { @@ -95,21 +96,21 @@ module.exports = { port: config.database.port, database: config.database.db, acquireTimeout: config.database.timeout, - connectionLimit: 1 + connectionLimit: 1, //debug: true }); getConnection(callback); - var keepAlive = function () { + let keepAlive = function () { if (!connection) return; connection.ping(); }; coordinator.on("gotDanmu", function (data) { - var room = data.room; + let room = data.room; connection.query("INSERT INTO `%table%` (danmu_user, danmu_text, danmu_publish, danmu_ip, danmu_useragent) VALUES (?, ?, ?, ?, ?)".replace("%table%", config.rooms[room].table), [ - data.hash, data.text, Math.round(new Date().getTime() / 1000), data.ip, data.ua + data.hash, data.text, Math.round(new Date().getTime() / 1000), data.ip, data.ua, ], function (err, rows) { if (err !== null) { log.log("数据库写入出错"); @@ -120,12 +121,12 @@ module.exports = { coordinator.on("searchDanmu", function (data) { - var room = data.room; + let room = data.room; connection.query('SELECT * from `%table%` where `danmu_text` LIKE ? LIMIT 20'.replace("%table%", config.rooms[room].table), [ - '%' + data.key + '%' + '%' + data.key + '%', ], function (err, rows) { if (err === null) { - var ret = []; + let ret = []; ret = JSON.stringify(rows).replace(/"danmu_/g, '"'); coordinator.emit("gotSearchDanmu", ret); } else { diff --git a/lib/database/none.js b/lib/database/none.js index 60c14e4..d387d7b 100644 --- a/lib/database/none.js +++ b/lib/database/none.js @@ -2,5 +2,5 @@ module.exports = { init: function (callback) { log.log("无数据库"); callback(null); - } + }, }; diff --git a/lib/ext/ext/autoban/index.js b/lib/ext/ext/autoban/index.js index e25a943..8deeb12 100644 --- a/lib/ext/ext/autoban/index.js +++ b/lib/ext/ext/autoban/index.js @@ -4,6 +4,7 @@ /* global config */ /* global coordinator */ /* global filter */ +'use strict'; module.exports = function () { // 弹幕被拦截达到一定次数后封号 coordinator.on("banDanmu", function (danmuData) { @@ -13,11 +14,11 @@ module.exports = function () { if (filter.checkUserBlock(danmuData.room, danmuData.hash)) return; cache.get("block_" + danmuData.hash, function (err, data) { - if (err !== null && typeof err != "undefined") { + if (err !== null && typeof err !== "undefined") { log.log("封禁用户查询失败"); console.log(err); data = 0; - } else if (typeof data == "undefined") { + } else if (typeof data === "undefined") { data = 0; } else { data = parseInt(data); diff --git a/lib/ext/ext/weibo/index.js b/lib/ext/ext/weibo/index.js index f9c0a77..90c74b0 100644 --- a/lib/ext/ext/weibo/index.js +++ b/lib/ext/ext/weibo/index.js @@ -5,12 +5,13 @@ /* global coordinator */ /* global log */ /* global utils */ -var passport = require('passport'); -var PassportSina = require('passport-sina'); -var session = require('express-session'); -var cookieParser = require('cookie-parser'); -var fs = require('fs'); -var path = require('path'); +'use strict'; +let Passport = require('passport'); +let PassportSina = require('passport-weibo-token'); +let session = require('express-session'); +let cookieParser = require('cookie-parser'); +let fs = require('fs'); +let path = require('path'); /* passport.serializeUser(function (user, callback) { @@ -21,35 +22,35 @@ passport.deserializeUser(function (obj, callback) { callback(null, obj); }); */ -passport.use(new PassportSina(config.ext.weibo, +Passport.use(new PassportSina(config.ext.weibo, function (accessToken, refreshToken, profile, callback) { - process.nextTick(function () { + process.nextTick(() => { return callback(null, { accessToken: accessToken, - profile: profile + profile: profile, }); }); })); module.exports = function () { - coordinator.on("httpBeforeRoute", function (app) { + coordinator.on("httpBeforeRoute", (app) => { app.use(session({ secret: config.http.sessionKey, resave: false, saveUninitialized: true, cookie: { - maxAge: 24 * 60 * 60 * 1000 // 1 day - } + maxAge: 24 * 60 * 60 * 1000, // 1 day + }, })); - app.use(passport.initialize()); + app.use(Passport.initialize()); app.use(cookieParser()); - app.get('/auth/sina', passport.authenticate('sina', { - session: false + app.get('/auth/sina', Passport.authenticate('sina', { + session: false, })); - app.get('/auth/sina/callback', function (req, res, next) { - passport.authenticate('sina', { - session: false + app.get('/auth/sina/callback', (req, res, next) => { + Passport.authenticate('sina', { + session: false, }, function (err, data) { if (err !== null) { console.log(err); @@ -62,19 +63,19 @@ module.exports = function () { res.end("") return; } - var hash = utils.getHash(data.profile.id, data.profile.name, data.profile.created_at); + let hash = utils.getHash(data.profile.id, data.profile.name, data.profile.created_at); cache.set('weibo_' + hash, JSON.stringify({ accessToken: data.accessToken, name: data.profile.name, id: data.profile.id, - nick: data.profile.screen_name - }), 24 * 60 * 60, function (err, data) { + nick: data.profile.screen_name, + }), 24 * 60 * 60, (err, data) => { // Do nothing.. // But it's necessary..... // Damn }); res.cookie("weibo", hash, { - maxAge: 24 * 60 * 60 * 1000 + maxAge: 24 * 60 * 60 * 1000, }); log.log("用户" + data.profile.id + "(" + data.profile.name + ")登录(" + hash + ")"); res.redirect("/"); @@ -83,11 +84,11 @@ module.exports = function () { app.use(function (req, res, next) { // 这里用来给req添加函数 req.getSina = function (callback) { - if (typeof req.cookies.weibo != "undefined") { + if (typeof req.cookies.weibo !== "undefined") { cache.get("weibo_" + req.cookies.weibo, function (err, data) { - if (err !== null && typeof err != "undefined") { + if (err !== null && typeof err !== "undefined") { callback(err, false); - } else if (typeof data == "undefined") { + } else if (typeof data === "undefined") { callback(null, false); } else { callback(null, JSON.parse(data)); @@ -102,7 +103,7 @@ module.exports = function () { }); // 未登录时直接跳转到新浪微博 - app.get("/", function (req, res, next) { + app.get("/", (req, res, next) => { async.waterfall([ function (callback) { req.getSina(callback); @@ -116,12 +117,12 @@ module.exports = function () { } else { next(); } - } + }, ]); }); - app.post("/post", function (req, res, next) { - req.getSina(function (err, data) { + app.post("/post", (req, res, next) => { + req.getSina((err, data) => { if (data === false) { res.end("你还没有用微博登录!请刷新页面后重试!"); } else { @@ -130,8 +131,8 @@ module.exports = function () { }); }); - coordinator.on("getDanmu", function (req, res, danmuData, callback) { - req.getSina(function (err, data) { + coordinator.on("getDanmu", (req, res, danmuData, callback) => { + req.getSina((err, data) => { if (data === false) { // Do nothing } else { @@ -142,10 +143,8 @@ module.exports = function () { }); }); - coordinator.on("danmuTransfer", function (data) { - data.data.forEach(function (item) { - item.text = "@" + item.hash + ": " + item.text; - }); + coordinator.on("danmuTransfer", (data) => { + data.data.forEach(item => item.text = "@" + item.hash + ": " + item.text); }); diff --git a/lib/ext/index.js b/lib/ext/index.js index 07743bf..b100f8d 100644 --- a/lib/ext/index.js +++ b/lib/ext/index.js @@ -1,7 +1,8 @@ /* global log */ /* global async */ -var fs = require('fs'); -var path = require('path'); +'use strict'; +let fs = require('fs'); +let path = require('path'); module.exports.init = function (callback) { Object.keys(config.ext).map(function (name) { diff --git a/lib/http/index.js b/lib/http/index.js index dc4fd85..efc4d38 100644 --- a/lib/http/index.js +++ b/lib/http/index.js @@ -2,31 +2,31 @@ /* global coordinator */ /* global log */ /* global config */ - -var fs = require('fs'); -var express = require('express'); -var logger = require('morgan'); -var errorHandler = require('errorhandler'); -var path = require('path'); -var app = express(); -var bodyParser = require('body-parser'); +'use strict'; +let fs = require('fs'); +let express = require('express'); +let logger = require('morgan'); +let errorHandler = require('errorhandler'); +let path = require('path'); +let app = express(); +let bodyParser = require('body-parser'); module.exports = { init: function (callback) { app .engine('.html', require('ejs').__express) - //.use(logger('dev')) + //.use(logger('dev')) .use(bodyParser.json()) .use(bodyParser.urlencoded({ - extended: true - })) + extended: true, + })) .use(errorHandler()) .set('view engine', 'html') .set('views', path.join(__dirname, "./view/")) .use(express.static(path.join(__dirname, "./res/"))); coordinator.emit("httpBeforeRoute", app); - + // 处理路由 fs.readdir(path.join(__dirname, "./route"), (err, files) => { files.forEach((filename) => { @@ -34,13 +34,13 @@ module.exports = { }); }); - var server = app.listen(config.http.port, () => { + let server = app.listen(config.http.port, () => { log.log("服务器于http://127.0.0.1:" + config.http.port + '/成功创建'); coordinator.emit("httpCreated", server); callback(null); }); - } + }, }; diff --git a/lib/http/route/index.js b/lib/http/route/index.js index 8a80bc3..c6a97aa 100644 --- a/lib/http/route/index.js +++ b/lib/http/route/index.js @@ -1,37 +1,36 @@ /* global config */ +'use strict'; module.exports = function (app) { function renderIndex(advanced) { - var keys = Object.keys(config.rooms); - var permissions = {}; - keys.map(function(item) { - permissions[item] = config.rooms[item].permissions; - }); + let keys = Object.keys(config.rooms); + let permissions = {}; + keys.forEach(item =>permissions[item] = config.rooms[item].permissions); return { config: config, advanced: advanced, roomKeys: keys, - permissions: permissions + permissions: permissions, } } - app.route("/*").all(function (req, res, next) { + app.route("/*").all((req, res, next)=> { res.append('Server', 'zsx\'s Danmu Server'); - for (var item in config.http.headers) { + for (let item in config.http.headers) { res.append(item, config.http.headers[item]); } next(); }); - app.get("/", function (req, res) { + app.get("/", (req, res) => { res.render('index', renderIndex(false)); }); - app.get("/advanced", function (req, res) { + app.get("/advanced", (req, res) => { res.render('index', renderIndex(true)); }); - app.post(function (req, res, next) { + app.post((req, res, next)=> { res.header("Content-Type", "text/html; charset=utf-8"); next(); }); diff --git a/lib/http/route/manage.js b/lib/http/route/manage.js index bea61da..98e4c62 100644 --- a/lib/http/route/manage.js +++ b/lib/http/route/manage.js @@ -1,29 +1,28 @@ +'use strict'; module.exports = function (app) { app.get("/manage", function (req, res) { res.render("manage", { - config: config + config: config, }); }); // 总身份验证 - app.post("/manage/*", function (req, res, next) { + app.post("/manage/*", (req, res, next) => { if (/room\/get/.test(req.url)) { // 如果是房间下发则不验证身份 return next(); } - var room = req.body.room; + let room = req.body.room; if (!config.rooms[room]) { res.status(404); - res.end('{"error": "房间错误"}'); - return; + return res.end('{"error": "房间错误"}'); } - if (config.rooms[room].managepassword != req.body.password) { + if (config.rooms[room].managepassword !== req.body.password) { res.status(403); - res.end('{"error": "密码错误"}'); - return; + return res.end('{"error": "密码错误"}'); } - next(); + return next(); }); diff --git a/lib/http/route/manage_block.js b/lib/http/route/manage_block.js index 74d3241..64e15d4 100644 --- a/lib/http/route/manage_block.js +++ b/lib/http/route/manage_block.js @@ -1,10 +1,11 @@ /* global coordinator */ /* global log */ /* global config */ +'use strict'; module.exports = function (app) { - app.post("/manage/block/add/", function (req, res) { - var room = req.body.room; + app.post("/manage/block/add/", (req, res) => { + let room = req.body.room; config.rooms[room].blockusers.push(req.body.user); log.log("封禁用户" + req.body.user + "成功"); @@ -12,15 +13,15 @@ module.exports = function (app) { res.end('{"error": "封禁用户成功"}'); }); - app.post("/manage/block/get/", function (req, res) { - var room = req.body.room; + app.post("/manage/block/get/", (req, res) => { + let room = req.body.room; log.log("请求被封禁用户成功"); res.end(JSON.stringify(config.rooms[room].blockusers)); }); - app.post("/manage/block/remove/", function (req, res) { - var room = req.body.room; - var indexOf = config.rooms[room].blockusers.indexOf(req.body.user); + app.post("/manage/block/remove/", (req, res) => { + let room = req.body.room; + let indexOf = config.rooms[room].blockusers.indexOf(req.body.user); if (indexOf >= 0) { log.log("已从黑名单移除标识为" + indexOf + "的用户" + config.rooms[room].blockusers[indexOf]); config.rooms[room].blockusers.splice(indexOf, 1); diff --git a/lib/http/route/manage_config.js b/lib/http/route/manage_config.js index f4f8024..28fdb1e 100644 --- a/lib/http/route/manage_config.js +++ b/lib/http/route/manage_config.js @@ -1,10 +1,11 @@ /* global coordinator */ /* global log */ /* global config */ +'use strict'; module.exports = function (app) { - app.post("/manage/config/set/", function (req, res) { - var room = req.body.room || ""; + app.post("/manage/config/set/", (req, res) => { + let room = req.body.room || ""; config.rooms[room].keyword.replacement = new RegExp(req.body.replaceKeyword, "ig"); config.rooms[room].keyword.block = new RegExp(req.body.blockKeyword, "ig"); config.rooms[room].keyword.ignore = new RegExp(req.body.ignoreKeyword, "ig"); @@ -13,54 +14,52 @@ module.exports = function (app) { config.websocket.interval = req.body.socketinterval; config.websocket.singlesize = req.body.socketsingle; - var newConfig = JSON.stringify(utils.buildConfigToArray(room)); + let newConfig = JSON.stringify(utils.buildConfigToArray(room)); log.log("收到配置信息:" + newConfig); coordinator.emit("configUpdated"); - res.end(newConfig); + return res.end(newConfig); }); - app.post("/manage/config/permissions/set/", function (req, res) { - var room = req.body.room || ""; - Object.keys(config.rooms[room].permissions).map(function (item) { - config.rooms[room].permissions[item] = !!req.body[item]; - }); - var newConfig = JSON.stringify(config.rooms[room].permissions); + app.post("/manage/config/permissions/set/", (req, res) => { + let room = req.body.room || ""; + Object.keys(config.rooms[room].permissions).map(item => config.rooms[room].permissions[item] = !!req.body[item]); + let newConfig = JSON.stringify(config.rooms[room].permissions); log.log("收到权限配置信息:" + newConfig); coordinator.emit("configUpdated"); - res.end(newConfig); + return res.end(newConfig); }); - app.post("/manage/config/password/set/", function (req, res) { - var type = req.body.type || ""; - var password = req.body.newPassword || ""; - var room = req.body.room || ""; + app.post("/manage/config/password/set/", (req, res) => { + let type = req.body.type || ""; + let password = req.body.newPassword || ""; + let room = req.body.room || ""; if (config.rooms[room][type]) { config.rooms[room][type] = password; log.log("房间(" + room + ")的" + type + "已更新为" + password); } coordinator.emit("configUpdated"); - res.end(); + return res.end(); }); - app.post("/manage/config/permissions/get/", function (req, res) { - var room = req.body.room || ""; + app.post("/manage/config/permissions/get/", (req, res) => { + let room = req.body.room || ""; log.log("已将权限配置向管理页面下发"); - res.end(JSON.stringify(config.rooms[room].permissions)); + return res.end(JSON.stringify(config.rooms[room].permissions)); }); - app.post("/manage/config/get/", function (req, res) { - var room = req.body.room || ""; + app.post("/manage/config/get/", (req, res) => { + let room = req.body.room || ""; log.log("已将配置向管理页面下发"); - res.end(JSON.stringify(utils.buildConfigToArray(room))); + return res.end(JSON.stringify(utils.buildConfigToArray(room))); }); - app.post("/manage/config/password/get/", function (req, res) { - var room = req.body.room || ""; + app.post("/manage/config/password/get/", (req, res) => { + let room = req.body.room || ""; log.log("已将密码向管理页面下发"); - res.end(JSON.stringify({ - connectpassword: config.rooms[room].connectpassword + return res.end(JSON.stringify({ + connectpassword: config.rooms[room].connectpassword, })); }); }; diff --git a/lib/http/route/manage_danmu.js b/lib/http/route/manage_danmu.js index 4361b9e..9da2028 100644 --- a/lib/http/route/manage_danmu.js +++ b/lib/http/route/manage_danmu.js @@ -4,20 +4,20 @@ "use strict"; module.exports = function (app) { - app.post("/manage/danmu/delete/", function (req, res) { + app.post("/manage/danmu/delete/", (req, res) => { req.body.hash = req.body.hash || ""; req.body.id = req.body.id || 0; req.body.room = req.body.room || ""; - if (req.body.id == 0) { + if (req.body.id === 0) { res.end({}); return; } let deleteObject = {}; deleteObject[req.body.room] = { - ids: [req.body.id], + ids: [req.body.id], hashs: [req.body.hash], }; coordinator.emit("danmuDelete", deleteObject); @@ -29,7 +29,7 @@ module.exports = function (app) { } log.log("删除弹幕 " + req.body.id + " 成功"); - res.end('{"error": "删除弹幕成功"}'); + return res.end('{"error": "删除弹幕成功"}'); }); diff --git a/lib/http/route/manage_room.js b/lib/http/route/manage_room.js index 9972e98..a6b094e 100644 --- a/lib/http/route/manage_room.js +++ b/lib/http/route/manage_room.js @@ -1,18 +1,19 @@ /* global coordinator */ /* global log */ /* global config */ +'use strict'; module.exports = function (app) { - app.post("/manage/room/get/", function (req, res) { - var ret = []; - Object.keys(config.rooms).map(function (room) { + app.post("/manage/room/get/", (req, res) => { + let ret = []; + Object.keys(config.rooms).map(room => { ret.push({ id: room, - display: config.rooms[room].display + display: config.rooms[room].display, }); }); log.log("已把房间信息向管理页面下发"); - res.end(JSON.stringify(ret)); + return res.end(JSON.stringify(ret)); }); }; diff --git a/lib/http/route/manage_search.js b/lib/http/route/manage_search.js index 3a72ef3..41eda94 100644 --- a/lib/http/route/manage_search.js +++ b/lib/http/route/manage_search.js @@ -1,15 +1,16 @@ /* global coordinator */ /* global log */ /* global config */ +'use strict'; module.exports = function (app) { app.post("/manage/search", function (req, res) { - var room = req.body.room; + let room = req.body.room; log.log("尝试搜索" + req.body.key); coordinator.emit("searchDanmu", { key: req.body.key, - room: room + room: room, }); coordinator.on("gotSearchDanmu", function (data) { log.log("搜索" + req.body.key + "成功"); diff --git a/lib/http/route/post.js b/lib/http/route/post.js index ec50e0d..e63f79f 100644 --- a/lib/http/route/post.js +++ b/lib/http/route/post.js @@ -3,11 +3,12 @@ /* global log */ /* global config */ /* global utils */ -var permissions = ["color", "style", "height", "lifeTime", "textStyle", "sourceCode"]; // 为了不foreach +'use strict'; +let permissions = ["color", "style", "height", "lifeTime", "textStyle", "sourceCode"]; // 为了不foreach module.exports = function (app) { - app.post("/post", function (req, res) { + app.post("/post", (req, res) => { // 请求合法性校验 req.body.hash = req.body.hash || ""; req.body.room = req.body.room || ""; @@ -16,9 +17,9 @@ module.exports = function (app) { req.body.password = req.body.password || ""; // 计算用户唯一身份识别信息 - var hash = utils.getHash(req.ip, req.headers['user-agent'], req.body.hash); - var room = req.body.room; - var danmuData = { + let hash = utils.getHash(req.ip, req.headers['user-agent'], req.body.hash); + let room = req.body.room; + let danmuData = { hash: hash, room: room, text: req.body.text, @@ -28,7 +29,7 @@ module.exports = function (app) { textStyle: "", lifeTime: "", color: "", - height: "", + height: "", sourceCode: "", }; @@ -41,14 +42,14 @@ module.exports = function (app) { // 等所有异步逻辑都执行完毕之后再进行下一步操作 // 如果这里用setTimeout 0的话就方便很多了,但是在这种入口用红黑树,效率太低了 - coordinator.emitAsync("getDanmu", req, res, danmuData, function () { + coordinator.emitAsync("getDanmu", req, res, danmuData, () => { - var isAdvanced = false; + let isAdvanced = false; if (!config.rooms[room].permissions.send) { return res.end("弹幕暂时被关闭"); } - if (req.body.type == "advanced") { - if (req.body.password != config.rooms[room].advancedpassword) { + if (req.body.type === "advanced") { + if (req.body.password !== config.rooms[room].advancedpassword) { return res.end("高级弹幕密码错误!"); } isAdvanced = true; @@ -63,7 +64,7 @@ module.exports = function (app) { return res.end("发送失败!\n请检查你发送的弹幕有无关键词,或确认自己未被封禁。"); } - permissions.forEach(function (val) { + permissions.forEach((val) => { if (isAdvanced || config.rooms[room].permissions[val]) { danmuData[val] = req.body[val] || ""; } diff --git a/lib/http/route/realtime.js b/lib/http/route/realtime.js index 4a5a461..86aa1c8 100644 --- a/lib/http/route/realtime.js +++ b/lib/http/route/realtime.js @@ -1,9 +1,9 @@ module.exports = function (app) { - app.get("/realtime", function (req, res) { + app.get("/realtime", (req, res) => { res.render("realtime", { - config: config, - version: version + config: config, + version: version, }); }); diff --git a/lib/socket/index.js b/lib/socket/index.js index 541640d..4dbca2b 100644 --- a/lib/socket/index.js +++ b/lib/socket/index.js @@ -2,7 +2,7 @@ /* global log */ /* global config */ "use strict"; -var io; +let io = null; module.exports = { init: function (callback) { @@ -32,7 +32,7 @@ module.exports = { log.log(socket.id + "试图加入未定义房间"); return false; } - if (data.password != config.rooms[room].connectpassword) { + if (data.password !== config.rooms[room].connectpassword) { socket.emit("init", "Password error"); return false; } @@ -42,7 +42,7 @@ module.exports = { } socket.join(room); socket.emit("connected", { - version: version + version: version, }); log.log(socket.id + "加入" + room); }); @@ -50,5 +50,5 @@ module.exports = { }); callback(null); - } + }, }; diff --git a/lib/transfer/index.js b/lib/transfer/index.js index 41b9594..bd98bba 100644 --- a/lib/transfer/index.js +++ b/lib/transfer/index.js @@ -2,34 +2,34 @@ /* global coordinator */ /* global log */ /* global config */ - -var io = null; -var danmuQueue = {}; -var danmuKeys = []; -var async = require("async"); -var danmuId = 0; +'use strict'; +let io = null; +let danmuQueue = {}; +let danmuKeys = []; +let async = require("async"); +let danmuId = 0; module.exports = { init: function (callback) { callback(null); - } + }, }; // 更新配置 -coordinator.on("configUpdated", function (data) { +coordinator.on("configUpdated", data => { clearAllTimeval(); initDanmuQueue(); startAllTimeval(); }); // 待推送弹幕 -coordinator.on("gotDanmu", function (data) { +coordinator.on("gotDanmu", data => { // 过老弹幕没有意义,直接从队列头出队列 while (danmuQueue[data.room].queue.length > config.rooms[data.room].maxlength) { danmuQueue[data.room].queue.shift(); } - var comment = data; + let comment = data; if (data.lifeTime === "") { data.lifeTime = utils.parseLifeTime(data); } @@ -38,19 +38,19 @@ coordinator.on("gotDanmu", function (data) { }); -var initDanmuQueue = function () { +let initDanmuQueue = function () { danmuQueue = {}; danmuKeys = Object.keys(config.rooms); - danmuKeys.forEach(function(room) { + danmuKeys.forEach(function (room) { danmuQueue[room] = { queue: [], - timeval: null + timeval: null, }; }); }; -var startAllTimeval = function () { - danmuKeys.map(function(room) { +let startAllTimeval = function () { + danmuKeys.map(room => { if (config.rooms[room].permissions.send) { danmuQueue[room].timeval = initTimeval(room); log.log("创建(" + room + ")定时器 - " + config.websocket.interval + "ms"); @@ -60,20 +60,20 @@ var startAllTimeval = function () { }); }; -var clearAllTimeval = function () { - danmuKeys.map(function(room) { +let clearAllTimeval = function () { + danmuKeys.map(room => { log.log("清理(" + room + ")定时器"); clearInterval(danmuQueue[room].timeval); }); }; -var initTimeval = function (room) { - return setInterval(function () { +let initTimeval = function (room) { + return setInterval(() => { // 定时推送 - var ret = []; + let ret = []; if (danmuQueue[room].queue.length === 0) return; while (ret.length < config.websocket.singlesize && danmuQueue[room].queue.length > 0) { - var object = danmuQueue[room].queue.pop(); + let object = danmuQueue[room].queue.pop(); // 只在传输时才需要进行替换 object.text = filter.replaceKeyword(room, object.text); object.id = ++danmuId; @@ -83,7 +83,7 @@ var initTimeval = function (room) { coordinator.emit("danmuTransfer", { room: room, - data: ret + data: ret, }); }, config.websocket.interval); diff --git a/lib/utils/filter.js b/lib/utils/filter.js index fc790ca..82b5849 100644 --- a/lib/utils/filter.js +++ b/lib/utils/filter.js @@ -1,10 +1,10 @@ /* global config */ /* global coordinator */ /* global filter */ - +'use strict'; // 全局过滤器模块 -var FilterBuilder = function () { +let FilterBuilder = function () { this.blockRegExp = {}; this.replaceRegExp = {}; this.ignoreRegExp = {}; @@ -13,7 +13,7 @@ FilterBuilder.prototype.initRegExp = function () { Object.keys(config.rooms).map(function (room) { // 加入警告 - if (typeof config.rooms[room].keyword.block == "string") { + if (typeof config.rooms[room].keyword.block === "string") { console.error("请升级你的配置,将所有字符串类型关键词转换为正则类型关键词。"); throw "Init RegExp Error"; } @@ -27,10 +27,10 @@ FilterBuilder.prototype.checkUserBlock = function (room, hash) { return (config.rooms[room].blockusers.indexOf(hash)) > -1; }; FilterBuilder.prototype.checkBlock = function (room, hash, str) { - var testStr = str.replace(this.ignoreRegExp[room], ""); + let testStr = str.replace(this.ignoreRegExp[room], ""); if (this.checkUserBlock(room, hash)) return true; - var ret = this.blockRegExp[room].test(testStr); + let ret = this.blockRegExp[room].test(testStr); this.blockRegExp[room].lastIndex = 0; // 把其flag恢复,否则index始终在最后,会导致下一次判断出错。 return ret; }; diff --git a/lib/utils/index.js b/lib/utils/index.js index b48f82d..10b5514 100644 --- a/lib/utils/index.js +++ b/lib/utils/index.js @@ -1,26 +1,26 @@ /* global utils */ - -var crypto = require('crypto'); -var util = require('util'); -var events = require('events'); +'use strict'; +let crypto = require('crypto'); +let util = require('util'); +let events = require('events'); global.async = require("async"); // EventEmitter继承 -var EventEmitter = function () { +let EventEmitter = function () { events.EventEmitter.call(this); }; util.inherits(EventEmitter, events.EventEmitter); EventEmitter.prototype.emitAsync = function (type) { // 目前的emit是Sync的 - var self = this; - var callback = arguments[arguments.length - 1]; - var len, args, listeners, i, handler; + let self = this; + let callback = arguments[arguments.length - 1]; + let len, args, listeners, i, handler; handler = this._events[type]; len = arguments.length; args = new Array(len - 2); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; - setImmediate(function () { + setImmediate(() => { // 不需要太复杂的功能,只需要能apply就行 if (util.isUndefined(handler)) { @@ -51,27 +51,22 @@ require("./filter"); global.log = { log: function (text) { console.log("[" + utils.getTime() + "] " + text); - } + }, }; // 全局工具 global.utils = { - md5: function (text) { - return crypto.createHash('md5').update(text).digest('hex'); - }, + md5: text => crypto.createHash('md5').update(text).digest('hex'), getTime: function () { - var d = new Date(); + let d = new Date(); return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); }, - getHash: function (ip, userAgent, hashCode) { - var str = [ - "IP=", ip, - "UA=", userAgent, - "HC=", hashCode - ].join("\n"); - return utils.md5(str); - }, - buildConfigToArray: function (room) { + getHash: (ip, userAgent, hashCode) => utils.md5([ + "IP=", ip, + "UA=", userAgent, + "HC=", hashCode, + ].join("\n")), + buildConfigToArray: room => { return { replaceKeyword: config.rooms[room].keyword.replacement.source, blockKeyword: config.rooms[room].keyword.block.source, @@ -82,8 +77,8 @@ global.utils = { }; }, parseLifeTime: function (data) { - var imageMatches = data.text.match(config.rooms[data.room].image.regex); - var imageLength = imageMatches === null ? 0 : imageMatches.length; + let imageMatches = data.text.match(config.rooms[data.room].image.regex); + let imageLength = imageMatches === null ? 0 : imageMatches.length; return (Math.trunc(data.text.length / 10)) * 60 + config.rooms[data.room].image.lifetime * imageLength; - } + }, };