From 62417f7fb86aa09aee79cba101a577fc0472ff98 Mon Sep 17 00:00:00 2001 From: Calvin Montgomery Date: Sat, 7 Apr 2018 15:30:30 -0700 Subject: [PATCH] Add eslint (#741) --- .eslintrc.yml | 33 +++++++++++++++ package.json | 4 ++ src/acp.js | 2 - src/asyncqueue.js | 2 +- src/bgtask.js | 4 +- src/channel-storage/db-chandump.js | 1 + src/channel-storage/dbstore.js | 10 +++-- src/channel-storage/filestore.js | 12 ++++-- src/channel-storage/migrator.js | 20 ++------- src/channel/accesscontrol.js | 5 +-- src/channel/anonymouscheck.js | 20 +++++---- src/channel/channel.js | 16 ++++---- src/channel/chat.js | 30 +++++++------- src/channel/customization.js | 2 +- src/channel/drink.js | 6 ++- src/channel/emotes.js | 15 +++---- src/channel/filters.js | 2 +- src/channel/kickban.js | 49 +++++++++-------------- src/channel/library.js | 4 +- src/channel/mediarefresher.js | 1 - src/channel/module.js | 18 ++++----- src/channel/opts.js | 44 +++++++++++--------- src/channel/permissions.js | 8 ++-- src/channel/playlist.js | 21 +++------- src/channel/poll.js | 7 ++-- src/channel/ranks.js | 5 +-- src/channel/voteskip.js | 4 +- src/config.js | 3 +- src/configuration/camoconfig.js | 2 +- src/configuration/emailconfig.js | 2 +- src/counters.js | 1 - src/custom-media.js | 1 - src/customembed.js | 2 +- src/database.js | 6 +-- src/database/accounts.js | 10 ++--- src/database/channels.js | 17 +------- src/database/tables.js | 8 +++- src/database/update.js | 4 +- src/db/aliases.js | 2 +- src/db/globalban.js | 3 -- src/db/password-reset.js | 2 +- src/ffmpeg.js | 23 ++++++----- src/get-info.js | 6 +-- src/io/cluster/nullclusterclient.js | 2 +- src/io/ioserver.js | 4 +- src/logger.js | 12 +++--- src/main.js | 10 ++--- src/partition/partitionchannelindex.js | 2 +- src/partition/partitioncli.js | 2 + src/partition/partitionmodule.js | 1 - src/poll.js | 14 +++---- src/redis/lualoader.js | 2 +- src/redis/redisclientprovider.js | 4 +- src/server.js | 18 ++++----- src/servsock.js | 4 +- src/session.js | 3 +- src/setuid.js | 20 ++++++--- src/tor.js | 4 +- src/ullist.js | 24 +++++------ src/user.js | 4 +- src/util/call-once.js | 2 +- src/util/murmur.js | 2 + src/utilities.js | 24 +++++------ src/web/account.js | 15 ++++--- src/web/acp.js | 4 +- src/web/auth.js | 2 - src/web/localchannelindex.js | 1 - src/web/middleware/ipsessioncookie.js | 4 -- src/web/routes/account/data.js | 2 +- src/web/routes/google_drive_userscript.js | 2 +- src/web/webserver.js | 1 - src/xss.js | 2 +- 72 files changed, 305 insertions(+), 323 deletions(-) create mode 100644 .eslintrc.yml diff --git a/.eslintrc.yml b/.eslintrc.yml new file mode 100644 index 00000000..5a14c560 --- /dev/null +++ b/.eslintrc.yml @@ -0,0 +1,33 @@ +env: + es6: true + node: true +extends: 'eslint:recommended' +parser: 'babel-eslint' +parserOptions: + sourceType: module + ecmaVersion: 2017 # For async/await +rules: + brace-style: + - error + - 1tbs + - allowSingleLine: true + indent: + - off # temporary... a lot of stuff needs to be reformatted + - 4 + - SwitchCase: 1 + linebreak-style: + - error + - unix + no-control-regex: + - off + no-trailing-spaces: + - error + no-unused-vars: + - error + - argsIgnorePattern: ^_ + varsIgnorePattern: ^_ + semi: + - error + - always + quotes: + - off # Old code uses double quotes, new code uses single / template diff --git a/package.json b/package.json index c0ca7d87..6514d123 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,8 @@ "build-player": "./bin/build-player.js", "build-server": "babel -D --source-maps --loose es6.destructuring,es6.forOf --out-dir lib/ src/", "flow": "flow", + "lint": "eslint src", + "pretest": "npm run lint", "postinstall": "./postinstall.sh", "server-dev": "babel -D --watch --source-maps --loose es6.destructuring,es6.forOf --out-dir lib/ src/", "generate-userscript": "$npm_node_execpath gdrive-userscript/generate-userscript $@ > www/js/cytube-google-drive.user.js", @@ -56,12 +58,14 @@ "devDependencies": { "babel-cli": "^6.24.1", "babel-core": "^6.25.0", + "babel-eslint": "^8.2.2", "babel-plugin-add-module-exports": "^0.2.1", "babel-plugin-transform-async-to-generator": "^6.24.1", "babel-plugin-transform-decorators-legacy": "^1.3.4", "babel-plugin-transform-flow-strip-types": "^6.22.0", "babel-preset-env": "^1.5.2", "coffeescript": "^1.9.2", + "eslint": "^4.19.1", "flow-bin": "^0.43.0", "mocha": "^3.2.0", "sinon": "^2.3.2" diff --git a/src/acp.js b/src/acp.js index e6fab725..5c9e8c66 100644 --- a/src/acp.js +++ b/src/acp.js @@ -2,8 +2,6 @@ var Logger = require("./logger"); var Server = require("./server"); var db = require("./database"); var util = require("./utilities"); -var Config = require("./config"); -var Server = require("./server"); import { v4 as uuidv4 } from 'uuid'; function eventUsername(user) { diff --git a/src/asyncqueue.js b/src/asyncqueue.js index 2383056c..3f15c54e 100644 --- a/src/asyncqueue.js +++ b/src/asyncqueue.js @@ -9,7 +9,7 @@ AsyncQueue.prototype.next = function () { if (!this.lock()) return; var item = this._q.shift(); - var fn = item[0], tm = item[1]; + var fn = item[0]; this._tm = Date.now() + item[1]; fn(this); } diff --git a/src/bgtask.js b/src/bgtask.js index cdd1fd1e..ab27429c 100644 --- a/src/bgtask.js +++ b/src/bgtask.js @@ -14,7 +14,7 @@ const LOGGER = require('@calzoneman/jsli')('bgtask'); var init = null; /* Alias cleanup */ -function initAliasCleanup(Server) { +function initAliasCleanup(_Server) { var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval")); var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age")); @@ -28,7 +28,7 @@ function initAliasCleanup(Server) { } /* Password reset cleanup */ -function initPasswordResetCleanup(Server) { +function initPasswordResetCleanup(_Server) { var CLEAN_INTERVAL = 8*60*60*1000; setInterval(function () { diff --git a/src/channel-storage/db-chandump.js b/src/channel-storage/db-chandump.js index 7e481413..4af1455f 100644 --- a/src/channel-storage/db-chandump.js +++ b/src/channel-storage/db-chandump.js @@ -4,6 +4,7 @@ import Config from '../config'; import db from '../database'; import { DatabaseStore } from './dbstore'; +/* eslint no-console: off */ function main() { Config.load('config.yaml'); db.init(); diff --git a/src/channel-storage/dbstore.js b/src/channel-storage/dbstore.js index 3475619a..52c39563 100644 --- a/src/channel-storage/dbstore.js +++ b/src/channel-storage/dbstore.js @@ -106,10 +106,12 @@ export class DatabaseStore { if (totalSize > SIZE_LIMIT) { throw new ChannelStateSizeError( - 'Channel state size is too large', { - limit: SIZE_LIMIT, - actual: totalSize - }); + 'Channel state size is too large', + { + limit: SIZE_LIMIT, + actual: totalSize + } + ); } saveRowcount.inc(rowCount); diff --git a/src/channel-storage/filestore.js b/src/channel-storage/filestore.js index 03e22ec6..7c03dfed 100644 --- a/src/channel-storage/filestore.js +++ b/src/channel-storage/filestore.js @@ -21,10 +21,14 @@ export class FileStore { return statAsync(filename).then(stats => { if (stats.size > SIZE_LIMIT) { return Promise.reject( - new ChannelStateSizeError('Channel state file is too large', { - limit: SIZE_LIMIT, - actual: stats.size - })); + new ChannelStateSizeError( + 'Channel state file is too large', + { + limit: SIZE_LIMIT, + actual: stats.size + } + ) + ); } else { return readFileAsync(filename); } diff --git a/src/channel-storage/migrator.js b/src/channel-storage/migrator.js index a182673e..d15be8f4 100644 --- a/src/channel-storage/migrator.js +++ b/src/channel-storage/migrator.js @@ -6,7 +6,8 @@ import { DatabaseStore } from './dbstore'; import { sanitizeHTML } from '../xss'; import { ChannelNotFoundError } from '../errors'; -const QUERY_CHANNEL_NAMES = 'SELECT name FROM channels WHERE 1'; +/* eslint no-console: off */ + const EXPECTED_KEYS = [ 'chatbuffer', 'chatmuted', @@ -22,21 +23,6 @@ const EXPECTED_KEYS = [ 'poll' ]; -function queryAsync(query, substitutions) { - return new Promise((resolve, reject) => { - db.query(query, substitutions, (err, res) => { - if (err) { - if (!(err instanceof Error)) { - err = new Error(err); - } - reject(err); - } else { - resolve(res); - } - }); - }); -} - function fixOldChandump(data) { const converted = {}; EXPECTED_KEYS.forEach(key => { @@ -146,7 +132,7 @@ function migrate(src, dest, opts) { return dest.save(name, data); }).then(() => { console.log(`Migrated /${chanPath}/${name}`); - }).catch(ChannelNotFoundError, err => { + }).catch(ChannelNotFoundError, _err => { console.log(`Skipping /${chanPath}/${name} (not present in the database)`); }).catch(err => { console.error(`Failed to migrate /${chanPath}/${name}: ${err.stack}`); diff --git a/src/channel/accesscontrol.js b/src/channel/accesscontrol.js index 8b0df57d..ed75a790 100644 --- a/src/channel/accesscontrol.js +++ b/src/channel/accesscontrol.js @@ -1,18 +1,15 @@ -var Account = require("../account"); var ChannelModule = require("./module"); var Flags = require("../flags"); -function AccessControlModule(channel) { +function AccessControlModule(_channel) { ChannelModule.apply(this, arguments); } AccessControlModule.prototype = Object.create(ChannelModule.prototype); -var pending = 0; AccessControlModule.prototype.onUserPreJoin = function (user, data, cb) { var chan = this.channel, opts = this.channel.modules.options; - var self = this; if (user.socket.disconnected) { return cb("User disconnected", ChannelModule.DENY); } diff --git a/src/channel/anonymouscheck.js b/src/channel/anonymouscheck.js index 0eb008e2..0b946b93 100644 --- a/src/channel/anonymouscheck.js +++ b/src/channel/anonymouscheck.js @@ -1,37 +1,35 @@ var ChannelModule = require("./module"); var Flags = require("../flags"); -function AnonymousCheck(channel) { +function AnonymousCheck(_channel) { ChannelModule.apply(this, arguments); } AnonymousCheck.prototype = Object.create(ChannelModule.prototype); AnonymousCheck.prototype.onUserPreJoin = function (user, data, cb) { - var chan = this.channel, - opts = this.channel.modules.options; + const opts = this.channel.modules.options; var anonymousBanned = opts.get("block_anonymous_users"); - + if (user.socket.disconnected) { return cb("User disconnected", ChannelModule.DENY); } - + if(anonymousBanned && user.isAnonymous()) { user.socket.on("disconnect", function () { if (!user.is(Flags.U_IN_CHANNEL)) { cb("User disconnected", ChannelModule.DENY); } }); - + user.socket.emit("errorMsg", { msg : "This channel has blocked anonymous users. Please provide a user name to join."}); user.waitFlag(Flags.U_LOGGED_IN, function () { cb(null, ChannelModule.PASSTHROUGH); - }); - return; - } - else{ + }); + return; + } else{ cb(null, ChannelModule.PASSTHROUGH); } }; -module.exports = AnonymousCheck; \ No newline at end of file +module.exports = AnonymousCheck; diff --git a/src/channel/channel.js b/src/channel/channel.js index 78dbafc6..1b9d24c4 100644 --- a/src/channel/channel.js +++ b/src/channel/channel.js @@ -6,7 +6,6 @@ var sio = require("socket.io"); var db = require("../database"); import * as ChannelStore from '../channel-storage/channelstore'; import { ChannelStateSizeError } from '../errors'; -import Promise from 'bluebird'; import { EventEmitter } from 'events'; import { throttle } from '../util/throttle'; import Logger from '../logger'; @@ -80,8 +79,11 @@ function Channel(name) { this.name = name; this.uniqueName = name.toLowerCase(); this.modules = {}; - this.logger = new Logger.Logger(path.join(__dirname, "..", "..", "chanlogs", - this.uniqueName + ".log")); + this.logger = new Logger.Logger( + path.join( + __dirname, "..", "..", "chanlogs", this.uniqueName + ".log" + ) + ); this.users = []; this.refCounter = new ReferenceCounter(this); this.flags = 0; @@ -419,8 +421,7 @@ Channel.prototype.acceptUser = function (user) { this.logger.log("[login] Accepted connection from Tor exit at " + user.displayip); - } - else { + } else { this.logger.log("[login] Accepted connection from " + user.displayip); } @@ -461,7 +462,7 @@ Channel.prototype.acceptUser = function (user) { self.sendUserMeta(self.users, user); // TODO: Drop legacy setAFK frame after a few months self.broadcastAll("setAFK", { name: user.getName(), afk: afk }); - }) + }); user.on("effectiveRankChange", (newRank, oldRank) => { this.maybeResendUserlist(user, newRank, oldRank); }); @@ -555,7 +556,7 @@ Channel.prototype.sendUserMeta = function (users, user, minrank) { var self = this; var userdata = self.packUserData(user); users.filter(function (u) { - return typeof minrank !== "number" || u.account.effectiveRank > minrank + return typeof minrank !== "number" || u.account.effectiveRank > minrank; }).forEach(function (u) { if (u.account.globalRank >= 255) { u.socket.emit("setUserMeta", { @@ -697,7 +698,6 @@ Channel.prototype.handleReadLog = function (user) { return; } - var shouldMaskIP = user.account.globalRank < 255; this.readLog(function (err, data) { if (err) { user.socket.emit("readChanLog", { diff --git a/src/channel/chat.js b/src/channel/chat.js index 5e250513..15145c28 100644 --- a/src/channel/chat.js +++ b/src/channel/chat.js @@ -1,16 +1,14 @@ var Config = require("../config"); -var User = require("../user"); var XSS = require("../xss"); var ChannelModule = require("./module"); var util = require("../utilities"); var Flags = require("../flags"); -var url = require("url"); var counters = require("../counters"); import { transformImgTags } from '../camo'; import { Counter } from 'prom-client'; const SHADOW_TAG = "[shadow]"; -const LINK = /(\w+:\/\/(?:[^:\/\[\]\s]+|\[[0-9a-f:]+\])(?::\d+)?(?:\/[^\/\s]*)*)/ig; +const LINK = /(\w+:\/\/(?:[^:/[\]\s]+|\[[0-9a-f:]+\])(?::\d+)?(?:\/[^/\s]*)*)/ig; const LINK_PLACEHOLDER = '\ueeee'; const LINK_PLACEHOLDER_RE = /\ueeee/g; @@ -31,7 +29,7 @@ const MIN_ANTIFLOOD = { sustained: 10 }; -function ChatModule(channel) { +function ChatModule(_channel) { ChannelModule.apply(this, arguments); this.buffer = []; this.muted = new util.Set(); @@ -66,7 +64,7 @@ ChatModule.prototype.load = function (data) { } if ("chatmuted" in data) { - for (var i = 0; i < data.chatmuted.length; i++) { + for (i = 0; i < data.chatmuted.length; i++) { this.muted.add(data.chatmuted[i]); } } @@ -79,7 +77,7 @@ ChatModule.prototype.save = function (data) { data.chatmuted = Array.prototype.slice.call(this.muted); }; -ChatModule.prototype.packInfo = function (data, isAdmin) { +ChatModule.prototype.packInfo = function (data, _isAdmin) { data.chat = Array.prototype.slice.call(this.buffer); }; @@ -231,7 +229,6 @@ ChatModule.prototype.handlePm = function (user, data) { return; } - var reallyTo = data.to; data.to = data.to.toLowerCase(); if (data.to === user.getLowerName()) { @@ -383,7 +380,6 @@ ChatModule.prototype.formatMessage = function (username, data) { ChatModule.prototype.filterMessage = function (msg) { var filters = this.channel.modules.filters.filters; - var chan = this.channel; var convertLinks = this.channel.modules.options.get("enable_link_regex"); var links = msg.match(LINK); var intermediate = msg.replace(LINK, LINK_PLACEHOLDER); @@ -450,9 +446,11 @@ ChatModule.prototype.sendMessage = function (msgobj) { this.buffer.shift(); } - this.channel.logger.log("<" + msgobj.username + (msgobj.meta.addClass ? - "." + msgobj.meta.addClass : "") + - "> " + XSS.decodeText(msgobj.msg)); + this.channel.logger.log( + "<" + msgobj.username + + (msgobj.meta.addClass ? "." + msgobj.meta.addClass : "") + + "> " + XSS.decodeText(msgobj.msg) + ); }; ChatModule.prototype.registerCommand = function (cmd, cb) { @@ -491,7 +489,7 @@ ChatModule.prototype.handleCmdSay = function (user, msg, meta) { this.processChatMsg(user, { msg: args.join(" "), meta: meta }); }; -ChatModule.prototype.handleCmdClear = function (user, msg, meta) { +ChatModule.prototype.handleCmdClear = function (user, _msg, _meta) { if (!this.channel.modules.permissions.canClearChat(user)) { return; } @@ -532,11 +530,11 @@ ChatModule.prototype.handleCmdAdminflair = function (user, msg, meta) { this.processChatMsg(user, { msg: cargs.join(" "), meta: meta }); }; -ChatModule.prototype.handleCmdAfk = function (user, msg, meta) { +ChatModule.prototype.handleCmdAfk = function (user, _msg, _meta) { user.setAFK(!user.is(Flags.U_AFK)); }; -ChatModule.prototype.handleCmdMute = function (user, msg, meta) { +ChatModule.prototype.handleCmdMute = function (user, msg, _meta) { if (!this.channel.modules.permissions.canMute(user)) { return; } @@ -586,7 +584,7 @@ ChatModule.prototype.handleCmdMute = function (user, msg, meta) { this.sendModMessage(user.getName() + " muted " + target.getName(), muteperm); }; -ChatModule.prototype.handleCmdSMute = function (user, msg, meta) { +ChatModule.prototype.handleCmdSMute = function (user, msg, _meta) { if (!this.channel.modules.permissions.canMute(user)) { return; } @@ -637,7 +635,7 @@ ChatModule.prototype.handleCmdSMute = function (user, msg, meta) { this.sendModMessage(user.getName() + " shadowmuted " + target.getName(), muteperm); }; -ChatModule.prototype.handleCmdUnmute = function (user, msg, meta) { +ChatModule.prototype.handleCmdUnmute = function (user, msg, _meta) { if (!this.channel.modules.permissions.canMute(user)) { return; } diff --git a/src/channel/customization.js b/src/channel/customization.js index 897aea58..38f644ab 100644 --- a/src/channel/customization.js +++ b/src/channel/customization.js @@ -13,7 +13,7 @@ const TYPE_SETMOTD = { motd: "string" }; -function CustomizationModule(channel) { +function CustomizationModule(_channel) { ChannelModule.apply(this, arguments); this.css = ""; this.js = ""; diff --git a/src/channel/drink.js b/src/channel/drink.js index 91959725..320e9324 100644 --- a/src/channel/drink.js +++ b/src/channel/drink.js @@ -1,6 +1,10 @@ +// TODO: figure out what to do with this module +// it serves a very niche use case and is only a core module because of +// legacy reasons (early channels requested it before I had criteria +// around what to include in core) var ChannelModule = require("./module"); -function DrinkModule(channel) { +function DrinkModule(_channel) { ChannelModule.apply(this, arguments); this.drinks = 0; } diff --git a/src/channel/emotes.js b/src/channel/emotes.js index 88641ca2..a24cbb20 100644 --- a/src/channel/emotes.js +++ b/src/channel/emotes.js @@ -21,9 +21,12 @@ EmoteList.prototype = { }, emoteExists: function (emote){ - if(this.emotes.filter((item)=>{ return item.name === emote.name }).length){ - return true; + for (let i = 0; i < this.emotes.length; i++) { + if (this.emotes[i].name === emote.name) { + return true; + } } + return false; }, @@ -61,7 +64,6 @@ EmoteList.prototype = { }, removeEmote: function (emote) { - var found = false; for (var i = 0; i < this.emotes.length; i++) { if (this.emotes[i].name === emote.name) { this.emotes.splice(i, 1); @@ -99,7 +101,7 @@ function validateEmote(f) { f.image = f.image.substring(0, 1000); f.image = XSS.sanitizeText(f.image); - var s = XSS.looseSanitizeText(f.name).replace(/([\\\.\?\+\*\$\^\|\(\)\[\]\{\}])/g, "\\$1"); + var s = XSS.looseSanitizeText(f.name).replace(/([\\.?+*$^|()[\]{}])/g, "\\$1"); s = "(^|\\s)" + s + "(?!\\S)"; f.source = s; @@ -114,9 +116,9 @@ function validateEmote(f) { } return f; -}; +} -function EmoteModule(channel) { +function EmoteModule(_channel) { ChannelModule.apply(this, arguments); this.emotes = new EmoteList(); this.supportsDirtyCheck = true; @@ -153,7 +155,6 @@ EmoteModule.prototype.onUserPostJoin = function (user) { EmoteModule.prototype.sendEmotes = function (users) { var f = this.emotes.pack(); - var chan = this.channel; users.forEach(function (u) { u.socket.emit("emoteList", f); }); diff --git a/src/channel/filters.js b/src/channel/filters.js index 082cbbf7..c72f41df 100644 --- a/src/channel/filters.js +++ b/src/channel/filters.js @@ -62,7 +62,7 @@ const DEFAULT_FILTERS = [ "\\1") ]; -function ChatFilterModule(channel) { +function ChatFilterModule(_channel) { ChannelModule.apply(this, arguments); this.filters = new FilterList(); this.supportsDirtyCheck = true; diff --git a/src/channel/kickban.js b/src/channel/kickban.js index 3feb0dbd..c080fa2b 100644 --- a/src/channel/kickban.js +++ b/src/channel/kickban.js @@ -15,7 +15,7 @@ const TYPE_UNBAN = { name: "string" }; -function KickBanModule(channel) { +function KickBanModule(_channel) { ChannelModule.apply(this, arguments); if (this.channel.modules.chat) { @@ -39,16 +39,6 @@ function checkIPBan(cname, ip, cb) { }); } -function checkNameBan(cname, name, cb) { - db.channels.isNameBanned(cname, name, function (err, banned) { - if (err) { - cb(false); - } else { - cb(banned); - } - }); -} - function checkBan(cname, ip, name, cb) { db.channels.isBanned(cname, ip, name, function (err, banned) { if (err) { @@ -65,7 +55,6 @@ KickBanModule.prototype.onUserPreJoin = function (user, data, cb) { } const cname = this.channel.name; - const check = (user.getName() !== '') ? checkBan : checkIPBan; function callback(banned) { if (banned) { cb(null, ChannelModule.DENY); @@ -162,7 +151,7 @@ KickBanModule.prototype.sendUnban = function (users, data) { }); }; -KickBanModule.prototype.handleCmdKick = function (user, msg, meta) { +KickBanModule.prototype.handleCmdKick = function (user, msg, _meta) { if (!this.channel.modules.permissions.canKick(user)) { return; } @@ -206,7 +195,7 @@ KickBanModule.prototype.handleCmdKick = function (user, msg, meta) { } }; -KickBanModule.prototype.handleCmdKickAnons = function (user, msg, meta) { +KickBanModule.prototype.handleCmdKickAnons = function (user, _msg, _meta) { if (!this.channel.modules.permissions.canKick(user)) { return; } @@ -226,7 +215,7 @@ KickBanModule.prototype.handleCmdKickAnons = function (user, msg, meta) { }; /* /ban - name bans */ -KickBanModule.prototype.handleCmdBan = function (user, msg, meta) { +KickBanModule.prototype.handleCmdBan = function (user, msg, _meta) { var args = msg.split(" "); args.shift(); /* shift off /ban */ if (args.length === 0 || args[0].trim() === "") { @@ -249,7 +238,7 @@ KickBanModule.prototype.handleCmdBan = function (user, msg, meta) { }; /* /ipban - bans name and IP addresses associated with it */ -KickBanModule.prototype.handleCmdIPBan = function (user, msg, meta) { +KickBanModule.prototype.handleCmdIPBan = function (user, msg, _meta) { var args = msg.split(" "); args.shift(); /* shift off /ipban */ if (args.length === 0 || args[0].trim() === "") { @@ -325,8 +314,8 @@ KickBanModule.prototype.banName = async function banName(actor, name, reason) { if (chan.modules.chat) { chan.modules.chat.sendModMessage( - actor.getName() + " namebanned " + name, - chan.modules.permissions.permissions.ban + actor.getName() + " namebanned " + name, + chan.modules.permissions.permissions.ban ); } @@ -364,14 +353,14 @@ KickBanModule.prototype.banIP = async function banIP(actor, ip, name, reason) { var cloaked = util.cloakIP(ip); chan.logger.log( - "[mod] " + actor.getName() + " banned " + cloaked + - " (" + name + ")" + "[mod] " + actor.getName() + " banned " + cloaked + + " (" + name + ")" ); if (chan.modules.chat) { chan.modules.chat.sendModMessage( - actor.getName() + " banned " + cloaked + " (" + name + ")", - chan.modules.permissions.permissions.ban + actor.getName() + " banned " + cloaked + " (" + name + ")", + chan.modules.permissions.permissions.ban ); } @@ -379,10 +368,10 @@ KickBanModule.prototype.banIP = async function banIP(actor, ip, name, reason) { }; KickBanModule.prototype.banAll = async function banAll( - actor, - name, - range, - reason + actor, + name, + range, + reason ) { reason = reason.substring(0, 255); @@ -411,7 +400,7 @@ KickBanModule.prototype.banAll = async function banAll( } const promises = Array.from(toBan).map(ip => - this.banIP(actor, ip, name, reason) + this.banIP(actor, ip, name, reason) ); if (!await dbIsNameBanned(chan.name, name)) { @@ -451,8 +440,10 @@ KickBanModule.prototype.handleUnban = function (user, data) { self.channel.logger.log("[mod] " + user.getName() + " unbanned " + data.name); if (self.channel.modules.chat) { var banperm = self.channel.modules.permissions.permissions.ban; - self.channel.modules.chat.sendModMessage(user.getName() + " unbanned " + - data.name, banperm); + self.channel.modules.chat.sendModMessage( + user.getName() + " unbanned " + data.name, + banperm + ); } self.channel.refCounter.unref("KickBanModule::handleUnban"); }); diff --git a/src/channel/library.js b/src/channel/library.js index da06e895..c8c4d7ca 100644 --- a/src/channel/library.js +++ b/src/channel/library.js @@ -15,7 +15,7 @@ const TYPE_SEARCH_MEDIA = { query: "string" }; -function LibraryModule(channel) { +function LibraryModule(_channel) { ChannelModule.apply(this, arguments); } @@ -67,7 +67,7 @@ LibraryModule.prototype.handleUncache = function (user, data) { const chan = this.channel; chan.refCounter.ref("LibraryModule::handleUncache"); - db.channels.deleteFromLibrary(chan.name, data.id, function (err, res) { + db.channels.deleteFromLibrary(chan.name, data.id, function (err, _res) { if (chan.dead) { return; } else if (err) { diff --git a/src/channel/mediarefresher.js b/src/channel/mediarefresher.js index 457669a8..4639f6a6 100644 --- a/src/channel/mediarefresher.js +++ b/src/channel/mediarefresher.js @@ -1,7 +1,6 @@ var Vimeo = require("cytube-mediaquery/lib/provider/vimeo"); var ChannelModule = require("./module"); var Config = require("../config"); -var InfoGetter = require("../get-info"); const LOGGER = require('@calzoneman/jsli')('mediarefresher'); diff --git a/src/channel/module.js b/src/channel/module.js index 34a0dd7a..b2268236 100644 --- a/src/channel/module.js +++ b/src/channel/module.js @@ -8,13 +8,13 @@ ChannelModule.prototype = { /** * Called when the channel is loading its data from a JSON object. */ - load: function (data) { + load: function (_data) { }, /** * Called when the channel is saving its state to a JSON object. */ - save: function (data) { + save: function (_data) { }, /** @@ -27,7 +27,7 @@ ChannelModule.prototype = { /** * Called to pack info, e.g. for channel detail view */ - packInfo: function (data, isAdmin) { + packInfo: function (_data, _isAdmin) { }, @@ -37,40 +37,40 @@ ChannelModule.prototype = { * data is the data sent by the client with the joinChannel * packet. */ - onUserPreJoin: function (user, data, cb) { + onUserPreJoin: function (_user, _data, cb) { cb(null, ChannelModule.PASSTHROUGH); }, /** * Called after a user has been accepted to the channel. */ - onUserPostJoin: function (user) { + onUserPostJoin: function (_user) { }, /** * Called after a user has been disconnected from the channel. */ - onUserPart: function (user) { + onUserPart: function (_user) { }, /** * Called when a chatMsg event is received */ - onUserPreChat: function (user, data, cb) { + onUserPreChat: function (_user, _data, cb) { cb(null, ChannelModule.PASSTHROUGH); }, /** * Called before a new video begins playing */ - onPreMediaChange: function (data, cb) { + onPreMediaChange: function (_data, cb) { cb(null, ChannelModule.PASSTHROUGH); }, /** * Called when a new video begins playing */ - onMediaChange: function (data) { + onMediaChange: function (_data) { }, }; diff --git a/src/channel/opts.js b/src/channel/opts.js index 79c57387..0d3250f1 100644 --- a/src/channel/opts.js +++ b/src/channel/opts.js @@ -7,7 +7,7 @@ function realTypeOf(thing) { return thing === null ? 'null' : typeof thing; } -function OptionsModule(channel) { +function OptionsModule(_channel) { ChannelModule.apply(this, arguments); this.opts = { allow_voteskip: true, // Allow users to voteskip @@ -28,7 +28,7 @@ function OptionsModule(channel) { password: false, // Channel password (false -> no password required for entry) allow_dupes: false, // Allow duplicate videos on the playlist torbanned: false, // Block connections from Tor exit nodes - block_anonymous_users: false, //Only allow connections from registered users. + block_anonymous_users: false, //Only allow connections from registered users. allow_ascii_control: false,// Allow ASCII control characters (\x00-\x1f) playlist_max_per_user: 0, // Maximum number of playlist items per user new_user_chat_delay: 0, // Minimum account/IP age to chat @@ -50,10 +50,14 @@ OptionsModule.prototype.load = function (data) { } } - this.opts.chat_antiflood_params.burst = Math.min(20, - this.opts.chat_antiflood_params.burst); - this.opts.chat_antiflood_params.sustained = Math.min(10, - this.opts.chat_antiflood_params.sustained); + this.opts.chat_antiflood_params.burst = Math.min( + 20, + this.opts.chat_antiflood_params.burst + ); + this.opts.chat_antiflood_params.sustained = Math.min( + 10, + this.opts.chat_antiflood_params.sustained + ); this.dirty = false; }; @@ -164,7 +168,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { if ("maxlength" in data) { var ml = 0; if (typeof data.maxlength !== "number") { - ml = Utilities.parseTime(data.maxlength); + ml = Utilities.parseTime(data.maxlength); } else { ml = parseInt(data.maxlength); } @@ -206,13 +210,13 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { target: "#cs-externalcss" }); } else { - var data = url.parse(link); - if (!data.protocol || data.protocol !== 'https:') { + var urldata = url.parse(link); + if (!urldata.protocol || urldata.protocol !== 'https:') { user.socket.emit("validationError", { target: "#cs-externalcss", message: prefix + " URL must begin with 'https://'" }); - } else if (!data.host) { + } else if (!urldata.host) { user.socket.emit("validationError", { target: "#cs-externalcss", message: prefix + "missing hostname" @@ -221,14 +225,14 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { user.socket.emit("validationPassed", { target: "#cs-externalcss" }); - this.opts.externalcss = data.href; + this.opts.externalcss = urldata.href; sendUpdate = true; } } } if ("externaljs" in data && user.account.effectiveRank >= 3) { - var prefix = "Invalid URL for external JS: "; + const prefix = "Invalid URL for external JS: "; if (typeof data.externaljs !== "string") { user.socket.emit("validationError", { target: "#cs-externaljs", @@ -237,7 +241,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { }); } - var link = data.externaljs.substring(0, 255).trim(); + const link = data.externaljs.substring(0, 255).trim(); if (!link) { sendUpdate = (this.opts.externaljs !== ""); this.opts.externaljs = ""; @@ -245,13 +249,13 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { target: "#cs-externaljs" }); } else { - var data = url.parse(link); - if (!data.protocol || data.protocol !== 'https:') { + const urldata = url.parse(link); + if (!urldata.protocol || urldata.protocol !== 'https:') { user.socket.emit("validationError", { target: "#cs-externaljs", message: prefix + " URL must begin with 'https://'" }); - } else if (!data.host) { + } else if (!urldata.host) { user.socket.emit("validationError", { target: "#cs-externaljs", message: prefix + "missing hostname" @@ -260,7 +264,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { user.socket.emit("validationPassed", { target: "#cs-externaljs" }); - this.opts.externaljs = data.href; + this.opts.externaljs = urldata.href; sendUpdate = true; } } @@ -333,7 +337,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { this.opts.block_anonymous_users = Boolean(data.block_anonymous_users); sendUpdate = true; } - + if ("allow_ascii_control" in data && user.account.effectiveRank >= 3) { this.opts.allow_ascii_control = Boolean(data.allow_ascii_control); sendUpdate = true; @@ -348,7 +352,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { } if ("new_user_chat_delay" in data) { - var delay = data.new_user_chat_delay; + const delay = data.new_user_chat_delay; if (!isNaN(delay) && delay >= 0) { this.opts.new_user_chat_delay = delay; sendUpdate = true; @@ -356,7 +360,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) { } if ("new_user_chat_link_delay" in data) { - var delay = data.new_user_chat_link_delay; + const delay = data.new_user_chat_link_delay; if (!isNaN(delay) && delay >= 0) { this.opts.new_user_chat_link_delay = delay; sendUpdate = true; diff --git a/src/channel/permissions.js b/src/channel/permissions.js index 3254f5c8..7609ac3e 100644 --- a/src/channel/permissions.js +++ b/src/channel/permissions.js @@ -46,7 +46,7 @@ const DEFAULT_PERMISSIONS = { exceedmaxdurationperuser: 2 // Exceed maximum total playlist length per user }; -function PermissionsModule(channel) { +function PermissionsModule(_channel) { ChannelModule.apply(this, arguments); this.permissions = {}; this.openPlaylist = false; @@ -148,7 +148,7 @@ PermissionsModule.prototype.handleSetPermissions = function (user, perms) { return; } - for (var key in perms) { + for (const key in perms) { if (typeof perms[key] !== "number") { perms[key] = parseFloat(perms[key]); if (isNaN(perms[key])) { @@ -157,7 +157,7 @@ PermissionsModule.prototype.handleSetPermissions = function (user, perms) { } } - for (var key in perms) { + for (const key in perms) { if (key in this.permissions) { this.permissions[key] = perms[key]; } @@ -215,7 +215,7 @@ PermissionsModule.prototype.canMoveVideo = function (account) { }; PermissionsModule.prototype.canDeleteVideo = function (account) { - return this.hasPermission(account, "playlistdelete") + return this.hasPermission(account, "playlistdelete"); }; PermissionsModule.prototype.canSkipVideo = function (account) { diff --git a/src/channel/playlist.js b/src/channel/playlist.js index f2470bcc..a5f12482 100644 --- a/src/channel/playlist.js +++ b/src/channel/playlist.js @@ -86,7 +86,7 @@ PlaylistItem.prototype = { } }; -function PlaylistModule(channel) { +function PlaylistModule(_channel) { ChannelModule.apply(this, arguments); this.items = new ULList(); this.meta = { @@ -541,7 +541,6 @@ PlaylistModule.prototype.queueStandard = function (user, data) { } function handleLookup() { - var channelName = self.channel.name; InfoGetter.getMedia(data.id, data.type, function (err, media) { if (err) { error(XSS.sanitizeText(String(err))); @@ -795,7 +794,7 @@ PlaylistModule.prototype.handleShuffle = function (user) { this.channel.users.forEach(function (u) { if (perms.canSeePlaylist(u)) { u.socket.emit("playlist", pl); - }; + } }); this.startPlayback(); }; @@ -1069,16 +1068,6 @@ PlaylistModule.prototype._addItem = function (media, data, user, cb) { } }; -function isExpired(media) { - if (media.meta.expiration && media.meta.expiration < Date.now()) { - return true; - } else if (media.type === "gd") { - return !media.meta.object; - } else if (media.type === "vi") { - return !media.meta.direct; - } -} - PlaylistModule.prototype.startPlayback = function (time) { var self = this; @@ -1150,7 +1139,7 @@ PlaylistModule.prototype.startPlayback = function (time) { } } ); -} +}; const UPDATE_INTERVAL = Config.get("playlist.update-interval"); @@ -1232,7 +1221,7 @@ PlaylistModule.prototype.clean = function (test) { * -flags) */ function generateTargetRegex(target) { - const flagsre = /^(-[img]+\s+)/i + const flagsre = /^(-[img]+\s+)/i; var m = target.match(flagsre); var flags = ""; if (m) { @@ -1242,7 +1231,7 @@ function generateTargetRegex(target) { return new RegExp(target, flags); } -PlaylistModule.prototype.handleClean = function (user, msg, meta) { +PlaylistModule.prototype.handleClean = function (user, msg, _meta) { if (!this.channel.modules.permissions.canDeleteVideo(user)) { return; } diff --git a/src/channel/poll.js b/src/channel/poll.js index f7bc70ce..26a1ec3a 100644 --- a/src/channel/poll.js +++ b/src/channel/poll.js @@ -18,7 +18,7 @@ const TYPE_VOTE = { const ROOM_VIEW_HIDDEN = ":viewHidden"; const ROOM_NO_VIEW_HIDDEN = ":noViewHidden"; -function PollModule(channel) { +function PollModule(_channel) { ChannelModule.apply(this, arguments); this.poll = null; @@ -125,7 +125,6 @@ PollModule.prototype.broadcastPoll = function (isNewPoll) { var obscured = this.poll.packUpdate(false); var unobscured = this.poll.packUpdate(true); - var perms = this.channel.modules.permissions; const event = isNewPoll ? "newPoll" : "updatePoll"; if (isNewPoll) { @@ -192,7 +191,7 @@ PollModule.prototype.handleNewPoll = function (user, data, ack) { poll.timer = setTimeout(function () { if (self.poll === poll) { self.handleClosePoll({ - getName: function () { return "[poll timer]" }, + getName: function () { return "[poll timer]"; }, effectiveRank: 255 }); } @@ -240,7 +239,7 @@ PollModule.prototype.handleClosePoll = function (user) { } }; -PollModule.prototype.handlePollCmd = function (obscured, user, msg, meta) { +PollModule.prototype.handlePollCmd = function (obscured, user, msg, _meta) { if (!this.channel.modules.permissions.canControlPoll(user)) { return; } diff --git a/src/channel/ranks.js b/src/channel/ranks.js index bdfeb9f9..bb61ddae 100644 --- a/src/channel/ranks.js +++ b/src/channel/ranks.js @@ -11,7 +11,7 @@ const TYPE_SET_CHANNEL_RANK = { rank: "number" }; -function RankModule(channel) { +function RankModule(_channel) { ChannelModule.apply(this, arguments); if (this.channel.modules.chat) { @@ -47,7 +47,7 @@ RankModule.prototype.sendChannelRanks = function (users) { }); }; -RankModule.prototype.handleCmdRank = function (user, msg, meta) { +RankModule.prototype.handleCmdRank = function (user, msg, _meta) { var args = msg.split(" "); args.shift(); /* shift off /rank */ var name = args.shift(); @@ -186,7 +186,6 @@ RankModule.prototype.updateDatabase = function (data, cb) { "You can't promote or demote someone" + " with equal or higher rank than you." ); - return; } return dbSetChannelRank(chan.name, data.name, data.rank); diff --git a/src/channel/voteskip.js b/src/channel/voteskip.js index 374641f8..608c970a 100644 --- a/src/channel/voteskip.js +++ b/src/channel/voteskip.js @@ -2,7 +2,7 @@ var ChannelModule = require("./module"); var Flags = require("../flags"); var Poll = require("../poll").Poll; -function VoteskipModule(channel) { +function VoteskipModule(_channel) { ChannelModule.apply(this, arguments); this.poll = false; @@ -128,7 +128,7 @@ VoteskipModule.prototype.reset = function reset() { this.sendVoteskipData(this.channel.users); }; -VoteskipModule.prototype.onMediaChange = function (data) { +VoteskipModule.prototype.onMediaChange = function (_data) { this.reset(); }; diff --git a/src/config.js b/src/config.js index d84401c0..98fc3f14 100644 --- a/src/config.js +++ b/src/config.js @@ -1,4 +1,3 @@ -var fs = require("fs"); var path = require("path"); var net = require("net"); var YAML = require("yamljs"); @@ -194,7 +193,7 @@ function checkLoadConfig(configClass, filename) { } if (typeof error.line !== 'undefined') { - LOGGER.error(`Error in conf/${fileanme}: ${error} (line ${error.line})`); + LOGGER.error(`Error in conf/${filename}: ${error} (line ${error.line})`); } else { LOGGER.error(`Error loading conf/${filename}: ${error.stack}`); } diff --git a/src/configuration/camoconfig.js b/src/configuration/camoconfig.js index 518ab57e..c3df2edd 100644 --- a/src/configuration/camoconfig.js +++ b/src/configuration/camoconfig.js @@ -1,4 +1,4 @@ -const SPECIALCHARS = /([\\\.\?\+\*\$\^\|\(\)\[\]\{\}])/g; +const SPECIALCHARS = /([\\.?+*$^|()[\]{}])/g; class CamoConfig { constructor(config = { camo: { enabled: false } }) { diff --git a/src/configuration/emailconfig.js b/src/configuration/emailconfig.js index 23d2e4f7..7cf0f629 100644 --- a/src/configuration/emailconfig.js +++ b/src/configuration/emailconfig.js @@ -23,7 +23,7 @@ class EmailConfig { getPassword() { return smtp.password; } - } + }; const reset = config['password-reset']; this._reset = { diff --git a/src/counters.js b/src/counters.js index b2ec44ca..2a042f3c 100644 --- a/src/counters.js +++ b/src/counters.js @@ -5,7 +5,6 @@ import { JSONFileMetricsReporter } from './metrics/jsonfilemetricsreporter'; const LOGGER = require('@calzoneman/jsli')('counters'); -var counters = {}; var server = null; exports.add = Metrics.incCounter; diff --git a/src/custom-media.js b/src/custom-media.js index 8c091493..d3c872d0 100644 --- a/src/custom-media.js +++ b/src/custom-media.js @@ -2,7 +2,6 @@ import { ValidationError } from './errors'; import { parse as urlParse } from 'url'; import net from 'net'; import Media from './media'; -import { hash } from './util/hash'; import { get as httpGet } from 'http'; import { get as httpsGet } from 'https'; diff --git a/src/customembed.js b/src/customembed.js index 1ce81200..ff87b13d 100644 --- a/src/customembed.js +++ b/src/customembed.js @@ -54,7 +54,7 @@ function filterEmbed(tag) { src: tag.attribs.src, params: {} } - } + }; for (var key in tag.attribs) { if (ALLOWED_PARAMS.test(key)) { diff --git a/src/database.js b/src/database.js index ebb1cd22..06ce6e65 100644 --- a/src/database.js +++ b/src/database.js @@ -1,9 +1,5 @@ -var mysql = require("mysql"); -var bcrypt = require("bcrypt"); var Config = require("./config"); var tables = require("./database/tables"); -var net = require("net"); -var util = require("./utilities"); import * as Metrics from './metrics/metrics'; import knex from 'knex'; import { GlobalBanDB } from './db/globalban'; @@ -127,7 +123,7 @@ module.exports.query = function (query, sub, callback) { } if (process.env.SHOW_SQL) { - console.log(query); + LOGGER.debug('%s', query); } const end = queryLatency.startTimer(); diff --git a/src/database/accounts.js b/src/database/accounts.js index a49ecbf4..7201348b 100644 --- a/src/database/accounts.js +++ b/src/database/accounts.js @@ -199,7 +199,7 @@ module.exports = { " VALUES " + "(?, ?, ?, ?, '', ?, ?, ?)", [name, hash, 1, email, ip, Date.now(), module.exports.dedupeUsername(name)], - function (err, res) { + function (err, _res) { delete registrationLock[lname]; if (err) { callback(err, null); @@ -292,7 +292,7 @@ module.exports = { db.query("UPDATE `users` SET password=? WHERE name=?", [hash, name], - function (err, result) { + function (err, _result) { callback(err, err ? null : true); }); }); @@ -347,7 +347,7 @@ module.exports = { } db.query("UPDATE `users` SET global_rank=? WHERE name=?", [rank, name], - function (err, result) { + function (err, _result) { callback(err, err ? null : true); }); }, @@ -427,7 +427,7 @@ module.exports = { } db.query("UPDATE `users` SET email=? WHERE name=?", [email, name], - function (err, result) { + function (err, _result) { callback(err, err ? null : true); }); }, @@ -509,7 +509,7 @@ module.exports = { }); db.query("UPDATE `users` SET profile=? WHERE name=?", [profilejson, name], - function (err, result) { + function (err, _result) { callback(err, err ? null : true); }); }, diff --git a/src/database/channels.js b/src/database/channels.js index 7f971581..c2f13579 100644 --- a/src/database/channels.js +++ b/src/database/channels.js @@ -2,7 +2,6 @@ var db = require("../database"); var valid = require("../utilities").isValidChannelName; var fs = require("fs"); var path = require("path"); -var tables = require("./tables"); var Flags = require("../flags"); var util = require("../utilities"); import { createMySQLDuplicateKeyUpdate } from '../util/on-duplicate-key-update'; @@ -12,18 +11,6 @@ const LOGGER = require('@calzoneman/jsli')('database/channels'); var blackHole = function () { }; -function dropTable(name, callback) { - db.query("DROP TABLE `" + name + "`", callback); -} - -function initTables(name, owner, callback) { - if (!valid(name)) { - callback("Invalid channel name", null); - return; - } - -} - module.exports = { init: function () { }, @@ -152,7 +139,7 @@ module.exports = { db.query("INSERT INTO `channels` " + "(`name`, `owner`, `time`, `last_loaded`) VALUES (?, ?, ?, ?)", [name, owner, Date.now(), new Date()], - function (err, res) { + function (err, _res) { if (err) { callback(err, null); return; @@ -220,7 +207,7 @@ module.exports = { } }); - callback(err, !Boolean(err)); + callback(err, !err); }); }, diff --git a/src/database/tables.js b/src/database/tables.js index 9f07387a..ab99514c 100644 --- a/src/database/tables.js +++ b/src/database/tables.js @@ -1,3 +1,5 @@ +const LOGGER = require('@calzoneman/jsli')('database/tables'); + const TBL_USERS = "" + "CREATE TABLE IF NOT EXISTS `users` (" + "`id` INT NOT NULL AUTO_INCREMENT," + @@ -134,7 +136,11 @@ module.exports.init = function (queryfn, cb) { aq.queue(function (lock) { queryfn(tables[tbl], function (err) { if (err) { - console.log(err); + LOGGER.error( + 'Failed to create table %s: %s', + tbl, + err.stack + ); hasError = true; } lock.release(); diff --git a/src/database/update.js b/src/database/update.js index df6294d8..5b1b914f 100644 --- a/src/database/update.js +++ b/src/database/update.js @@ -17,7 +17,7 @@ module.exports.checkVersion = function () { "db_version=" + DB_VERSION); db.query("INSERT INTO `meta` (`key`, `value`) VALUES ('db_version', ?)", [DB_VERSION], - function (err) { + function (_err) { }); } else { var v = parseInt(rows[0].value); @@ -89,7 +89,7 @@ function populateUsernameDedupeColumn(cb) { cb(); }).catch(error => { LOGGER.error("Unable to perform database upgrade to add dedupe column: " + (error.stack ? error.stack : error)); - }) + }); }); } diff --git a/src/db/aliases.js b/src/db/aliases.js index f11db976..d2149567 100644 --- a/src/db/aliases.js +++ b/src/db/aliases.js @@ -31,7 +31,7 @@ class AliasesDB { return this.db.runTransaction(async tx => { const query = tx.table('aliases'); if (net.isIP(ip)) { - query.where({ ip: ip }) + query.where({ ip: ip }); } else { const delimiter = /^[0-9]+\./.test(ip) ? '.' : ':'; query.where('ip', 'LIKE', ip + delimiter + '%'); diff --git a/src/db/globalban.js b/src/db/globalban.js index 259f4460..8d992fb5 100644 --- a/src/db/globalban.js +++ b/src/db/globalban.js @@ -1,6 +1,3 @@ -import util from '../utilities'; -import Promise from 'bluebird'; - const LOGGER = require('@calzoneman/jsli')('GlobalBanDB'); class GlobalBanDB { diff --git a/src/db/password-reset.js b/src/db/password-reset.js index d8552b15..6f711542 100644 --- a/src/db/password-reset.js +++ b/src/db/password-reset.js @@ -44,7 +44,7 @@ class PasswordResetDB { cleanup(threshold = ONE_DAY) { return this.db.runTransaction(tx => { return tx.table('password_reset') - .where('expire', '<', Date.now() - ONE_DAY) + .where('expire', '<', Date.now() - threshold) .del(); }); } diff --git a/src/ffmpeg.js b/src/ffmpeg.js index b69aef99..99895951 100644 --- a/src/ffmpeg.js +++ b/src/ffmpeg.js @@ -14,37 +14,37 @@ const ECODE_MESSAGES = { `Unknown host "${e.hostname}". ` + 'Please check that the link is correct.' ), - EPROTO: e => 'The remote server does not support HTTPS.', - ECONNRESET: e => 'The remote server unexpectedly closed the connection.', - ECONNREFUSED: e => ( + EPROTO: _e => 'The remote server does not support HTTPS.', + ECONNRESET: _e => 'The remote server unexpectedly closed the connection.', + ECONNREFUSED: _e => ( 'The remote server refused the connection. ' + 'Please check that the link is correct and the server is running.' ), - ETIMEDOUT: e => ( + ETIMEDOUT: _e => ( 'The connection to the remote server timed out. ' + 'Please check that the link is correct.' ), - ENETUNREACH: e => ( + ENETUNREACH: _e => ( "The remote server's network is unreachable from this server. " + "Please contact an administrator for assistance." ), - EHOSTUNREACH: e => ( + EHOSTUNREACH: _e => ( "The remote server is unreachable from this server. " + "Please contact the video server's administrator for assistance." ), - DEPTH_ZERO_SELF_SIGNED_CERT: e => ( + DEPTH_ZERO_SELF_SIGNED_CERT: _e => ( 'The remote server provided an invalid ' + '(self-signed) SSL certificate. Raw file support requires a ' + 'trusted certificate. See https://letsencrypt.org/ to get ' + 'a free, trusted certificate.' ), - UNABLE_TO_VERIFY_LEAF_SIGNATURE: e => ( + UNABLE_TO_VERIFY_LEAF_SIGNATURE: _e => ( "The remote server's SSL certificate chain could not be validated. " + "Please contact the administrator of the server to correct their " + "SSL certificate configuration." ), - CERT_HAS_EXPIRED: e => ( + CERT_HAS_EXPIRED: _e => ( "The remote server's SSL certificate has expired. Please contact " + "the administrator of the server to renew the certificate." ) @@ -73,6 +73,7 @@ var audioOnlyContainers = { function fflog() { } +/* eslint no-func-assign: off */ function initFFLog() { if (fflog.initialized) return; var logger = new Logger.Logger(path.resolve(__dirname, "..", "ffmpeg.log")); @@ -200,7 +201,7 @@ function testUrl(url, cb, params = { redirCount: 0, cookie: '' }) { cb("An unexpected error occurred while trying to process the link. " + "Try again, and contact support for further troubleshooting if the " + - "problem continues." + (!!err.code ? (" Error code: " + err.code) : "")); + "problem continues." + (err.code ? (" Error code: " + err.code) : "")); }); req.end(); @@ -389,7 +390,7 @@ exports.ffprobe = function ffprobe(filename, cb) { return cb(null, result); }); -} +}; exports.query = function (filename, cb) { if (Config.get("ffmpeg.log") && !fflog.initialized) { diff --git a/src/get-info.js b/src/get-info.js index 642c4a19..25e0c80a 100644 --- a/src/get-info.js +++ b/src/get-info.js @@ -1,6 +1,5 @@ var http = require("http"); var https = require("https"); -var cheerio = require('cheerio'); var Media = require("./media"); var CustomEmbedFilter = require("./customembed").filter; var Config = require("./config"); @@ -9,7 +8,6 @@ var mediaquery = require("cytube-mediaquery"); var YouTube = require("cytube-mediaquery/lib/provider/youtube"); var Vimeo = require("cytube-mediaquery/lib/provider/vimeo"); var Streamable = require("cytube-mediaquery/lib/provider/streamable"); -var GoogleDrive = require("cytube-mediaquery/lib/provider/googledrive"); var TwitchVOD = require("cytube-mediaquery/lib/provider/twitch-vod"); var TwitchClip = require("cytube-mediaquery/lib/provider/twitch-clip"); import { Counter } from 'prom-client'; @@ -209,7 +207,7 @@ var Getters = { /* TODO: require server owners to register their own API key, put in config */ const SC_CLIENT = "2e0c82ab5a020f3a7509318146128abd"; - var m = id.match(/([\w-\/\.:]+)/); + var m = id.match(/([\w-/.:]+)/); if (m) { id = m[1]; } else { @@ -377,7 +375,7 @@ var Getters = { * http://www.ustream.tv/foo so they do both. * [](/cleese) */ - var m = id.match(/([^\?&#]+)|(channel\/[^\?&#]+)/); + var m = id.match(/([^?&#]+)|(channel\/[^?&#]+)/); if (m) { id = m[1]; } else { diff --git a/src/io/cluster/nullclusterclient.js b/src/io/cluster/nullclusterclient.js index 89284355..5accc375 100644 --- a/src/io/cluster/nullclusterclient.js +++ b/src/io/cluster/nullclusterclient.js @@ -5,7 +5,7 @@ export default class NullClusterClient { this.ioConfig = ioConfig; } - getSocketConfig(channel) { + getSocketConfig(_channel) { const servers = this.ioConfig.getSocketEndpoints(); return Promise.resolve({ servers: servers diff --git a/src/io/ioserver.js b/src/io/ioserver.js index 697627db..f72a6ac6 100644 --- a/src/io/ioserver.js +++ b/src/io/ioserver.js @@ -201,7 +201,7 @@ class IOServer { if (auth) { promises.push(verifySession(auth).then(user => { socket.context.user = Object.assign({}, user); - }).catch(error => { + }).catch(_error => { authFailureCount.inc(1); LOGGER.warn('Unable to verify session for %s - ignoring auth', socket.context.ipAddress); @@ -210,7 +210,7 @@ class IOServer { promises.push(getAliases(socket.context.ipAddress).then(aliases => { socket.context.aliases = aliases; - }).catch(error => { + }).catch(_error => { LOGGER.warn('Unable to load aliases for %s', socket.context.ipAddress); })); diff --git a/src/logger.js b/src/logger.js index fbf12e83..2c68f4f9 100644 --- a/src/logger.js +++ b/src/logger.js @@ -16,7 +16,7 @@ var Logger = function(filename) { flags: "a", encoding: "utf-8" }); -} +}; Logger.prototype.log = function () { var msg = ""; @@ -35,7 +35,7 @@ Logger.prototype.log = function () { errlog.log("Message was: " + msg); errlog.log(e); } -} +}; Logger.prototype.close = function () { try { @@ -43,15 +43,16 @@ Logger.prototype.close = function () { } catch(e) { errlog.log("Log close failed: " + this.filename); } -} +}; function makeConsoleLogger(filename) { + /* eslint no-console: off */ var log = new Logger(filename); log._log = log.log; log.log = function () { console.log.apply(console, arguments); this._log.apply(this, arguments); - } + }; return log; } @@ -79,7 +80,8 @@ class LegacyLogger extends JsliLogger { } } -const level: LogLevel = !!process.env.DEBUG ? LogLevel.DEBUG : LogLevel.INFO; +// TODO: allow reconfiguration of log level at runtime +const level: LogLevel = process.env.DEBUG ? LogLevel.DEBUG : LogLevel.INFO; jsli.setLogBackend((loggerName) => { return new LegacyLogger(loggerName, level); diff --git a/src/main.js b/src/main.js index ec68a5d0..b1b7522e 100644 --- a/src/main.js +++ b/src/main.js @@ -50,22 +50,22 @@ function handleLine(line) { const ip = args.shift(); const comment = args.join(' '); // TODO: this is broken by the knex refactoring - require('./database').globalBanIP(ip, comment, function (err, res) { + require('./database').globalBanIP(ip, comment, function (err, _res) { if (!err) { eventlog.log('[acp] ' + 'SYSTEM' + ' global banned ' + ip); } - }) + }); } } else if (line.indexOf('/unglobalban') === 0) { var args = line.split(/\s+/); args.shift(); if (args.length >= 1 && validIP(args[0]) !== 0) { var ip = args.shift(); // TODO: this is broken by the knex refactoring - require('./database').globalUnbanIP(ip, function (err, res) { + require('./database').globalUnbanIP(ip, function (err, _res) { if (!err) { eventlog.log('[acp] ' + 'SYSTEM' + ' un-global banned ' + ip); } - }) + }); } } else if (line.indexOf('/save') === 0) { sv.forceSave(); @@ -160,6 +160,6 @@ process.on('SIGUSR2', () => { }); require('bluebird'); -process.on('unhandledRejection', function (reason, promise) { +process.on('unhandledRejection', function (reason, _promise) { LOGGER.error('Unhandled rejection: %s', reason.stack); }); diff --git a/src/partition/partitionchannelindex.js b/src/partition/partitionchannelindex.js index 9d739118..deafe4a3 100644 --- a/src/partition/partitionchannelindex.js +++ b/src/partition/partitionchannelindex.js @@ -9,7 +9,7 @@ var SERVER = null; const CHANNEL_INDEX = 'publicChannelList'; const CACHE_REFRESH_INTERVAL = 30 * 1000; const CACHE_EXPIRE_DELAY = 40 * 1000; -const READ_CHANNEL_LIST = path.join(__dirname, 'read_channel_list.lua') +const READ_CHANNEL_LIST = path.join(__dirname, 'read_channel_list.lua'); class PartitionChannelIndex { constructor(redisClient) { diff --git a/src/partition/partitioncli.js b/src/partition/partitioncli.js index 8a97e18b..8bd11248 100644 --- a/src/partition/partitioncli.js +++ b/src/partition/partitioncli.js @@ -2,6 +2,8 @@ import { PartitionModule } from './partitionmodule'; import { PartitionMap } from './partitionmap'; import fs from 'fs'; +/* eslint no-console: off */ + const partitionModule = new PartitionModule(); partitionModule.cliMode = true; diff --git a/src/partition/partitionmodule.js b/src/partition/partitionmodule.js index 748393eb..75e29fa1 100644 --- a/src/partition/partitionmodule.js +++ b/src/partition/partitionmodule.js @@ -3,7 +3,6 @@ import { PartitionConfig } from './partitionconfig'; import { PartitionDecider } from './partitiondecider'; import { PartitionClusterClient } from '../io/cluster/partitionclusterclient'; import RedisClientProvider from '../redis/redisclientprovider'; -import LegacyConfig from '../config'; import path from 'path'; import { AnnouncementRefresher } from './announcementrefresher'; import { RedisPartitionMapReloader } from './redispartitionmapreloader'; diff --git a/src/poll.js b/src/poll.js index 411b92c1..43dafc82 100644 --- a/src/poll.js +++ b/src/poll.js @@ -1,4 +1,4 @@ -const link = /(\w+:\/\/(?:[^:\/\[\]\s]+|\[[0-9a-f:]+\])(?::\d+)?(?:\/[^\/\s]*)*)/ig; +const link = /(\w+:\/\/(?:[^:/[\]\s]+|\[[0-9a-f:]+\])(?::\d+)?(?:\/[^/\s]*)*)/ig; var XSS = require("./xss"); var Poll = function(initiator, title, options, obscured) { @@ -6,33 +6,33 @@ var Poll = function(initiator, title, options, obscured) { title = XSS.sanitizeText(title); this.title = title.replace(link, "$1"); this.options = options; - for (var i = 0; i < this.options.length; i++) { + for (let i = 0; i < this.options.length; i++) { this.options[i] = XSS.sanitizeText(this.options[i]); this.options[i] = this.options[i].replace(link, "$1"); } this.obscured = obscured || false; this.counts = new Array(options.length); - for(var i = 0; i < this.counts.length; i++) { + for(let i = 0; i < this.counts.length; i++) { this.counts[i] = 0; } this.votes = {}; this.timestamp = Date.now(); -} +}; Poll.prototype.vote = function(ip, option) { if(!(ip in this.votes) || this.votes[ip] == null) { this.votes[ip] = option; this.counts[option]++; } -} +}; Poll.prototype.unvote = function(ip) { if(ip in this.votes && this.votes[ip] != null) { this.counts[this.votes[ip]]--; this.votes[ip] = null; } -} +}; Poll.prototype.packUpdate = function (showhidden) { var counts = Array.prototype.slice.call(this.counts); @@ -51,6 +51,6 @@ Poll.prototype.packUpdate = function (showhidden) { timestamp: this.timestamp }; return packed; -} +}; exports.Poll = Poll; diff --git a/src/redis/lualoader.js b/src/redis/lualoader.js index dc1d44ed..23899bcf 100644 --- a/src/redis/lualoader.js +++ b/src/redis/lualoader.js @@ -24,7 +24,7 @@ function loadAndExecuteScript(redisClient, filename, args) { function runEvalSha(redisClient, filename, args) { const evalInput = args.slice(); - evalInput.unshift(EVALSHA_CACHE[filename]) + evalInput.unshift(EVALSHA_CACHE[filename]); return redisClient.evalshaAsync.apply(redisClient, evalInput); } diff --git a/src/redis/redisclientprovider.js b/src/redis/redisclientprovider.js index 7007c9dd..deead932 100644 --- a/src/redis/redisclientprovider.js +++ b/src/redis/redisclientprovider.js @@ -42,8 +42,8 @@ class RedisClientProvider { * @param {Error} err error from the client * @private */ - _defaultErrorHandler(err) { + _defaultErrorHandler(_err) { } } -export default RedisClientProvider +export default RedisClientProvider; diff --git a/src/server.js b/src/server.js index 99728346..1ed26111 100644 --- a/src/server.js +++ b/src/server.js @@ -35,7 +35,6 @@ module.exports = { var path = require("path"); var fs = require("fs"); -var http = require("http"); var https = require("https"); var express = require("express"); var Channel = require("./channel/channel"); @@ -46,11 +45,9 @@ import LocalChannelIndex from './web/localchannelindex'; import { PartitionChannelIndex } from './partition/partitionchannelindex'; import IOConfiguration from './configuration/ioconfig'; import WebConfiguration from './configuration/webconfig'; -import NullClusterClient from './io/cluster/nullclusterclient'; import session from './session'; import { LegacyModule } from './legacymodule'; import { PartitionModule } from './partition/partitionmodule'; -import * as Switches from './switches'; import { Gauge } from 'prom-client'; import { AccountDB } from './db/account'; import { ChannelDB } from './db/channel'; @@ -108,7 +105,7 @@ var Server = function () { } else { emailTransport = { sendMail() { - throw new Error('Email is not enabled on this server') + throw new Error('Email is not enabled on this server'); } }; } @@ -177,6 +174,7 @@ var Server = function () { try { socket.destroy(); } catch (e) { + // Ignore } }); } else if (bind.http) { @@ -185,6 +183,7 @@ var Server = function () { try { socket.destroy(); } catch (e) { + // Ignore } }); } @@ -341,12 +340,11 @@ Server.prototype.unloadChannel = function (chan, options) { LOGGER.info("Unloaded channel " + chan.name); chan.broadcastUsercount.cancel(); // Empty all outward references from the channel - var keys = Object.keys(chan); - for (var i in keys) { - if (keys[i] !== "refCounter") { - delete chan[keys[i]]; + Object.keys(chan).forEach(key => { + if (key !== "refCounter") { + delete chan[key]; } - } + }); chan.dead = true; promActiveChannels.dec(); } @@ -361,7 +359,6 @@ Server.prototype.packChannelList = function (publicOnly, isAdmin) { return c.modules.options && c.modules.options.get("show_public"); }); - var self = this; return channels.map(function (c) { return c.packInfo(isAdmin); }); @@ -442,6 +439,7 @@ Server.prototype.handlePartitionMapChange = function () { try { u.socket.disconnect(); } catch (error) { + // Ignore } }); this.unloadChannel(channel, { skipSave: true }); diff --git a/src/servsock.js b/src/servsock.js index b368112d..4597c96e 100644 --- a/src/servsock.js +++ b/src/servsock.js @@ -1,6 +1,8 @@ var fs = require('fs'); var net = require('net'); +/* eslint no-console: off */ + export default class ServiceSocket { constructor() { @@ -11,7 +13,7 @@ export default class ServiceSocket { this.handler = handler; this.socket = socket; - fs.stat(this.socket, (err, stats) => { + fs.stat(this.socket, (err, _stats) => { if (err) { return this.openServiceSocket(); } diff --git a/src/session.js b/src/session.js index b6dd2328..8cc1cd2c 100644 --- a/src/session.js +++ b/src/session.js @@ -1,5 +1,4 @@ var dbAccounts = require("./database/accounts"); -var util = require("./utilities"); var crypto = require("crypto"); function sha256(input) { @@ -30,7 +29,7 @@ exports.verifySession = function (input, cb) { return cb(new Error("Invalid auth string")); } - const [name, expiration, salt, hash, global_rank] = parts; + const [name, expiration, salt, hash, _global_rank] = parts; if (Date.now() > parseInt(expiration, 10)) { return cb(new Error("Session expired")); diff --git a/src/setuid.js b/src/setuid.js index 8941adba..516c88bf 100644 --- a/src/setuid.js +++ b/src/setuid.js @@ -3,6 +3,8 @@ var fs = require("fs"); var path = require("path"); var execSync = require("child_process").execSync; +const LOGGER = require('@calzoneman/jsli')('setuid'); + var needPermissionsFixed = [ path.join(__dirname, "..", "chanlogs"), path.join(__dirname, "..", "chandump"), @@ -31,15 +33,21 @@ if (Config.get("setuid.enabled")) { setTimeout(function() { try { fixPermissions(Config.get("setuid.user"), Config.get("setuid.group")); - console.log("Old User ID: " + process.getuid() + ", Old Group ID: " + - process.getgid()); + LOGGER.info( + 'Old User ID: %s, Old Group ID: %s', + process.getuid(), + process.getgid() + ); process.setgid(Config.get("setuid.group")); process.setuid(Config.get("setuid.user")); - console.log("New User ID: " + process.getuid() + ", New Group ID: " - + process.getgid()); + LOGGER.info( + 'New User ID: %s, New Group ID: %s', + process.getuid(), + process.getgid() + ); } catch (err) { - console.log("Error setting uid: " + err.stack); + LOGGER.error('Error setting uid: %s', err.stack); process.exit(1); } }, (Config.get("setuid.timeout"))); -}; +} diff --git a/src/tor.js b/src/tor.js index 8909d5a0..bd641945 100644 --- a/src/tor.js +++ b/src/tor.js @@ -61,7 +61,7 @@ function loadTorListFromWebsite() { }); }).on('error', error => { reject(error); - }) + }); }); } @@ -83,4 +83,4 @@ loadTorList().then(exits => { export function isTorExit(ip) { return TOR_EXIT_IPS.has(ip); -}; +} diff --git a/src/ullist.js b/src/ullist.js index 535c3982..405aaafd 100644 --- a/src/ullist.js +++ b/src/ullist.js @@ -17,30 +17,28 @@ ULList.prototype.prepend = function(item) { if(this.first !== null) { item.next = this.first; this.first.prev = item; - } - else { + } else { this.last = item; } this.first = item; this.first.prev = null; this.length++; return true; -} +}; /* Add an item to the end of the list */ ULList.prototype.append = function(item) { if(this.last !== null) { item.prev = this.last; this.last.next = item; - } - else { + } else { this.first = item; } this.last = item; this.last.next = null; this.length++; return true; -} +}; /* Insert an item after one which has a specified UID */ ULList.prototype.insertAfter = function(item, uid) { @@ -63,7 +61,7 @@ ULList.prototype.insertAfter = function(item, uid) { this.length++; return true; -} +}; /* Insert an item before one that has a specified UID */ ULList.prototype.insertBefore = function(item, uid) { @@ -86,7 +84,7 @@ ULList.prototype.insertBefore = function(item, uid) { this.length++; return true; -} +}; /* Remove an item from the list */ ULList.prototype.remove = function(uid) { @@ -108,7 +106,7 @@ ULList.prototype.remove = function(uid) { this.length--; return true; -} +}; /* Find an element in the list, return false if specified UID not found */ ULList.prototype.find = function(uid) { @@ -126,14 +124,14 @@ ULList.prototype.find = function(uid) { if(item && item.uid == uid) return item; return false; -} +}; /* Clear all elements from the list */ ULList.prototype.clear = function() { this.first = null; this.last = null; this.length = 0; -} +}; /* Dump the contents of the list into an array */ ULList.prototype.toArray = function(pack) { @@ -148,7 +146,7 @@ ULList.prototype.toArray = function(pack) { item = item.next; } return arr; -} +}; /* iterate across the playlist */ ULList.prototype.forEach = function (fn) { @@ -178,6 +176,6 @@ ULList.prototype.findAll = function(fn) { } }); return result; -} +}; module.exports = ULList; diff --git a/src/user.js b/src/user.js index 842ad522..f7fcca79 100644 --- a/src/user.js +++ b/src/user.js @@ -156,14 +156,14 @@ User.prototype.handleLogin = function handleLogin(data) { }; User.prototype.die = function () { - for (var key in this.socket._events) { + for (const key in this.socket._events) { delete this.socket._events[key]; } delete this.socket.typecheckedOn; delete this.socket.typecheckedOnce; - for (var key in this.__evHandlers) { + for (const key in this.__evHandlers) { delete this.__evHandlers[key]; } diff --git a/src/util/call-once.js b/src/util/call-once.js index 2753a46e..b288e0db 100644 --- a/src/util/call-once.js +++ b/src/util/call-once.js @@ -3,5 +3,5 @@ export function callOnce(fn) { return (...args) => { called || fn(...args), called = true; - } + }; } diff --git a/src/util/murmur.js b/src/util/murmur.js index 60416891..3f311a49 100644 --- a/src/util/murmur.js +++ b/src/util/murmur.js @@ -2,6 +2,8 @@ const SEED = 0x1234; const M = 0xc6a4a793; const R = 16; +/* eslint no-fallthrough: off */ + export function murmurHash1(str) { const buffer = new Buffer(str, 'utf8'); var length = buffer.length; diff --git a/src/utilities.js b/src/utilities.js index 3fc151c6..59f0e348 100644 --- a/src/utilities.js +++ b/src/utilities.js @@ -1,17 +1,9 @@ (function () { - var root, crypto, net = false; - - if (typeof window === "undefined") { - root = module.exports; - } else { - root = window.utils = {}; - } - - if (typeof require === "function") { - crypto = require("crypto"); - net = require("net"); - } + const root = module.exports; + const net = require("net"); + const crypto = require("crypto"); + // TODO: now that the Set type is native, find usages and remove this var Set = function (items) { this._items = {}; var self = this; @@ -157,6 +149,8 @@ root.parseTime = function (time) { var parts = time.split(":").reverse(); var seconds = 0; + // TODO: consider refactoring to remove this suppression + /* eslint no-fallthrough: off */ switch (parts.length) { case 3: seconds += parseInt(parts[2]) * 3600; @@ -278,12 +272,12 @@ var shasum = crypto.createHash("sha1"); shasum.update(data); return shasum.digest("hex"); - } + }, root.cloakIP = function (ip) { if (ip.match(/\d+\.\d+(\.\d+)?(\.\d+)?/)) { return cloakIPv4(ip); - } else if (ip.match(/([0-9a-f]{1,4}\:){1,7}[0-9a-f]{1,4}/)) { + } else if (ip.match(/([0-9a-f]{1,4}:){1,7}[0-9a-f]{1,4}/)) { return cloakIPv6(ip); } else { return ip; @@ -323,5 +317,5 @@ while (parts.length < 4) parts.push("*"); return parts.join(":"); } - } + }; })(); diff --git a/src/web/account.js b/src/web/account.js index 510929b0..a6a821e9 100644 --- a/src/web/account.js +++ b/src/web/account.js @@ -10,7 +10,6 @@ var Logger = require("../logger"); var db = require("../database"); var $util = require("../utilities"); var Config = require("../config"); -var Server = require("../server"); var session = require("../session"); var csrf = require("./csrf"); const url = require("url"); @@ -110,7 +109,7 @@ async function handleChangePassword(req, res) { newpassword = newpassword.substring(0, 100); - db.users.verifyLogin(name, oldpassword, function (err, user) { + db.users.verifyLogin(name, oldpassword, function (err, _user) { if (err) { sendPug(res, "account-edit", { errorMessage: err @@ -118,7 +117,7 @@ async function handleChangePassword(req, res) { return; } - db.users.setPassword(name, newpassword, function (err, dbres) { + db.users.setPassword(name, newpassword, function (err, _dbres) { if (err) { sendPug(res, "account-edit", { errorMessage: err @@ -177,7 +176,7 @@ function handleChangeEmail(req, res) { return; } - db.users.verifyLogin(name, password, function (err, user) { + db.users.verifyLogin(name, password, function (err, _user) { if (err) { sendPug(res, "account-edit", { errorMessage: err @@ -185,7 +184,7 @@ function handleChangeEmail(req, res) { return; } - db.users.setEmail(name, email, function (err, dbres) { + db.users.setEmail(name, email, function (err, _dbres) { if (err) { sendPug(res, "account-edit", { errorMessage: err @@ -292,7 +291,7 @@ async function handleNewChannel(req, res) { return; } - db.channels.register(name, user.name, function (err, channel) { + db.channels.register(name, user.name, function (err, _channel) { if (!err) { Logger.eventlog.log("[channel] " + user.name + "@" + req.realIP + @@ -565,7 +564,7 @@ function handlePasswordReset(req, res) { email: email, hash: hash, expire: expire - }, function (err, dbres) { + }, function (err, _dbres) { if (err) { sendPug(res, "account-passwordreset", { reset: false, @@ -594,7 +593,7 @@ function handlePasswordReset(req, res) { username: name, address: email, url: `${baseUrl}/account/passwordrecover/${hash}` - }).then(result => { + }).then(_result => { sendPug(res, "account-passwordreset", { reset: true, resetEmail: email, diff --git a/src/web/acp.js b/src/web/acp.js index 926c12eb..ff5b896f 100644 --- a/src/web/acp.js +++ b/src/web/acp.js @@ -3,8 +3,6 @@ var fs = require("fs"); var webserver = require("./webserver"); var sendPug = require("./pug").sendPug; var Logger = require("../logger"); -var db = require("../database"); -var Config = require("../config"); let ioConfig; @@ -29,7 +27,7 @@ function checkAdmin(cb) { /** * Handles a request for the ACP */ -function handleAcp(req, res, user) { +function handleAcp(req, res, _user) { const ioServers = ioConfig.getSocketEndpoints(); const chosenServer = ioServers[0]; diff --git a/src/web/auth.js b/src/web/auth.js index a4448898..90f9bbea 100644 --- a/src/web/auth.js +++ b/src/web/auth.js @@ -4,8 +4,6 @@ * @author Calvin Montgomery */ -var pug = require("pug"); -var path = require("path"); var webserver = require("./webserver"); var sendPug = require("./pug").sendPug; var Logger = require("../logger"); diff --git a/src/web/localchannelindex.js b/src/web/localchannelindex.js index 6dc73c32..c8ed5eb4 100644 --- a/src/web/localchannelindex.js +++ b/src/web/localchannelindex.js @@ -1,5 +1,4 @@ import Promise from 'bluebird'; -import Server from '../server'; var SERVER = null; diff --git a/src/web/middleware/ipsessioncookie.js b/src/web/middleware/ipsessioncookie.js index 4ae23638..be0041b0 100644 --- a/src/web/middleware/ipsessioncookie.js +++ b/src/web/middleware/ipsessioncookie.js @@ -1,7 +1,3 @@ -import path from 'path'; -import fs from 'fs'; -import crypto from 'crypto'; - const NO_EXPIRATION = new Date('Fri, 31 Dec 9999 23:59:59 GMT'); export function createIPSessionCookie(ip, date) { diff --git a/src/web/routes/account/data.js b/src/web/routes/account/data.js index 451f63ed..79f139ed 100644 --- a/src/web/routes/account/data.js +++ b/src/web/routes/account/data.js @@ -1,6 +1,6 @@ +// TODO: either finish this refactoring or just delete it import { GET, POST, PATCH, DELETE } from '@calzoneman/express-babel-decorators'; import { CSRFError, InvalidRequestError } from '../../../errors'; -import Promise from 'bluebird'; const LOGGER = require('@calzoneman/jsli')('AccountDataRoute'); diff --git a/src/web/routes/google_drive_userscript.js b/src/web/routes/google_drive_userscript.js index 72515bb9..f06cbca7 100644 --- a/src/web/routes/google_drive_userscript.js +++ b/src/web/routes/google_drive_userscript.js @@ -2,6 +2,6 @@ import { sendPug } from '../pug'; export default function initialize(app) { app.get('/google_drive_userscript', (req, res) => { - return sendPug(res, 'google_drive_userscript') + return sendPug(res, 'google_drive_userscript'); }); } diff --git a/src/web/webserver.js b/src/web/webserver.js index a25b4498..767c53ae 100644 --- a/src/web/webserver.js +++ b/src/web/webserver.js @@ -1,6 +1,5 @@ import fs from 'fs'; import path from 'path'; -import net from 'net'; import { sendPug } from './pug'; import Config from '../config'; import bodyParser from 'body-parser'; diff --git a/src/xss.js b/src/xss.js index b88c6764..7972b009 100644 --- a/src/xss.js +++ b/src/xss.js @@ -50,7 +50,7 @@ var ATTRIBUTE_MAP = { table: ["cellpadding", "cellspacing"], th: ["colspan", "rowspan"], td: ["colspan", "rowspan"] -} +}; for (var key in ATTRIBUTE_MAP) { ALLOWED_ATTRIBUTES.forEach(function (attr) {