Add eslint (#741)

This commit is contained in:
Calvin Montgomery 2018-04-07 15:30:30 -07:00 committed by GitHub
parent 953428cad5
commit 62417f7fb8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
72 changed files with 305 additions and 323 deletions

33
.eslintrc.yml Normal file
View File

@ -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

View File

@ -47,6 +47,8 @@
"build-player": "./bin/build-player.js", "build-player": "./bin/build-player.js",
"build-server": "babel -D --source-maps --loose es6.destructuring,es6.forOf --out-dir lib/ src/", "build-server": "babel -D --source-maps --loose es6.destructuring,es6.forOf --out-dir lib/ src/",
"flow": "flow", "flow": "flow",
"lint": "eslint src",
"pretest": "npm run lint",
"postinstall": "./postinstall.sh", "postinstall": "./postinstall.sh",
"server-dev": "babel -D --watch --source-maps --loose es6.destructuring,es6.forOf --out-dir lib/ src/", "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", "generate-userscript": "$npm_node_execpath gdrive-userscript/generate-userscript $@ > www/js/cytube-google-drive.user.js",
@ -56,12 +58,14 @@
"devDependencies": { "devDependencies": {
"babel-cli": "^6.24.1", "babel-cli": "^6.24.1",
"babel-core": "^6.25.0", "babel-core": "^6.25.0",
"babel-eslint": "^8.2.2",
"babel-plugin-add-module-exports": "^0.2.1", "babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-async-to-generator": "^6.24.1", "babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4", "babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-flow-strip-types": "^6.22.0", "babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-env": "^1.5.2", "babel-preset-env": "^1.5.2",
"coffeescript": "^1.9.2", "coffeescript": "^1.9.2",
"eslint": "^4.19.1",
"flow-bin": "^0.43.0", "flow-bin": "^0.43.0",
"mocha": "^3.2.0", "mocha": "^3.2.0",
"sinon": "^2.3.2" "sinon": "^2.3.2"

View File

@ -2,8 +2,6 @@ var Logger = require("./logger");
var Server = require("./server"); var Server = require("./server");
var db = require("./database"); var db = require("./database");
var util = require("./utilities"); var util = require("./utilities");
var Config = require("./config");
var Server = require("./server");
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
function eventUsername(user) { function eventUsername(user) {

View File

@ -9,7 +9,7 @@ AsyncQueue.prototype.next = function () {
if (!this.lock()) if (!this.lock())
return; return;
var item = this._q.shift(); var item = this._q.shift();
var fn = item[0], tm = item[1]; var fn = item[0];
this._tm = Date.now() + item[1]; this._tm = Date.now() + item[1];
fn(this); fn(this);
} }

View File

@ -14,7 +14,7 @@ const LOGGER = require('@calzoneman/jsli')('bgtask');
var init = null; var init = null;
/* Alias cleanup */ /* Alias cleanup */
function initAliasCleanup(Server) { function initAliasCleanup(_Server) {
var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval")); var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval"));
var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age")); var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age"));
@ -28,7 +28,7 @@ function initAliasCleanup(Server) {
} }
/* Password reset cleanup */ /* Password reset cleanup */
function initPasswordResetCleanup(Server) { function initPasswordResetCleanup(_Server) {
var CLEAN_INTERVAL = 8*60*60*1000; var CLEAN_INTERVAL = 8*60*60*1000;
setInterval(function () { setInterval(function () {

View File

@ -4,6 +4,7 @@ import Config from '../config';
import db from '../database'; import db from '../database';
import { DatabaseStore } from './dbstore'; import { DatabaseStore } from './dbstore';
/* eslint no-console: off */
function main() { function main() {
Config.load('config.yaml'); Config.load('config.yaml');
db.init(); db.init();

View File

@ -106,10 +106,12 @@ export class DatabaseStore {
if (totalSize > SIZE_LIMIT) { if (totalSize > SIZE_LIMIT) {
throw new ChannelStateSizeError( throw new ChannelStateSizeError(
'Channel state size is too large', { 'Channel state size is too large',
{
limit: SIZE_LIMIT, limit: SIZE_LIMIT,
actual: totalSize actual: totalSize
}); }
);
} }
saveRowcount.inc(rowCount); saveRowcount.inc(rowCount);

View File

@ -21,10 +21,14 @@ export class FileStore {
return statAsync(filename).then(stats => { return statAsync(filename).then(stats => {
if (stats.size > SIZE_LIMIT) { if (stats.size > SIZE_LIMIT) {
return Promise.reject( return Promise.reject(
new ChannelStateSizeError('Channel state file is too large', { new ChannelStateSizeError(
'Channel state file is too large',
{
limit: SIZE_LIMIT, limit: SIZE_LIMIT,
actual: stats.size actual: stats.size
})); }
)
);
} else { } else {
return readFileAsync(filename); return readFileAsync(filename);
} }

View File

@ -6,7 +6,8 @@ import { DatabaseStore } from './dbstore';
import { sanitizeHTML } from '../xss'; import { sanitizeHTML } from '../xss';
import { ChannelNotFoundError } from '../errors'; import { ChannelNotFoundError } from '../errors';
const QUERY_CHANNEL_NAMES = 'SELECT name FROM channels WHERE 1'; /* eslint no-console: off */
const EXPECTED_KEYS = [ const EXPECTED_KEYS = [
'chatbuffer', 'chatbuffer',
'chatmuted', 'chatmuted',
@ -22,21 +23,6 @@ const EXPECTED_KEYS = [
'poll' '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) { function fixOldChandump(data) {
const converted = {}; const converted = {};
EXPECTED_KEYS.forEach(key => { EXPECTED_KEYS.forEach(key => {
@ -146,7 +132,7 @@ function migrate(src, dest, opts) {
return dest.save(name, data); return dest.save(name, data);
}).then(() => { }).then(() => {
console.log(`Migrated /${chanPath}/${name}`); console.log(`Migrated /${chanPath}/${name}`);
}).catch(ChannelNotFoundError, err => { }).catch(ChannelNotFoundError, _err => {
console.log(`Skipping /${chanPath}/${name} (not present in the database)`); console.log(`Skipping /${chanPath}/${name} (not present in the database)`);
}).catch(err => { }).catch(err => {
console.error(`Failed to migrate /${chanPath}/${name}: ${err.stack}`); console.error(`Failed to migrate /${chanPath}/${name}: ${err.stack}`);

View File

@ -1,18 +1,15 @@
var Account = require("../account");
var ChannelModule = require("./module"); var ChannelModule = require("./module");
var Flags = require("../flags"); var Flags = require("../flags");
function AccessControlModule(channel) { function AccessControlModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
} }
AccessControlModule.prototype = Object.create(ChannelModule.prototype); AccessControlModule.prototype = Object.create(ChannelModule.prototype);
var pending = 0;
AccessControlModule.prototype.onUserPreJoin = function (user, data, cb) { AccessControlModule.prototype.onUserPreJoin = function (user, data, cb) {
var chan = this.channel, var chan = this.channel,
opts = this.channel.modules.options; opts = this.channel.modules.options;
var self = this;
if (user.socket.disconnected) { if (user.socket.disconnected) {
return cb("User disconnected", ChannelModule.DENY); return cb("User disconnected", ChannelModule.DENY);
} }

View File

@ -1,15 +1,14 @@
var ChannelModule = require("./module"); var ChannelModule = require("./module");
var Flags = require("../flags"); var Flags = require("../flags");
function AnonymousCheck(channel) { function AnonymousCheck(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
} }
AnonymousCheck.prototype = Object.create(ChannelModule.prototype); AnonymousCheck.prototype = Object.create(ChannelModule.prototype);
AnonymousCheck.prototype.onUserPreJoin = function (user, data, cb) { AnonymousCheck.prototype.onUserPreJoin = function (user, data, cb) {
var chan = this.channel, const opts = this.channel.modules.options;
opts = this.channel.modules.options;
var anonymousBanned = opts.get("block_anonymous_users"); var anonymousBanned = opts.get("block_anonymous_users");
if (user.socket.disconnected) { if (user.socket.disconnected) {
@ -28,8 +27,7 @@ AnonymousCheck.prototype.onUserPreJoin = function (user, data, cb) {
cb(null, ChannelModule.PASSTHROUGH); cb(null, ChannelModule.PASSTHROUGH);
}); });
return; return;
} } else{
else{
cb(null, ChannelModule.PASSTHROUGH); cb(null, ChannelModule.PASSTHROUGH);
} }
}; };

View File

@ -6,7 +6,6 @@ var sio = require("socket.io");
var db = require("../database"); var db = require("../database");
import * as ChannelStore from '../channel-storage/channelstore'; import * as ChannelStore from '../channel-storage/channelstore';
import { ChannelStateSizeError } from '../errors'; import { ChannelStateSizeError } from '../errors';
import Promise from 'bluebird';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { throttle } from '../util/throttle'; import { throttle } from '../util/throttle';
import Logger from '../logger'; import Logger from '../logger';
@ -80,8 +79,11 @@ function Channel(name) {
this.name = name; this.name = name;
this.uniqueName = name.toLowerCase(); this.uniqueName = name.toLowerCase();
this.modules = {}; this.modules = {};
this.logger = new Logger.Logger(path.join(__dirname, "..", "..", "chanlogs", this.logger = new Logger.Logger(
this.uniqueName + ".log")); path.join(
__dirname, "..", "..", "chanlogs", this.uniqueName + ".log"
)
);
this.users = []; this.users = [];
this.refCounter = new ReferenceCounter(this); this.refCounter = new ReferenceCounter(this);
this.flags = 0; this.flags = 0;
@ -419,8 +421,7 @@ Channel.prototype.acceptUser = function (user) {
this.logger.log("[login] Accepted connection from Tor exit at " + this.logger.log("[login] Accepted connection from Tor exit at " +
user.displayip); user.displayip);
} } else {
else {
this.logger.log("[login] Accepted connection from " + user.displayip); this.logger.log("[login] Accepted connection from " + user.displayip);
} }
@ -461,7 +462,7 @@ Channel.prototype.acceptUser = function (user) {
self.sendUserMeta(self.users, user); self.sendUserMeta(self.users, user);
// TODO: Drop legacy setAFK frame after a few months // TODO: Drop legacy setAFK frame after a few months
self.broadcastAll("setAFK", { name: user.getName(), afk: afk }); self.broadcastAll("setAFK", { name: user.getName(), afk: afk });
}) });
user.on("effectiveRankChange", (newRank, oldRank) => { user.on("effectiveRankChange", (newRank, oldRank) => {
this.maybeResendUserlist(user, newRank, oldRank); this.maybeResendUserlist(user, newRank, oldRank);
}); });
@ -555,7 +556,7 @@ Channel.prototype.sendUserMeta = function (users, user, minrank) {
var self = this; var self = this;
var userdata = self.packUserData(user); var userdata = self.packUserData(user);
users.filter(function (u) { users.filter(function (u) {
return typeof minrank !== "number" || u.account.effectiveRank > minrank return typeof minrank !== "number" || u.account.effectiveRank > minrank;
}).forEach(function (u) { }).forEach(function (u) {
if (u.account.globalRank >= 255) { if (u.account.globalRank >= 255) {
u.socket.emit("setUserMeta", { u.socket.emit("setUserMeta", {
@ -697,7 +698,6 @@ Channel.prototype.handleReadLog = function (user) {
return; return;
} }
var shouldMaskIP = user.account.globalRank < 255;
this.readLog(function (err, data) { this.readLog(function (err, data) {
if (err) { if (err) {
user.socket.emit("readChanLog", { user.socket.emit("readChanLog", {

View File

@ -1,16 +1,14 @@
var Config = require("../config"); var Config = require("../config");
var User = require("../user");
var XSS = require("../xss"); var XSS = require("../xss");
var ChannelModule = require("./module"); var ChannelModule = require("./module");
var util = require("../utilities"); var util = require("../utilities");
var Flags = require("../flags"); var Flags = require("../flags");
var url = require("url");
var counters = require("../counters"); var counters = require("../counters");
import { transformImgTags } from '../camo'; import { transformImgTags } from '../camo';
import { Counter } from 'prom-client'; import { Counter } from 'prom-client';
const SHADOW_TAG = "[shadow]"; 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 = '\ueeee';
const LINK_PLACEHOLDER_RE = /\ueeee/g; const LINK_PLACEHOLDER_RE = /\ueeee/g;
@ -31,7 +29,7 @@ const MIN_ANTIFLOOD = {
sustained: 10 sustained: 10
}; };
function ChatModule(channel) { function ChatModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.buffer = []; this.buffer = [];
this.muted = new util.Set(); this.muted = new util.Set();
@ -66,7 +64,7 @@ ChatModule.prototype.load = function (data) {
} }
if ("chatmuted" in 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]); this.muted.add(data.chatmuted[i]);
} }
} }
@ -79,7 +77,7 @@ ChatModule.prototype.save = function (data) {
data.chatmuted = Array.prototype.slice.call(this.muted); 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); data.chat = Array.prototype.slice.call(this.buffer);
}; };
@ -231,7 +229,6 @@ ChatModule.prototype.handlePm = function (user, data) {
return; return;
} }
var reallyTo = data.to;
data.to = data.to.toLowerCase(); data.to = data.to.toLowerCase();
if (data.to === user.getLowerName()) { if (data.to === user.getLowerName()) {
@ -383,7 +380,6 @@ ChatModule.prototype.formatMessage = function (username, data) {
ChatModule.prototype.filterMessage = function (msg) { ChatModule.prototype.filterMessage = function (msg) {
var filters = this.channel.modules.filters.filters; var filters = this.channel.modules.filters.filters;
var chan = this.channel;
var convertLinks = this.channel.modules.options.get("enable_link_regex"); var convertLinks = this.channel.modules.options.get("enable_link_regex");
var links = msg.match(LINK); var links = msg.match(LINK);
var intermediate = msg.replace(LINK, LINK_PLACEHOLDER); var intermediate = msg.replace(LINK, LINK_PLACEHOLDER);
@ -450,9 +446,11 @@ ChatModule.prototype.sendMessage = function (msgobj) {
this.buffer.shift(); this.buffer.shift();
} }
this.channel.logger.log("<" + msgobj.username + (msgobj.meta.addClass ? this.channel.logger.log(
"." + msgobj.meta.addClass : "") + "<" + msgobj.username +
"> " + XSS.decodeText(msgobj.msg)); (msgobj.meta.addClass ? "." + msgobj.meta.addClass : "") +
"> " + XSS.decodeText(msgobj.msg)
);
}; };
ChatModule.prototype.registerCommand = function (cmd, cb) { 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 }); 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)) { if (!this.channel.modules.permissions.canClearChat(user)) {
return; return;
} }
@ -532,11 +530,11 @@ ChatModule.prototype.handleCmdAdminflair = function (user, msg, meta) {
this.processChatMsg(user, { msg: cargs.join(" "), meta: 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)); 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)) { if (!this.channel.modules.permissions.canMute(user)) {
return; return;
} }
@ -586,7 +584,7 @@ ChatModule.prototype.handleCmdMute = function (user, msg, meta) {
this.sendModMessage(user.getName() + " muted " + target.getName(), muteperm); 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)) { if (!this.channel.modules.permissions.canMute(user)) {
return; return;
} }
@ -637,7 +635,7 @@ ChatModule.prototype.handleCmdSMute = function (user, msg, meta) {
this.sendModMessage(user.getName() + " shadowmuted " + target.getName(), muteperm); 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)) { if (!this.channel.modules.permissions.canMute(user)) {
return; return;
} }

View File

@ -13,7 +13,7 @@ const TYPE_SETMOTD = {
motd: "string" motd: "string"
}; };
function CustomizationModule(channel) { function CustomizationModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.css = ""; this.css = "";
this.js = ""; this.js = "";

View File

@ -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"); var ChannelModule = require("./module");
function DrinkModule(channel) { function DrinkModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.drinks = 0; this.drinks = 0;
} }

View File

@ -21,9 +21,12 @@ EmoteList.prototype = {
}, },
emoteExists: function (emote){ emoteExists: function (emote){
if(this.emotes.filter((item)=>{ return item.name === emote.name }).length){ for (let i = 0; i < this.emotes.length; i++) {
if (this.emotes[i].name === emote.name) {
return true; return true;
} }
}
return false; return false;
}, },
@ -61,7 +64,6 @@ EmoteList.prototype = {
}, },
removeEmote: function (emote) { removeEmote: function (emote) {
var found = false;
for (var i = 0; i < this.emotes.length; i++) { for (var i = 0; i < this.emotes.length; i++) {
if (this.emotes[i].name === emote.name) { if (this.emotes[i].name === emote.name) {
this.emotes.splice(i, 1); this.emotes.splice(i, 1);
@ -99,7 +101,7 @@ function validateEmote(f) {
f.image = f.image.substring(0, 1000); f.image = f.image.substring(0, 1000);
f.image = XSS.sanitizeText(f.image); 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)"; s = "(^|\\s)" + s + "(?!\\S)";
f.source = s; f.source = s;
@ -114,9 +116,9 @@ function validateEmote(f) {
} }
return f; return f;
}; }
function EmoteModule(channel) { function EmoteModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.emotes = new EmoteList(); this.emotes = new EmoteList();
this.supportsDirtyCheck = true; this.supportsDirtyCheck = true;
@ -153,7 +155,6 @@ EmoteModule.prototype.onUserPostJoin = function (user) {
EmoteModule.prototype.sendEmotes = function (users) { EmoteModule.prototype.sendEmotes = function (users) {
var f = this.emotes.pack(); var f = this.emotes.pack();
var chan = this.channel;
users.forEach(function (u) { users.forEach(function (u) {
u.socket.emit("emoteList", f); u.socket.emit("emoteList", f);
}); });

View File

@ -62,7 +62,7 @@ const DEFAULT_FILTERS = [
"<span class=\"spoiler\">\\1</span>") "<span class=\"spoiler\">\\1</span>")
]; ];
function ChatFilterModule(channel) { function ChatFilterModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.filters = new FilterList(); this.filters = new FilterList();
this.supportsDirtyCheck = true; this.supportsDirtyCheck = true;

View File

@ -15,7 +15,7 @@ const TYPE_UNBAN = {
name: "string" name: "string"
}; };
function KickBanModule(channel) { function KickBanModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
if (this.channel.modules.chat) { 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) { function checkBan(cname, ip, name, cb) {
db.channels.isBanned(cname, ip, name, function (err, banned) { db.channels.isBanned(cname, ip, name, function (err, banned) {
if (err) { if (err) {
@ -65,7 +55,6 @@ KickBanModule.prototype.onUserPreJoin = function (user, data, cb) {
} }
const cname = this.channel.name; const cname = this.channel.name;
const check = (user.getName() !== '') ? checkBan : checkIPBan;
function callback(banned) { function callback(banned) {
if (banned) { if (banned) {
cb(null, ChannelModule.DENY); 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)) { if (!this.channel.modules.permissions.canKick(user)) {
return; 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)) { if (!this.channel.modules.permissions.canKick(user)) {
return; return;
} }
@ -226,7 +215,7 @@ KickBanModule.prototype.handleCmdKickAnons = function (user, msg, meta) {
}; };
/* /ban - name bans */ /* /ban - name bans */
KickBanModule.prototype.handleCmdBan = function (user, msg, meta) { KickBanModule.prototype.handleCmdBan = function (user, msg, _meta) {
var args = msg.split(" "); var args = msg.split(" ");
args.shift(); /* shift off /ban */ args.shift(); /* shift off /ban */
if (args.length === 0 || args[0].trim() === "") { 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 */ /* /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(" "); var args = msg.split(" ");
args.shift(); /* shift off /ipban */ args.shift(); /* shift off /ipban */
if (args.length === 0 || args[0].trim() === "") { if (args.length === 0 || args[0].trim() === "") {
@ -451,8 +440,10 @@ KickBanModule.prototype.handleUnban = function (user, data) {
self.channel.logger.log("[mod] " + user.getName() + " unbanned " + data.name); self.channel.logger.log("[mod] " + user.getName() + " unbanned " + data.name);
if (self.channel.modules.chat) { if (self.channel.modules.chat) {
var banperm = self.channel.modules.permissions.permissions.ban; var banperm = self.channel.modules.permissions.permissions.ban;
self.channel.modules.chat.sendModMessage(user.getName() + " unbanned " + self.channel.modules.chat.sendModMessage(
data.name, banperm); user.getName() + " unbanned " + data.name,
banperm
);
} }
self.channel.refCounter.unref("KickBanModule::handleUnban"); self.channel.refCounter.unref("KickBanModule::handleUnban");
}); });

View File

@ -15,7 +15,7 @@ const TYPE_SEARCH_MEDIA = {
query: "string" query: "string"
}; };
function LibraryModule(channel) { function LibraryModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
} }
@ -67,7 +67,7 @@ LibraryModule.prototype.handleUncache = function (user, data) {
const chan = this.channel; const chan = this.channel;
chan.refCounter.ref("LibraryModule::handleUncache"); 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) { if (chan.dead) {
return; return;
} else if (err) { } else if (err) {

View File

@ -1,7 +1,6 @@
var Vimeo = require("cytube-mediaquery/lib/provider/vimeo"); var Vimeo = require("cytube-mediaquery/lib/provider/vimeo");
var ChannelModule = require("./module"); var ChannelModule = require("./module");
var Config = require("../config"); var Config = require("../config");
var InfoGetter = require("../get-info");
const LOGGER = require('@calzoneman/jsli')('mediarefresher'); const LOGGER = require('@calzoneman/jsli')('mediarefresher');

View File

@ -8,13 +8,13 @@ ChannelModule.prototype = {
/** /**
* Called when the channel is loading its data from a JSON object. * 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. * 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 * 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 * data is the data sent by the client with the joinChannel
* packet. * packet.
*/ */
onUserPreJoin: function (user, data, cb) { onUserPreJoin: function (_user, _data, cb) {
cb(null, ChannelModule.PASSTHROUGH); cb(null, ChannelModule.PASSTHROUGH);
}, },
/** /**
* Called after a user has been accepted to the channel. * 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. * Called after a user has been disconnected from the channel.
*/ */
onUserPart: function (user) { onUserPart: function (_user) {
}, },
/** /**
* Called when a chatMsg event is received * Called when a chatMsg event is received
*/ */
onUserPreChat: function (user, data, cb) { onUserPreChat: function (_user, _data, cb) {
cb(null, ChannelModule.PASSTHROUGH); cb(null, ChannelModule.PASSTHROUGH);
}, },
/** /**
* Called before a new video begins playing * Called before a new video begins playing
*/ */
onPreMediaChange: function (data, cb) { onPreMediaChange: function (_data, cb) {
cb(null, ChannelModule.PASSTHROUGH); cb(null, ChannelModule.PASSTHROUGH);
}, },
/** /**
* Called when a new video begins playing * Called when a new video begins playing
*/ */
onMediaChange: function (data) { onMediaChange: function (_data) {
}, },
}; };

View File

@ -7,7 +7,7 @@ function realTypeOf(thing) {
return thing === null ? 'null' : typeof thing; return thing === null ? 'null' : typeof thing;
} }
function OptionsModule(channel) { function OptionsModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.opts = { this.opts = {
allow_voteskip: true, // Allow users to voteskip allow_voteskip: true, // Allow users to voteskip
@ -50,10 +50,14 @@ OptionsModule.prototype.load = function (data) {
} }
} }
this.opts.chat_antiflood_params.burst = Math.min(20, this.opts.chat_antiflood_params.burst = Math.min(
this.opts.chat_antiflood_params.burst); 20,
this.opts.chat_antiflood_params.sustained = Math.min(10, this.opts.chat_antiflood_params.burst
this.opts.chat_antiflood_params.sustained); );
this.opts.chat_antiflood_params.sustained = Math.min(
10,
this.opts.chat_antiflood_params.sustained
);
this.dirty = false; this.dirty = false;
}; };
@ -206,13 +210,13 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
target: "#cs-externalcss" target: "#cs-externalcss"
}); });
} else { } else {
var data = url.parse(link); var urldata = url.parse(link);
if (!data.protocol || data.protocol !== 'https:') { if (!urldata.protocol || urldata.protocol !== 'https:') {
user.socket.emit("validationError", { user.socket.emit("validationError", {
target: "#cs-externalcss", target: "#cs-externalcss",
message: prefix + " URL must begin with 'https://'" message: prefix + " URL must begin with 'https://'"
}); });
} else if (!data.host) { } else if (!urldata.host) {
user.socket.emit("validationError", { user.socket.emit("validationError", {
target: "#cs-externalcss", target: "#cs-externalcss",
message: prefix + "missing hostname" message: prefix + "missing hostname"
@ -221,14 +225,14 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
user.socket.emit("validationPassed", { user.socket.emit("validationPassed", {
target: "#cs-externalcss" target: "#cs-externalcss"
}); });
this.opts.externalcss = data.href; this.opts.externalcss = urldata.href;
sendUpdate = true; sendUpdate = true;
} }
} }
} }
if ("externaljs" in data && user.account.effectiveRank >= 3) { 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") { if (typeof data.externaljs !== "string") {
user.socket.emit("validationError", { user.socket.emit("validationError", {
target: "#cs-externaljs", 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) { if (!link) {
sendUpdate = (this.opts.externaljs !== ""); sendUpdate = (this.opts.externaljs !== "");
this.opts.externaljs = ""; this.opts.externaljs = "";
@ -245,13 +249,13 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
target: "#cs-externaljs" target: "#cs-externaljs"
}); });
} else { } else {
var data = url.parse(link); const urldata = url.parse(link);
if (!data.protocol || data.protocol !== 'https:') { if (!urldata.protocol || urldata.protocol !== 'https:') {
user.socket.emit("validationError", { user.socket.emit("validationError", {
target: "#cs-externaljs", target: "#cs-externaljs",
message: prefix + " URL must begin with 'https://'" message: prefix + " URL must begin with 'https://'"
}); });
} else if (!data.host) { } else if (!urldata.host) {
user.socket.emit("validationError", { user.socket.emit("validationError", {
target: "#cs-externaljs", target: "#cs-externaljs",
message: prefix + "missing hostname" message: prefix + "missing hostname"
@ -260,7 +264,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
user.socket.emit("validationPassed", { user.socket.emit("validationPassed", {
target: "#cs-externaljs" target: "#cs-externaljs"
}); });
this.opts.externaljs = data.href; this.opts.externaljs = urldata.href;
sendUpdate = true; sendUpdate = true;
} }
} }
@ -348,7 +352,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
} }
if ("new_user_chat_delay" in 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) { if (!isNaN(delay) && delay >= 0) {
this.opts.new_user_chat_delay = delay; this.opts.new_user_chat_delay = delay;
sendUpdate = true; sendUpdate = true;
@ -356,7 +360,7 @@ OptionsModule.prototype.handleSetOptions = function (user, data) {
} }
if ("new_user_chat_link_delay" in 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) { if (!isNaN(delay) && delay >= 0) {
this.opts.new_user_chat_link_delay = delay; this.opts.new_user_chat_link_delay = delay;
sendUpdate = true; sendUpdate = true;

View File

@ -46,7 +46,7 @@ const DEFAULT_PERMISSIONS = {
exceedmaxdurationperuser: 2 // Exceed maximum total playlist length per user exceedmaxdurationperuser: 2 // Exceed maximum total playlist length per user
}; };
function PermissionsModule(channel) { function PermissionsModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.permissions = {}; this.permissions = {};
this.openPlaylist = false; this.openPlaylist = false;
@ -148,7 +148,7 @@ PermissionsModule.prototype.handleSetPermissions = function (user, perms) {
return; return;
} }
for (var key in perms) { for (const key in perms) {
if (typeof perms[key] !== "number") { if (typeof perms[key] !== "number") {
perms[key] = parseFloat(perms[key]); perms[key] = parseFloat(perms[key]);
if (isNaN(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) { if (key in this.permissions) {
this.permissions[key] = perms[key]; this.permissions[key] = perms[key];
} }
@ -215,7 +215,7 @@ PermissionsModule.prototype.canMoveVideo = function (account) {
}; };
PermissionsModule.prototype.canDeleteVideo = function (account) { PermissionsModule.prototype.canDeleteVideo = function (account) {
return this.hasPermission(account, "playlistdelete") return this.hasPermission(account, "playlistdelete");
}; };
PermissionsModule.prototype.canSkipVideo = function (account) { PermissionsModule.prototype.canSkipVideo = function (account) {

View File

@ -86,7 +86,7 @@ PlaylistItem.prototype = {
} }
}; };
function PlaylistModule(channel) { function PlaylistModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.items = new ULList(); this.items = new ULList();
this.meta = { this.meta = {
@ -541,7 +541,6 @@ PlaylistModule.prototype.queueStandard = function (user, data) {
} }
function handleLookup() { function handleLookup() {
var channelName = self.channel.name;
InfoGetter.getMedia(data.id, data.type, function (err, media) { InfoGetter.getMedia(data.id, data.type, function (err, media) {
if (err) { if (err) {
error(XSS.sanitizeText(String(err))); error(XSS.sanitizeText(String(err)));
@ -795,7 +794,7 @@ PlaylistModule.prototype.handleShuffle = function (user) {
this.channel.users.forEach(function (u) { this.channel.users.forEach(function (u) {
if (perms.canSeePlaylist(u)) { if (perms.canSeePlaylist(u)) {
u.socket.emit("playlist", pl); u.socket.emit("playlist", pl);
}; }
}); });
this.startPlayback(); 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) { PlaylistModule.prototype.startPlayback = function (time) {
var self = this; var self = this;
@ -1150,7 +1139,7 @@ PlaylistModule.prototype.startPlayback = function (time) {
} }
} }
); );
} };
const UPDATE_INTERVAL = Config.get("playlist.update-interval"); const UPDATE_INTERVAL = Config.get("playlist.update-interval");
@ -1232,7 +1221,7 @@ PlaylistModule.prototype.clean = function (test) {
* -flags) * -flags)
*/ */
function generateTargetRegex(target) { function generateTargetRegex(target) {
const flagsre = /^(-[img]+\s+)/i const flagsre = /^(-[img]+\s+)/i;
var m = target.match(flagsre); var m = target.match(flagsre);
var flags = ""; var flags = "";
if (m) { if (m) {
@ -1242,7 +1231,7 @@ function generateTargetRegex(target) {
return new RegExp(target, flags); 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)) { if (!this.channel.modules.permissions.canDeleteVideo(user)) {
return; return;
} }

View File

@ -18,7 +18,7 @@ const TYPE_VOTE = {
const ROOM_VIEW_HIDDEN = ":viewHidden"; const ROOM_VIEW_HIDDEN = ":viewHidden";
const ROOM_NO_VIEW_HIDDEN = ":noViewHidden"; const ROOM_NO_VIEW_HIDDEN = ":noViewHidden";
function PollModule(channel) { function PollModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.poll = null; this.poll = null;
@ -125,7 +125,6 @@ PollModule.prototype.broadcastPoll = function (isNewPoll) {
var obscured = this.poll.packUpdate(false); var obscured = this.poll.packUpdate(false);
var unobscured = this.poll.packUpdate(true); var unobscured = this.poll.packUpdate(true);
var perms = this.channel.modules.permissions;
const event = isNewPoll ? "newPoll" : "updatePoll"; const event = isNewPoll ? "newPoll" : "updatePoll";
if (isNewPoll) { if (isNewPoll) {
@ -192,7 +191,7 @@ PollModule.prototype.handleNewPoll = function (user, data, ack) {
poll.timer = setTimeout(function () { poll.timer = setTimeout(function () {
if (self.poll === poll) { if (self.poll === poll) {
self.handleClosePoll({ self.handleClosePoll({
getName: function () { return "[poll timer]" }, getName: function () { return "[poll timer]"; },
effectiveRank: 255 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)) { if (!this.channel.modules.permissions.canControlPoll(user)) {
return; return;
} }

View File

@ -11,7 +11,7 @@ const TYPE_SET_CHANNEL_RANK = {
rank: "number" rank: "number"
}; };
function RankModule(channel) { function RankModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
if (this.channel.modules.chat) { 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(" "); var args = msg.split(" ");
args.shift(); /* shift off /rank */ args.shift(); /* shift off /rank */
var name = args.shift(); var name = args.shift();
@ -186,7 +186,6 @@ RankModule.prototype.updateDatabase = function (data, cb) {
"You can't promote or demote someone" + "You can't promote or demote someone" +
" with equal or higher rank than you." " with equal or higher rank than you."
); );
return;
} }
return dbSetChannelRank(chan.name, data.name, data.rank); return dbSetChannelRank(chan.name, data.name, data.rank);

View File

@ -2,7 +2,7 @@ var ChannelModule = require("./module");
var Flags = require("../flags"); var Flags = require("../flags");
var Poll = require("../poll").Poll; var Poll = require("../poll").Poll;
function VoteskipModule(channel) { function VoteskipModule(_channel) {
ChannelModule.apply(this, arguments); ChannelModule.apply(this, arguments);
this.poll = false; this.poll = false;
@ -128,7 +128,7 @@ VoteskipModule.prototype.reset = function reset() {
this.sendVoteskipData(this.channel.users); this.sendVoteskipData(this.channel.users);
}; };
VoteskipModule.prototype.onMediaChange = function (data) { VoteskipModule.prototype.onMediaChange = function (_data) {
this.reset(); this.reset();
}; };

View File

@ -1,4 +1,3 @@
var fs = require("fs");
var path = require("path"); var path = require("path");
var net = require("net"); var net = require("net");
var YAML = require("yamljs"); var YAML = require("yamljs");
@ -194,7 +193,7 @@ function checkLoadConfig(configClass, filename) {
} }
if (typeof error.line !== 'undefined') { 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 { } else {
LOGGER.error(`Error loading conf/${filename}: ${error.stack}`); LOGGER.error(`Error loading conf/${filename}: ${error.stack}`);
} }

View File

@ -1,4 +1,4 @@
const SPECIALCHARS = /([\\\.\?\+\*\$\^\|\(\)\[\]\{\}])/g; const SPECIALCHARS = /([\\.?+*$^|()[\]{}])/g;
class CamoConfig { class CamoConfig {
constructor(config = { camo: { enabled: false } }) { constructor(config = { camo: { enabled: false } }) {

View File

@ -23,7 +23,7 @@ class EmailConfig {
getPassword() { getPassword() {
return smtp.password; return smtp.password;
} }
} };
const reset = config['password-reset']; const reset = config['password-reset'];
this._reset = { this._reset = {

View File

@ -5,7 +5,6 @@ import { JSONFileMetricsReporter } from './metrics/jsonfilemetricsreporter';
const LOGGER = require('@calzoneman/jsli')('counters'); const LOGGER = require('@calzoneman/jsli')('counters');
var counters = {};
var server = null; var server = null;
exports.add = Metrics.incCounter; exports.add = Metrics.incCounter;

View File

@ -2,7 +2,6 @@ import { ValidationError } from './errors';
import { parse as urlParse } from 'url'; import { parse as urlParse } from 'url';
import net from 'net'; import net from 'net';
import Media from './media'; import Media from './media';
import { hash } from './util/hash';
import { get as httpGet } from 'http'; import { get as httpGet } from 'http';
import { get as httpsGet } from 'https'; import { get as httpsGet } from 'https';

View File

@ -54,7 +54,7 @@ function filterEmbed(tag) {
src: tag.attribs.src, src: tag.attribs.src,
params: {} params: {}
} }
} };
for (var key in tag.attribs) { for (var key in tag.attribs) {
if (ALLOWED_PARAMS.test(key)) { if (ALLOWED_PARAMS.test(key)) {

View File

@ -1,9 +1,5 @@
var mysql = require("mysql");
var bcrypt = require("bcrypt");
var Config = require("./config"); var Config = require("./config");
var tables = require("./database/tables"); var tables = require("./database/tables");
var net = require("net");
var util = require("./utilities");
import * as Metrics from './metrics/metrics'; import * as Metrics from './metrics/metrics';
import knex from 'knex'; import knex from 'knex';
import { GlobalBanDB } from './db/globalban'; import { GlobalBanDB } from './db/globalban';
@ -127,7 +123,7 @@ module.exports.query = function (query, sub, callback) {
} }
if (process.env.SHOW_SQL) { if (process.env.SHOW_SQL) {
console.log(query); LOGGER.debug('%s', query);
} }
const end = queryLatency.startTimer(); const end = queryLatency.startTimer();

View File

@ -199,7 +199,7 @@ module.exports = {
" VALUES " + " VALUES " +
"(?, ?, ?, ?, '', ?, ?, ?)", "(?, ?, ?, ?, '', ?, ?, ?)",
[name, hash, 1, email, ip, Date.now(), module.exports.dedupeUsername(name)], [name, hash, 1, email, ip, Date.now(), module.exports.dedupeUsername(name)],
function (err, res) { function (err, _res) {
delete registrationLock[lname]; delete registrationLock[lname];
if (err) { if (err) {
callback(err, null); callback(err, null);
@ -292,7 +292,7 @@ module.exports = {
db.query("UPDATE `users` SET password=? WHERE name=?", db.query("UPDATE `users` SET password=? WHERE name=?",
[hash, name], [hash, name],
function (err, result) { function (err, _result) {
callback(err, err ? null : true); callback(err, err ? null : true);
}); });
}); });
@ -347,7 +347,7 @@ module.exports = {
} }
db.query("UPDATE `users` SET global_rank=? WHERE name=?", [rank, name], db.query("UPDATE `users` SET global_rank=? WHERE name=?", [rank, name],
function (err, result) { function (err, _result) {
callback(err, err ? null : true); callback(err, err ? null : true);
}); });
}, },
@ -427,7 +427,7 @@ module.exports = {
} }
db.query("UPDATE `users` SET email=? WHERE name=?", [email, name], db.query("UPDATE `users` SET email=? WHERE name=?", [email, name],
function (err, result) { function (err, _result) {
callback(err, err ? null : true); callback(err, err ? null : true);
}); });
}, },
@ -509,7 +509,7 @@ module.exports = {
}); });
db.query("UPDATE `users` SET profile=? WHERE name=?", [profilejson, name], db.query("UPDATE `users` SET profile=? WHERE name=?", [profilejson, name],
function (err, result) { function (err, _result) {
callback(err, err ? null : true); callback(err, err ? null : true);
}); });
}, },

View File

@ -2,7 +2,6 @@ var db = require("../database");
var valid = require("../utilities").isValidChannelName; var valid = require("../utilities").isValidChannelName;
var fs = require("fs"); var fs = require("fs");
var path = require("path"); var path = require("path");
var tables = require("./tables");
var Flags = require("../flags"); var Flags = require("../flags");
var util = require("../utilities"); var util = require("../utilities");
import { createMySQLDuplicateKeyUpdate } from '../util/on-duplicate-key-update'; import { createMySQLDuplicateKeyUpdate } from '../util/on-duplicate-key-update';
@ -12,18 +11,6 @@ const LOGGER = require('@calzoneman/jsli')('database/channels');
var blackHole = function () { }; 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 = { module.exports = {
init: function () { init: function () {
}, },
@ -152,7 +139,7 @@ module.exports = {
db.query("INSERT INTO `channels` " + db.query("INSERT INTO `channels` " +
"(`name`, `owner`, `time`, `last_loaded`) VALUES (?, ?, ?, ?)", "(`name`, `owner`, `time`, `last_loaded`) VALUES (?, ?, ?, ?)",
[name, owner, Date.now(), new Date()], [name, owner, Date.now(), new Date()],
function (err, res) { function (err, _res) {
if (err) { if (err) {
callback(err, null); callback(err, null);
return; return;
@ -220,7 +207,7 @@ module.exports = {
} }
}); });
callback(err, !Boolean(err)); callback(err, !err);
}); });
}, },

View File

@ -1,3 +1,5 @@
const LOGGER = require('@calzoneman/jsli')('database/tables');
const TBL_USERS = "" + const TBL_USERS = "" +
"CREATE TABLE IF NOT EXISTS `users` (" + "CREATE TABLE IF NOT EXISTS `users` (" +
"`id` INT NOT NULL AUTO_INCREMENT," + "`id` INT NOT NULL AUTO_INCREMENT," +
@ -134,7 +136,11 @@ module.exports.init = function (queryfn, cb) {
aq.queue(function (lock) { aq.queue(function (lock) {
queryfn(tables[tbl], function (err) { queryfn(tables[tbl], function (err) {
if (err) { if (err) {
console.log(err); LOGGER.error(
'Failed to create table %s: %s',
tbl,
err.stack
);
hasError = true; hasError = true;
} }
lock.release(); lock.release();

View File

@ -17,7 +17,7 @@ module.exports.checkVersion = function () {
"db_version=" + DB_VERSION); "db_version=" + DB_VERSION);
db.query("INSERT INTO `meta` (`key`, `value`) VALUES ('db_version', ?)", db.query("INSERT INTO `meta` (`key`, `value`) VALUES ('db_version', ?)",
[DB_VERSION], [DB_VERSION],
function (err) { function (_err) {
}); });
} else { } else {
var v = parseInt(rows[0].value); var v = parseInt(rows[0].value);
@ -89,7 +89,7 @@ function populateUsernameDedupeColumn(cb) {
cb(); cb();
}).catch(error => { }).catch(error => {
LOGGER.error("Unable to perform database upgrade to add dedupe column: " + (error.stack ? error.stack : error)); LOGGER.error("Unable to perform database upgrade to add dedupe column: " + (error.stack ? error.stack : error));
}) });
}); });
} }

View File

@ -31,7 +31,7 @@ class AliasesDB {
return this.db.runTransaction(async tx => { return this.db.runTransaction(async tx => {
const query = tx.table('aliases'); const query = tx.table('aliases');
if (net.isIP(ip)) { if (net.isIP(ip)) {
query.where({ ip: ip }) query.where({ ip: ip });
} else { } else {
const delimiter = /^[0-9]+\./.test(ip) ? '.' : ':'; const delimiter = /^[0-9]+\./.test(ip) ? '.' : ':';
query.where('ip', 'LIKE', ip + delimiter + '%'); query.where('ip', 'LIKE', ip + delimiter + '%');

View File

@ -1,6 +1,3 @@
import util from '../utilities';
import Promise from 'bluebird';
const LOGGER = require('@calzoneman/jsli')('GlobalBanDB'); const LOGGER = require('@calzoneman/jsli')('GlobalBanDB');
class GlobalBanDB { class GlobalBanDB {

View File

@ -44,7 +44,7 @@ class PasswordResetDB {
cleanup(threshold = ONE_DAY) { cleanup(threshold = ONE_DAY) {
return this.db.runTransaction(tx => { return this.db.runTransaction(tx => {
return tx.table('password_reset') return tx.table('password_reset')
.where('expire', '<', Date.now() - ONE_DAY) .where('expire', '<', Date.now() - threshold)
.del(); .del();
}); });
} }

View File

@ -14,37 +14,37 @@ const ECODE_MESSAGES = {
`Unknown host "${e.hostname}". ` + `Unknown host "${e.hostname}". ` +
'Please check that the link is correct.' 'Please check that the link is correct.'
), ),
EPROTO: e => 'The remote server does not support HTTPS.', EPROTO: _e => 'The remote server does not support HTTPS.',
ECONNRESET: e => 'The remote server unexpectedly closed the connection.', ECONNRESET: _e => 'The remote server unexpectedly closed the connection.',
ECONNREFUSED: e => ( ECONNREFUSED: _e => (
'The remote server refused the connection. ' + 'The remote server refused the connection. ' +
'Please check that the link is correct and the server is running.' 'Please check that the link is correct and the server is running.'
), ),
ETIMEDOUT: e => ( ETIMEDOUT: _e => (
'The connection to the remote server timed out. ' + 'The connection to the remote server timed out. ' +
'Please check that the link is correct.' 'Please check that the link is correct.'
), ),
ENETUNREACH: e => ( ENETUNREACH: _e => (
"The remote server's network is unreachable from this server. " + "The remote server's network is unreachable from this server. " +
"Please contact an administrator for assistance." "Please contact an administrator for assistance."
), ),
EHOSTUNREACH: e => ( EHOSTUNREACH: _e => (
"The remote server is unreachable from this server. " + "The remote server is unreachable from this server. " +
"Please contact the video server's administrator for assistance." "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 ' + 'The remote server provided an invalid ' +
'(self-signed) SSL certificate. Raw file support requires a ' + '(self-signed) SSL certificate. Raw file support requires a ' +
'trusted certificate. See https://letsencrypt.org/ to get ' + 'trusted certificate. See https://letsencrypt.org/ to get ' +
'a free, trusted certificate.' '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. " + "The remote server's SSL certificate chain could not be validated. " +
"Please contact the administrator of the server to correct their " + "Please contact the administrator of the server to correct their " +
"SSL certificate configuration." "SSL certificate configuration."
), ),
CERT_HAS_EXPIRED: e => ( CERT_HAS_EXPIRED: _e => (
"The remote server's SSL certificate has expired. Please contact " + "The remote server's SSL certificate has expired. Please contact " +
"the administrator of the server to renew the certificate." "the administrator of the server to renew the certificate."
) )
@ -73,6 +73,7 @@ var audioOnlyContainers = {
function fflog() { } function fflog() { }
/* eslint no-func-assign: off */
function initFFLog() { function initFFLog() {
if (fflog.initialized) return; if (fflog.initialized) return;
var logger = new Logger.Logger(path.resolve(__dirname, "..", "ffmpeg.log")); 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. " + cb("An unexpected error occurred while trying to process the link. " +
"Try again, and contact support for further troubleshooting if the " + "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(); req.end();
@ -389,7 +390,7 @@ exports.ffprobe = function ffprobe(filename, cb) {
return cb(null, result); return cb(null, result);
}); });
} };
exports.query = function (filename, cb) { exports.query = function (filename, cb) {
if (Config.get("ffmpeg.log") && !fflog.initialized) { if (Config.get("ffmpeg.log") && !fflog.initialized) {

View File

@ -1,6 +1,5 @@
var http = require("http"); var http = require("http");
var https = require("https"); var https = require("https");
var cheerio = require('cheerio');
var Media = require("./media"); var Media = require("./media");
var CustomEmbedFilter = require("./customembed").filter; var CustomEmbedFilter = require("./customembed").filter;
var Config = require("./config"); var Config = require("./config");
@ -9,7 +8,6 @@ var mediaquery = require("cytube-mediaquery");
var YouTube = require("cytube-mediaquery/lib/provider/youtube"); var YouTube = require("cytube-mediaquery/lib/provider/youtube");
var Vimeo = require("cytube-mediaquery/lib/provider/vimeo"); var Vimeo = require("cytube-mediaquery/lib/provider/vimeo");
var Streamable = require("cytube-mediaquery/lib/provider/streamable"); 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 TwitchVOD = require("cytube-mediaquery/lib/provider/twitch-vod");
var TwitchClip = require("cytube-mediaquery/lib/provider/twitch-clip"); var TwitchClip = require("cytube-mediaquery/lib/provider/twitch-clip");
import { Counter } from 'prom-client'; import { Counter } from 'prom-client';
@ -209,7 +207,7 @@ var Getters = {
/* TODO: require server owners to register their own API key, put in config */ /* TODO: require server owners to register their own API key, put in config */
const SC_CLIENT = "2e0c82ab5a020f3a7509318146128abd"; const SC_CLIENT = "2e0c82ab5a020f3a7509318146128abd";
var m = id.match(/([\w-\/\.:]+)/); var m = id.match(/([\w-/.:]+)/);
if (m) { if (m) {
id = m[1]; id = m[1];
} else { } else {
@ -377,7 +375,7 @@ var Getters = {
* http://www.ustream.tv/foo so they do both. * http://www.ustream.tv/foo so they do both.
* [](/cleese) * [](/cleese)
*/ */
var m = id.match(/([^\?&#]+)|(channel\/[^\?&#]+)/); var m = id.match(/([^?&#]+)|(channel\/[^?&#]+)/);
if (m) { if (m) {
id = m[1]; id = m[1];
} else { } else {

View File

@ -5,7 +5,7 @@ export default class NullClusterClient {
this.ioConfig = ioConfig; this.ioConfig = ioConfig;
} }
getSocketConfig(channel) { getSocketConfig(_channel) {
const servers = this.ioConfig.getSocketEndpoints(); const servers = this.ioConfig.getSocketEndpoints();
return Promise.resolve({ return Promise.resolve({
servers: servers servers: servers

View File

@ -201,7 +201,7 @@ class IOServer {
if (auth) { if (auth) {
promises.push(verifySession(auth).then(user => { promises.push(verifySession(auth).then(user => {
socket.context.user = Object.assign({}, user); socket.context.user = Object.assign({}, user);
}).catch(error => { }).catch(_error => {
authFailureCount.inc(1); authFailureCount.inc(1);
LOGGER.warn('Unable to verify session for %s - ignoring auth', LOGGER.warn('Unable to verify session for %s - ignoring auth',
socket.context.ipAddress); socket.context.ipAddress);
@ -210,7 +210,7 @@ class IOServer {
promises.push(getAliases(socket.context.ipAddress).then(aliases => { promises.push(getAliases(socket.context.ipAddress).then(aliases => {
socket.context.aliases = aliases; socket.context.aliases = aliases;
}).catch(error => { }).catch(_error => {
LOGGER.warn('Unable to load aliases for %s', LOGGER.warn('Unable to load aliases for %s',
socket.context.ipAddress); socket.context.ipAddress);
})); }));

View File

@ -16,7 +16,7 @@ var Logger = function(filename) {
flags: "a", flags: "a",
encoding: "utf-8" encoding: "utf-8"
}); });
} };
Logger.prototype.log = function () { Logger.prototype.log = function () {
var msg = ""; var msg = "";
@ -35,7 +35,7 @@ Logger.prototype.log = function () {
errlog.log("Message was: " + msg); errlog.log("Message was: " + msg);
errlog.log(e); errlog.log(e);
} }
} };
Logger.prototype.close = function () { Logger.prototype.close = function () {
try { try {
@ -43,15 +43,16 @@ Logger.prototype.close = function () {
} catch(e) { } catch(e) {
errlog.log("Log close failed: " + this.filename); errlog.log("Log close failed: " + this.filename);
} }
} };
function makeConsoleLogger(filename) { function makeConsoleLogger(filename) {
/* eslint no-console: off */
var log = new Logger(filename); var log = new Logger(filename);
log._log = log.log; log._log = log.log;
log.log = function () { log.log = function () {
console.log.apply(console, arguments); console.log.apply(console, arguments);
this._log.apply(this, arguments); this._log.apply(this, arguments);
} };
return log; 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) => { jsli.setLogBackend((loggerName) => {
return new LegacyLogger(loggerName, level); return new LegacyLogger(loggerName, level);

View File

@ -50,22 +50,22 @@ function handleLine(line) {
const ip = args.shift(); const ip = args.shift();
const comment = args.join(' '); const comment = args.join(' ');
// TODO: this is broken by the knex refactoring // 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) { if (!err) {
eventlog.log('[acp] ' + 'SYSTEM' + ' global banned ' + ip); eventlog.log('[acp] ' + 'SYSTEM' + ' global banned ' + ip);
} }
}) });
} }
} else if (line.indexOf('/unglobalban') === 0) { } else if (line.indexOf('/unglobalban') === 0) {
var args = line.split(/\s+/); args.shift(); var args = line.split(/\s+/); args.shift();
if (args.length >= 1 && validIP(args[0]) !== 0) { if (args.length >= 1 && validIP(args[0]) !== 0) {
var ip = args.shift(); var ip = args.shift();
// TODO: this is broken by the knex refactoring // TODO: this is broken by the knex refactoring
require('./database').globalUnbanIP(ip, function (err, res) { require('./database').globalUnbanIP(ip, function (err, _res) {
if (!err) { if (!err) {
eventlog.log('[acp] ' + 'SYSTEM' + ' un-global banned ' + ip); eventlog.log('[acp] ' + 'SYSTEM' + ' un-global banned ' + ip);
} }
}) });
} }
} else if (line.indexOf('/save') === 0) { } else if (line.indexOf('/save') === 0) {
sv.forceSave(); sv.forceSave();
@ -160,6 +160,6 @@ process.on('SIGUSR2', () => {
}); });
require('bluebird'); require('bluebird');
process.on('unhandledRejection', function (reason, promise) { process.on('unhandledRejection', function (reason, _promise) {
LOGGER.error('Unhandled rejection: %s', reason.stack); LOGGER.error('Unhandled rejection: %s', reason.stack);
}); });

View File

@ -9,7 +9,7 @@ var SERVER = null;
const CHANNEL_INDEX = 'publicChannelList'; const CHANNEL_INDEX = 'publicChannelList';
const CACHE_REFRESH_INTERVAL = 30 * 1000; const CACHE_REFRESH_INTERVAL = 30 * 1000;
const CACHE_EXPIRE_DELAY = 40 * 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 { class PartitionChannelIndex {
constructor(redisClient) { constructor(redisClient) {

View File

@ -2,6 +2,8 @@ import { PartitionModule } from './partitionmodule';
import { PartitionMap } from './partitionmap'; import { PartitionMap } from './partitionmap';
import fs from 'fs'; import fs from 'fs';
/* eslint no-console: off */
const partitionModule = new PartitionModule(); const partitionModule = new PartitionModule();
partitionModule.cliMode = true; partitionModule.cliMode = true;

View File

@ -3,7 +3,6 @@ import { PartitionConfig } from './partitionconfig';
import { PartitionDecider } from './partitiondecider'; import { PartitionDecider } from './partitiondecider';
import { PartitionClusterClient } from '../io/cluster/partitionclusterclient'; import { PartitionClusterClient } from '../io/cluster/partitionclusterclient';
import RedisClientProvider from '../redis/redisclientprovider'; import RedisClientProvider from '../redis/redisclientprovider';
import LegacyConfig from '../config';
import path from 'path'; import path from 'path';
import { AnnouncementRefresher } from './announcementrefresher'; import { AnnouncementRefresher } from './announcementrefresher';
import { RedisPartitionMapReloader } from './redispartitionmapreloader'; import { RedisPartitionMapReloader } from './redispartitionmapreloader';

View File

@ -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 XSS = require("./xss");
var Poll = function(initiator, title, options, obscured) { var Poll = function(initiator, title, options, obscured) {
@ -6,33 +6,33 @@ var Poll = function(initiator, title, options, obscured) {
title = XSS.sanitizeText(title); title = XSS.sanitizeText(title);
this.title = title.replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>"); this.title = title.replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>");
this.options = options; 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] = XSS.sanitizeText(this.options[i]);
this.options[i] = this.options[i].replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>"); this.options[i] = this.options[i].replace(link, "<a href=\"$1\" target=\"_blank\">$1</a>");
} }
this.obscured = obscured || false; this.obscured = obscured || false;
this.counts = new Array(options.length); 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.counts[i] = 0;
} }
this.votes = {}; this.votes = {};
this.timestamp = Date.now(); this.timestamp = Date.now();
} };
Poll.prototype.vote = function(ip, option) { Poll.prototype.vote = function(ip, option) {
if(!(ip in this.votes) || this.votes[ip] == null) { if(!(ip in this.votes) || this.votes[ip] == null) {
this.votes[ip] = option; this.votes[ip] = option;
this.counts[option]++; this.counts[option]++;
} }
} };
Poll.prototype.unvote = function(ip) { Poll.prototype.unvote = function(ip) {
if(ip in this.votes && this.votes[ip] != null) { if(ip in this.votes && this.votes[ip] != null) {
this.counts[this.votes[ip]]--; this.counts[this.votes[ip]]--;
this.votes[ip] = null; this.votes[ip] = null;
} }
} };
Poll.prototype.packUpdate = function (showhidden) { Poll.prototype.packUpdate = function (showhidden) {
var counts = Array.prototype.slice.call(this.counts); var counts = Array.prototype.slice.call(this.counts);
@ -51,6 +51,6 @@ Poll.prototype.packUpdate = function (showhidden) {
timestamp: this.timestamp timestamp: this.timestamp
}; };
return packed; return packed;
} };
exports.Poll = Poll; exports.Poll = Poll;

View File

@ -24,7 +24,7 @@ function loadAndExecuteScript(redisClient, filename, args) {
function runEvalSha(redisClient, filename, args) { function runEvalSha(redisClient, filename, args) {
const evalInput = args.slice(); const evalInput = args.slice();
evalInput.unshift(EVALSHA_CACHE[filename]) evalInput.unshift(EVALSHA_CACHE[filename]);
return redisClient.evalshaAsync.apply(redisClient, evalInput); return redisClient.evalshaAsync.apply(redisClient, evalInput);
} }

View File

@ -42,8 +42,8 @@ class RedisClientProvider {
* @param {Error} err error from the client * @param {Error} err error from the client
* @private * @private
*/ */
_defaultErrorHandler(err) { _defaultErrorHandler(_err) {
} }
} }
export default RedisClientProvider export default RedisClientProvider;

View File

@ -35,7 +35,6 @@ module.exports = {
var path = require("path"); var path = require("path");
var fs = require("fs"); var fs = require("fs");
var http = require("http");
var https = require("https"); var https = require("https");
var express = require("express"); var express = require("express");
var Channel = require("./channel/channel"); var Channel = require("./channel/channel");
@ -46,11 +45,9 @@ import LocalChannelIndex from './web/localchannelindex';
import { PartitionChannelIndex } from './partition/partitionchannelindex'; import { PartitionChannelIndex } from './partition/partitionchannelindex';
import IOConfiguration from './configuration/ioconfig'; import IOConfiguration from './configuration/ioconfig';
import WebConfiguration from './configuration/webconfig'; import WebConfiguration from './configuration/webconfig';
import NullClusterClient from './io/cluster/nullclusterclient';
import session from './session'; import session from './session';
import { LegacyModule } from './legacymodule'; import { LegacyModule } from './legacymodule';
import { PartitionModule } from './partition/partitionmodule'; import { PartitionModule } from './partition/partitionmodule';
import * as Switches from './switches';
import { Gauge } from 'prom-client'; import { Gauge } from 'prom-client';
import { AccountDB } from './db/account'; import { AccountDB } from './db/account';
import { ChannelDB } from './db/channel'; import { ChannelDB } from './db/channel';
@ -108,7 +105,7 @@ var Server = function () {
} else { } else {
emailTransport = { emailTransport = {
sendMail() { 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 { try {
socket.destroy(); socket.destroy();
} catch (e) { } catch (e) {
// Ignore
} }
}); });
} else if (bind.http) { } else if (bind.http) {
@ -185,6 +183,7 @@ var Server = function () {
try { try {
socket.destroy(); socket.destroy();
} catch (e) { } catch (e) {
// Ignore
} }
}); });
} }
@ -341,12 +340,11 @@ Server.prototype.unloadChannel = function (chan, options) {
LOGGER.info("Unloaded channel " + chan.name); LOGGER.info("Unloaded channel " + chan.name);
chan.broadcastUsercount.cancel(); chan.broadcastUsercount.cancel();
// Empty all outward references from the channel // Empty all outward references from the channel
var keys = Object.keys(chan); Object.keys(chan).forEach(key => {
for (var i in keys) { if (key !== "refCounter") {
if (keys[i] !== "refCounter") { delete chan[key];
delete chan[keys[i]];
}
} }
});
chan.dead = true; chan.dead = true;
promActiveChannels.dec(); promActiveChannels.dec();
} }
@ -361,7 +359,6 @@ Server.prototype.packChannelList = function (publicOnly, isAdmin) {
return c.modules.options && c.modules.options.get("show_public"); return c.modules.options && c.modules.options.get("show_public");
}); });
var self = this;
return channels.map(function (c) { return channels.map(function (c) {
return c.packInfo(isAdmin); return c.packInfo(isAdmin);
}); });
@ -442,6 +439,7 @@ Server.prototype.handlePartitionMapChange = function () {
try { try {
u.socket.disconnect(); u.socket.disconnect();
} catch (error) { } catch (error) {
// Ignore
} }
}); });
this.unloadChannel(channel, { skipSave: true }); this.unloadChannel(channel, { skipSave: true });

View File

@ -1,6 +1,8 @@
var fs = require('fs'); var fs = require('fs');
var net = require('net'); var net = require('net');
/* eslint no-console: off */
export default class ServiceSocket { export default class ServiceSocket {
constructor() { constructor() {
@ -11,7 +13,7 @@ export default class ServiceSocket {
this.handler = handler; this.handler = handler;
this.socket = socket; this.socket = socket;
fs.stat(this.socket, (err, stats) => { fs.stat(this.socket, (err, _stats) => {
if (err) { if (err) {
return this.openServiceSocket(); return this.openServiceSocket();
} }

View File

@ -1,5 +1,4 @@
var dbAccounts = require("./database/accounts"); var dbAccounts = require("./database/accounts");
var util = require("./utilities");
var crypto = require("crypto"); var crypto = require("crypto");
function sha256(input) { function sha256(input) {
@ -30,7 +29,7 @@ exports.verifySession = function (input, cb) {
return cb(new Error("Invalid auth string")); 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)) { if (Date.now() > parseInt(expiration, 10)) {
return cb(new Error("Session expired")); return cb(new Error("Session expired"));

View File

@ -3,6 +3,8 @@ var fs = require("fs");
var path = require("path"); var path = require("path");
var execSync = require("child_process").execSync; var execSync = require("child_process").execSync;
const LOGGER = require('@calzoneman/jsli')('setuid');
var needPermissionsFixed = [ var needPermissionsFixed = [
path.join(__dirname, "..", "chanlogs"), path.join(__dirname, "..", "chanlogs"),
path.join(__dirname, "..", "chandump"), path.join(__dirname, "..", "chandump"),
@ -31,15 +33,21 @@ if (Config.get("setuid.enabled")) {
setTimeout(function() { setTimeout(function() {
try { try {
fixPermissions(Config.get("setuid.user"), Config.get("setuid.group")); fixPermissions(Config.get("setuid.user"), Config.get("setuid.group"));
console.log("Old User ID: " + process.getuid() + ", Old Group ID: " + LOGGER.info(
process.getgid()); 'Old User ID: %s, Old Group ID: %s',
process.getuid(),
process.getgid()
);
process.setgid(Config.get("setuid.group")); process.setgid(Config.get("setuid.group"));
process.setuid(Config.get("setuid.user")); process.setuid(Config.get("setuid.user"));
console.log("New User ID: " + process.getuid() + ", New Group ID: " LOGGER.info(
+ process.getgid()); 'New User ID: %s, New Group ID: %s',
process.getuid(),
process.getgid()
);
} catch (err) { } catch (err) {
console.log("Error setting uid: " + err.stack); LOGGER.error('Error setting uid: %s', err.stack);
process.exit(1); process.exit(1);
} }
}, (Config.get("setuid.timeout"))); }, (Config.get("setuid.timeout")));
}; }

View File

@ -61,7 +61,7 @@ function loadTorListFromWebsite() {
}); });
}).on('error', error => { }).on('error', error => {
reject(error); reject(error);
}) });
}); });
} }
@ -83,4 +83,4 @@ loadTorList().then(exits => {
export function isTorExit(ip) { export function isTorExit(ip) {
return TOR_EXIT_IPS.has(ip); return TOR_EXIT_IPS.has(ip);
}; }

View File

@ -17,30 +17,28 @@ ULList.prototype.prepend = function(item) {
if(this.first !== null) { if(this.first !== null) {
item.next = this.first; item.next = this.first;
this.first.prev = item; this.first.prev = item;
} } else {
else {
this.last = item; this.last = item;
} }
this.first = item; this.first = item;
this.first.prev = null; this.first.prev = null;
this.length++; this.length++;
return true; return true;
} };
/* Add an item to the end of the list */ /* Add an item to the end of the list */
ULList.prototype.append = function(item) { ULList.prototype.append = function(item) {
if(this.last !== null) { if(this.last !== null) {
item.prev = this.last; item.prev = this.last;
this.last.next = item; this.last.next = item;
} } else {
else {
this.first = item; this.first = item;
} }
this.last = item; this.last = item;
this.last.next = null; this.last.next = null;
this.length++; this.length++;
return true; return true;
} };
/* Insert an item after one which has a specified UID */ /* Insert an item after one which has a specified UID */
ULList.prototype.insertAfter = function(item, uid) { ULList.prototype.insertAfter = function(item, uid) {
@ -63,7 +61,7 @@ ULList.prototype.insertAfter = function(item, uid) {
this.length++; this.length++;
return true; return true;
} };
/* Insert an item before one that has a specified UID */ /* Insert an item before one that has a specified UID */
ULList.prototype.insertBefore = function(item, uid) { ULList.prototype.insertBefore = function(item, uid) {
@ -86,7 +84,7 @@ ULList.prototype.insertBefore = function(item, uid) {
this.length++; this.length++;
return true; return true;
} };
/* Remove an item from the list */ /* Remove an item from the list */
ULList.prototype.remove = function(uid) { ULList.prototype.remove = function(uid) {
@ -108,7 +106,7 @@ ULList.prototype.remove = function(uid) {
this.length--; this.length--;
return true; return true;
} };
/* Find an element in the list, return false if specified UID not found */ /* Find an element in the list, return false if specified UID not found */
ULList.prototype.find = function(uid) { ULList.prototype.find = function(uid) {
@ -126,14 +124,14 @@ ULList.prototype.find = function(uid) {
if(item && item.uid == uid) if(item && item.uid == uid)
return item; return item;
return false; return false;
} };
/* Clear all elements from the list */ /* Clear all elements from the list */
ULList.prototype.clear = function() { ULList.prototype.clear = function() {
this.first = null; this.first = null;
this.last = null; this.last = null;
this.length = 0; this.length = 0;
} };
/* Dump the contents of the list into an array */ /* Dump the contents of the list into an array */
ULList.prototype.toArray = function(pack) { ULList.prototype.toArray = function(pack) {
@ -148,7 +146,7 @@ ULList.prototype.toArray = function(pack) {
item = item.next; item = item.next;
} }
return arr; return arr;
} };
/* iterate across the playlist */ /* iterate across the playlist */
ULList.prototype.forEach = function (fn) { ULList.prototype.forEach = function (fn) {
@ -178,6 +176,6 @@ ULList.prototype.findAll = function(fn) {
} }
}); });
return result; return result;
} };
module.exports = ULList; module.exports = ULList;

View File

@ -156,14 +156,14 @@ User.prototype.handleLogin = function handleLogin(data) {
}; };
User.prototype.die = function () { 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._events[key];
} }
delete this.socket.typecheckedOn; delete this.socket.typecheckedOn;
delete this.socket.typecheckedOnce; delete this.socket.typecheckedOnce;
for (var key in this.__evHandlers) { for (const key in this.__evHandlers) {
delete this.__evHandlers[key]; delete this.__evHandlers[key];
} }

View File

@ -3,5 +3,5 @@ export function callOnce(fn) {
return (...args) => { return (...args) => {
called || fn(...args), called = true; called || fn(...args), called = true;
} };
} }

View File

@ -2,6 +2,8 @@ const SEED = 0x1234;
const M = 0xc6a4a793; const M = 0xc6a4a793;
const R = 16; const R = 16;
/* eslint no-fallthrough: off */
export function murmurHash1(str) { export function murmurHash1(str) {
const buffer = new Buffer(str, 'utf8'); const buffer = new Buffer(str, 'utf8');
var length = buffer.length; var length = buffer.length;

View File

@ -1,17 +1,9 @@
(function () { (function () {
var root, crypto, net = false; const root = module.exports;
const net = require("net");
if (typeof window === "undefined") { const crypto = require("crypto");
root = module.exports;
} else {
root = window.utils = {};
}
if (typeof require === "function") {
crypto = require("crypto");
net = require("net");
}
// TODO: now that the Set type is native, find usages and remove this
var Set = function (items) { var Set = function (items) {
this._items = {}; this._items = {};
var self = this; var self = this;
@ -157,6 +149,8 @@
root.parseTime = function (time) { root.parseTime = function (time) {
var parts = time.split(":").reverse(); var parts = time.split(":").reverse();
var seconds = 0; var seconds = 0;
// TODO: consider refactoring to remove this suppression
/* eslint no-fallthrough: off */
switch (parts.length) { switch (parts.length) {
case 3: case 3:
seconds += parseInt(parts[2]) * 3600; seconds += parseInt(parts[2]) * 3600;
@ -278,12 +272,12 @@
var shasum = crypto.createHash("sha1"); var shasum = crypto.createHash("sha1");
shasum.update(data); shasum.update(data);
return shasum.digest("hex"); return shasum.digest("hex");
} },
root.cloakIP = function (ip) { root.cloakIP = function (ip) {
if (ip.match(/\d+\.\d+(\.\d+)?(\.\d+)?/)) { if (ip.match(/\d+\.\d+(\.\d+)?(\.\d+)?/)) {
return cloakIPv4(ip); 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); return cloakIPv6(ip);
} else { } else {
return ip; return ip;
@ -323,5 +317,5 @@
while (parts.length < 4) parts.push("*"); while (parts.length < 4) parts.push("*");
return parts.join(":"); return parts.join(":");
} }
} };
})(); })();

View File

@ -10,7 +10,6 @@ var Logger = require("../logger");
var db = require("../database"); var db = require("../database");
var $util = require("../utilities"); var $util = require("../utilities");
var Config = require("../config"); var Config = require("../config");
var Server = require("../server");
var session = require("../session"); var session = require("../session");
var csrf = require("./csrf"); var csrf = require("./csrf");
const url = require("url"); const url = require("url");
@ -110,7 +109,7 @@ async function handleChangePassword(req, res) {
newpassword = newpassword.substring(0, 100); newpassword = newpassword.substring(0, 100);
db.users.verifyLogin(name, oldpassword, function (err, user) { db.users.verifyLogin(name, oldpassword, function (err, _user) {
if (err) { if (err) {
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
errorMessage: err errorMessage: err
@ -118,7 +117,7 @@ async function handleChangePassword(req, res) {
return; return;
} }
db.users.setPassword(name, newpassword, function (err, dbres) { db.users.setPassword(name, newpassword, function (err, _dbres) {
if (err) { if (err) {
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
errorMessage: err errorMessage: err
@ -177,7 +176,7 @@ function handleChangeEmail(req, res) {
return; return;
} }
db.users.verifyLogin(name, password, function (err, user) { db.users.verifyLogin(name, password, function (err, _user) {
if (err) { if (err) {
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
errorMessage: err errorMessage: err
@ -185,7 +184,7 @@ function handleChangeEmail(req, res) {
return; return;
} }
db.users.setEmail(name, email, function (err, dbres) { db.users.setEmail(name, email, function (err, _dbres) {
if (err) { if (err) {
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
errorMessage: err errorMessage: err
@ -292,7 +291,7 @@ async function handleNewChannel(req, res) {
return; return;
} }
db.channels.register(name, user.name, function (err, channel) { db.channels.register(name, user.name, function (err, _channel) {
if (!err) { if (!err) {
Logger.eventlog.log("[channel] " + user.name + "@" + Logger.eventlog.log("[channel] " + user.name + "@" +
req.realIP + req.realIP +
@ -565,7 +564,7 @@ function handlePasswordReset(req, res) {
email: email, email: email,
hash: hash, hash: hash,
expire: expire expire: expire
}, function (err, dbres) { }, function (err, _dbres) {
if (err) { if (err) {
sendPug(res, "account-passwordreset", { sendPug(res, "account-passwordreset", {
reset: false, reset: false,
@ -594,7 +593,7 @@ function handlePasswordReset(req, res) {
username: name, username: name,
address: email, address: email,
url: `${baseUrl}/account/passwordrecover/${hash}` url: `${baseUrl}/account/passwordrecover/${hash}`
}).then(result => { }).then(_result => {
sendPug(res, "account-passwordreset", { sendPug(res, "account-passwordreset", {
reset: true, reset: true,
resetEmail: email, resetEmail: email,

View File

@ -3,8 +3,6 @@ var fs = require("fs");
var webserver = require("./webserver"); var webserver = require("./webserver");
var sendPug = require("./pug").sendPug; var sendPug = require("./pug").sendPug;
var Logger = require("../logger"); var Logger = require("../logger");
var db = require("../database");
var Config = require("../config");
let ioConfig; let ioConfig;
@ -29,7 +27,7 @@ function checkAdmin(cb) {
/** /**
* Handles a request for the ACP * Handles a request for the ACP
*/ */
function handleAcp(req, res, user) { function handleAcp(req, res, _user) {
const ioServers = ioConfig.getSocketEndpoints(); const ioServers = ioConfig.getSocketEndpoints();
const chosenServer = ioServers[0]; const chosenServer = ioServers[0];

View File

@ -4,8 +4,6 @@
* @author Calvin Montgomery <cyzon@cyzon.us> * @author Calvin Montgomery <cyzon@cyzon.us>
*/ */
var pug = require("pug");
var path = require("path");
var webserver = require("./webserver"); var webserver = require("./webserver");
var sendPug = require("./pug").sendPug; var sendPug = require("./pug").sendPug;
var Logger = require("../logger"); var Logger = require("../logger");

View File

@ -1,5 +1,4 @@
import Promise from 'bluebird'; import Promise from 'bluebird';
import Server from '../server';
var SERVER = null; var SERVER = null;

View File

@ -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'); const NO_EXPIRATION = new Date('Fri, 31 Dec 9999 23:59:59 GMT');
export function createIPSessionCookie(ip, date) { export function createIPSessionCookie(ip, date) {

View File

@ -1,6 +1,6 @@
// TODO: either finish this refactoring or just delete it
import { GET, POST, PATCH, DELETE } from '@calzoneman/express-babel-decorators'; import { GET, POST, PATCH, DELETE } from '@calzoneman/express-babel-decorators';
import { CSRFError, InvalidRequestError } from '../../../errors'; import { CSRFError, InvalidRequestError } from '../../../errors';
import Promise from 'bluebird';
const LOGGER = require('@calzoneman/jsli')('AccountDataRoute'); const LOGGER = require('@calzoneman/jsli')('AccountDataRoute');

View File

@ -2,6 +2,6 @@ import { sendPug } from '../pug';
export default function initialize(app) { export default function initialize(app) {
app.get('/google_drive_userscript', (req, res) => { app.get('/google_drive_userscript', (req, res) => {
return sendPug(res, 'google_drive_userscript') return sendPug(res, 'google_drive_userscript');
}); });
} }

View File

@ -1,6 +1,5 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import net from 'net';
import { sendPug } from './pug'; import { sendPug } from './pug';
import Config from '../config'; import Config from '../config';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';

View File

@ -50,7 +50,7 @@ var ATTRIBUTE_MAP = {
table: ["cellpadding", "cellspacing"], table: ["cellpadding", "cellspacing"],
th: ["colspan", "rowspan"], th: ["colspan", "rowspan"],
td: ["colspan", "rowspan"] td: ["colspan", "rowspan"]
} };
for (var key in ATTRIBUTE_MAP) { for (var key in ATTRIBUTE_MAP) {
ALLOWED_ATTRIBUTES.forEach(function (attr) { ALLOWED_ATTRIBUTES.forEach(function (attr) {