mirror of
				https://github.com/NodeBB/NodeBB.git
				synced 2025-10-27 17:16:14 +01:00 
			
		
		
		
	chore: eslint prefer-arrow-callback
This commit is contained in:
		
				
					committed by
					
						 Julian Lam
						Julian Lam
					
				
			
			
				
	
			
			
			
						parent
						
							707b55b6a5
						
					
				
				
					commit
					b56d9e12b5
				
			| @@ -110,7 +110,6 @@ | |||||||
| 		// WORKING ON | 		// WORKING ON | ||||||
| 		"prefer-rest-params": "off", | 		"prefer-rest-params": "off", | ||||||
| 		"prefer-spread": "off", | 		"prefer-spread": "off", | ||||||
| 		"prefer-arrow-callback": "off", |  | ||||||
| 		"no-var": "off", | 		"no-var": "off", | ||||||
| 		"vars-on-top": "off", | 		"vars-on-top": "off", | ||||||
|  |  | ||||||
|   | |||||||
| @@ -164,7 +164,7 @@ module.exports = function (grunt) { | |||||||
| 	grunt.task.run('init'); | 	grunt.task.run('init'); | ||||||
|  |  | ||||||
| 	grunt.event.removeAllListeners('watch'); | 	grunt.event.removeAllListeners('watch'); | ||||||
| 	grunt.event.on('watch', function update(action, filepath, target) { | 	grunt.event.on('watch', (action, filepath, target) => { | ||||||
| 		var compiling; | 		var compiling; | ||||||
| 		if (target === 'styleUpdated_Client') { | 		if (target === 'styleUpdated_Client') { | ||||||
| 			compiling = 'clientCSS'; | 			compiling = 'clientCSS'; | ||||||
| @@ -183,7 +183,7 @@ module.exports = function (grunt) { | |||||||
| 			return run(); | 			return run(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		require('./src/meta/build').build([compiling], function (err) { | 		require('./src/meta/build').build([compiling], (err) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				winston.error(err.stack); | 				winston.error(err.stack); | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -72,7 +72,7 @@ web.install = async function (port) { | |||||||
| 	winston.info(`Launching web installer on port ${port}`); | 	winston.info(`Launching web installer on port ${port}`); | ||||||
|  |  | ||||||
| 	app.use(express.static('public', {})); | 	app.use(express.static('public', {})); | ||||||
| 	app.engine('tpl', function (filepath, options, callback) { | 	app.engine('tpl', (filepath, options, callback) => { | ||||||
| 		filepath = filepath.replace(/\.tpl$/, '.js'); | 		filepath = filepath.replace(/\.tpl$/, '.js'); | ||||||
|  |  | ||||||
| 		Benchpress.__express(filepath, options, callback); | 		Benchpress.__express(filepath, options, callback); | ||||||
| @@ -99,7 +99,7 @@ web.install = async function (port) { | |||||||
|  |  | ||||||
|  |  | ||||||
| function launchExpress(port) { | function launchExpress(port) { | ||||||
| 	server = app.listen(port, function () { | 	server = app.listen(port, () => { | ||||||
| 		winston.info('Web installer listening on http://%s:%s', '0.0.0.0', port); | 		winston.info('Web installer listening on http://%s:%s', '0.0.0.0', port); | ||||||
| 	}); | 	}); | ||||||
| } | } | ||||||
| @@ -118,10 +118,8 @@ function ping(req, res) { | |||||||
|  |  | ||||||
| function welcome(req, res) { | function welcome(req, res) { | ||||||
| 	var dbs = ['redis', 'mongo', 'postgres']; | 	var dbs = ['redis', 'mongo', 'postgres']; | ||||||
| 	var databases = dbs.map(function (databaseName) { | 	var databases = dbs.map((databaseName) => { | ||||||
| 		var questions = require(`../src/database/${databaseName}`).questions.filter(function (question) { | 		var questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall); | ||||||
| 			return question && !question.hideOnWebInstall; |  | ||||||
| 		}); |  | ||||||
|  |  | ||||||
| 		return { | 		return { | ||||||
| 			name: databaseName, | 			name: databaseName, | ||||||
| @@ -180,7 +178,7 @@ function install(req, res) { | |||||||
| 		env: setupEnvVars, | 		env: setupEnvVars, | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	child.on('close', function (data) { | 	child.on('close', (data) => { | ||||||
| 		installing = false; | 		installing = false; | ||||||
| 		success = data === 0; | 		success = data === 0; | ||||||
| 		error = data !== 0; | 		error = data !== 0; | ||||||
|   | |||||||
							
								
								
									
										18
									
								
								loader.js
									
									
									
									
									
								
							
							
						
						
									
										18
									
								
								loader.js
									
									
									
									
									
								
							| @@ -60,14 +60,14 @@ Loader.displayStartupMessages = function (callback) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| Loader.addWorkerEvents = function (worker) { | Loader.addWorkerEvents = function (worker) { | ||||||
| 	worker.on('exit', function (code, signal) { | 	worker.on('exit', (code, signal) => { | ||||||
| 		if (code !== 0) { | 		if (code !== 0) { | ||||||
| 			if (Loader.timesStarted < numProcs * 3) { | 			if (Loader.timesStarted < numProcs * 3) { | ||||||
| 				Loader.timesStarted += 1; | 				Loader.timesStarted += 1; | ||||||
| 				if (Loader.crashTimer) { | 				if (Loader.crashTimer) { | ||||||
| 					clearTimeout(Loader.crashTimer); | 					clearTimeout(Loader.crashTimer); | ||||||
| 				} | 				} | ||||||
| 				Loader.crashTimer = setTimeout(function () { | 				Loader.crashTimer = setTimeout(() => { | ||||||
| 					Loader.timesStarted = 0; | 					Loader.timesStarted = 0; | ||||||
| 				}, 10000); | 				}, 10000); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -84,7 +84,7 @@ Loader.addWorkerEvents = function (worker) { | |||||||
| 		} | 		} | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	worker.on('message', function (message) { | 	worker.on('message', (message) => { | ||||||
| 		if (message && typeof message === 'object' && message.action) { | 		if (message && typeof message === 'object' && message.action) { | ||||||
| 			switch (message.action) { | 			switch (message.action) { | ||||||
| 				case 'restart': | 				case 'restart': | ||||||
| @@ -92,12 +92,12 @@ Loader.addWorkerEvents = function (worker) { | |||||||
| 					Loader.restart(); | 					Loader.restart(); | ||||||
| 					break; | 					break; | ||||||
| 				case 'pubsub': | 				case 'pubsub': | ||||||
| 					workers.forEach(function (w) { | 					workers.forEach((w) => { | ||||||
| 						w.send(message); | 						w.send(message); | ||||||
| 					}); | 					}); | ||||||
| 					break; | 					break; | ||||||
| 				case 'socket.io': | 				case 'socket.io': | ||||||
| 					workers.forEach(function (w) { | 					workers.forEach((w) => { | ||||||
| 						if (w !== worker) { | 						if (w !== worker) { | ||||||
| 							w.send(message); | 							w.send(message); | ||||||
| 						} | 						} | ||||||
| @@ -172,7 +172,7 @@ Loader.restart = function () { | |||||||
| 	nconf.remove('file'); | 	nconf.remove('file'); | ||||||
| 	nconf.use('file', { file: pathToConfig }); | 	nconf.use('file', { file: pathToConfig }); | ||||||
|  |  | ||||||
| 	fs.readFile(pathToConfig, { encoding: 'utf-8' }, function (err, configFile) { | 	fs.readFile(pathToConfig, { encoding: 'utf-8' }, (err, configFile) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			console.error('Error reading config'); | 			console.error('Error reading config'); | ||||||
| 			throw err; | 			throw err; | ||||||
| @@ -201,13 +201,13 @@ Loader.stop = function () { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| function killWorkers() { | function killWorkers() { | ||||||
| 	workers.forEach(function (worker) { | 	workers.forEach((worker) => { | ||||||
| 		worker.suicide = true; | 		worker.suicide = true; | ||||||
| 		worker.kill(); | 		worker.kill(); | ||||||
| 	}); | 	}); | ||||||
| } | } | ||||||
|  |  | ||||||
| fs.open(pathToConfig, 'r', function (err) { | fs.open(pathToConfig, 'r', (err) => { | ||||||
| 	if (err) { | 	if (err) { | ||||||
| 		// No config detected, kickstart web installer | 		// No config detected, kickstart web installer | ||||||
| 		fork('app'); | 		fork('app'); | ||||||
| @@ -238,7 +238,7 @@ fs.open(pathToConfig, 'r', function (err) { | |||||||
| 		Loader.init, | 		Loader.init, | ||||||
| 		Loader.displayStartupMessages, | 		Loader.displayStartupMessages, | ||||||
| 		Loader.start, | 		Loader.start, | ||||||
| 	], function (err) { | 	], (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			console.error('[loader] Error during startup'); | 			console.error('[loader] Error during startup'); | ||||||
| 			throw err; | 			throw err; | ||||||
|   | |||||||
| @@ -10,20 +10,22 @@ const file = require('../file'); | |||||||
| const Translator = require('../translator').Translator; | const Translator = require('../translator').Translator; | ||||||
|  |  | ||||||
| function filterDirectories(directories) { | function filterDirectories(directories) { | ||||||
| 	return directories.map(function (dir) { | 	return directories.map( | ||||||
| 		// get the relative path | 		// get the relative path | ||||||
| 		// convert dir to use forward slashes | 		// convert dir to use forward slashes | ||||||
| 		return dir.replace(/^.*(admin.*?).tpl$/, '$1').split(path.sep).join('/'); | 		dir => dir.replace(/^.*(admin.*?).tpl$/, '$1').split(path.sep).join('/') | ||||||
| 	}).filter(function (dir) { | 	).filter( | ||||||
| 		// exclude .js files | 		// exclude .js files | ||||||
| 		// exclude partials | 		// exclude partials | ||||||
| 		// only include subpaths | 		// only include subpaths | ||||||
| 		// exclude category.tpl, group.tpl, category-analytics.tpl | 		// exclude category.tpl, group.tpl, category-analytics.tpl | ||||||
| 		return !dir.endsWith('.js') && | 		dir => ( | ||||||
|  | 			!dir.endsWith('.js') && | ||||||
| 			!dir.includes('/partials/') && | 			!dir.includes('/partials/') && | ||||||
| 			/\/.*\//.test(dir) && | 			/\/.*\//.test(dir) && | ||||||
| 			!/manage\/(category|group|category-analytics)$/.test(dir); | 			!/manage\/(category|group|category-analytics)$/.test(dir) | ||||||
| 	}); | 		) | ||||||
|  | 	); | ||||||
| } | } | ||||||
|  |  | ||||||
| async function getAdminNamespaces() { | async function getAdminNamespaces() { | ||||||
| @@ -50,9 +52,7 @@ function simplify(translations) { | |||||||
| } | } | ||||||
|  |  | ||||||
| function nsToTitle(namespace) { | function nsToTitle(namespace) { | ||||||
| 	return namespace.replace('admin/', '').split('/').map(function (str) { | 	return namespace.replace('admin/', '').split('/').map(str => str[0].toUpperCase() + str.slice(1)).join(' > ') | ||||||
| 		return str[0].toUpperCase() + str.slice(1); |  | ||||||
| 	}).join(' > ') |  | ||||||
| 		.replace(/[^a-zA-Z> ]/g, ' '); | 		.replace(/[^a-zA-Z> ]/g, ' '); | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -97,9 +97,7 @@ async function buildNamespace(language, namespace) { | |||||||
| 			return await fallback(namespace); | 			return await fallback(namespace); | ||||||
| 		} | 		} | ||||||
| 		// join all translations into one string separated by newlines | 		// join all translations into one string separated by newlines | ||||||
| 		let str = Object.keys(translations).map(function (key) { | 		let str = Object.keys(translations).map(key => translations[key]).join('\n'); | ||||||
| 			return translations[key]; |  | ||||||
| 		}).join('\n'); |  | ||||||
| 		str = sanitize(str); | 		str = sanitize(str); | ||||||
|  |  | ||||||
| 		let title = namespace; | 		let title = namespace; | ||||||
|   | |||||||
| @@ -23,7 +23,7 @@ function getLatestVersion(callback) { | |||||||
| 		json: true, | 		json: true, | ||||||
| 		headers: headers, | 		headers: headers, | ||||||
| 		timeout: 2000, | 		timeout: 2000, | ||||||
| 	}, function (err, res, latestRelease) { | 	}, (err, res, latestRelease) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -33,9 +33,9 @@ Analytics.init = async function () { | |||||||
| 		maxAge: 0, | 		maxAge: 0, | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	new cronJob('*/10 * * * * *', function () { | 	new cronJob('*/10 * * * * *', (() => { | ||||||
| 		Analytics.writeData(); | 		Analytics.writeData(); | ||||||
| 	}, null, true); | 	}), null, true); | ||||||
| }; | }; | ||||||
|  |  | ||||||
| Analytics.increment = function (keys, callback) { | Analytics.increment = function (keys, callback) { | ||||||
| @@ -43,7 +43,7 @@ Analytics.increment = function (keys, callback) { | |||||||
|  |  | ||||||
| 	plugins.hooks.fire('action:analytics.increment', { keys: keys }); | 	plugins.hooks.fire('action:analytics.increment', { keys: keys }); | ||||||
|  |  | ||||||
| 	keys.forEach(function (key) { | 	keys.forEach((key) => { | ||||||
| 		counters[key] = counters[key] || 0; | 		counters[key] = counters[key] || 0; | ||||||
| 		counters[key] += 1; | 		counters[key] += 1; | ||||||
| 	}); | 	}); | ||||||
| @@ -163,14 +163,14 @@ Analytics.getHourlyStatsForSet = async function (set, hour, numHours) { | |||||||
|  |  | ||||||
| 	const counts = await db.sortedSetScores(set, hoursArr); | 	const counts = await db.sortedSetScores(set, hoursArr); | ||||||
|  |  | ||||||
| 	hoursArr.forEach(function (term, index) { | 	hoursArr.forEach((term, index) => { | ||||||
| 		terms[term] = parseInt(counts[index], 10) || 0; | 		terms[term] = parseInt(counts[index], 10) || 0; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	const termsArr = []; | 	const termsArr = []; | ||||||
|  |  | ||||||
| 	hoursArr.reverse(); | 	hoursArr.reverse(); | ||||||
| 	hoursArr.forEach(function (hour) { | 	hoursArr.forEach((hour) => { | ||||||
| 		termsArr.push(terms[hour]); | 		termsArr.push(terms[hour]); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -54,7 +54,7 @@ exports.doTopicAction = async function (action, event, caller, { tids }) { | |||||||
|  |  | ||||||
| 	const uids = await user.getUidsFromSet('users:online', 0, -1); | 	const uids = await user.getUidsFromSet('users:online', 0, -1); | ||||||
|  |  | ||||||
| 	await Promise.all(tids.map(async function (tid) { | 	await Promise.all(tids.map(async (tid) => { | ||||||
| 		const title = await topics.getTopicField(tid, 'title'); | 		const title = await topics.getTopicField(tid, 'title'); | ||||||
| 		const data = await topics.tools[action](tid, caller.uid); | 		const data = await topics.tools[action](tid, caller.uid); | ||||||
| 		const notifyUids = await privileges.categories.filterUids('topics:read', data.cid, uids); | 		const notifyUids = await privileges.categories.filterUids('topics:read', data.cid, uids); | ||||||
|   | |||||||
| @@ -55,11 +55,11 @@ module.exports = function (opts) { | |||||||
| 		cache.misses = 0; | 		cache.misses = 0; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	pubsub.on(`${cache.name}:cache:reset`, function () { | 	pubsub.on(`${cache.name}:cache:reset`, () => { | ||||||
| 		localReset(); | 		localReset(); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	pubsub.on(`${cache.name}:cache:del`, function (keys) { | 	pubsub.on(`${cache.name}:cache:del`, (keys) => { | ||||||
| 		if (Array.isArray(keys)) { | 		if (Array.isArray(keys)) { | ||||||
| 			keys.forEach(key => cacheDel.apply(cache, [key])); | 			keys.forEach(key => cacheDel.apply(cache, [key])); | ||||||
| 		} | 		} | ||||||
| @@ -71,7 +71,7 @@ module.exports = function (opts) { | |||||||
| 		} | 		} | ||||||
| 		let data; | 		let data; | ||||||
| 		let isCached; | 		let isCached; | ||||||
| 		const unCachedKeys = keys.filter(function (key) { | 		const unCachedKeys = keys.filter((key) => { | ||||||
| 			data = cache.get(key); | 			data = cache.get(key); | ||||||
| 			isCached = data !== undefined; | 			isCached = data !== undefined; | ||||||
| 			if (isCached) { | 			if (isCached) { | ||||||
|   | |||||||
| @@ -104,7 +104,7 @@ module.exports = function (Categories) { | |||||||
|  |  | ||||||
| 		children = children[0]; | 		children = children[0]; | ||||||
|  |  | ||||||
| 		children.forEach(function (child) { | 		children.forEach((child) => { | ||||||
| 			child.parentCid = parentCid; | 			child.parentCid = parentCid; | ||||||
| 			child.cloneFromCid = child.cid; | 			child.cloneFromCid = child.cid; | ||||||
| 			child.cloneChildren = true; | 			child.cloneChildren = true; | ||||||
| @@ -195,7 +195,7 @@ module.exports = function (Categories) { | |||||||
|  |  | ||||||
| 		const currentMembers = await db.getSortedSetsMembers(toGroups.concat(fromGroups)); | 		const currentMembers = await db.getSortedSetsMembers(toGroups.concat(fromGroups)); | ||||||
| 		const copyGroups = _.uniq(_.flatten(currentMembers)); | 		const copyGroups = _.uniq(_.flatten(currentMembers)); | ||||||
| 		await async.each(copyGroups, async function (group) { | 		await async.each(copyGroups, async (group) => { | ||||||
| 			await copyPrivilegesByGroup(privileges, fromCid, toCid, group); | 			await copyPrivilegesByGroup(privileges, fromCid, toCid, group); | ||||||
| 		}); | 		}); | ||||||
| 	} | 	} | ||||||
|   | |||||||
| @@ -11,14 +11,14 @@ var cache = require('../cache'); | |||||||
|  |  | ||||||
| module.exports = function (Categories) { | module.exports = function (Categories) { | ||||||
| 	Categories.purge = async function (cid, uid) { | 	Categories.purge = async function (cid, uid) { | ||||||
| 		await batch.processSortedSet(`cid:${cid}:tids`, async function (tids) { | 		await batch.processSortedSet(`cid:${cid}:tids`, async (tids) => { | ||||||
| 			await async.eachLimit(tids, 10, async function (tid) { | 			await async.eachLimit(tids, 10, async (tid) => { | ||||||
| 				await topics.purgePostsAndTopic(tid, uid); | 				await topics.purgePostsAndTopic(tid, uid); | ||||||
| 			}); | 			}); | ||||||
| 		}, { alwaysStartAt: 0 }); | 		}, { alwaysStartAt: 0 }); | ||||||
|  |  | ||||||
| 		const pinnedTids = await db.getSortedSetRevRange(`cid:${cid}:tids:pinned`, 0, -1); | 		const pinnedTids = await db.getSortedSetRevRange(`cid:${cid}:tids:pinned`, 0, -1); | ||||||
| 		await async.eachLimit(pinnedTids, 10, async function (tid) { | 		await async.eachLimit(pinnedTids, 10, async (tid) => { | ||||||
| 			await topics.purgePostsAndTopic(tid, uid); | 			await topics.purgePostsAndTopic(tid, uid); | ||||||
| 		}); | 		}); | ||||||
| 		const categoryData = await Categories.getCategoryData(cid); | 		const categoryData = await Categories.getCategoryData(cid); | ||||||
| @@ -58,7 +58,7 @@ module.exports = function (Categories) { | |||||||
| 		]); | 		]); | ||||||
|  |  | ||||||
| 		const bulkAdd = []; | 		const bulkAdd = []; | ||||||
| 		const childrenKeys = children.map(function (cid) { | 		const childrenKeys = children.map((cid) => { | ||||||
| 			bulkAdd.push(['cid:0:children', cid, cid]); | 			bulkAdd.push(['cid:0:children', cid, cid]); | ||||||
| 			return `category:${cid}`; | 			return `category:${cid}`; | ||||||
| 		}); | 		}); | ||||||
|   | |||||||
| @@ -97,7 +97,7 @@ Categories.getModerators = async function (cid) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| Categories.getModeratorUids = async function (cids) { | Categories.getModeratorUids = async function (cids) { | ||||||
| 	const groupNames = cids.reduce(function (memo, cid) { | 	const groupNames = cids.reduce((memo, cid) => { | ||||||
| 		memo.push(`cid:${cid}:privileges:moderate`); | 		memo.push(`cid:${cid}:privileges:moderate`); | ||||||
| 		memo.push(`cid:${cid}:privileges:groups:moderate`); | 		memo.push(`cid:${cid}:privileges:groups:moderate`); | ||||||
| 		return memo; | 		return memo; | ||||||
| @@ -105,7 +105,7 @@ Categories.getModeratorUids = async function (cids) { | |||||||
|  |  | ||||||
| 	const memberSets = await groups.getMembersOfGroups(groupNames); | 	const memberSets = await groups.getMembersOfGroups(groupNames); | ||||||
| 	// Every other set is actually a list of user groups, not uids, so convert those to members | 	// Every other set is actually a list of user groups, not uids, so convert those to members | ||||||
| 	const sets = memberSets.reduce(function (memo, set, idx) { | 	const sets = memberSets.reduce((memo, set, idx) => { | ||||||
| 		if (idx % 2) { | 		if (idx % 2) { | ||||||
| 			memo.groupNames.push(set); | 			memo.groupNames.push(set); | ||||||
| 		} else { | 		} else { | ||||||
| @@ -137,7 +137,7 @@ Categories.getCategories = async function (cids, uid) { | |||||||
| 		Categories.getTagWhitelist(cids), | 		Categories.getTagWhitelist(cids), | ||||||
| 		Categories.hasReadCategories(cids, uid), | 		Categories.hasReadCategories(cids, uid), | ||||||
| 	]); | 	]); | ||||||
| 	categories.forEach(function (category, i) { | 	categories.forEach((category, i) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			category.tagWhitelist = tagWhitelist[i]; | 			category.tagWhitelist = tagWhitelist[i]; | ||||||
| 			category['unread-class'] = (category.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; | 			category['unread-class'] = (category.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; | ||||||
| @@ -180,7 +180,7 @@ function calculateTopicPostCount(category) { | |||||||
| 	let postCount = category.post_count; | 	let postCount = category.post_count; | ||||||
| 	let topicCount = category.topic_count; | 	let topicCount = category.topic_count; | ||||||
| 	if (Array.isArray(category.children)) { | 	if (Array.isArray(category.children)) { | ||||||
| 		category.children.forEach(function (child) { | 		category.children.forEach((child) => { | ||||||
| 			calculateTopicPostCount(child); | 			calculateTopicPostCount(child); | ||||||
| 			postCount += parseInt(child.totalPostCount, 10) || 0; | 			postCount += parseInt(child.totalPostCount, 10) || 0; | ||||||
| 			topicCount += parseInt(child.totalTopicCount, 10) || 0; | 			topicCount += parseInt(child.totalTopicCount, 10) || 0; | ||||||
| @@ -222,7 +222,7 @@ async function getChildrenTree(category, uid) { | |||||||
| 	childrenData = childrenData.filter(Boolean); | 	childrenData = childrenData.filter(Boolean); | ||||||
| 	childrenCids = childrenData.map(child => child.cid); | 	childrenCids = childrenData.map(child => child.cid); | ||||||
| 	const hasRead = await Categories.hasReadCategories(childrenCids, uid); | 	const hasRead = await Categories.hasReadCategories(childrenCids, uid); | ||||||
| 	childrenData.forEach(function (child, i) { | 	childrenData.forEach((child, i) => { | ||||||
| 		child['unread-class'] = (child.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; | 		child['unread-class'] = (child.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; | ||||||
| 	}); | 	}); | ||||||
| 	Categories.getTree([category].concat(childrenData), category.parentCid); | 	Categories.getTree([category].concat(childrenData), category.parentCid); | ||||||
| @@ -270,7 +270,7 @@ Categories.getChildrenCids = async function (rootCid) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| Categories.flattenCategories = function (allCategories, categoryData) { | Categories.flattenCategories = function (allCategories, categoryData) { | ||||||
| 	categoryData.forEach(function (category) { | 	categoryData.forEach((category) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			allCategories.push(category); | 			allCategories.push(category); | ||||||
|  |  | ||||||
| @@ -302,7 +302,7 @@ Categories.getTree = function (categories, parentCid) { | |||||||
|  |  | ||||||
| 	const tree = []; | 	const tree = []; | ||||||
|  |  | ||||||
| 	categories.forEach(function (category) { | 	categories.forEach((category) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			category.children = category.children || []; | 			category.children = category.children || []; | ||||||
| 			if (!category.cid) { | 			if (!category.cid) { | ||||||
|   | |||||||
| @@ -95,7 +95,7 @@ module.exports = function (Categories) { | |||||||
| 			tids, | 			tids, | ||||||
| 			['tid', 'mainPid', 'slug', 'title', 'teaserPid', 'cid', 'postcount'] | 			['tid', 'mainPid', 'slug', 'title', 'teaserPid', 'cid', 'postcount'] | ||||||
| 		); | 		); | ||||||
| 		topicData.forEach(function (topic) { | 		topicData.forEach((topic) => { | ||||||
| 			if (topic) { | 			if (topic) { | ||||||
| 				topic.teaserPid = topic.teaserPid || topic.mainPid; | 				topic.teaserPid = topic.teaserPid || topic.mainPid; | ||||||
| 			} | 			} | ||||||
| @@ -108,7 +108,7 @@ module.exports = function (Categories) { | |||||||
| 		]); | 		]); | ||||||
| 		const cidToRoot = _.zipObject(cids, toRoot); | 		const cidToRoot = _.zipObject(cids, toRoot); | ||||||
|  |  | ||||||
| 		teasers.forEach(function (teaser, index) { | 		teasers.forEach((teaser, index) => { | ||||||
| 			if (teaser) { | 			if (teaser) { | ||||||
| 				teaser.cid = topicData[index].cid; | 				teaser.cid = topicData[index].cid; | ||||||
| 				teaser.parentCids = cidToRoot[teaser.cid]; | 				teaser.parentCids = cidToRoot[teaser.cid]; | ||||||
| @@ -124,7 +124,7 @@ module.exports = function (Categories) { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	function assignTopicsToCategories(categories, topics) { | 	function assignTopicsToCategories(categories, topics) { | ||||||
| 		categories.forEach(function (category) { | 		categories.forEach((category) => { | ||||||
| 			if (category) { | 			if (category) { | ||||||
| 				category.posts = topics.filter(t => t.cid && (t.cid === category.cid || t.parentCids.includes(category.cid))) | 				category.posts = topics.filter(t => t.cid && (t.cid === category.cid || t.parentCids.includes(category.cid))) | ||||||
| 					.sort((a, b) => b.pid - a.pid) | 					.sort((a, b) => b.pid - a.pid) | ||||||
| @@ -135,7 +135,7 @@ module.exports = function (Categories) { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	function bubbleUpChildrenPosts(categoryData) { | 	function bubbleUpChildrenPosts(categoryData) { | ||||||
| 		categoryData.forEach(function (category) { | 		categoryData.forEach((category) => { | ||||||
| 			if (category) { | 			if (category) { | ||||||
| 				if (category.posts.length) { | 				if (category.posts.length) { | ||||||
| 					return; | 					return; | ||||||
| @@ -168,7 +168,7 @@ module.exports = function (Categories) { | |||||||
| 			topics.getTopicField(tid, 'deleted'), | 			topics.getTopicField(tid, 'deleted'), | ||||||
| 		]); | 		]); | ||||||
|  |  | ||||||
| 		await batch.processArray(pids, async function (pids) { | 		await batch.processArray(pids, async (pids) => { | ||||||
| 			const postData = await posts.getPostsFields(pids, ['pid', 'deleted', 'uid', 'timestamp', 'upvotes', 'downvotes']); | 			const postData = await posts.getPostsFields(pids, ['pid', 'deleted', 'uid', 'timestamp', 'upvotes', 'downvotes']); | ||||||
|  |  | ||||||
| 			const bulkRemove = []; | 			const bulkRemove = []; | ||||||
|   | |||||||
| @@ -41,16 +41,16 @@ module.exports = function (Categories) { | |||||||
|  |  | ||||||
| 		Categories.getTree(categoryData, 0); | 		Categories.getTree(categoryData, 0); | ||||||
| 		await Categories.getRecentTopicReplies(categoryData, uid, data.qs); | 		await Categories.getRecentTopicReplies(categoryData, uid, data.qs); | ||||||
| 		categoryData.forEach(function (category) { | 		categoryData.forEach((category) => { | ||||||
| 			if (category && Array.isArray(category.children)) { | 			if (category && Array.isArray(category.children)) { | ||||||
| 				category.children = category.children.slice(0, category.subCategoriesPerPage); | 				category.children = category.children.slice(0, category.subCategoriesPerPage); | ||||||
| 				category.children.forEach(function (child) { | 				category.children.forEach((child) => { | ||||||
| 					child.children = undefined; | 					child.children = undefined; | ||||||
| 				}); | 				}); | ||||||
| 			} | 			} | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		categoryData.sort(function (c1, c2) { | 		categoryData.sort((c1, c2) => { | ||||||
| 			if (c1.parentCid !== c2.parentCid) { | 			if (c1.parentCid !== c2.parentCid) { | ||||||
| 				return c1.parentCid - c2.parentCid; | 				return c1.parentCid - c2.parentCid; | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -150,7 +150,7 @@ module.exports = function (Categories) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		topics.forEach(function (topic) { | 		topics.forEach((topic) => { | ||||||
| 			if (topic.deleted && !topic.isOwner) { | 			if (topic.deleted && !topic.isOwner) { | ||||||
| 				topic.title = '[[topic:topic_is_deleted]]'; | 				topic.title = '[[topic:topic_is_deleted]]'; | ||||||
| 				topic.slug = topic.tid; | 				topic.slug = topic.tid; | ||||||
|   | |||||||
| @@ -37,7 +37,7 @@ module.exports = function (Categories) { | |||||||
| 			fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]); | 			fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await async.eachSeries(fields, async function (key) { | 		await async.eachSeries(fields, async (key) => { | ||||||
| 			await updateCategoryField(cid, key, category[key]); | 			await updateCategoryField(cid, key, category[key]); | ||||||
| 		}); | 		}); | ||||||
| 		plugins.hooks.fire('action:category.update', { cid: cid, modified: category }); | 		plugins.hooks.fire('action:category.update', { cid: cid, modified: category }); | ||||||
|   | |||||||
| @@ -61,9 +61,7 @@ function humanReadableArgName(arg) { | |||||||
| } | } | ||||||
|  |  | ||||||
| Command.prototype.usage = function () { | Command.prototype.usage = function () { | ||||||
| 	var args = this._args.map(function (arg) { | 	var args = this._args.map(arg => humanReadableArgName(arg)); | ||||||
| 		return humanReadableArgName(arg); |  | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	var usage = '[options]'[optionColor] + | 	var usage = '[options]'[optionColor] + | ||||||
| 		(this.commands.length ? ' [command]' : '')[subCommandColor] + | 		(this.commands.length ? ' [command]' : '')[subCommandColor] + | ||||||
| @@ -82,12 +80,8 @@ Command.prototype.commandHelp = function () { | |||||||
| 		return ''; | 		return ''; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	var commands = this.commands.filter(function (cmd) { | 	var commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => { | ||||||
| 		return !cmd._noHelp; | 		var args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); | ||||||
| 	}).map(function (cmd) { |  | ||||||
| 		var args = cmd._args.map(function (arg) { |  | ||||||
| 			return humanReadableArgName(arg); |  | ||||||
| 		}).join(' '); |  | ||||||
|  |  | ||||||
| 		return [ | 		return [ | ||||||
| 			`${cmd._name[subCommandColor] + | 			`${cmd._name[subCommandColor] + | ||||||
| @@ -98,15 +92,13 @@ Command.prototype.commandHelp = function () { | |||||||
| 		]; | 		]; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	var width = commands.reduce(function (max, command) { | 	var width = commands.reduce((max, command) => Math.max(max, command[0].length), 0); | ||||||
| 		return Math.max(max, command[0].length); |  | ||||||
| 	}, 0); |  | ||||||
|  |  | ||||||
| 	return [ | 	return [ | ||||||
| 		'', | 		'', | ||||||
| 		'  Commands:', | 		'  Commands:', | ||||||
| 		'', | 		'', | ||||||
| 		commands.map(function (cmd) { | 		commands.map((cmd) => { | ||||||
| 			var desc = cmd[1] ? `  ${cmd[1]}` : ''; | 			var desc = cmd[1] ? `  ${cmd[1]}` : ''; | ||||||
| 			return pad(cmd[0], width) + desc; | 			return pad(cmd[0], width) + desc; | ||||||
| 		}).join('\n').replace(/^/gm, '    '), | 		}).join('\n').replace(/^/gm, '    '), | ||||||
| @@ -119,9 +111,7 @@ Command.prototype.optionHelp = function () { | |||||||
|  |  | ||||||
| 	// Append the help information | 	// Append the help information | ||||||
| 	return this.options | 	return this.options | ||||||
| 		.map(function (option) { | 		.map(option => `${pad(option.flags, width)[optionColor]}  ${option.description}`) | ||||||
| 			return `${pad(option.flags, width)[optionColor]}  ${option.description}`; |  | ||||||
| 		}) |  | ||||||
| 		.concat([`${pad('-h, --help', width)[optionColor]}  output usage information`]) | 		.concat([`${pad('-h, --help', width)[optionColor]}  output usage information`]) | ||||||
| 		.join('\n'); | 		.join('\n'); | ||||||
| }; | }; | ||||||
|   | |||||||
| @@ -119,7 +119,7 @@ process.env.CONFIG = configFile; | |||||||
| program | program | ||||||
| 	.command('start') | 	.command('start') | ||||||
| 	.description('Start the NodeBB server') | 	.description('Start the NodeBB server') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./running').start(program); | 		require('./running').start(program); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| @@ -127,7 +127,7 @@ program | |||||||
| 		noHelp: true, | 		noHelp: true, | ||||||
| 	}) | 	}) | ||||||
| 	.description('Start the NodeBB server and view the live output log') | 	.description('Start the NodeBB server and view the live output log') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		program.log = true; | 		program.log = true; | ||||||
| 		require('./running').start(program); | 		require('./running').start(program); | ||||||
| 	}); | 	}); | ||||||
| @@ -136,7 +136,7 @@ program | |||||||
| 		noHelp: true, | 		noHelp: true, | ||||||
| 	}) | 	}) | ||||||
| 	.description('Start NodeBB in verbose development mode') | 	.description('Start NodeBB in verbose development mode') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		program.dev = true; | 		program.dev = true; | ||||||
| 		process.env.NODE_ENV = 'development'; | 		process.env.NODE_ENV = 'development'; | ||||||
| 		global.env = 'development'; | 		global.env = 'development'; | ||||||
| @@ -145,25 +145,25 @@ program | |||||||
| program | program | ||||||
| 	.command('stop') | 	.command('stop') | ||||||
| 	.description('Stop the NodeBB server') | 	.description('Stop the NodeBB server') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./running').stop(program); | 		require('./running').stop(program); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('restart') | 	.command('restart') | ||||||
| 	.description('Restart the NodeBB server') | 	.description('Restart the NodeBB server') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./running').restart(program); | 		require('./running').restart(program); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('status') | 	.command('status') | ||||||
| 	.description('Check the running status of the NodeBB server') | 	.description('Check the running status of the NodeBB server') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./running').status(program); | 		require('./running').status(program); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('log') | 	.command('log') | ||||||
| 	.description('Open the output log (useful for debugging)') | 	.description('Open the output log (useful for debugging)') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./running').log(program); | 		require('./running').log(program); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -172,7 +172,7 @@ program | |||||||
| 	.command('setup [config]') | 	.command('setup [config]') | ||||||
| 	.description('Run the NodeBB setup script, or setup with an initial config') | 	.description('Run the NodeBB setup script, or setup with an initial config') | ||||||
| 	.option('--skip-build', 'Run setup without building assets') | 	.option('--skip-build', 'Run setup without building assets') | ||||||
| 	.action(function (initConfig) { | 	.action((initConfig) => { | ||||||
| 		if (initConfig) { | 		if (initConfig) { | ||||||
| 			try { | 			try { | ||||||
| 				initConfig = JSON.parse(initConfig); | 				initConfig = JSON.parse(initConfig); | ||||||
| @@ -189,41 +189,41 @@ program | |||||||
| program | program | ||||||
| 	.command('install') | 	.command('install') | ||||||
| 	.description('Launch the NodeBB web installer for configuration setup') | 	.description('Launch the NodeBB web installer for configuration setup') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./setup').webInstall(); | 		require('./setup').webInstall(); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('build [targets...]') | 	.command('build [targets...]') | ||||||
| 	.description(`Compile static assets ${'(JS, CSS, templates, languages)'.red}`) | 	.description(`Compile static assets ${'(JS, CSS, templates, languages)'.red}`) | ||||||
| 	.option('-s, --series', 'Run builds in series without extra processes') | 	.option('-s, --series', 'Run builds in series without extra processes') | ||||||
| 	.action(function (targets, options) { | 	.action((targets, options) => { | ||||||
| 		require('./manage').build(targets.length ? targets : true, options); | 		require('./manage').build(targets.length ? targets : true, options); | ||||||
| 	}) | 	}) | ||||||
| 	.on('--help', function () { | 	.on('--help', () => { | ||||||
| 		require('../meta/aliases').buildTargets(); | 		require('../meta/aliases').buildTargets(); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('activate [plugin]') | 	.command('activate [plugin]') | ||||||
| 	.description('Activate a plugin for the next startup of NodeBB (nodebb-plugin- prefix is optional)') | 	.description('Activate a plugin for the next startup of NodeBB (nodebb-plugin- prefix is optional)') | ||||||
| 	.action(function (plugin) { | 	.action((plugin) => { | ||||||
| 		require('./manage').activate(plugin); | 		require('./manage').activate(plugin); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('plugins') | 	.command('plugins') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./manage').listPlugins(); | 		require('./manage').listPlugins(); | ||||||
| 	}) | 	}) | ||||||
| 	.description('List all installed plugins'); | 	.description('List all installed plugins'); | ||||||
| program | program | ||||||
| 	.command('events [count]') | 	.command('events [count]') | ||||||
| 	.description('Outputs the most recent administrative events recorded by NodeBB') | 	.description('Outputs the most recent administrative events recorded by NodeBB') | ||||||
| 	.action(function (count) { | 	.action((count) => { | ||||||
| 		require('./manage').listEvents(count); | 		require('./manage').listEvents(count); | ||||||
| 	}); | 	}); | ||||||
| program | program | ||||||
| 	.command('info') | 	.command('info') | ||||||
| 	.description('Outputs various system info') | 	.description('Outputs various system info') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./manage').info(); | 		require('./manage').info(); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -237,16 +237,14 @@ resetCommand | |||||||
| 	.option('-w, --widgets', 'Disable all widgets') | 	.option('-w, --widgets', 'Disable all widgets') | ||||||
| 	.option('-s, --settings', 'Reset settings to their default values') | 	.option('-s, --settings', 'Reset settings to their default values') | ||||||
| 	.option('-a, --all', 'All of the above') | 	.option('-a, --all', 'All of the above') | ||||||
| 	.action(function (options) { | 	.action((options) => { | ||||||
| 		const valid = ['theme', 'plugin', 'widgets', 'settings', 'all'].some(function (x) { | 		const valid = ['theme', 'plugin', 'widgets', 'settings', 'all'].some(x => options[x]); | ||||||
| 			return options[x]; |  | ||||||
| 		}); |  | ||||||
| 		if (!valid) { | 		if (!valid) { | ||||||
| 			console.warn('\n  No valid options passed in, so nothing was reset.'.red); | 			console.warn('\n  No valid options passed in, so nothing was reset.'.red); | ||||||
| 			resetCommand.help(); | 			resetCommand.help(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		require('./reset').reset(options, function (err) { | 		require('./reset').reset(options, (err) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				return process.exit(1); | 				return process.exit(1); | ||||||
| 			} | 			} | ||||||
| @@ -264,7 +262,7 @@ program | |||||||
| 	.option('-p, --plugins', 'Check installed plugins for updates', false) | 	.option('-p, --plugins', 'Check installed plugins for updates', false) | ||||||
| 	.option('-s, --schema', 'Update NodeBB data store schema', false) | 	.option('-s, --schema', 'Update NodeBB data store schema', false) | ||||||
| 	.option('-b, --build', 'Rebuild assets', false) | 	.option('-b, --build', 'Rebuild assets', false) | ||||||
| 	.on('--help', function () { | 	.on('--help', () => { | ||||||
| 		console.log(`\n${[ | 		console.log(`\n${[ | ||||||
| 			'When running particular upgrade scripts, options are ignored.', | 			'When running particular upgrade scripts, options are ignored.', | ||||||
| 			'By default all options are enabled. Passing any options disables that default.', | 			'By default all options are enabled. Passing any options disables that default.', | ||||||
| @@ -272,7 +270,7 @@ program | |||||||
| 			`Only database update: ${'./nodebb upgrade -s'.yellow}`, | 			`Only database update: ${'./nodebb upgrade -s'.yellow}`, | ||||||
| 		].join('\n')}`); | 		].join('\n')}`); | ||||||
| 	}) | 	}) | ||||||
| 	.action(function (scripts, options) { | 	.action((scripts, options) => { | ||||||
| 		require('./upgrade').upgrade(scripts.length ? scripts : true, options); | 		require('./upgrade').upgrade(scripts.length ? scripts : true, options); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -282,8 +280,8 @@ program | |||||||
| 	}) | 	}) | ||||||
| 	.alias('upgradePlugins') | 	.alias('upgradePlugins') | ||||||
| 	.description('Upgrade plugins') | 	.description('Upgrade plugins') | ||||||
| 	.action(function () { | 	.action(() => { | ||||||
| 		require('./upgrade-plugins').upgradePlugins(function (err) { | 		require('./upgrade-plugins').upgradePlugins((err) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				throw err; | 				throw err; | ||||||
| 			} | 			} | ||||||
| @@ -295,12 +293,12 @@ program | |||||||
| program | program | ||||||
| 	.command('help [command]') | 	.command('help [command]') | ||||||
| 	.description('Display help for [command]') | 	.description('Display help for [command]') | ||||||
| 	.action(function (name) { | 	.action((name) => { | ||||||
| 		if (!name) { | 		if (!name) { | ||||||
| 			return program.help(); | 			return program.help(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const command = program.commands.find(function (command) { return command._name === name; }); | 		const command = program.commands.find(command => command._name === name); | ||||||
| 		if (command) { | 		if (command) { | ||||||
| 			command.help(); | 			command.help(); | ||||||
| 		} else { | 		} else { | ||||||
|   | |||||||
| @@ -86,7 +86,7 @@ async function listEvents(count) { | |||||||
| 	await db.init(); | 	await db.init(); | ||||||
| 	const eventData = await events.getEvents('', 0, (count || 10) - 1); | 	const eventData = await events.getEvents('', 0, (count || 10) - 1); | ||||||
| 	console.log((`\nDisplaying last ${count} administrative events...`).bold); | 	console.log((`\nDisplaying last ${count} administrative events...`).bold); | ||||||
| 	eventData.forEach(function (event) { | 	eventData.forEach((event) => { | ||||||
| 		console.log(`  * ${String(event.timestampISO).green} ${String(event.type).yellow}${event.text ? ` ${event.text}` : ''}${' (uid: '.reset}${event.uid ? event.uid : 0})`); | 		console.log(`  * ${String(event.timestampISO).green} ${String(event.type).yellow}${event.text ? ` ${event.text}` : ''}${' (uid: '.reset}${event.uid ? event.uid : 0})`); | ||||||
| 	}); | 	}); | ||||||
| 	process.exit(); | 	process.exit(); | ||||||
| @@ -132,7 +132,7 @@ async function info() { | |||||||
| 	const min = Math.min(...analyticsData); | 	const min = Math.min(...analyticsData); | ||||||
| 	const max = Math.max(...analyticsData); | 	const max = Math.max(...analyticsData); | ||||||
|  |  | ||||||
| 	analyticsData.forEach(function (point, idx) { | 	analyticsData.forEach((point, idx) => { | ||||||
| 		graph.addPoint(idx + 1, Math.round(point / max * 10)); | 		graph.addPoint(idx + 1, Math.round(point / max * 10)); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -99,14 +99,14 @@ function preserveExtraneousPlugins() { | |||||||
|  |  | ||||||
| 	const extraneous = packages | 	const extraneous = packages | ||||||
| 		// only extraneous plugins (ones not in package.json) which are not links | 		// only extraneous plugins (ones not in package.json) which are not links | ||||||
| 		.filter(function (pkgName) { | 		.filter((pkgName) => { | ||||||
| 			const extraneous = !packageContents.dependencies.hasOwnProperty(pkgName); | 			const extraneous = !packageContents.dependencies.hasOwnProperty(pkgName); | ||||||
| 			const isLink = fs.lstatSync(path.join(paths.nodeModules, pkgName)).isSymbolicLink(); | 			const isLink = fs.lstatSync(path.join(paths.nodeModules, pkgName)).isSymbolicLink(); | ||||||
|  |  | ||||||
| 			return extraneous && !isLink; | 			return extraneous && !isLink; | ||||||
| 		}) | 		}) | ||||||
| 		// reduce to a map of package names to package versions | 		// reduce to a map of package names to package versions | ||||||
| 		.reduce(function (map, pkgName) { | 		.reduce((map, pkgName) => { | ||||||
| 			const pkgConfig = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, pkgName, 'package.json'), 'utf8')); | 			const pkgConfig = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, pkgName, 'package.json'), 'utf8')); | ||||||
| 			map[pkgName] = pkgConfig.version; | 			map[pkgName] = pkgConfig.version; | ||||||
| 			return map; | 			return map; | ||||||
|   | |||||||
| @@ -11,7 +11,7 @@ const cwd = paths.baseDir; | |||||||
| function getRunningPid(callback) { | function getRunningPid(callback) { | ||||||
| 	fs.readFile(paths.pidfile, { | 	fs.readFile(paths.pidfile, { | ||||||
| 		encoding: 'utf-8', | 		encoding: 'utf-8', | ||||||
| 	}, function (err, pid) { | 	}, (err, pid) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
| 		} | 		} | ||||||
| @@ -69,7 +69,7 @@ function start(options) { | |||||||
| } | } | ||||||
|  |  | ||||||
| function stop() { | function stop() { | ||||||
| 	getRunningPid(function (err, pid) { | 	getRunningPid((err, pid) => { | ||||||
| 		if (!err) { | 		if (!err) { | ||||||
| 			process.kill(pid, 'SIGTERM'); | 			process.kill(pid, 'SIGTERM'); | ||||||
| 			console.log('Stopping NodeBB. Goodbye!'); | 			console.log('Stopping NodeBB. Goodbye!'); | ||||||
| @@ -80,7 +80,7 @@ function stop() { | |||||||
| } | } | ||||||
|  |  | ||||||
| function restart(options) { | function restart(options) { | ||||||
| 	getRunningPid(function (err, pid) { | 	getRunningPid((err, pid) => { | ||||||
| 		if (!err) { | 		if (!err) { | ||||||
| 			console.log('\nRestarting NodeBB'.bold); | 			console.log('\nRestarting NodeBB'.bold); | ||||||
| 			process.kill(pid, 'SIGTERM'); | 			process.kill(pid, 'SIGTERM'); | ||||||
| @@ -94,7 +94,7 @@ function restart(options) { | |||||||
| } | } | ||||||
|  |  | ||||||
| function status() { | function status() { | ||||||
| 	getRunningPid(function (err, pid) { | 	getRunningPid((err, pid) => { | ||||||
| 		if (!err) { | 		if (!err) { | ||||||
| 			console.log(`\n${[ | 			console.log(`\n${[ | ||||||
| 				'NodeBB Running '.bold + (`(pid ${pid.toString()})`).cyan, | 				'NodeBB Running '.bold + (`(pid ${pid.toString()})`).cyan, | ||||||
|   | |||||||
| @@ -40,7 +40,7 @@ function setup(initConfig) { | |||||||
| 				setImmediate(next); | 				setImmediate(next); | ||||||
| 			} | 			} | ||||||
| 		}, | 		}, | ||||||
| 	], function (err, data) { | 	], (err, data) => { | ||||||
| 		// Disregard build step data | 		// Disregard build step data | ||||||
| 		data = data[0]; | 		data = data[0]; | ||||||
|  |  | ||||||
|   | |||||||
| @@ -25,8 +25,8 @@ if (process.platform === 'win32') { | |||||||
| function getModuleVersions(modules, callback) { | function getModuleVersions(modules, callback) { | ||||||
| 	const versionHash = {}; | 	const versionHash = {}; | ||||||
|  |  | ||||||
| 	async.eachLimit(modules, 50, function (module, next) { | 	async.eachLimit(modules, 50, (module, next) => { | ||||||
| 		fs.readFile(path.join(paths.nodeModules, module, 'package.json'), { encoding: 'utf-8' }, function (err, pkg) { | 		fs.readFile(path.join(paths.nodeModules, module, 'package.json'), { encoding: 'utf-8' }, (err, pkg) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				return next(err); | 				return next(err); | ||||||
| 			} | 			} | ||||||
| @@ -39,7 +39,7 @@ function getModuleVersions(modules, callback) { | |||||||
| 				next(err); | 				next(err); | ||||||
| 			} | 			} | ||||||
| 		}); | 		}); | ||||||
| 	}, function (err) { | 	}, (err) => { | ||||||
| 		callback(err, versionHash); | 		callback(err, versionHash); | ||||||
| 	}); | 	}); | ||||||
| } | } | ||||||
| @@ -49,14 +49,12 @@ function getInstalledPlugins(callback) { | |||||||
| 		files: async.apply(fs.readdir, paths.nodeModules), | 		files: async.apply(fs.readdir, paths.nodeModules), | ||||||
| 		deps: async.apply(fs.readFile, paths.currentPackage, { encoding: 'utf-8' }), | 		deps: async.apply(fs.readFile, paths.currentPackage, { encoding: 'utf-8' }), | ||||||
| 		bundled: async.apply(fs.readFile, paths.installPackage, { encoding: 'utf-8' }), | 		bundled: async.apply(fs.readFile, paths.installPackage, { encoding: 'utf-8' }), | ||||||
| 	}, function (err, payload) { | 	}, (err, payload) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		payload.files = payload.files.filter(function (file) { | 		payload.files = payload.files.filter(file => pluginNamePattern.test(file)); | ||||||
| 			return pluginNamePattern.test(file); |  | ||||||
| 		}); |  | ||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| 			payload.deps = Object.keys(JSON.parse(payload.deps).dependencies); | 			payload.deps = Object.keys(JSON.parse(payload.deps).dependencies); | ||||||
| @@ -65,15 +63,11 @@ function getInstalledPlugins(callback) { | |||||||
| 			return callback(err); | 			return callback(err); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		payload.bundled = payload.bundled.filter(function (pkgName) { | 		payload.bundled = payload.bundled.filter(pkgName => pluginNamePattern.test(pkgName)); | ||||||
| 			return pluginNamePattern.test(pkgName); | 		payload.deps = payload.deps.filter(pkgName => pluginNamePattern.test(pkgName)); | ||||||
| 		}); |  | ||||||
| 		payload.deps = payload.deps.filter(function (pkgName) { |  | ||||||
| 			return pluginNamePattern.test(pkgName); |  | ||||||
| 		}); |  | ||||||
|  |  | ||||||
| 		// Whittle down deps to send back only extraneously installed plugins/themes/etc | 		// Whittle down deps to send back only extraneously installed plugins/themes/etc | ||||||
| 		const checklist = payload.deps.filter(function (pkgName) { | 		const checklist = payload.deps.filter((pkgName) => { | ||||||
| 			if (payload.bundled.includes(pkgName)) { | 			if (payload.bundled.includes(pkgName)) { | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
| @@ -92,7 +86,7 @@ function getInstalledPlugins(callback) { | |||||||
| } | } | ||||||
|  |  | ||||||
| function getCurrentVersion(callback) { | function getCurrentVersion(callback) { | ||||||
| 	fs.readFile(paths.installPackage, { encoding: 'utf-8' }, function (err, pkg) { | 	fs.readFile(paths.installPackage, { encoding: 'utf-8' }, (err, pkg) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
| 		} | 		} | ||||||
| @@ -128,7 +122,7 @@ function checkPlugins(standalone, callback) { | |||||||
| 				method: 'GET', | 				method: 'GET', | ||||||
| 				url: `https://packages.nodebb.org/api/v1/suggest?version=${payload.version}&package[]=${toCheck.join('&package[]=')}`, | 				url: `https://packages.nodebb.org/api/v1/suggest?version=${payload.version}&package[]=${toCheck.join('&package[]=')}`, | ||||||
| 				json: true, | 				json: true, | ||||||
| 			}, function (err, res, body) { | 			}, (err, res, body) => { | ||||||
| 				if (err) { | 				if (err) { | ||||||
| 					process.stdout.write('error'.red + ''.reset); | 					process.stdout.write('error'.red + ''.reset); | ||||||
| 					return next(err); | 					return next(err); | ||||||
| @@ -141,7 +135,7 @@ function checkPlugins(standalone, callback) { | |||||||
|  |  | ||||||
| 				let current; | 				let current; | ||||||
| 				let suggested; | 				let suggested; | ||||||
| 				const upgradable = body.map(function (suggestObj) { | 				const upgradable = body.map((suggestObj) => { | ||||||
| 					current = payload.plugins[suggestObj.package]; | 					current = payload.plugins[suggestObj.package]; | ||||||
| 					suggested = suggestObj.version; | 					suggested = suggestObj.version; | ||||||
|  |  | ||||||
| @@ -168,7 +162,7 @@ function upgradePlugins(callback) { | |||||||
| 		standalone = true; | 		standalone = true; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	checkPlugins(standalone, function (err, found) { | 	checkPlugins(standalone, (err, found) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			console.log('Warning'.yellow + ': An unexpected error occured when attempting to verify plugin upgradability'.reset); | 			console.log('Warning'.yellow + ': An unexpected error occured when attempting to verify plugin upgradability'.reset); | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
| @@ -176,7 +170,7 @@ function upgradePlugins(callback) { | |||||||
|  |  | ||||||
| 		if (found && found.length) { | 		if (found && found.length) { | ||||||
| 			process.stdout.write(`\n\nA total of ${String(found.length).bold} package(s) can be upgraded:\n\n`); | 			process.stdout.write(`\n\nA total of ${String(found.length).bold} package(s) can be upgraded:\n\n`); | ||||||
| 			found.forEach(function (suggestObj) { | 			found.forEach((suggestObj) => { | ||||||
| 				process.stdout.write(`${'  * '.yellow + suggestObj.name.reset} (${suggestObj.current.yellow}${' -> '.reset}${suggestObj.suggested.green}${')\n'.reset}`); | 				process.stdout.write(`${'  * '.yellow + suggestObj.name.reset} (${suggestObj.current.yellow}${' -> '.reset}${suggestObj.suggested.green}${')\n'.reset}`); | ||||||
| 			}); | 			}); | ||||||
| 		} else { | 		} else { | ||||||
| @@ -194,18 +188,16 @@ function upgradePlugins(callback) { | |||||||
| 			name: 'upgrade', | 			name: 'upgrade', | ||||||
| 			description: '\nProceed with upgrade (y|n)?'.reset, | 			description: '\nProceed with upgrade (y|n)?'.reset, | ||||||
| 			type: 'string', | 			type: 'string', | ||||||
| 		}, function (err, result) { | 		}, (err, result) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				return callback(err); | 				return callback(err); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			if (['y', 'Y', 'yes', 'YES'].includes(result.upgrade)) { | 			if (['y', 'Y', 'yes', 'YES'].includes(result.upgrade)) { | ||||||
| 				console.log('\nUpgrading packages...'); | 				console.log('\nUpgrading packages...'); | ||||||
| 				const args = packageManagerInstallArgs.concat(found.map(function (suggestObj) { | 				const args = packageManagerInstallArgs.concat(found.map(suggestObj => `${suggestObj.name}@${suggestObj.suggested}`)); | ||||||
| 					return `${suggestObj.name}@${suggestObj.suggested}`; |  | ||||||
| 				})); |  | ||||||
|  |  | ||||||
| 				cproc.execFile(packageManagerExecutable, args, { stdio: 'ignore' }, function (err) { | 				cproc.execFile(packageManagerExecutable, args, { stdio: 'ignore' }, (err) => { | ||||||
| 					callback(err, false); | 					callback(err, false); | ||||||
| 				}); | 				}); | ||||||
| 			} else { | 			} else { | ||||||
|   | |||||||
| @@ -53,17 +53,15 @@ var steps = { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| function runSteps(tasks) { | function runSteps(tasks) { | ||||||
| 	tasks = tasks.map(function (key, i) { | 	tasks = tasks.map((key, i) => function (next) { | ||||||
| 		return function (next) { |  | ||||||
| 		process.stdout.write(`\n${(`${i + 1}. `).bold}${steps[key].message.yellow}`); | 		process.stdout.write(`\n${(`${i + 1}. `).bold}${steps[key].message.yellow}`); | ||||||
| 			return steps[key].handler(function (err) { | 		return steps[key].handler((err) => { | ||||||
| 			if (err) { return next(err); } | 			if (err) { return next(err); } | ||||||
| 			next(); | 			next(); | ||||||
| 		}); | 		}); | ||||||
| 		}; |  | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	async.series(tasks, function (err) { | 	async.series(tasks, (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			console.error(`Error occurred during upgrade: ${err.stack}`); | 			console.error(`Error occurred during upgrade: ${err.stack}`); | ||||||
| 			throw err; | 			throw err; | ||||||
| @@ -90,9 +88,7 @@ function runUpgrade(upgrades, options) { | |||||||
| 		var tasks = Object.keys(steps); | 		var tasks = Object.keys(steps); | ||||||
| 		if (options.package || options.install || | 		if (options.package || options.install || | ||||||
| 				options.plugins || options.schema || options.build) { | 				options.plugins || options.schema || options.build) { | ||||||
| 			tasks = tasks.filter(function (key) { | 			tasks = tasks.filter(key => options[key]); | ||||||
| 				return options[key]; |  | ||||||
| 			}); |  | ||||||
| 		} | 		} | ||||||
| 		runSteps(tasks); | 		runSteps(tasks); | ||||||
| 		return; | 		return; | ||||||
| @@ -104,7 +100,7 @@ function runUpgrade(upgrades, options) { | |||||||
| 		async function () { | 		async function () { | ||||||
| 			await upgrade.runParticular(upgrades); | 			await upgrade.runParticular(upgrades); | ||||||
| 		}, | 		}, | ||||||
| 	], function (err) { | 	], (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			throw err; | 			throw err; | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -26,7 +26,7 @@ categoriesController.get = async function (req, res, next) { | |||||||
| 	const categoriesData = allCategoriesData.slice(start, stop + 1); | 	const categoriesData = allCategoriesData.slice(start, stop + 1); | ||||||
|  |  | ||||||
|  |  | ||||||
| 	categoriesData.forEach(function (category) { | 	categoriesData.forEach((category) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			category.isIgnored = states[category.cid] === categories.watchStates.ignoring; | 			category.isIgnored = states[category.cid] === categories.watchStates.ignoring; | ||||||
| 			category.isWatched = states[category.cid] === categories.watchStates.watching; | 			category.isWatched = states[category.cid] === categories.watchStates.watching; | ||||||
|   | |||||||
| @@ -49,7 +49,7 @@ editController.get = async function (req, res, next) { | |||||||
| 		} | 		} | ||||||
| 		return i1 - i2; | 		return i1 - i2; | ||||||
| 	}); | 	}); | ||||||
| 	userData.groups.forEach(function (group) { | 	userData.groups.forEach((group) => { | ||||||
| 		group.userTitle = group.userTitle || group.displayName; | 		group.userTitle = group.userTitle || group.displayName; | ||||||
| 		group.selected = userData.groupTitleArray.includes(group.name); | 		group.selected = userData.groupTitleArray.includes(group.name); | ||||||
| 	}); | 	}); | ||||||
|   | |||||||
| @@ -15,7 +15,7 @@ groupsController.get = async function (req, res, next) { | |||||||
| 	groupsData = groupsData[0]; | 	groupsData = groupsData[0]; | ||||||
| 	const groupNames = groupsData.filter(Boolean).map(group => group.name); | 	const groupNames = groupsData.filter(Boolean).map(group => group.name); | ||||||
| 	const members = await groups.getMemberUsers(groupNames, 0, 3); | 	const members = await groups.getMemberUsers(groupNames, 0, 3); | ||||||
| 	groupsData.forEach(function (group, index) { | 	groupsData.forEach((group, index) => { | ||||||
| 		group.members = members[index]; | 		group.members = members[index]; | ||||||
| 	}); | 	}); | ||||||
| 	userData.groups = groupsData; | 	userData.groups = groupsData; | ||||||
|   | |||||||
| @@ -231,7 +231,7 @@ async function parseAboutMe(userData) { | |||||||
| } | } | ||||||
|  |  | ||||||
| function filterLinks(links, states) { | function filterLinks(links, states) { | ||||||
| 	return links.filter(function (link, index) { | 	return links.filter((link, index) => { | ||||||
| 		// Default visibility | 		// Default visibility | ||||||
| 		link.visibility = { self: true, | 		link.visibility = { self: true, | ||||||
| 			other: true, | 			other: true, | ||||||
| @@ -241,9 +241,7 @@ function filterLinks(links, states) { | |||||||
| 			canViewInfo: true, | 			canViewInfo: true, | ||||||
| 			...link.visibility }; | 			...link.visibility }; | ||||||
|  |  | ||||||
| 		var permit = Object.keys(states).some(function (state) { | 		var permit = Object.keys(states).some(state => states[state] && link.visibility[state]); | ||||||
| 			return states[state] && link.visibility[state]; |  | ||||||
| 		}); |  | ||||||
|  |  | ||||||
| 		links[index].public = permit; | 		links[index].public = permit; | ||||||
| 		return permit; | 		return permit; | ||||||
|   | |||||||
| @@ -44,7 +44,7 @@ notificationsController.get = async function (req, res, next) { | |||||||
| 			{ separator: true }, | 			{ separator: true }, | ||||||
| 		]).concat(filters.moderatorFilters); | 		]).concat(filters.moderatorFilters); | ||||||
| 	} | 	} | ||||||
| 	const selectedFilter = allFilters.find(function (filterData) { | 	const selectedFilter = allFilters.find((filterData) => { | ||||||
| 		filterData.selected = filterData.filter === filter; | 		filterData.selected = filterData.filter === filter; | ||||||
| 		return filterData.selected; | 		return filterData.selected; | ||||||
| 	}); | 	}); | ||||||
|   | |||||||
| @@ -178,7 +178,7 @@ async function getFromUserSet(template, req, res, callback) { | |||||||
| 		{ url: `${baseUrl}?sort=lastpost`, name: '[[global:lastpost]]' }, | 		{ url: `${baseUrl}?sort=lastpost`, name: '[[global:lastpost]]' }, | ||||||
| 		{ url: `${baseUrl}?sort=firstpost`, name: '[[global:firstpost]]' }, | 		{ url: `${baseUrl}?sort=firstpost`, name: '[[global:firstpost]]' }, | ||||||
| 	]; | 	]; | ||||||
| 	userData.sortOptions.forEach(function (option) { | 	userData.sortOptions.forEach((option) => { | ||||||
| 		option.selected = option.url.includes(`sort=${req.query.sort}`); | 		option.selected = option.url.includes(`sort=${req.query.sort}`); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -76,16 +76,16 @@ settingsController.get = async function (req, res, next) { | |||||||
| 		{ name: 'Yeti', value: 'yeti' }, | 		{ name: 'Yeti', value: 'yeti' }, | ||||||
| 	]; | 	]; | ||||||
|  |  | ||||||
| 	userData.bootswatchSkinOptions.forEach(function (skin) { | 	userData.bootswatchSkinOptions.forEach((skin) => { | ||||||
| 		skin.selected = skin.value === userData.settings.bootswatchSkin; | 		skin.selected = skin.value === userData.settings.bootswatchSkin; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	userData.languages.forEach(function (language) { | 	userData.languages.forEach((language) => { | ||||||
| 		language.selected = language.code === userData.settings.userLang; | 		language.selected = language.code === userData.settings.userLang; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	if (userData.isAdmin && userData.isSelf) { | 	if (userData.isAdmin && userData.isSelf) { | ||||||
| 		userData.acpLanguages.forEach(function (language) { | 		userData.acpLanguages.forEach((language) => { | ||||||
| 			language.selected = language.code === userData.settings.acpLang; | 			language.selected = language.code === userData.settings.acpLang; | ||||||
| 		}); | 		}); | ||||||
| 	} | 	} | ||||||
| @@ -122,7 +122,7 @@ settingsController.get = async function (req, res, next) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| const unsubscribable = ['digest', 'notification']; | const unsubscribable = ['digest', 'notification']; | ||||||
| const jwtVerifyAsync = util.promisify(function (token, callback) { | const jwtVerifyAsync = util.promisify((token, callback) => { | ||||||
| 	jwt.verify(token, nconf.get('secret'), (err, payload) => callback(err, payload)); | 	jwt.verify(token, nconf.get('secret'), (err, payload) => callback(err, payload)); | ||||||
| }); | }); | ||||||
| const doUnsubscribe = async (payload) => { | const doUnsubscribe = async (payload) => { | ||||||
| @@ -221,7 +221,7 @@ async function getHomePageRoutes(userData) { | |||||||
| 	// Set selected for each route | 	// Set selected for each route | ||||||
| 	var customIdx; | 	var customIdx; | ||||||
| 	var hasSelected = false; | 	var hasSelected = false; | ||||||
| 	routes = routes.map(function (route, idx) { | 	routes = routes.map((route, idx) => { | ||||||
| 		if (route.route === userData.settings.homePageRoute) { | 		if (route.route === userData.settings.homePageRoute) { | ||||||
| 			route.selected = true; | 			route.selected = true; | ||||||
| 			hasSelected = true; | 			hasSelected = true; | ||||||
|   | |||||||
| @@ -25,12 +25,10 @@ uploadsController.get = async function (req, res, next) { | |||||||
| 		db.getSortedSetRevRange(`uid:${userData.uid}:uploads`, start, stop), | 		db.getSortedSetRevRange(`uid:${userData.uid}:uploads`, start, stop), | ||||||
| 	]); | 	]); | ||||||
|  |  | ||||||
| 	userData.uploads = uploadNames.map(function (uploadName) { | 	userData.uploads = uploadNames.map(uploadName => ({ | ||||||
| 		return { |  | ||||||
| 		name: uploadName, | 		name: uploadName, | ||||||
| 		url: nconf.get('upload_url') + uploadName, | 		url: nconf.get('upload_url') + uploadName, | ||||||
| 		}; | 	})); | ||||||
| 	}); |  | ||||||
| 	const pageCount = Math.ceil(itemCount / itemsPerPage); | 	const pageCount = Math.ceil(itemCount / itemsPerPage); | ||||||
| 	userData.pagination = pagination.create(page, pageCount, req.query); | 	userData.pagination = pagination.create(page, pageCount, req.query); | ||||||
| 	userData.privateUploads = meta.config.privateUploads === 1; | 	userData.privateUploads = meta.config.privateUploads === 1; | ||||||
|   | |||||||
| @@ -50,7 +50,7 @@ cacheController.dump = function (req, res, next) { | |||||||
| 	const data = JSON.stringify(caches[req.query.name].dump(), null, 4); | 	const data = JSON.stringify(caches[req.query.name].dump(), null, 4); | ||||||
| 	res.setHeader('Content-disposition', `attachment; filename= ${req.query.name}-cache.json`); | 	res.setHeader('Content-disposition', `attachment; filename= ${req.query.name}-cache.json`); | ||||||
| 	res.setHeader('Content-type', 'application/json'); | 	res.setHeader('Content-type', 'application/json'); | ||||||
| 	res.write(data, function (err) { | 	res.write(data, (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return next(err); | 			return next(err); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -116,7 +116,7 @@ async function buildBreadcrumbs(req, categoryData) { | |||||||
| 	const allCrumbs = await helpers.buildCategoryBreadcrumbs(categoryData.parentCid); | 	const allCrumbs = await helpers.buildCategoryBreadcrumbs(categoryData.parentCid); | ||||||
| 	const crumbs = allCrumbs.filter(c => c.cid); | 	const crumbs = allCrumbs.filter(c => c.cid); | ||||||
|  |  | ||||||
| 	crumbs.forEach(function (c) { | 	crumbs.forEach((c) => { | ||||||
| 		c.url = `/admin/manage/categories?cid=${c.cid}`; | 		c.url = `/admin/manage/categories?cid=${c.cid}`; | ||||||
| 	}); | 	}); | ||||||
| 	crumbs.unshift({ | 	crumbs.unshift({ | ||||||
|   | |||||||
| @@ -25,13 +25,11 @@ eventsController.get = async function (req, res) { | |||||||
| 		events.getEvents(currentFilter, start, stop, from || '-inf', to), | 		events.getEvents(currentFilter, start, stop, from || '-inf', to), | ||||||
| 	]); | 	]); | ||||||
|  |  | ||||||
| 	const types = [''].concat(events.types).map(function (type) { | 	const types = [''].concat(events.types).map(type => ({ | ||||||
| 		return { |  | ||||||
| 		value: type, | 		value: type, | ||||||
| 		name: type || 'all', | 		name: type || 'all', | ||||||
| 		selected: type === currentFilter, | 		selected: type === currentFilter, | ||||||
| 		}; | 	})); | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	const pageCount = Math.max(1, Math.ceil(eventCount / itemsPerPage)); | 	const pageCount = Math.max(1, Math.ceil(eventCount / itemsPerPage)); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -42,13 +42,11 @@ groupsController.get = async function (req, res, next) { | |||||||
| 	} | 	} | ||||||
| 	group.isOwner = true; | 	group.isOwner = true; | ||||||
|  |  | ||||||
| 	const groupNameData = groupNames.map(function (name) { | 	const groupNameData = groupNames.map(name => ({ | ||||||
| 		return { |  | ||||||
| 		encodedName: encodeURIComponent(name), | 		encodedName: encodeURIComponent(name), | ||||||
| 		displayName: validator.escape(String(name)), | 		displayName: validator.escape(String(name)), | ||||||
| 		selected: name === groupName, | 		selected: name === groupName, | ||||||
| 		}; | 	})); | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	res.render('admin/manage/group', { | 	res.render('admin/manage/group', { | ||||||
| 		group: group, | 		group: group, | ||||||
|   | |||||||
| @@ -7,7 +7,7 @@ const hooksController = module.exports; | |||||||
|  |  | ||||||
| hooksController.get = function (req, res) { | hooksController.get = function (req, res) { | ||||||
| 	const hooks = []; | 	const hooks = []; | ||||||
| 	Object.keys(plugins.loadedHooks).forEach(function (key, hookIndex) { | 	Object.keys(plugins.loadedHooks).forEach((key, hookIndex) => { | ||||||
| 		const current = { | 		const current = { | ||||||
| 			hookName: key, | 			hookName: key, | ||||||
| 			methods: [], | 			methods: [], | ||||||
| @@ -15,7 +15,7 @@ hooksController.get = function (req, res) { | |||||||
| 			count: plugins.loadedHooks[key].length, | 			count: plugins.loadedHooks[key].length, | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		plugins.loadedHooks[key].forEach(function (hookData, methodIndex) { | 		plugins.loadedHooks[key].forEach((hookData, methodIndex) => { | ||||||
| 			current.methods.push({ | 			current.methods.push({ | ||||||
| 				id: hookData.id, | 				id: hookData.id, | ||||||
| 				priority: hookData.priority, | 				priority: hookData.priority, | ||||||
|   | |||||||
| @@ -16,10 +16,10 @@ infoController.get = function (req, res) { | |||||||
| 	info = {}; | 	info = {}; | ||||||
| 	pubsub.publish('sync:node:info:start'); | 	pubsub.publish('sync:node:info:start'); | ||||||
| 	const timeoutMS = 1000; | 	const timeoutMS = 1000; | ||||||
| 	setTimeout(function () { | 	setTimeout(() => { | ||||||
| 		const data = []; | 		const data = []; | ||||||
| 		Object.keys(info).forEach(key => data.push(info[key])); | 		Object.keys(info).forEach(key => data.push(info[key])); | ||||||
| 		data.sort(function (a, b) { | 		data.sort((a, b) => { | ||||||
| 			if (a.id < b.id) { | 			if (a.id < b.id) { | ||||||
| 				return -1; | 				return -1; | ||||||
| 			} | 			} | ||||||
| @@ -46,7 +46,7 @@ infoController.get = function (req, res) { | |||||||
| 	}, timeoutMS); | 	}, timeoutMS); | ||||||
| }; | }; | ||||||
|  |  | ||||||
| pubsub.on('sync:node:info:start', async function () { | pubsub.on('sync:node:info:start', async () => { | ||||||
| 	try { | 	try { | ||||||
| 		const data = await getNodeInfo(); | 		const data = await getNodeInfo(); | ||||||
| 		data.id = `${os.hostname()}:${nconf.get('port')}`; | 		data.id = `${os.hostname()}:${nconf.get('port')}`; | ||||||
| @@ -56,7 +56,7 @@ pubsub.on('sync:node:info:start', async function () { | |||||||
| 	} | 	} | ||||||
| }); | }); | ||||||
|  |  | ||||||
| pubsub.on('sync:node:info:end', function (data) { | pubsub.on('sync:node:info:end', (data) => { | ||||||
| 	info[data.id] = data.data; | 	info[data.id] = data.data; | ||||||
| }); | }); | ||||||
|  |  | ||||||
| @@ -77,7 +77,7 @@ async function getNodeInfo() { | |||||||
| 			platform: os.platform(), | 			platform: os.platform(), | ||||||
| 			arch: os.arch(), | 			arch: os.arch(), | ||||||
| 			release: os.release(), | 			release: os.release(), | ||||||
| 			load: os.loadavg().map(function (load) { return load.toFixed(2); }).join(', '), | 			load: os.loadavg().map(load => load.toFixed(2)).join(', '), | ||||||
| 			freemem: os.freemem(), | 			freemem: os.freemem(), | ||||||
| 			totalmem: os.totalmem(), | 			totalmem: os.totalmem(), | ||||||
| 		}, | 		}, | ||||||
| @@ -118,7 +118,7 @@ function humanReadableUptime(seconds) { | |||||||
|  |  | ||||||
| async function getGitInfo() { | async function getGitInfo() { | ||||||
| 	function get(cmd, callback) { | 	function get(cmd, callback) { | ||||||
| 		exec(cmd, function (err, stdout) { | 		exec(cmd, (err, stdout) => { | ||||||
| 			if (err) { | 			if (err) { | ||||||
| 				winston.error(err.stack); | 				winston.error(err.stack); | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -32,18 +32,14 @@ pluginsController.get = async function (req, res) { | |||||||
| 		installedCount: installedPlugins.length, | 		installedCount: installedPlugins.length, | ||||||
| 		activeCount: activePlugins.length, | 		activeCount: activePlugins.length, | ||||||
| 		inactiveCount: Math.max(0, installedPlugins.length - activePlugins.length), | 		inactiveCount: Math.max(0, installedPlugins.length - activePlugins.length), | ||||||
| 		upgradeCount: compatible.reduce(function (count, current) { | 		upgradeCount: compatible.reduce((count, current) => { | ||||||
| 			if (current.installed && current.outdated) { | 			if (current.installed && current.outdated) { | ||||||
| 				count += 1; | 				count += 1; | ||||||
| 			} | 			} | ||||||
| 			return count; | 			return count; | ||||||
| 		}, 0), | 		}, 0), | ||||||
| 		download: compatible.filter(function (plugin) { | 		download: compatible.filter(plugin => !plugin.installed), | ||||||
| 			return !plugin.installed; | 		incompatible: all.filter(plugin => !compatiblePkgNames.includes(plugin.name)), | ||||||
| 		}), |  | ||||||
| 		incompatible: all.filter(function (plugin) { |  | ||||||
| 			return !compatiblePkgNames.includes(plugin.name); |  | ||||||
| 		}), |  | ||||||
| 		trending: trendingPlugins, | 		trending: trendingPlugins, | ||||||
| 		submitPluginUsage: meta.config.submitPluginUsage, | 		submitPluginUsage: meta.config.submitPluginUsage, | ||||||
| 		version: nconf.get('version'), | 		version: nconf.get('version'), | ||||||
|   | |||||||
| @@ -27,7 +27,7 @@ privilegesController.get = async function (req, res) { | |||||||
| 	}]; | 	}]; | ||||||
|  |  | ||||||
| 	let selectedCategory; | 	let selectedCategory; | ||||||
| 	categoriesData.forEach(function (category) { | 	categoriesData.forEach((category) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			category.selected = category.cid === (!isAdminPriv ? cid : 'admin'); | 			category.selected = category.cid === (!isAdminPriv ? cid : 'admin'); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -30,12 +30,10 @@ settingsController.email = async (req, res) => { | |||||||
|  |  | ||||||
| settingsController.user = async (req, res) => { | settingsController.user = async (req, res) => { | ||||||
| 	const notificationTypes = await notifications.getAllNotificationTypes(); | 	const notificationTypes = await notifications.getAllNotificationTypes(); | ||||||
| 	const notificationSettings = notificationTypes.map(function (type) { | 	const notificationSettings = notificationTypes.map(type => ({ | ||||||
| 		return { |  | ||||||
| 		name: type, | 		name: type, | ||||||
| 		label: `[[notifications:${type}]]`, | 		label: `[[notifications:${type}]]`, | ||||||
| 		}; | 	})); | ||||||
| 	}); |  | ||||||
| 	res.render('admin/settings/user', { | 	res.render('admin/settings/user', { | ||||||
| 		notificationSettings: notificationSettings, | 		notificationSettings: notificationSettings, | ||||||
| 	}); | 	}); | ||||||
| @@ -50,7 +48,7 @@ settingsController.post = async (req, res) => { | |||||||
|  |  | ||||||
| settingsController.languages = async function (req, res) { | settingsController.languages = async function (req, res) { | ||||||
| 	const languageData = await languages.list(); | 	const languageData = await languages.list(); | ||||||
| 	languageData.forEach(function (language) { | 	languageData.forEach((language) => { | ||||||
| 		language.selected = language.code === meta.config.defaultLang; | 		language.selected = language.code === meta.config.defaultLang; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -69,20 +67,18 @@ settingsController.navigation = async function (req, res) { | |||||||
| 	allGroups.sort((a, b) => b.system - a.system); | 	allGroups.sort((a, b) => b.system - a.system); | ||||||
|  |  | ||||||
| 	admin.groups = allGroups.map(group => ({ name: group.name, displayName: group.displayName })); | 	admin.groups = allGroups.map(group => ({ name: group.name, displayName: group.displayName })); | ||||||
| 	admin.enabled.forEach(function (enabled, index) { | 	admin.enabled.forEach((enabled, index) => { | ||||||
| 		enabled.index = index; | 		enabled.index = index; | ||||||
| 		enabled.selected = index === 0; | 		enabled.selected = index === 0; | ||||||
| 		enabled.title = translator.escape(enabled.title); | 		enabled.title = translator.escape(enabled.title); | ||||||
| 		enabled.text = translator.escape(enabled.text); | 		enabled.text = translator.escape(enabled.text); | ||||||
| 		enabled.groups = admin.groups.map(function (group) { | 		enabled.groups = admin.groups.map(group => ({ | ||||||
| 			return { |  | ||||||
| 			displayName: group.displayName, | 			displayName: group.displayName, | ||||||
| 			selected: enabled.groups.includes(group.name), | 			selected: enabled.groups.includes(group.name), | ||||||
| 			}; | 		})); | ||||||
| 		}); |  | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	admin.available.forEach(function (available) { | 	admin.available.forEach((available) => { | ||||||
| 		available.groups = admin.groups; | 		available.groups = admin.groups; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -33,7 +33,7 @@ uploadsController.get = async function (req, res, next) { | |||||||
| 		files = await filesToData(currentFolder, files); | 		files = await filesToData(currentFolder, files); | ||||||
|  |  | ||||||
| 		// Float directories to the top | 		// Float directories to the top | ||||||
| 		files.sort(function (a, b) { | 		files.sort((a, b) => { | ||||||
| 			if (a.isDirectory && !b.isDirectory) { | 			if (a.isDirectory && !b.isDirectory) { | ||||||
| 				return -1; | 				return -1; | ||||||
| 			} else if (!a.isDirectory && b.isDirectory) { | 			} else if (!a.isDirectory && b.isDirectory) { | ||||||
| @@ -48,7 +48,7 @@ uploadsController.get = async function (req, res, next) { | |||||||
| 		// Add post usage info if in /files | 		// Add post usage info if in /files | ||||||
| 		if (['/files', '/files/'].includes(req.query.dir)) { | 		if (['/files', '/files/'].includes(req.query.dir)) { | ||||||
| 			const usage = await posts.uploads.getUsage(files); | 			const usage = await posts.uploads.getUsage(files); | ||||||
| 			files.forEach(function (file, idx) { | 			files.forEach((file, idx) => { | ||||||
| 				file.inPids = usage[idx].map(pid => parseInt(pid, 10)); | 				file.inPids = usage[idx].map(pid => parseInt(pid, 10)); | ||||||
| 			}); | 			}); | ||||||
| 		} | 		} | ||||||
| @@ -68,7 +68,7 @@ function buildBreadcrumbs(currentFolder) { | |||||||
| 	var crumbs = []; | 	var crumbs = []; | ||||||
| 	var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); | 	var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); | ||||||
| 	var currentPath = ''; | 	var currentPath = ''; | ||||||
| 	parts.forEach(function (part) { | 	parts.forEach((part) => { | ||||||
| 		var dir = path.join(currentPath, part); | 		var dir = path.join(currentPath, part); | ||||||
| 		crumbs.push({ | 		crumbs.push({ | ||||||
| 			text: part || 'Uploads', | 			text: part || 'Uploads', | ||||||
|   | |||||||
| @@ -164,7 +164,7 @@ usersController.search = async function (req, res) { | |||||||
| 	const uids = searchData.users.map(user => user && user.uid); | 	const uids = searchData.users.map(user => user && user.uid); | ||||||
| 	const userInfo = await user.getUsersFields(uids, ['email', 'flags', 'lastonline', 'joindate']); | 	const userInfo = await user.getUsersFields(uids, ['email', 'flags', 'lastonline', 'joindate']); | ||||||
|  |  | ||||||
| 	searchData.users.forEach(function (user, index) { | 	searchData.users.forEach((user, index) => { | ||||||
| 		if (user && userInfo[index]) { | 		if (user && userInfo[index]) { | ||||||
| 			user.email = userInfo[index].email; | 			user.email = userInfo[index].email; | ||||||
| 			user.flags = userInfo[index].flags || 0; | 			user.flags = userInfo[index].flags || 0; | ||||||
| @@ -203,7 +203,7 @@ async function getInvites() { | |||||||
| 	let usernames = await user.getUsersFields(uids, ['username']); | 	let usernames = await user.getUsersFields(uids, ['username']); | ||||||
| 	usernames = usernames.map(user => user.username); | 	usernames = usernames.map(user => user.username); | ||||||
|  |  | ||||||
| 	invitations.forEach(function (invites, index) { | 	invitations.forEach((invites, index) => { | ||||||
| 		invites.username = usernames[index]; | 		invites.username = usernames[index]; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -215,13 +215,11 @@ async function getInvites() { | |||||||
|  |  | ||||||
| 	usernames = await Promise.all(invitations.map(invites => getUsernamesByEmails(invites.invitations))); | 	usernames = await Promise.all(invitations.map(invites => getUsernamesByEmails(invites.invitations))); | ||||||
|  |  | ||||||
| 	invitations.forEach(function (invites, index) { | 	invitations.forEach((invites, index) => { | ||||||
| 		invites.invitations = invites.invitations.map(function (email, i) { | 		invites.invitations = invites.invitations.map((email, i) => ({ | ||||||
| 			return { |  | ||||||
| 			email: email, | 			email: email, | ||||||
| 			username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i], | 			username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i], | ||||||
| 			}; | 		})); | ||||||
| 		}); |  | ||||||
| 	}); | 	}); | ||||||
| 	return invitations; | 	return invitations; | ||||||
| } | } | ||||||
| @@ -238,7 +236,7 @@ async function render(req, res, data) { | |||||||
| 		data[`searchBy_${validator.escape(String(req.query.searchBy))}`] = true; | 		data[`searchBy_${validator.escape(String(req.query.searchBy))}`] = true; | ||||||
| 	} | 	} | ||||||
| 	const filterBy = Array.isArray(req.query.filters || []) ? (req.query.filters || []) : [req.query.filters]; | 	const filterBy = Array.isArray(req.query.filters || []) ? (req.query.filters || []) : [req.query.filters]; | ||||||
| 	filterBy.forEach(function (filter) { | 	filterBy.forEach((filter) => { | ||||||
| 		data[`filterBy_${validator.escape(String(filter))}`] = true; | 		data[`filterBy_${validator.escape(String(filter))}`] = true; | ||||||
| 	}); | 	}); | ||||||
| 	data.userCount = parseInt(await db.getObjectField('global', 'userCount'), 10); | 	data.userCount = parseInt(await db.getObjectField('global', 'userCount'), 10); | ||||||
| @@ -265,7 +263,7 @@ usersController.getCSV = async function (req, res, next) { | |||||||
| 			'Content-Type': 'text/csv', | 			'Content-Type': 'text/csv', | ||||||
| 			'Content-Disposition': 'attachment; filename=users.csv', | 			'Content-Disposition': 'attachment; filename=users.csv', | ||||||
| 		}, | 		}, | ||||||
| 	}, function (err) { | 	}, (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			if (err.code === 'ENOENT') { | 			if (err.code === 'ENOENT') { | ||||||
| 				res.locals.isAPI = false; | 				res.locals.isAPI = false; | ||||||
|   | |||||||
| @@ -142,7 +142,7 @@ authenticationController.registerComplete = function (req, res, next) { | |||||||
| 			return next(err); | 			return next(err); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		var callbacks = data.interstitials.reduce(function (memo, cur) { | 		var callbacks = data.interstitials.reduce((memo, cur) => { | ||||||
| 			if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') { | 			if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') { | ||||||
| 				req.body.files = req.files; | 				req.body.files = req.files; | ||||||
| 				memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback)); | 				memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback)); | ||||||
| @@ -201,7 +201,7 @@ authenticationController.registerComplete = function (req, res, next) { | |||||||
|  |  | ||||||
| authenticationController.registerAbort = function (req, res) { | authenticationController.registerAbort = function (req, res) { | ||||||
| 	// End the session and redirect to home | 	// End the session and redirect to home | ||||||
| 	req.session.destroy(function () { | 	req.session.destroy(() => { | ||||||
| 		res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get()); | 		res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get()); | ||||||
| 		res.redirect(`${nconf.get('relative_path')}/`); | 		res.redirect(`${nconf.get('relative_path')}/`); | ||||||
| 	}); | 	}); | ||||||
| @@ -248,7 +248,7 @@ authenticationController.login = async (req, res, next) => { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| function continueLogin(strategy, req, res, next) { | function continueLogin(strategy, req, res, next) { | ||||||
| 	passport.authenticate(strategy, async function (err, userData, info) { | 	passport.authenticate(strategy, async (err, userData, info) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			return helpers.noScriptErrors(req, res, err.message, 403); | 			return helpers.noScriptErrors(req, res, err.message, 403); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -41,7 +41,7 @@ categoriesController.list = async function (req, res) { | |||||||
| 		pagination: pagination.create(page, pageCount, req.query), | 		pagination: pagination.create(page, pageCount, req.query), | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	data.categories.forEach(function (category) { | 	data.categories.forEach((category) => { | ||||||
| 		if (category) { | 		if (category) { | ||||||
| 			helpers.trimChildren(category); | 			helpers.trimChildren(category); | ||||||
| 			helpers.setCategoryTeaser(category); | 			helpers.setCategoryTeaser(category); | ||||||
|   | |||||||
| @@ -104,7 +104,7 @@ categoryController.get = async function (req, res, next) { | |||||||
| 		categoryData.hasMoreSubCategories = categoryData.children.length > categoryData.subCategoriesPerPage; | 		categoryData.hasMoreSubCategories = categoryData.children.length > categoryData.subCategoriesPerPage; | ||||||
| 		categoryData.nextSubCategoryStart = categoryData.subCategoriesPerPage; | 		categoryData.nextSubCategoryStart = categoryData.subCategoriesPerPage; | ||||||
| 		categoryData.children = categoryData.children.slice(0, categoryData.subCategoriesPerPage); | 		categoryData.children = categoryData.children.slice(0, categoryData.subCategoriesPerPage); | ||||||
| 		categoryData.children.forEach(function (child) { | 		categoryData.children.forEach((child) => { | ||||||
| 			if (child) { | 			if (child) { | ||||||
| 				helpers.trimChildren(child); | 				helpers.trimChildren(child); | ||||||
| 				helpers.setCategoryTeaser(child); | 				helpers.setCategoryTeaser(child); | ||||||
| @@ -130,7 +130,7 @@ categoryController.get = async function (req, res, next) { | |||||||
| 	categoryData['feeds:disableRSS'] = meta.config['feeds:disableRSS'] || 0; | 	categoryData['feeds:disableRSS'] = meta.config['feeds:disableRSS'] || 0; | ||||||
| 	categoryData['reputation:disabled'] = meta.config['reputation:disabled']; | 	categoryData['reputation:disabled'] = meta.config['reputation:disabled']; | ||||||
| 	categoryData.pagination = pagination.create(currentPage, pageCount, req.query); | 	categoryData.pagination = pagination.create(currentPage, pageCount, req.query); | ||||||
| 	categoryData.pagination.rel.forEach(function (rel) { | 	categoryData.pagination.rel.forEach((rel) => { | ||||||
| 		rel.href = `${url}/category/${categoryData.slug}${rel.href}`; | 		rel.href = `${url}/category/${categoryData.slug}${rel.href}`; | ||||||
| 		res.locals.linkTags.push(rel); | 		res.locals.linkTags.push(rel); | ||||||
| 	}); | 	}); | ||||||
|   | |||||||
| @@ -67,7 +67,7 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di | |||||||
|  |  | ||||||
| 	plugins.hooks.fire('filter:error.handle', { | 	plugins.hooks.fire('filter:error.handle', { | ||||||
| 		cases: cases, | 		cases: cases, | ||||||
| 	}, function (_err, data) { | 	}, (_err, data) => { | ||||||
| 		if (_err) { | 		if (_err) { | ||||||
| 			// Assume defaults | 			// Assume defaults | ||||||
| 			winston.warn(`[errors/handle] Unable to retrieve plugin handlers for errors: ${_err.message}`); | 			winston.warn(`[errors/handle] Unable to retrieve plugin handlers for errors: ${_err.message}`); | ||||||
|   | |||||||
| @@ -58,7 +58,7 @@ helpers.addLinkTags = function (params) { | |||||||
| 		href: `${url}/${params.url}`, | 		href: `${url}/${params.url}`, | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	params.tags.forEach(function (rel) { | 	params.tags.forEach((rel) => { | ||||||
| 		rel.href = `${url}/${params.url}${rel.href}`; | 		rel.href = `${url}/${params.url}${rel.href}`; | ||||||
| 		params.res.locals.linkTags.push(rel); | 		params.res.locals.linkTags.push(rel); | ||||||
| 	}); | 	}); | ||||||
| @@ -208,7 +208,7 @@ helpers.buildBreadcrumbs = function (crumbs) { | |||||||
| 		}, | 		}, | ||||||
| 	]; | 	]; | ||||||
|  |  | ||||||
| 	crumbs.forEach(function (crumb) { | 	crumbs.forEach((crumb) => { | ||||||
| 		if (crumb) { | 		if (crumb) { | ||||||
| 			if (crumb.url) { | 			if (crumb.url) { | ||||||
| 				crumb.url = relative_path + crumb.url; | 				crumb.url = relative_path + crumb.url; | ||||||
| @@ -253,7 +253,7 @@ async function getCategoryData(cids, uid, selectedCid, states, privilege) { | |||||||
|  |  | ||||||
| 	let selectedCategory = []; | 	let selectedCategory = []; | ||||||
| 	const selectedCids = []; | 	const selectedCids = []; | ||||||
| 	categoriesData.forEach(function (category) { | 	categoriesData.forEach((category) => { | ||||||
| 		category.selected = selectedCid ? selectedCid.includes(String(category.cid)) : false; | 		category.selected = selectedCid ? selectedCid.includes(String(category.cid)) : false; | ||||||
| 		if (category.selected) { | 		if (category.selected) { | ||||||
| 			selectedCategory.push(category); | 			selectedCategory.push(category); | ||||||
| @@ -312,7 +312,7 @@ helpers.getVisibleCategories = async function (params) { | |||||||
| 	const cidToCategory = _.zipObject(cids, categoriesData); | 	const cidToCategory = _.zipObject(cids, categoriesData); | ||||||
| 	const cidToWatchState = _.zipObject(cids, watchState); | 	const cidToWatchState = _.zipObject(cids, watchState); | ||||||
|  |  | ||||||
| 	return categoriesData.filter(function (c) { | 	return categoriesData.filter((c) => { | ||||||
| 		if (!c) { | 		if (!c) { | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
| @@ -360,7 +360,7 @@ helpers.getSelectedCategory = async function (cid) { | |||||||
| helpers.trimChildren = function (category) { | helpers.trimChildren = function (category) { | ||||||
| 	if (Array.isArray(category.children)) { | 	if (Array.isArray(category.children)) { | ||||||
| 		category.children = category.children.slice(0, category.subCategoriesPerPage); | 		category.children = category.children.slice(0, category.subCategoriesPerPage); | ||||||
| 		category.children.forEach(function (child) { | 		category.children.forEach((child) => { | ||||||
| 			child.children = undefined; | 			child.children = undefined; | ||||||
| 		}); | 		}); | ||||||
| 	} | 	} | ||||||
|   | |||||||
| @@ -216,7 +216,7 @@ Controllers.registerInterstitial = async function (req, res, next) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| Controllers.confirmEmail = function (req, res) { | Controllers.confirmEmail = function (req, res) { | ||||||
| 	user.email.confirmByCode(req.params.code, function (err) { | 	user.email.confirmByCode(req.params.code, (err) => { | ||||||
| 		res.render('confirm', { | 		res.render('confirm', { | ||||||
| 			error: err ? err.message : '', | 			error: err ? err.message : '', | ||||||
| 			title: '[[pages:confirm]]', | 			title: '[[pages:confirm]]', | ||||||
|   | |||||||
| @@ -39,7 +39,7 @@ modsController.flags.list = async function (req, res, next) { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// Parse query string params for filters, eliminate non-valid filters | 	// Parse query string params for filters, eliminate non-valid filters | ||||||
| 	filters = filters.reduce(function (memo, cur) { | 	filters = filters.reduce((memo, cur) => { | ||||||
| 		if (req.query.hasOwnProperty(cur)) { | 		if (req.query.hasOwnProperty(cur)) { | ||||||
| 			if (req.query[cur] !== '') { | 			if (req.query[cur] !== '') { | ||||||
| 				memo[cur] = req.query[cur]; | 				memo[cur] = req.query[cur]; | ||||||
| @@ -129,7 +129,7 @@ modsController.flags.detail = async function (req, res, next) { | |||||||
|  |  | ||||||
| 	res.render('flags/detail', Object.assign(results.flagData, { | 	res.render('flags/detail', Object.assign(results.flagData, { | ||||||
| 		assignees: results.assignees, | 		assignees: results.assignees, | ||||||
| 		type_bool: ['post', 'user', 'empty'].reduce(function (memo, cur) { | 		type_bool: ['post', 'user', 'empty'].reduce((memo, cur) => { | ||||||
| 			if (cur !== 'empty') { | 			if (cur !== 'empty') { | ||||||
| 				memo[cur] = results.flagData.type === cur && (!results.flagData.target || !!Object.keys(results.flagData.target).length); | 				memo[cur] = results.flagData.type === cur && (!results.flagData.target || !!Object.keys(results.flagData.target).length); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -196,7 +196,7 @@ modsController.postQueue = async function (req, res, next) { | |||||||
| async function getQueuedPosts(ids) { | async function getQueuedPosts(ids) { | ||||||
| 	const keys = ids.map(id => `post:queue:${id}`); | 	const keys = ids.map(id => `post:queue:${id}`); | ||||||
| 	const postData = await db.getObjects(keys); | 	const postData = await db.getObjects(keys); | ||||||
| 	postData.forEach(function (data) { | 	postData.forEach((data) => { | ||||||
| 		if (data) { | 		if (data) { | ||||||
| 			data.data = JSON.parse(data.data); | 			data.data = JSON.parse(data.data); | ||||||
| 			data.data.timestampISO = utils.toISOString(data.data.timestamp); | 			data.data.timestampISO = utils.toISOString(data.data.timestamp); | ||||||
| @@ -204,7 +204,7 @@ async function getQueuedPosts(ids) { | |||||||
| 	}); | 	}); | ||||||
| 	const uids = postData.map(data => data && data.uid); | 	const uids = postData.map(data => data && data.uid); | ||||||
| 	const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); | 	const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); | ||||||
| 	postData.forEach(function (postData, index) { | 	postData.forEach((postData, index) => { | ||||||
| 		if (postData) { | 		if (postData) { | ||||||
| 			postData.user = userData[index]; | 			postData.user = userData[index]; | ||||||
| 			postData.data.rawContent = validator.escape(String(postData.data.content)); | 			postData.data.rawContent = validator.escape(String(postData.data.content)); | ||||||
|   | |||||||
| @@ -24,9 +24,7 @@ sitemapController.getCategories = function (req, res, next) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| sitemapController.getTopicPage = function (req, res, next) { | sitemapController.getTopicPage = function (req, res, next) { | ||||||
| 	sendSitemap(async function () { | 	sendSitemap(async () => await sitemap.getTopicPage(parseInt(req.params[0], 10)), res, next); | ||||||
| 		return await sitemap.getTopicPage(parseInt(req.params[0], 10)); |  | ||||||
| 	}, res, next); |  | ||||||
| }; | }; | ||||||
|  |  | ||||||
| async function sendSitemap(method, res, callback) { | async function sendSitemap(method, res, callback) { | ||||||
|   | |||||||
| @@ -102,7 +102,7 @@ topicsController.get = async function getTopic(req, res, callback) { | |||||||
| 	]); | 	]); | ||||||
|  |  | ||||||
| 	topicData.pagination = pagination.create(currentPage, pageCount, req.query); | 	topicData.pagination = pagination.create(currentPage, pageCount, req.query); | ||||||
| 	topicData.pagination.rel.forEach(function (rel) { | 	topicData.pagination.rel.forEach((rel) => { | ||||||
| 		rel.href = `${url}/topic/${topicData.slug}${rel.href}`; | 		rel.href = `${url}/topic/${topicData.slug}${rel.href}`; | ||||||
| 		res.locals.linkTags.push(rel); | 		res.locals.linkTags.push(rel); | ||||||
| 	}); | 	}); | ||||||
| @@ -344,7 +344,7 @@ topicsController.pagination = async function (req, res, callback) { | |||||||
| 	const pageCount = Math.max(1, Math.ceil(postCount / settings.postsPerPage)); | 	const pageCount = Math.max(1, Math.ceil(postCount / settings.postsPerPage)); | ||||||
|  |  | ||||||
| 	const paginationData = pagination.create(currentPage, pageCount); | 	const paginationData = pagination.create(currentPage, pageCount); | ||||||
| 	paginationData.rel.forEach(function (rel) { | 	paginationData.rel.forEach((rel) => { | ||||||
| 		rel.href = `${url}/topic/${topic.slug}${rel.href}`; | 		rel.href = `${url}/topic/${topic.slug}${rel.href}`; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -49,7 +49,7 @@ uploadsController.upload = async function (req, res, filesIterator) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| uploadsController.uploadPost = async function (req, res) { | uploadsController.uploadPost = async function (req, res) { | ||||||
| 	await uploadsController.upload(req, res, async function (uploadedFile) { | 	await uploadsController.upload(req, res, async (uploadedFile) => { | ||||||
| 		const isImage = uploadedFile.type.match(/image./); | 		const isImage = uploadedFile.type.match(/image./); | ||||||
| 		if (isImage) { | 		if (isImage) { | ||||||
| 			return await uploadAsImage(req, uploadedFile); | 			return await uploadAsImage(req, uploadedFile); | ||||||
| @@ -123,7 +123,7 @@ uploadsController.uploadThumb = async function (req, res) { | |||||||
| 		return helpers.formatApiResponse(503, res, new Error('[[error:topic-thumbnails-are-disabled]]')); | 		return helpers.formatApiResponse(503, res, new Error('[[error:topic-thumbnails-are-disabled]]')); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return await uploadsController.upload(req, res, async function (uploadedFile) { | 	return await uploadsController.upload(req, res, async (uploadedFile) => { | ||||||
| 		if (!uploadedFile.type.match(/image./)) { | 		if (!uploadedFile.type.match(/image./)) { | ||||||
| 			throw new Error('[[error:invalid-file]]'); | 			throw new Error('[[error:invalid-file]]'); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -95,7 +95,7 @@ function sendExport(filename, type, res, next) { | |||||||
| 			'Content-Type': type, | 			'Content-Type': type, | ||||||
| 			'Content-Disposition': `attachment; filename=${filename}`, | 			'Content-Disposition': `attachment; filename=${filename}`, | ||||||
| 		}, | 		}, | ||||||
| 	}, function (err) { | 	}, (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			if (err.code === 'ENOENT') { | 			if (err.code === 'ENOENT') { | ||||||
| 				res.locals.isAPI = false; | 				res.locals.isAPI = false; | ||||||
|   | |||||||
| @@ -50,7 +50,7 @@ usersController.getOnlineUsers = async function (req, res) { | |||||||
|  |  | ||||||
| 	let hiddenCount = 0; | 	let hiddenCount = 0; | ||||||
| 	if (!userData.isAdminOrGlobalMod) { | 	if (!userData.isAdminOrGlobalMod) { | ||||||
| 		userData.users = userData.users.filter(function (user) { | 		userData.users = userData.users.filter((user) => { | ||||||
| 			if (user && user.status === 'offline') { | 			if (user && user.status === 'offline') { | ||||||
| 				hiddenCount += 1; | 				hiddenCount += 1; | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -152,7 +152,7 @@ Topics.migrateThumbs = async (req, res) => { | |||||||
|  |  | ||||||
| Topics.deleteThumb = async (req, res) => { | Topics.deleteThumb = async (req, res) => { | ||||||
| 	if (!req.body.path.startsWith('http')) { | 	if (!req.body.path.startsWith('http')) { | ||||||
| 		await middleware.assert.path(req, res, function () {}); | 		await middleware.assert.path(req, res, () => {}); | ||||||
| 		if (res.headersSent) { | 		if (res.headersSent) { | ||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -136,7 +136,7 @@ Users.deleteToken = async (req, res) => { | |||||||
| 	} | 	} | ||||||
| }; | }; | ||||||
|  |  | ||||||
| const getSessionAsync = util.promisify(function (sid, callback) { | const getSessionAsync = util.promisify((sid, callback) => { | ||||||
| 	db.sessionStore.get(sid, (err, sessionObj) => callback(err, sessionObj || null)); | 	db.sessionStore.get(sid, (err, sessionObj) => callback(err, sessionObj || null)); | ||||||
| }); | }); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -135,8 +135,7 @@ mongoModule.info = async function (db) { | |||||||
| 	stats.serverStatusError = serverStatusError; | 	stats.serverStatusError = serverStatusError; | ||||||
| 	const scale = 1024 * 1024 * 1024; | 	const scale = 1024 * 1024 * 1024; | ||||||
|  |  | ||||||
| 	listCollections = listCollections.map(function (collectionInfo) { | 	listCollections = listCollections.map(collectionInfo => ({ | ||||||
| 		return { |  | ||||||
| 		name: collectionInfo.ns, | 		name: collectionInfo.ns, | ||||||
| 		count: collectionInfo.count, | 		count: collectionInfo.count, | ||||||
| 		size: collectionInfo.size, | 		size: collectionInfo.size, | ||||||
| @@ -144,8 +143,7 @@ mongoModule.info = async function (db) { | |||||||
| 		storageSize: collectionInfo.storageSize, | 		storageSize: collectionInfo.storageSize, | ||||||
| 		totalIndexSize: collectionInfo.totalIndexSize, | 		totalIndexSize: collectionInfo.totalIndexSize, | ||||||
| 		indexSizes: collectionInfo.indexSizes, | 		indexSizes: collectionInfo.indexSizes, | ||||||
| 		}; | 	})); | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	stats.mem = serverStatus.mem || { resident: 0, virtual: 0, mapped: 0 }; | 	stats.mem = serverStatus.mem || { resident: 0, virtual: 0, mapped: 0 }; | ||||||
| 	stats.mem.resident = (stats.mem.resident / 1024).toFixed(3); | 	stats.mem.resident = (stats.mem.resident / 1024).toFixed(3); | ||||||
|   | |||||||
| @@ -115,7 +115,7 @@ module.exports = function (module) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const map = helpers.toMap(data); | 		const map = helpers.toMap(data); | ||||||
| 		unCachedKeys.forEach(function (key) { | 		unCachedKeys.forEach((key) => { | ||||||
| 			cachedData[key] = map[key] || null; | 			cachedData[key] = map[key] || null; | ||||||
| 			cache.set(key, cachedData[key]); | 			cache.set(key, cachedData[key]); | ||||||
| 		}); | 		}); | ||||||
| @@ -123,7 +123,7 @@ module.exports = function (module) { | |||||||
| 		if (!fields.length) { | 		if (!fields.length) { | ||||||
| 			return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); | 			return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); | ||||||
| 		} | 		} | ||||||
| 		return keys.map(function (key) { | 		return keys.map((key) => { | ||||||
| 			const item = cachedData[key] || {}; | 			const item = cachedData[key] || {}; | ||||||
| 			const result = {}; | 			const result = {}; | ||||||
| 			fields.forEach((field) => { | 			fields.forEach((field) => { | ||||||
| @@ -154,7 +154,7 @@ module.exports = function (module) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const data = {}; | 		const data = {}; | ||||||
| 		fields.forEach(function (field) { | 		fields.forEach((field) => { | ||||||
| 			field = helpers.fieldToString(field); | 			field = helpers.fieldToString(field); | ||||||
| 			data[field] = 1; | 			data[field] = 1; | ||||||
| 		}); | 		}); | ||||||
| @@ -178,7 +178,7 @@ module.exports = function (module) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		var data = {}; | 		var data = {}; | ||||||
| 		fields.forEach(function (field) { | 		fields.forEach((field) => { | ||||||
| 			field = helpers.fieldToString(field); | 			field = helpers.fieldToString(field); | ||||||
| 			data[field] = ''; | 			data[field] = ''; | ||||||
| 		}); | 		}); | ||||||
| @@ -211,7 +211,7 @@ module.exports = function (module) { | |||||||
|  |  | ||||||
| 		if (Array.isArray(key)) { | 		if (Array.isArray(key)) { | ||||||
| 			var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); | 			var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); | ||||||
| 			key.forEach(function (key) { | 			key.forEach((key) => { | ||||||
| 				bulk.find({ _key: key }).upsert().update({ $inc: increment }); | 				bulk.find({ _key: key }).upsert().update({ $inc: increment }); | ||||||
| 			}); | 			}); | ||||||
| 			await bulk.execute(); | 			await bulk.execute(); | ||||||
|   | |||||||
| @@ -22,7 +22,7 @@ module.exports = function (module) { | |||||||
| 			}, { _id: 0, _key: 1 }).toArray(); | 			}, { _id: 0, _key: 1 }).toArray(); | ||||||
|  |  | ||||||
| 			const map = {}; | 			const map = {}; | ||||||
| 			data.forEach(function (item) { | 			data.forEach((item) => { | ||||||
| 				map[item._key] = true; | 				map[item._key] = true; | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -104,7 +104,7 @@ module.exports = function (module) { | |||||||
| 		const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray(); | 		const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray(); | ||||||
|  |  | ||||||
| 		var map = {}; | 		var map = {}; | ||||||
| 		result.forEach(function (item) { | 		result.forEach((item) => { | ||||||
| 			map[item._key] = true; | 			map[item._key] = true; | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| @@ -127,7 +127,7 @@ module.exports = function (module) { | |||||||
| 		const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray(); | 		const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray(); | ||||||
|  |  | ||||||
| 		var sets = {}; | 		var sets = {}; | ||||||
| 		data.forEach(function (set) { | 		data.forEach((set) => { | ||||||
| 			sets[set._key] = set.members || []; | 			sets[set._key] = set.members || []; | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -247,7 +247,7 @@ module.exports = function (module) { | |||||||
| 			return [await getSortedSetRank(reverse, key, values[0])]; | 			return [await getSortedSetRank(reverse, key, values[0])]; | ||||||
| 		} | 		} | ||||||
| 		const sortedSet = await module[reverse ? 'getSortedSetRevRange' : 'getSortedSetRange'](key, 0, -1); | 		const sortedSet = await module[reverse ? 'getSortedSetRevRange' : 'getSortedSetRange'](key, 0, -1); | ||||||
| 		return values.map(function (value) { | 		return values.map((value) => { | ||||||
| 			if (!value) { | 			if (!value) { | ||||||
| 				return null; | 				return null; | ||||||
| 			} | 			} | ||||||
| @@ -272,7 +272,7 @@ module.exports = function (module) { | |||||||
| 		value = helpers.valueToString(value); | 		value = helpers.valueToString(value); | ||||||
| 		const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray(); | 		const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray(); | ||||||
| 		var map = {}; | 		var map = {}; | ||||||
| 		result.forEach(function (item) { | 		result.forEach((item) => { | ||||||
| 			if (item) { | 			if (item) { | ||||||
| 				map[item._key] = item; | 				map[item._key] = item; | ||||||
| 			} | 			} | ||||||
| @@ -292,7 +292,7 @@ module.exports = function (module) { | |||||||
| 		const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray(); | 		const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray(); | ||||||
|  |  | ||||||
| 		var valueToScore = {}; | 		var valueToScore = {}; | ||||||
| 		result.forEach(function (item) { | 		result.forEach((item) => { | ||||||
| 			if (item) { | 			if (item) { | ||||||
| 				valueToScore[item.value] = item.score; | 				valueToScore[item.value] = item.score; | ||||||
| 			} | 			} | ||||||
| @@ -329,7 +329,7 @@ module.exports = function (module) { | |||||||
| 		}).toArray(); | 		}).toArray(); | ||||||
|  |  | ||||||
| 		var isMember = {}; | 		var isMember = {}; | ||||||
| 		results.forEach(function (item) { | 		results.forEach((item) => { | ||||||
| 			if (item) { | 			if (item) { | ||||||
| 				isMember[item.value] = true; | 				isMember[item.value] = true; | ||||||
| 			} | 			} | ||||||
| @@ -350,7 +350,7 @@ module.exports = function (module) { | |||||||
| 		}).toArray(); | 		}).toArray(); | ||||||
|  |  | ||||||
| 		var isMember = {}; | 		var isMember = {}; | ||||||
| 		results.forEach(function (item) { | 		results.forEach((item) => { | ||||||
| 			if (item) { | 			if (item) { | ||||||
| 				isMember[item._key] = true; | 				isMember[item._key] = true; | ||||||
| 			} | 			} | ||||||
| @@ -381,7 +381,7 @@ module.exports = function (module) { | |||||||
| 			return [data.map(item => item.value)]; | 			return [data.map(item => item.value)]; | ||||||
| 		} | 		} | ||||||
| 		const sets = {}; | 		const sets = {}; | ||||||
| 		data.forEach(function (item) { | 		data.forEach((item) => { | ||||||
| 			sets[item._key] = sets[item._key] || []; | 			sets[item._key] = sets[item._key] || []; | ||||||
| 			sets[item._key].push(item.value); | 			sets[item._key].push(item.value); | ||||||
| 		}); | 		}); | ||||||
|   | |||||||
| @@ -75,7 +75,7 @@ module.exports = function (module) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 		var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); | 		var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); | ||||||
| 		data.forEach(function (item) { | 		data.forEach((item) => { | ||||||
| 			if (!utils.isNumber(item[1])) { | 			if (!utils.isNumber(item[1])) { | ||||||
| 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -140,7 +140,7 @@ module.exports = function (module) { | |||||||
| 				items.push(nextItem); | 				items.push(nextItem); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			const members = await Promise.all(otherSets.map(async function (s) { | 			const members = await Promise.all(otherSets.map(async (s) => { | ||||||
| 				const data = await module.client.collection('objects').find({ | 				const data = await module.client.collection('objects').find({ | ||||||
| 					_key: s, value: { $in: items.map(i => i.value) }, | 					_key: s, value: { $in: items.map(i => i.value) }, | ||||||
| 				}, { | 				}, { | ||||||
| @@ -170,7 +170,7 @@ module.exports = function (module) { | |||||||
| 		} | 		} | ||||||
| 		const pipeline = [{ $match: { _key: { $in: params.sets } } }]; | 		const pipeline = [{ $match: { _key: { $in: params.sets } } }]; | ||||||
|  |  | ||||||
| 		params.weights.forEach(function (weight, index) { | 		params.weights.forEach((weight, index) => { | ||||||
| 			if (weight !== 1) { | 			if (weight !== 1) { | ||||||
| 				pipeline.push({ | 				pipeline.push({ | ||||||
| 					$project: { | 					$project: { | ||||||
|   | |||||||
| @@ -337,7 +337,7 @@ postgresModule.createIndices = function (callback) { | |||||||
| 	async.series([ | 	async.series([ | ||||||
| 		async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_zset__key__score" ON "legacy_zset"("_key" ASC, "score" DESC)`), | 		async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_zset__key__score" ON "legacy_zset"("_key" ASC, "score" DESC)`), | ||||||
| 		async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_object__expireAt" ON "legacy_object"("expireAt" ASC)`), | 		async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_object__expireAt" ON "legacy_object"("expireAt" ASC)`), | ||||||
| 	], function (err) { | 	], (err) => { | ||||||
| 		if (err) { | 		if (err) { | ||||||
| 			winston.error(`Error creating index ${err.message}`); | 			winston.error(`Error creating index ${err.message}`); | ||||||
| 			return callback(err); | 			return callback(err); | ||||||
|   | |||||||
| @@ -12,7 +12,7 @@ module.exports = function (module) { | |||||||
| 			delete data['']; | 			delete data['']; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			const dataString = JSON.stringify(data); | 			const dataString = JSON.stringify(data); | ||||||
| 			async function setOne(key) { | 			async function setOne(key) { | ||||||
| 				await helpers.ensureLegacyObjectType(client, key, 'hash'); | 				await helpers.ensureLegacyObjectType(client, key, 'hash'); | ||||||
| @@ -47,7 +47,7 @@ module.exports = function (module) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			const valueString = JSON.stringify(value); | 			const valueString = JSON.stringify(value); | ||||||
| 			async function setOne(key) { | 			async function setOne(key) { | ||||||
| 				await helpers.ensureLegacyObjectType(client, key, 'hash'); | 				await helpers.ensureLegacyObjectType(client, key, 'hash'); | ||||||
| @@ -159,7 +159,7 @@ SELECT (SELECT jsonb_object_agg(f, d."value") | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		var obj = {}; | 		var obj = {}; | ||||||
| 		fields.forEach(function (f) { | 		fields.forEach((f) => { | ||||||
| 			obj[f] = null; | 			obj[f] = null; | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| @@ -292,7 +292,7 @@ SELECT (h."data" ? $2::TEXT AND h."data"->>$2::TEXT IS NOT NULL) b | |||||||
| 			return null; | 			return null; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return await module.transaction(async function (client) { | 		return await module.transaction(async (client) => { | ||||||
| 			if (Array.isArray(key)) { | 			if (Array.isArray(key)) { | ||||||
| 				await helpers.ensureLegacyObjectsType(client, key, 'hash'); | 				await helpers.ensureLegacyObjectsType(client, key, 'hash'); | ||||||
| 			} else { | 			} else { | ||||||
|   | |||||||
| @@ -88,9 +88,7 @@ SELECT "_key", "type" | |||||||
| 		throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`); | 		throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	var missing = keys.filter(function (k) { | 	var missing = keys.filter(k => !res.rows.some(r => r._key === k)); | ||||||
| 		return !res.rows.some(r => r._key === k); |  | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	if (missing.length) { | 	if (missing.length) { | ||||||
| 		throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`); | 		throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`); | ||||||
|   | |||||||
| @@ -8,7 +8,7 @@ module.exports = function (module) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'list'); | 			await helpers.ensureLegacyObjectType(client, key, 'list'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'listPrepend', | 				name: 'listPrepend', | ||||||
| @@ -27,7 +27,7 @@ DO UPDATE SET "array" = ARRAY[$2::TEXT] || "legacy_list"."array"`, | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'list'); | 			await helpers.ensureLegacyObjectType(client, key, 'list'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'listAppend', | 				name: 'listAppend', | ||||||
|   | |||||||
| @@ -26,9 +26,7 @@ module.exports = function (module) { | |||||||
|  				WHERE o."_key" = ANY($1::TEXT[])`, |  				WHERE o."_key" = ANY($1::TEXT[])`, | ||||||
| 				values: [key], | 				values: [key], | ||||||
| 			}); | 			}); | ||||||
| 			return key.map(function (k) { | 			return key.map(k => res.rows.some(r => r.k === k)); | ||||||
| 				return res.rows.some(r => r.k === k); |  | ||||||
| 			}); |  | ||||||
| 		} | 		} | ||||||
| 		const res =	await module.pool.query({ | 		const res =	await module.pool.query({ | ||||||
| 			name: 'exists', | 			name: 'exists', | ||||||
| @@ -115,7 +113,7 @@ SELECT s."data" t | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'string'); | 			await helpers.ensureLegacyObjectType(client, key, 'string'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'set', | 				name: 'set', | ||||||
| @@ -134,7 +132,7 @@ DO UPDATE SET "data" = $2::TEXT`, | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return await module.transaction(async function (client) { | 		return await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'string'); | 			await helpers.ensureLegacyObjectType(client, key, 'string'); | ||||||
| 			const res = await client.query({ | 			const res = await client.query({ | ||||||
| 				name: 'increment', | 				name: 'increment', | ||||||
| @@ -151,7 +149,7 @@ RETURNING "data" d`, | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.rename = async function (oldKey, newKey) { | 	module.rename = async function (oldKey, newKey) { | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'deleteRename', | 				name: 'deleteRename', | ||||||
| 				text: ` | 				text: ` | ||||||
|   | |||||||
| @@ -12,7 +12,7 @@ module.exports = function (module) { | |||||||
| 		if (!value.length) { | 		if (!value.length) { | ||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'set'); | 			await helpers.ensureLegacyObjectType(client, key, 'set'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'setAdd', | 				name: 'setAdd', | ||||||
| @@ -38,7 +38,7 @@ DO NOTHING`, | |||||||
|  |  | ||||||
| 		keys = _.uniq(keys); | 		keys = _.uniq(keys); | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectsType(client, keys, 'set'); | 			await helpers.ensureLegacyObjectsType(client, keys, 'set'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'setsAdd', | 				name: 'setsAdd', | ||||||
| @@ -129,9 +129,7 @@ SELECT s."member" m | |||||||
| 			values: [key, values], | 			values: [key, values], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return values.map(function (v) { | 		return values.map(v => res.rows.some(r => r.m === v)); | ||||||
| 			return res.rows.some(r => r.m === v); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.isMemberOfSets = async function (sets, value) { | 	module.isMemberOfSets = async function (sets, value) { | ||||||
| @@ -154,9 +152,7 @@ SELECT o."_key" k | |||||||
| 			values: [sets, value], | 			values: [sets, value], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return sets.map(function (s) { | 		return sets.map(s => res.rows.some(r => r.k === s)); | ||||||
| 			return res.rows.some(r => r.k === s); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.getSetMembers = async function (key) { | 	module.getSetMembers = async function (key) { | ||||||
| @@ -198,9 +194,7 @@ SELECT o."_key" k, | |||||||
| 			values: [keys], | 			values: [keys], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map(k => (res.rows.find(r => r.k === k) || { m: [] }).m); | ||||||
| 			return (res.rows.find(r => r.k === k) || { m: [] }).m; |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.setCount = async function (key) { | 	module.setCount = async function (key) { | ||||||
| @@ -238,9 +232,7 @@ SELECT o."_key" k, | |||||||
| 			values: [keys], | 			values: [keys], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map(k => (res.rows.find(r => r.k === k) || { c: 0 }).c); | ||||||
| 			return (res.rows.find(r => r.k === k) || { c: 0 }).c; |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.setRemoveRandom = async function (key) { | 	module.setRemoveRandom = async function (key) { | ||||||
|   | |||||||
| @@ -218,9 +218,7 @@ SELECT o."_key" k, | |||||||
| 			values: [keys], | 			values: [keys], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map(k => parseInt((res.rows.find(r => r.k === k) || { c: 0 }).c, 10)); | ||||||
| 			return parseInt((res.rows.find(r => r.k === k) || { c: 0 }).c, 10); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.sortedSetsCardSum = async function (keys) { | 	module.sortedSetsCardSum = async function (keys) { | ||||||
| @@ -347,7 +345,7 @@ SELECT o."_key" k, | |||||||
| 			values: [keys, value], | 			values: [keys, value], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map((k) => { | ||||||
| 			var s = res.rows.find(r => r.k === k); | 			var s = res.rows.find(r => r.k === k); | ||||||
| 			return s ? parseFloat(s.s) : null; | 			return s ? parseFloat(s.s) : null; | ||||||
| 		}); | 		}); | ||||||
| @@ -376,7 +374,7 @@ SELECT z."value" v, | |||||||
| 			values: [key, values], | 			values: [key, values], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return values.map(function (v) { | 		return values.map((v) => { | ||||||
| 			var s = res.rows.find(r => r.v === v); | 			var s = res.rows.find(r => r.v === v); | ||||||
| 			return s ? parseFloat(s.s) : null; | 			return s ? parseFloat(s.s) : null; | ||||||
| 		}); | 		}); | ||||||
| @@ -428,9 +426,7 @@ SELECT z."value" v | |||||||
| 			values: [key, values], | 			values: [key, values], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return values.map(function (v) { | 		return values.map(v => res.rows.some(r => r.v === v)); | ||||||
| 			return res.rows.some(r => r.v === v); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.isMemberOfSortedSets = async function (keys, value) { | 	module.isMemberOfSortedSets = async function (keys, value) { | ||||||
| @@ -453,9 +449,7 @@ SELECT o."_key" k | |||||||
| 			values: [keys, value], | 			values: [keys, value], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map(k => res.rows.some(r => r.k === k)); | ||||||
| 			return res.rows.some(r => r.k === k); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.getSortedSetMembers = async function (key) { | 	module.getSortedSetMembers = async function (key) { | ||||||
| @@ -477,9 +471,7 @@ SELECT "_key" k, | |||||||
| 			values: [keys], | 			values: [keys], | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		return keys.map(function (k) { | 		return keys.map(k => (res.rows.find(r => r.k === k) || {}).m || []); | ||||||
| 			return (res.rows.find(r => r.k === k) || {}).m || []; |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	module.sortedSetIncrBy = async function (key, increment, value) { | 	module.sortedSetIncrBy = async function (key, increment, value) { | ||||||
| @@ -490,7 +482,7 @@ SELECT "_key" k, | |||||||
| 		value = helpers.valueToString(value); | 		value = helpers.valueToString(value); | ||||||
| 		increment = parseFloat(increment); | 		increment = parseFloat(increment); | ||||||
|  |  | ||||||
| 		return await module.transaction(async function (client) { | 		return await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | ||||||
| 			const res = await client.query({ | 			const res = await client.query({ | ||||||
| 				name: 'sortedSetIncrBy', | 				name: 'sortedSetIncrBy', | ||||||
|   | |||||||
| @@ -18,7 +18,7 @@ module.exports = function (module) { | |||||||
| 		value = helpers.valueToString(value); | 		value = helpers.valueToString(value); | ||||||
| 		score = parseFloat(score); | 		score = parseFloat(score); | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'sortedSetAdd', | 				name: 'sortedSetAdd', | ||||||
| @@ -49,7 +49,7 @@ module.exports = function (module) { | |||||||
|  |  | ||||||
| 		helpers.removeDuplicateValues(values, scores); | 		helpers.removeDuplicateValues(values, scores); | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | 			await helpers.ensureLegacyObjectType(client, key, 'zset'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'sortedSetAddBulk', | 				name: 'sortedSetAddBulk', | ||||||
| @@ -81,7 +81,7 @@ DO UPDATE SET "score" = EXCLUDED."score"`, | |||||||
| 		value = helpers.valueToString(value); | 		value = helpers.valueToString(value); | ||||||
| 		scores = isArrayOfScores ? scores.map(score => parseFloat(score)) : parseFloat(scores); | 		scores = isArrayOfScores ? scores.map(score => parseFloat(score)) : parseFloat(scores); | ||||||
|  |  | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectsType(client, keys, 'zset'); | 			await helpers.ensureLegacyObjectsType(client, keys, 'zset'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: isArrayOfScores ? 'sortedSetsAddScores' : 'sortedSetsAdd', | 				name: isArrayOfScores ? 'sortedSetsAddScores' : 'sortedSetsAdd', | ||||||
| @@ -108,7 +108,7 @@ INSERT INTO "legacy_zset" ("_key", "value", "score") | |||||||
| 		const keys = []; | 		const keys = []; | ||||||
| 		const values = []; | 		const values = []; | ||||||
| 		const scores = []; | 		const scores = []; | ||||||
| 		data.forEach(function (item) { | 		data.forEach((item) => { | ||||||
| 			if (!utils.isNumber(item[1])) { | 			if (!utils.isNumber(item[1])) { | ||||||
| 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | ||||||
| 			} | 			} | ||||||
| @@ -116,7 +116,7 @@ INSERT INTO "legacy_zset" ("_key", "value", "score") | |||||||
| 			scores.push(item[1]); | 			scores.push(item[1]); | ||||||
| 			values.push(item[2]); | 			values.push(item[2]); | ||||||
| 		}); | 		}); | ||||||
| 		await module.transaction(async function (client) { | 		await module.transaction(async (client) => { | ||||||
| 			await helpers.ensureLegacyObjectsType(client, keys, 'zset'); | 			await helpers.ensureLegacyObjectsType(client, keys, 'zset'); | ||||||
| 			await client.query({ | 			await client.query({ | ||||||
| 				name: 'sortedSetAddBulk2', | 				name: 'sortedSetAddBulk2', | ||||||
|   | |||||||
| @@ -79,12 +79,10 @@ OFFSET $3::INTEGER`, | |||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		if (params.withScores) { | 		if (params.withScores) { | ||||||
| 			res.rows = res.rows.map(function (r) { | 			res.rows = res.rows.map(r => ({ | ||||||
| 				return { |  | ||||||
| 				value: r.value, | 				value: r.value, | ||||||
| 				score: parseFloat(r.score), | 				score: parseFloat(r.score), | ||||||
| 				}; | 			})); | ||||||
| 			}); |  | ||||||
| 		} else { | 		} else { | ||||||
| 			res.rows = res.rows.map(r => r.value); | 			res.rows = res.rows.map(r => r.value); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -71,12 +71,10 @@ OFFSET $3::INTEGER`, | |||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		if (params.withScores) { | 		if (params.withScores) { | ||||||
| 			res.rows = res.rows.map(function (r) { | 			res.rows = res.rows.map(r => ({ | ||||||
| 				return { |  | ||||||
| 				value: r.value, | 				value: r.value, | ||||||
| 				score: parseFloat(r.score), | 				score: parseFloat(r.score), | ||||||
| 				}; | 			})); | ||||||
| 			}); |  | ||||||
| 		} else { | 		} else { | ||||||
| 			res.rows = res.rows.map(r => r.value); | 			res.rows = res.rows.map(r => r.value); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -76,7 +76,7 @@ redisModule.info = async function (cxn) { | |||||||
| 	const data = await infoAsync(); | 	const data = await infoAsync(); | ||||||
| 	const lines = data.toString().split('\r\n').sort(); | 	const lines = data.toString().split('\r\n').sort(); | ||||||
| 	const redisData = {}; | 	const redisData = {}; | ||||||
| 	lines.forEach(function (line) { | 	lines.forEach((line) => { | ||||||
| 		const parts = line.split(':'); | 		const parts = line.split(':'); | ||||||
| 		if (parts[1]) { | 		if (parts[1]) { | ||||||
| 			redisData[parts[0]] = parts[1]; | 			redisData[parts[0]] = parts[1]; | ||||||
|   | |||||||
| @@ -20,7 +20,7 @@ connection.getConnectionOptions = function (redis) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| connection.connect = async function (options) { | connection.connect = async function (options) { | ||||||
| 	return new Promise(function (resolve, reject) { | 	return new Promise((resolve, reject) => { | ||||||
| 		options = options || nconf.get('redis'); | 		options = options || nconf.get('redis'); | ||||||
| 		const redis_socket_or_host = options.host; | 		const redis_socket_or_host = options.host; | ||||||
| 		const connOptions = connection.getConnectionOptions(options); | 		const connOptions = connection.getConnectionOptions(options); | ||||||
| @@ -39,11 +39,11 @@ connection.connect = async function (options) { | |||||||
| 			throw new Error('[[error:no-database-selected]]'); | 			throw new Error('[[error:no-database-selected]]'); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		cxn.on('error', function (err) { | 		cxn.on('error', (err) => { | ||||||
| 			winston.error(err.stack); | 			winston.error(err.stack); | ||||||
| 			reject(err); | 			reject(err); | ||||||
| 		}); | 		}); | ||||||
| 		cxn.on('ready', function () { | 		cxn.on('ready', () => { | ||||||
| 			resolve(cxn); | 			resolve(cxn); | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
|   | |||||||
| @@ -16,7 +16,7 @@ module.exports = function (module) { | |||||||
| 			delete data['']; | 			delete data['']; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		Object.keys(data).forEach(function (key) { | 		Object.keys(data).forEach((key) => { | ||||||
| 			if (data[key] === undefined || data[key] === null) { | 			if (data[key] === undefined || data[key] === null) { | ||||||
| 				delete data[key]; | 				delete data[key]; | ||||||
| 			} | 			} | ||||||
| @@ -99,7 +99,7 @@ module.exports = function (module) { | |||||||
| 			return []; | 			return []; | ||||||
| 		} | 		} | ||||||
| 		if (!Array.isArray(fields)) { | 		if (!Array.isArray(fields)) { | ||||||
| 			return keys.map(function () { return {}; }); | 			return keys.map(() => ({})); | ||||||
| 		} | 		} | ||||||
| 		const cachedData = {}; | 		const cachedData = {}; | ||||||
| 		const unCachedKeys = cache.getUnCachedKeys(keys, cachedData); | 		const unCachedKeys = cache.getUnCachedKeys(keys, cachedData); | ||||||
| @@ -113,7 +113,7 @@ module.exports = function (module) { | |||||||
| 			data = [await module.client.async.hgetall(unCachedKeys[0])]; | 			data = [await module.client.async.hgetall(unCachedKeys[0])]; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		unCachedKeys.forEach(function (key, i) { | 		unCachedKeys.forEach((key, i) => { | ||||||
| 			cachedData[key] = data[i] || null; | 			cachedData[key] = data[i] || null; | ||||||
| 			cache.set(key, cachedData[key]); | 			cache.set(key, cachedData[key]); | ||||||
| 		}); | 		}); | ||||||
| @@ -121,7 +121,7 @@ module.exports = function (module) { | |||||||
| 		if (!fields.length) { | 		if (!fields.length) { | ||||||
| 			return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); | 			return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); | ||||||
| 		} | 		} | ||||||
| 		return keys.map(function (key) { | 		return keys.map((key) => { | ||||||
| 			const item = cachedData[key] || {}; | 			const item = cachedData[key] || {}; | ||||||
| 			const result = {}; | 			const result = {}; | ||||||
| 			fields.forEach((field) => { | 			fields.forEach((field) => { | ||||||
|   | |||||||
| @@ -11,10 +11,10 @@ const PubSub = function () { | |||||||
| 	const self = this; | 	const self = this; | ||||||
| 	channelName = `db:${nconf.get('redis:database')}:pubsub_channel`; | 	channelName = `db:${nconf.get('redis:database')}:pubsub_channel`; | ||||||
|  |  | ||||||
| 	connection.connect().then(function (client) { | 	connection.connect().then((client) => { | ||||||
| 		self.subClient = client; | 		self.subClient = client; | ||||||
| 		self.subClient.subscribe(channelName); | 		self.subClient.subscribe(channelName); | ||||||
| 		self.subClient.on('message', function (channel, message) { | 		self.subClient.on('message', (channel, message) => { | ||||||
| 			if (channel !== channelName) { | 			if (channel !== channelName) { | ||||||
| 				return; | 				return; | ||||||
| 			} | 			} | ||||||
| @@ -28,7 +28,7 @@ const PubSub = function () { | |||||||
| 		}); | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	connection.connect().then(function (client) { | 	connection.connect().then((client) => { | ||||||
| 		self.pubClient = client; | 		self.pubClient = client; | ||||||
| 	}); | 	}); | ||||||
| }; | }; | ||||||
|   | |||||||
| @@ -65,7 +65,7 @@ module.exports = function (module) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 		var batch = module.client.batch(); | 		var batch = module.client.batch(); | ||||||
| 		data.forEach(function (item) { | 		data.forEach((item) => { | ||||||
| 			if (!utils.isNumber(item[1])) { | 			if (!utils.isNumber(item[1])) { | ||||||
| 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | 				throw new Error(`[[error:invalid-score, ${item[1]}]]`); | ||||||
| 			} | 			} | ||||||
|   | |||||||
| @@ -98,8 +98,8 @@ events.getEvents = async function (filter, start, stop, from, to) { | |||||||
| 	eventsData = eventsData.filter(Boolean); | 	eventsData = eventsData.filter(Boolean); | ||||||
| 	await addUserData(eventsData, 'uid', 'user'); | 	await addUserData(eventsData, 'uid', 'user'); | ||||||
| 	await addUserData(eventsData, 'targetUid', 'targetUser'); | 	await addUserData(eventsData, 'targetUid', 'targetUser'); | ||||||
| 	eventsData.forEach(function (event) { | 	eventsData.forEach((event) => { | ||||||
| 		Object.keys(event).forEach(function (key) { | 		Object.keys(event).forEach((key) => { | ||||||
| 			if (typeof event[key] === 'string') { | 			if (typeof event[key] === 'string') { | ||||||
| 				event[key] = validator.escape(String(event[key] || '')); | 				event[key] = validator.escape(String(event[key] || '')); | ||||||
| 			} | 			} | ||||||
| @@ -129,12 +129,12 @@ async function addUserData(eventsData, field, objectName) { | |||||||
| 	]); | 	]); | ||||||
|  |  | ||||||
| 	const map = {}; | 	const map = {}; | ||||||
| 	userData.forEach(function (user, index) { | 	userData.forEach((user, index) => { | ||||||
| 		user.isAdmin = isAdmin[index]; | 		user.isAdmin = isAdmin[index]; | ||||||
| 		map[user.uid] = user; | 		map[user.uid] = user; | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	eventsData.forEach(function (event) { | 	eventsData.forEach((event) => { | ||||||
| 		if (map[event[field]]) { | 		if (map[event[field]]) { | ||||||
| 			event[objectName] = map[event[field]]; | 			event[objectName] = map[event[field]]; | ||||||
| 		} | 		} | ||||||
| @@ -153,7 +153,7 @@ events.deleteEvents = async function (eids) { | |||||||
| }; | }; | ||||||
|  |  | ||||||
| events.deleteAll = async function () { | events.deleteAll = async function () { | ||||||
| 	await batch.processSortedSet('events:time', async function (eids) { | 	await batch.processSortedSet('events:time', async (eids) => { | ||||||
| 		await events.deleteEvents(eids); | 		await events.deleteEvents(eids); | ||||||
| 	}, { alwaysStartAt: 0, batch: 500 }); | 	}, { alwaysStartAt: 0, batch: 500 }); | ||||||
| }; | }; | ||||||
|   | |||||||
| @@ -60,7 +60,7 @@ file.allowedExtensions = function () { | |||||||
| 		return []; | 		return []; | ||||||
| 	} | 	} | ||||||
| 	allowedExtensions = allowedExtensions.split(','); | 	allowedExtensions = allowedExtensions.split(','); | ||||||
| 	allowedExtensions = allowedExtensions.filter(Boolean).map(function (extension) { | 	allowedExtensions = allowedExtensions.filter(Boolean).map((extension) => { | ||||||
| 		extension = extension.trim(); | 		extension = extension.trim(); | ||||||
| 		if (!extension.startsWith('.')) { | 		if (!extension.startsWith('.')) { | ||||||
| 			extension = `.${extension}`; | 			extension = `.${extension}`; | ||||||
|   | |||||||
							
								
								
									
										14
									
								
								src/flags.js
									
									
									
									
									
								
							
							
						
						
									
										14
									
								
								src/flags.js
									
									
									
									
									
								
							| @@ -235,9 +235,7 @@ Flags.sort = async function (flagIds, sort) { | |||||||
| 			const mapped = heat.map((el, i) => ({ | 			const mapped = heat.map((el, i) => ({ | ||||||
| 				index: i, heat: el, | 				index: i, heat: el, | ||||||
| 			})); | 			})); | ||||||
| 			mapped.sort(function (a, b) { | 			mapped.sort((a, b) => b.heat - a.heat); | ||||||
| 				return b.heat - a.heat; |  | ||||||
| 			}); |  | ||||||
| 			flagIds = mapped.map(obj => flagIds[obj.index]); | 			flagIds = mapped.map(obj => flagIds[obj.index]); | ||||||
| 			break; | 			break; | ||||||
| 		} | 		} | ||||||
| @@ -340,7 +338,7 @@ Flags.getFlagIdByTarget = async function (type, id) { | |||||||
|  |  | ||||||
| async function modifyNotes(notes) { | async function modifyNotes(notes) { | ||||||
| 	const uids = []; | 	const uids = []; | ||||||
| 	notes = notes.map(function (note) { | 	notes = notes.map((note) => { | ||||||
| 		const noteObj = JSON.parse(note.value); | 		const noteObj = JSON.parse(note.value); | ||||||
| 		uids.push(noteObj[0]); | 		uids.push(noteObj[0]); | ||||||
| 		return { | 		return { | ||||||
| @@ -351,7 +349,7 @@ async function modifyNotes(notes) { | |||||||
| 		}; | 		}; | ||||||
| 	}); | 	}); | ||||||
| 	const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); | 	const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); | ||||||
| 	return notes.map(function (note, idx) { | 	return notes.map((note, idx) => { | ||||||
| 		note.user = userData[idx]; | 		note.user = userData[idx]; | ||||||
| 		note.content = validator.escape(note.content); | 		note.content = validator.escape(note.content); | ||||||
| 		return note; | 		return note; | ||||||
| @@ -452,7 +450,7 @@ Flags.create = async function (type, id, uid, reason, timestamp) { | |||||||
|  |  | ||||||
| Flags.getReports = async function (flagId) { | Flags.getReports = async function (flagId) { | ||||||
| 	const payload = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:reports`, 0, -1); | 	const payload = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:reports`, 0, -1); | ||||||
| 	const [reports, uids] = payload.reduce(function (memo, cur) { | 	const [reports, uids] = payload.reduce((memo, cur) => { | ||||||
| 		const value = cur.value.split(';'); | 		const value = cur.value.split(';'); | ||||||
| 		memo[1].push(value.shift()); | 		memo[1].push(value.shift()); | ||||||
| 		cur.value = value.join(';'); | 		cur.value = value.join(';'); | ||||||
| @@ -634,7 +632,7 @@ Flags.resolveFlag = async function (type, id, uid) { | |||||||
|  |  | ||||||
| Flags.resolveUserPostFlags = async function (uid, callerUid) { | Flags.resolveUserPostFlags = async function (uid, callerUid) { | ||||||
| 	if (meta.config['flags:autoResolveOnBan']) { | 	if (meta.config['flags:autoResolveOnBan']) { | ||||||
| 		await batch.processSortedSet(`uid:${uid}:posts`, async function (pids) { | 		await batch.processSortedSet(`uid:${uid}:posts`, async (pids) => { | ||||||
| 			let postData = await posts.getPostsFields(pids, ['pid', 'flagId']); | 			let postData = await posts.getPostsFields(pids, ['pid', 'flagId']); | ||||||
| 			postData = postData.filter(p => p && p.flagId); | 			postData = postData.filter(p => p && p.flagId); | ||||||
| 			for (const postObj of postData) { | 			for (const postObj of postData) { | ||||||
| @@ -654,7 +652,7 @@ Flags.getHistory = async function (flagId) { | |||||||
| 	let history = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:history`, 0, -1); | 	let history = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:history`, 0, -1); | ||||||
| 	const targetUid = await db.getObjectField(`flag:${flagId}`, 'targetUid'); | 	const targetUid = await db.getObjectField(`flag:${flagId}`, 'targetUid'); | ||||||
|  |  | ||||||
| 	history = history.map(function (entry) { | 	history = history.map((entry) => { | ||||||
| 		entry.value = JSON.parse(entry.value); | 		entry.value = JSON.parse(entry.value); | ||||||
|  |  | ||||||
| 		uids.push(entry.value[0]); | 		uids.push(entry.value[0]); | ||||||
|   | |||||||
| @@ -19,7 +19,7 @@ module.exports = function (Groups) { | |||||||
| 			return []; | 			return []; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const ephemeralIdx = groupNames.reduce(function (memo, cur, idx) { | 		const ephemeralIdx = groupNames.reduce((memo, cur, idx) => { | ||||||
| 			if (Groups.ephemeralGroups.includes(cur)) { | 			if (Groups.ephemeralGroups.includes(cur)) { | ||||||
| 				memo.push(idx); | 				memo.push(idx); | ||||||
| 			} | 			} | ||||||
| @@ -29,7 +29,7 @@ module.exports = function (Groups) { | |||||||
| 		const keys = groupNames.map(groupName => `group:${groupName}`); | 		const keys = groupNames.map(groupName => `group:${groupName}`); | ||||||
| 		const groupData = await (fields.length ? db.getObjectsFields(keys, fields) : db.getObjects(keys)); | 		const groupData = await (fields.length ? db.getObjectsFields(keys, fields) : db.getObjects(keys)); | ||||||
| 		if (ephemeralIdx.length) { | 		if (ephemeralIdx.length) { | ||||||
| 			ephemeralIdx.forEach(function (idx) { | 			ephemeralIdx.forEach((idx) => { | ||||||
| 				groupData[idx] = Groups.getEphemeralGroup(groupNames[idx]); | 				groupData[idx] = Groups.getEphemeralGroup(groupNames[idx]); | ||||||
| 			}); | 			}); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -17,7 +17,7 @@ module.exports = function (Groups) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 		const keys = []; | 		const keys = []; | ||||||
| 		groupNames.forEach(function (groupName) { | 		groupNames.forEach((groupName) => { | ||||||
| 			keys.push(`group:${groupName}`, | 			keys.push(`group:${groupName}`, | ||||||
| 				`group:${groupName}:members`, | 				`group:${groupName}:members`, | ||||||
| 				`group:${groupName}:pending`, | 				`group:${groupName}:pending`, | ||||||
| @@ -45,7 +45,7 @@ module.exports = function (Groups) { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	async function removeGroupsFromPrivilegeGroups(groupNames) { | 	async function removeGroupsFromPrivilegeGroups(groupNames) { | ||||||
| 		await batch.processSortedSet('groups:createtime', async function (otherGroups) { | 		await batch.processSortedSet('groups:createtime', async (otherGroups) => { | ||||||
| 			const privilegeGroups = otherGroups.filter(group => Groups.isPrivilegeGroup(group)); | 			const privilegeGroups = otherGroups.filter(group => Groups.isPrivilegeGroup(group)); | ||||||
| 			const keys = privilegeGroups.map(group => `group:${group}:members`); | 			const keys = privilegeGroups.map(group => `group:${group}:members`); | ||||||
| 			await db.sortedSetRemove(keys, groupNames); | 			await db.sortedSetRemove(keys, groupNames); | ||||||
|   | |||||||
| @@ -100,7 +100,7 @@ Groups.getGroupsAndMembers = async function (groupNames) { | |||||||
| 		Groups.getGroupsData(groupNames), | 		Groups.getGroupsData(groupNames), | ||||||
| 		Groups.getMemberUsers(groupNames, 0, 3), | 		Groups.getMemberUsers(groupNames, 0, 3), | ||||||
| 	]); | 	]); | ||||||
| 	groups.forEach(function (group, index) { | 	groups.forEach((group, index) => { | ||||||
| 		if (group) { | 		if (group) { | ||||||
| 			group.members = members[index] || []; | 			group.members = members[index] || []; | ||||||
| 			group.truncated = group.memberCount > group.members.length; | 			group.truncated = group.memberCount > group.members.length; | ||||||
| @@ -157,7 +157,7 @@ Groups.getOwnersAndMembers = async function (groupName, uid, start, stop) { | |||||||
| 	const countToReturn = stop - start + 1; | 	const countToReturn = stop - start + 1; | ||||||
| 	const ownerUidsOnPage = ownerUids.slice(start, stop !== -1 ? stop + 1 : undefined); | 	const ownerUidsOnPage = ownerUids.slice(start, stop !== -1 ? stop + 1 : undefined); | ||||||
| 	const owners = await user.getUsers(ownerUidsOnPage, uid); | 	const owners = await user.getUsers(ownerUidsOnPage, uid); | ||||||
| 	owners.forEach(function (user) { | 	owners.forEach((user) => { | ||||||
| 		if (user) { | 		if (user) { | ||||||
| 			user.isOwner = true; | 			user.isOwner = true; | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -74,7 +74,7 @@ module.exports = function (Groups) { | |||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		await async.eachSeries(groupsToCreate, async function (groupName) { | 		await async.eachSeries(groupsToCreate, async (groupName) => { | ||||||
| 			try { | 			try { | ||||||
| 				await Groups.create({ | 				await Groups.create({ | ||||||
| 					name: groupName, | 					name: groupName, | ||||||
|   | |||||||
| @@ -55,7 +55,7 @@ module.exports = function (Groups) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const isMembers = await db.isSortedSetMembers(`group:${groupName}:members`, nonCachedUids); | 		const isMembers = await db.isSortedSetMembers(`group:${groupName}:members`, nonCachedUids); | ||||||
| 		nonCachedUids.forEach(function (uid, index) { | 		nonCachedUids.forEach((uid, index) => { | ||||||
| 			cachedData[`${uid}:${groupName}`] = isMembers[index]; | 			cachedData[`${uid}:${groupName}`] = isMembers[index]; | ||||||
| 			Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); | 			Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); | ||||||
| 		}); | 		}); | ||||||
| @@ -74,7 +74,7 @@ module.exports = function (Groups) { | |||||||
| 		} | 		} | ||||||
| 		const nonCachedGroupsMemberSets = nonCachedGroups.map(groupName => `group:${groupName}:members`); | 		const nonCachedGroupsMemberSets = nonCachedGroups.map(groupName => `group:${groupName}:members`); | ||||||
| 		const isMembers = await db.isMemberOfSortedSets(nonCachedGroupsMemberSets, uid); | 		const isMembers = await db.isMemberOfSortedSets(nonCachedGroupsMemberSets, uid); | ||||||
| 		nonCachedGroups.forEach(function (groupName, index) { | 		nonCachedGroups.forEach((groupName, index) => { | ||||||
| 			cachedData[`${uid}:${groupName}`] = isMembers[index]; | 			cachedData[`${uid}:${groupName}`] = isMembers[index]; | ||||||
| 			Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); | 			Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); | ||||||
| 		}); | 		}); | ||||||
| @@ -124,9 +124,7 @@ module.exports = function (Groups) { | |||||||
| 		const isMembers = await Groups.isMemberOfGroups(uid, uniqueGroups); | 		const isMembers = await Groups.isMemberOfGroups(uid, uniqueGroups); | ||||||
| 		const isGroupMember = _.zipObject(uniqueGroups, isMembers); | 		const isGroupMember = _.zipObject(uniqueGroups, isMembers); | ||||||
|  |  | ||||||
| 		return members.map(function (groupNames) { | 		return members.map(groupNames => !!groupNames.find(name => isGroupMember[name])); | ||||||
| 			return !!groupNames.find(name => isGroupMember[name]); |  | ||||||
| 		}); |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	Groups.isMembersOfGroupList = async function (uids, groupListKey) { | 	Groups.isMembersOfGroupList = async function (uids, groupListKey) { | ||||||
| @@ -139,8 +137,8 @@ module.exports = function (Groups) { | |||||||
| 		} | 		} | ||||||
| 		const isGroupMembers = await Promise.all(groupNames.map(name => Groups.isMembers(uids, name))); | 		const isGroupMembers = await Promise.all(groupNames.map(name => Groups.isMembers(uids, name))); | ||||||
|  |  | ||||||
| 		isGroupMembers.forEach(function (isMembers) { | 		isGroupMembers.forEach((isMembers) => { | ||||||
| 			results.forEach(function (isMember, index) { | 			results.forEach((isMember, index) => { | ||||||
| 				if (!isMember && isMembers[index]) { | 				if (!isMember && isMembers[index]) { | ||||||
| 					results[index] = true; | 					results[index] = true; | ||||||
| 				} | 				} | ||||||
| @@ -154,7 +152,7 @@ module.exports = function (Groups) { | |||||||
| 		keys = isArray ? keys : [keys]; | 		keys = isArray ? keys : [keys]; | ||||||
|  |  | ||||||
| 		const cachedData = {}; | 		const cachedData = {}; | ||||||
| 		const nonCachedKeys = keys.filter(function (groupName) { | 		const nonCachedKeys = keys.filter((groupName) => { | ||||||
| 			const groupMembers = cache.get(`group:${groupName}:members`); | 			const groupMembers = cache.get(`group:${groupName}:members`); | ||||||
| 			const isInCache = groupMembers !== undefined; | 			const isInCache = groupMembers !== undefined; | ||||||
| 			if (isInCache) { | 			if (isInCache) { | ||||||
| @@ -168,7 +166,7 @@ module.exports = function (Groups) { | |||||||
| 		} | 		} | ||||||
| 		const groupMembers = await db.getSortedSetsMembers(nonCachedKeys.map(name => `group:${name}:members`)); | 		const groupMembers = await db.getSortedSetsMembers(nonCachedKeys.map(name => `group:${name}:members`)); | ||||||
|  |  | ||||||
| 		nonCachedKeys.forEach(function (groupName, index) { | 		nonCachedKeys.forEach((groupName, index) => { | ||||||
| 			cachedData[groupName] = groupMembers[index]; | 			cachedData[groupName] = groupMembers[index]; | ||||||
| 			cache.set(`group:${groupName}:members`, groupMembers[index]); | 			cache.set(`group:${groupName}:members`, groupMembers[index]); | ||||||
| 		}); | 		}); | ||||||
|   | |||||||
| @@ -65,13 +65,13 @@ module.exports = function (Groups) { | |||||||
| 		const uids = results.users.map(user => user && user.uid); | 		const uids = results.users.map(user => user && user.uid); | ||||||
| 		const isOwners = await Groups.ownership.isOwners(uids, data.groupName); | 		const isOwners = await Groups.ownership.isOwners(uids, data.groupName); | ||||||
|  |  | ||||||
| 		results.users.forEach(function (user, index) { | 		results.users.forEach((user, index) => { | ||||||
| 			if (user) { | 			if (user) { | ||||||
| 				user.isOwner = isOwners[index]; | 				user.isOwner = isOwners[index]; | ||||||
| 			} | 			} | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		results.users.sort(function (a, b) { | 		results.users.sort((a, b) => { | ||||||
| 			if (a.isOwner && !b.isOwner) { | 			if (a.isOwner && !b.isOwner) { | ||||||
| 				return -1; | 				return -1; | ||||||
| 			} else if (!a.isOwner && b.isOwner) { | 			} else if (!a.isOwner && b.isOwner) { | ||||||
|   | |||||||
| @@ -216,11 +216,11 @@ module.exports = function (Groups) { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	async function updateMemberGroupTitles(oldName, newName) { | 	async function updateMemberGroupTitles(oldName, newName) { | ||||||
| 		await batch.processSortedSet(`group:${oldName}:members`, async function (uids) { | 		await batch.processSortedSet(`group:${oldName}:members`, async (uids) => { | ||||||
| 			let usersData = await user.getUsersData(uids); | 			let usersData = await user.getUsersData(uids); | ||||||
| 			usersData = usersData.filter(userData => userData && userData.groupTitleArray.includes(oldName)); | 			usersData = usersData.filter(userData => userData && userData.groupTitleArray.includes(oldName)); | ||||||
|  |  | ||||||
| 			usersData.forEach(function (userData) { | 			usersData.forEach((userData) => { | ||||||
| 				userData.newTitleArray = userData.groupTitleArray.map(oldTitle => (oldTitle === oldName ? newName : oldTitle)); | 				userData.newTitleArray = userData.groupTitleArray.map(oldTitle => (oldTitle === oldName ? newName : oldTitle)); | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
| @@ -242,7 +242,7 @@ module.exports = function (Groups) { | |||||||
| 	async function updateNavigationItems(oldName, newName) { | 	async function updateNavigationItems(oldName, newName) { | ||||||
| 		const navigation = require('../navigation/admin'); | 		const navigation = require('../navigation/admin'); | ||||||
| 		const navItems = await navigation.get(); | 		const navItems = await navigation.get(); | ||||||
| 		navItems.forEach(function (navItem) { | 		navItems.forEach((navItem) => { | ||||||
| 			if (navItem && Array.isArray(navItem.groups) && navItem.groups.includes(oldName)) { | 			if (navItem && Array.isArray(navItem.groups) && navItem.groups.includes(oldName)) { | ||||||
| 				navItem.groups.splice(navItem.groups.indexOf(oldName), 1, newName); | 				navItem.groups.splice(navItem.groups.indexOf(oldName), 1, newName); | ||||||
| 			} | 			} | ||||||
| @@ -257,9 +257,9 @@ module.exports = function (Groups) { | |||||||
|  |  | ||||||
| 		const data = await admin.get(); | 		const data = await admin.get(); | ||||||
|  |  | ||||||
| 		data.areas.forEach(function (area) { | 		data.areas.forEach((area) => { | ||||||
| 			area.widgets = area.data; | 			area.widgets = area.data; | ||||||
| 			area.widgets.forEach(function (widget) { | 			area.widgets.forEach((widget) => { | ||||||
| 				if (widget && widget.data && Array.isArray(widget.data.groups) && widget.data.groups.includes(oldName)) { | 				if (widget && widget.data && Array.isArray(widget.data.groups) && widget.data.groups.includes(oldName)) { | ||||||
| 					widget.data.groups.splice(widget.data.groups.indexOf(oldName), 1, newName); | 					widget.data.groups.splice(widget.data.groups.indexOf(oldName), 1, newName); | ||||||
| 				} | 				} | ||||||
|   | |||||||
| @@ -131,7 +131,7 @@ async function setupConfig() { | |||||||
| 		const postgresQuestions = require('./database/postgres').questions; | 		const postgresQuestions = require('./database/postgres').questions; | ||||||
| 		const allQuestions = questions.main.concat(questions.optional).concat(redisQuestions).concat(mongoQuestions).concat(postgresQuestions); | 		const allQuestions = questions.main.concat(questions.optional).concat(redisQuestions).concat(mongoQuestions).concat(postgresQuestions); | ||||||
|  |  | ||||||
| 		allQuestions.forEach(function (question) { | 		allQuestions.forEach((question) => { | ||||||
| 			if (install.values.hasOwnProperty(question.name)) { | 			if (install.values.hasOwnProperty(question.name)) { | ||||||
| 				config[question.name] = install.values[question.name]; | 				config[question.name] = install.values[question.name]; | ||||||
| 			} else if (question.hasOwnProperty('default')) { | 			} else if (question.hasOwnProperty('default')) { | ||||||
|   | |||||||
| @@ -43,7 +43,7 @@ Languages.list = async function () { | |||||||
|  |  | ||||||
| 	const codes = await Languages.listCodes(); | 	const codes = await Languages.listCodes(); | ||||||
|  |  | ||||||
| 	let languages = await Promise.all(codes.map(async function (folder) { | 	let languages = await Promise.all(codes.map(async (folder) => { | ||||||
| 		try { | 		try { | ||||||
| 			const configPath = path.join(languagesPath, folder, 'language.json'); | 			const configPath = path.join(languagesPath, folder, 'language.json'); | ||||||
| 			const file = await fs.promises.readFile(configPath, 'utf8'); | 			const file = await fs.promises.readFile(configPath, 'utf8'); | ||||||
|   | |||||||
| @@ -87,7 +87,7 @@ Logger.open = function (value) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if (stream) { | 		if (stream) { | ||||||
| 			stream.on('error', function (err) { | 			stream.on('error', (err) => { | ||||||
| 				winston.error(err.stack); | 				winston.error(err.stack); | ||||||
| 			}); | 			}); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -45,7 +45,7 @@ module.exports = function (Messaging) { | |||||||
| 		let messages = await Messaging.getMessagesFields(mids, []); | 		let messages = await Messaging.getMessagesFields(mids, []); | ||||||
| 		messages = await user.blocks.filter(uid, 'fromuid', messages); | 		messages = await user.blocks.filter(uid, 'fromuid', messages); | ||||||
| 		messages = messages | 		messages = messages | ||||||
| 			.map(function (msg, idx) { | 			.map((msg, idx) => { | ||||||
| 				if (msg) { | 				if (msg) { | ||||||
| 					msg.messageId = parseInt(mids[idx], 10); | 					msg.messageId = parseInt(mids[idx], 10); | ||||||
| 					msg.ip = undefined; | 					msg.ip = undefined; | ||||||
| @@ -59,7 +59,7 @@ module.exports = function (Messaging) { | |||||||
| 			['uid', 'username', 'userslug', 'picture', 'status', 'banned'] | 			['uid', 'username', 'userslug', 'picture', 'status', 'banned'] | ||||||
| 		); | 		); | ||||||
|  |  | ||||||
| 		messages.forEach(function (message, index) { | 		messages.forEach((message, index) => { | ||||||
| 			message.fromUser = users[index]; | 			message.fromUser = users[index]; | ||||||
| 			message.fromUser.banned = !!message.fromUser.banned; | 			message.fromUser.banned = !!message.fromUser.banned; | ||||||
| 			message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0; | 			message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0; | ||||||
| @@ -88,7 +88,7 @@ module.exports = function (Messaging) { | |||||||
|  |  | ||||||
| 		if (messages.length > 1) { | 		if (messages.length > 1) { | ||||||
| 			// Add a spacer in between messages with time gaps between them | 			// Add a spacer in between messages with time gaps between them | ||||||
| 			messages = messages.map(function (message, index) { | 			messages = messages.map((message, index) => { | ||||||
| 				// Compare timestamps with the previous message, and check if a spacer needs to be added | 				// Compare timestamps with the previous message, and check if a spacer needs to be added | ||||||
| 				if (index > 0 && message.timestamp > messages[index - 1].timestamp + Messaging.newMessageCutoff) { | 				if (index > 0 && message.timestamp > messages[index - 1].timestamp + Messaging.newMessageCutoff) { | ||||||
| 					// If it's been 5 minutes, this is a new set of messages | 					// If it's been 5 minutes, this is a new set of messages | ||||||
|   | |||||||
| @@ -20,7 +20,7 @@ module.exports = function (Messaging) { | |||||||
| 			Messaging.getMessagesData([mid], uid, roomId, true), | 			Messaging.getMessagesData([mid], uid, roomId, true), | ||||||
| 		]); | 		]); | ||||||
|  |  | ||||||
| 		uids.forEach(function (_uid) { | 		uids.forEach((_uid) => { | ||||||
| 			if (parseInt(_uid, 10) !== parseInt(uid, 10)) { | 			if (parseInt(_uid, 10) !== parseInt(uid, 10)) { | ||||||
| 				if (state === 1) { | 				if (state === 1) { | ||||||
| 					sockets.in(`uid_${_uid}`).emit('event:chats.delete', mid); | 					sockets.in(`uid_${_uid}`).emit('event:chats.delete', mid); | ||||||
|   | |||||||
| @@ -32,7 +32,7 @@ module.exports = function (Messaging) { | |||||||
| 			Messaging.getMessagesData([mid], uid, roomId, true), | 			Messaging.getMessagesData([mid], uid, roomId, true), | ||||||
| 		]); | 		]); | ||||||
|  |  | ||||||
| 		uids.forEach(function (uid) { | 		uids.forEach((uid) => { | ||||||
| 			sockets.in(`uid_${uid}`).emit('event:chats.edit', { | 			sockets.in(`uid_${uid}`).emit('event:chats.edit', { | ||||||
| 				messages: messages, | 				messages: messages, | ||||||
| 			}); | 			}); | ||||||
|   | |||||||
| @@ -36,13 +36,13 @@ Messaging.getMessages = async (params) => { | |||||||
| 	if (!mids.length) { | 	if (!mids.length) { | ||||||
| 		return []; | 		return []; | ||||||
| 	} | 	} | ||||||
| 	mids.forEach(function (mid, index) { | 	mids.forEach((mid, index) => { | ||||||
| 		indices[mid] = start + index; | 		indices[mid] = start + index; | ||||||
| 	}); | 	}); | ||||||
| 	mids.reverse(); | 	mids.reverse(); | ||||||
|  |  | ||||||
| 	const messageData = await Messaging.getMessagesData(mids, params.uid, params.roomId, isNew); | 	const messageData = await Messaging.getMessagesData(mids, params.uid, params.roomId, isNew); | ||||||
| 	messageData.forEach(function (messageData) { | 	messageData.forEach((messageData) => { | ||||||
| 		messageData.index = indices[messageData.messageId.toString()]; | 		messageData.index = indices[messageData.messageId.toString()]; | ||||||
| 		messageData.isOwner = messageData.fromuid === parseInt(params.uid, 10); | 		messageData.isOwner = messageData.fromuid === parseInt(params.uid, 10); | ||||||
| 		if (messageData.deleted && !messageData.isOwner) { | 		if (messageData.deleted && !messageData.isOwner) { | ||||||
| @@ -106,21 +106,19 @@ Messaging.getRecentChats = async (callerUid, uid, start, stop) => { | |||||||
| 		teasers: Promise.all(roomIds.map(async roomId => Messaging.getTeaser(uid, roomId))), | 		teasers: Promise.all(roomIds.map(async roomId => Messaging.getTeaser(uid, roomId))), | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	results.roomData.forEach(function (room, index) { | 	results.roomData.forEach((room, index) => { | ||||||
| 		if (room) { | 		if (room) { | ||||||
| 			room.users = results.users[index]; | 			room.users = results.users[index]; | ||||||
| 			room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : room.users.length > 2; | 			room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : room.users.length > 2; | ||||||
| 			room.unread = results.unread[index]; | 			room.unread = results.unread[index]; | ||||||
| 			room.teaser = results.teasers[index]; | 			room.teaser = results.teasers[index]; | ||||||
|  |  | ||||||
| 			room.users.forEach(function (userData) { | 			room.users.forEach((userData) => { | ||||||
| 				if (userData && parseInt(userData.uid, 10)) { | 				if (userData && parseInt(userData.uid, 10)) { | ||||||
| 					userData.status = user.getStatus(userData); | 					userData.status = user.getStatus(userData); | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
| 			room.users = room.users.filter(function (user) { | 			room.users = room.users.filter(user => user && parseInt(user.uid, 10)); | ||||||
| 				return user && parseInt(user.uid, 10); |  | ||||||
| 			}); |  | ||||||
| 			room.lastUser = room.users[0]; | 			room.lastUser = room.users[0]; | ||||||
|  |  | ||||||
| 			room.usernames = Messaging.generateUsernames(room.users, uid); | 			room.usernames = Messaging.generateUsernames(room.users, uid); | ||||||
| @@ -254,9 +252,7 @@ Messaging.hasPrivateChat = async (uid, withUid) => { | |||||||
| 		myRooms: db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, 0, -1), | 		myRooms: db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, 0, -1), | ||||||
| 		theirRooms: db.getSortedSetRevRange(`uid:${withUid}:chat:rooms`, 0, -1), | 		theirRooms: db.getSortedSetRevRange(`uid:${withUid}:chat:rooms`, 0, -1), | ||||||
| 	}); | 	}); | ||||||
| 	const roomIds = results.myRooms.filter(function (roomId) { | 	const roomIds = results.myRooms.filter(roomId => roomId && results.theirRooms.includes(roomId)); | ||||||
| 		return roomId && results.theirRooms.includes(roomId); |  | ||||||
| 	}); |  | ||||||
|  |  | ||||||
| 	if (!roomIds.length) { | 	if (!roomIds.length) { | ||||||
| 		return 0; | 		return 0; | ||||||
|   | |||||||
| @@ -25,7 +25,7 @@ module.exports = function (Messaging) { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		uids = data.uids; | 		uids = data.uids; | ||||||
| 		uids.forEach(function (uid) { | 		uids.forEach((uid) => { | ||||||
| 			data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0; | 			data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0; | ||||||
| 			Messaging.pushUnreadCount(uid); | 			Messaging.pushUnreadCount(uid); | ||||||
| 			sockets.in(`uid_${uid}`).emit('event:chats.receive', data); | 			sockets.in(`uid_${uid}`).emit('event:chats.receive', data); | ||||||
| @@ -45,7 +45,7 @@ module.exports = function (Messaging) { | |||||||
| 			Messaging.notifyQueue[`${fromUid}:${roomId}`] = queueObj; | 			Messaging.notifyQueue[`${fromUid}:${roomId}`] = queueObj; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		queueObj.timeout = setTimeout(function () { | 		queueObj.timeout = setTimeout(() => { | ||||||
| 			sendNotifications(fromUid, uids, roomId, queueObj.message); | 			sendNotifications(fromUid, uids, roomId, queueObj.message); | ||||||
| 		}, (parseFloat(meta.config.notificationSendDelay) || 60) * 1000); | 		}, (parseFloat(meta.config.notificationSendDelay) || 60) * 1000); | ||||||
| 	}; | 	}; | ||||||
|   | |||||||
| @@ -26,7 +26,7 @@ module.exports = function (Messaging) { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	function modifyRoomData(rooms) { | 	function modifyRoomData(rooms) { | ||||||
| 		rooms.forEach(function (data) { | 		rooms.forEach((data) => { | ||||||
| 			if (data) { | 			if (data) { | ||||||
| 				data.roomName = data.roomName || ''; | 				data.roomName = data.roomName || ''; | ||||||
| 				data.roomName = validator.escape(String(data.roomName)); | 				data.roomName = validator.escape(String(data.roomName)); | ||||||
| @@ -170,7 +170,7 @@ module.exports = function (Messaging) { | |||||||
| 			db.getObjectField(`chat:room:${roomId}`, 'owner'), | 			db.getObjectField(`chat:room:${roomId}`, 'owner'), | ||||||
| 		]); | 		]); | ||||||
|  |  | ||||||
| 		return users.map(function (user) { | 		return users.map((user) => { | ||||||
| 			user.isOwner = parseInt(user.uid, 10) === parseInt(ownerId, 10); | 			user.isOwner = parseInt(user.uid, 10) === parseInt(ownerId, 10); | ||||||
| 			return user; | 			return user; | ||||||
| 		}); | 		}); | ||||||
| @@ -236,9 +236,7 @@ module.exports = function (Messaging) { | |||||||
| 		var room = roomData; | 		var room = roomData; | ||||||
| 		room.messages = messages; | 		room.messages = messages; | ||||||
| 		room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10); | 		room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10); | ||||||
| 		room.users = users.filter(function (user) { | 		room.users = users.filter(user => user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10)); | ||||||
| 			return user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10); |  | ||||||
| 		}); |  | ||||||
| 		room.canReply = canReply; | 		room.canReply = canReply; | ||||||
| 		room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : users.length > 2; | 		room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : users.length > 2; | ||||||
| 		room.usernames = Messaging.generateUsernames(users, uid); | 		room.usernames = Messaging.generateUsernames(users, uid); | ||||||
|   | |||||||
| @@ -23,16 +23,14 @@ exports.aliases = aliases; | |||||||
|  |  | ||||||
| function buildTargets() { | function buildTargets() { | ||||||
| 	var length = 0; | 	var length = 0; | ||||||
| 	var output = Object.keys(aliases).map(function (name) { | 	var output = Object.keys(aliases).map((name) => { | ||||||
| 		var arr = aliases[name]; | 		var arr = aliases[name]; | ||||||
| 		if (name.length > length) { | 		if (name.length > length) { | ||||||
| 			length = name.length; | 			length = name.length; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return [name, arr.join(', ')]; | 		return [name, arr.join(', ')]; | ||||||
| 	}).map(function (tuple) { | 	}).map(tuple => `     ${_.padEnd(`"${tuple[0]}"`, length + 2).magenta}  |  ${tuple[1]}`).join('\n'); | ||||||
| 		return `     ${_.padEnd(`"${tuple[0]}"`, length + 2).magenta}  |  ${tuple[1]}`; |  | ||||||
| 	}).join('\n'); |  | ||||||
| 	console.log( | 	console.log( | ||||||
| 		`\n\n  Build targets:\n${ | 		`\n\n  Build targets:\n${ | ||||||
| 			(`\n     ${_.padEnd('Target', length + 2)}  |  Aliases`).green | 			(`\n     ${_.padEnd('Target', length + 2)}  |  Aliases`).green | ||||||
|   | |||||||
| @@ -64,7 +64,7 @@ Blacklist.test = async function (clientIp) { | |||||||
| 	if ( | 	if ( | ||||||
| 		!Blacklist._rules.ipv4.includes(clientIp) &&	// not explicitly specified in ipv4 list | 		!Blacklist._rules.ipv4.includes(clientIp) &&	// not explicitly specified in ipv4 list | ||||||
| 		!Blacklist._rules.ipv6.includes(clientIp) &&	// not explicitly specified in ipv6 list | 		!Blacklist._rules.ipv6.includes(clientIp) &&	// not explicitly specified in ipv6 list | ||||||
| 		!Blacklist._rules.cidr.some(function (subnet) { | 		!Blacklist._rules.cidr.some((subnet) => { | ||||||
| 			var cidr = ipaddr.parseCIDR(subnet); | 			var cidr = ipaddr.parseCIDR(subnet); | ||||||
| 			if (addr.kind() !== cidr[0].kind()) { | 			if (addr.kind() !== cidr[0].kind()) { | ||||||
| 				return false; | 				return false; | ||||||
| @@ -101,7 +101,7 @@ Blacklist.validate = function (rules) { | |||||||
|  |  | ||||||
| 	// Filter out blank lines and lines starting with the hash character (comments) | 	// Filter out blank lines and lines starting with the hash character (comments) | ||||||
| 	// Also trim inputs and remove inline comments | 	// Also trim inputs and remove inline comments | ||||||
| 	rules = rules.map(function (rule) { | 	rules = rules.map((rule) => { | ||||||
| 		rule = rule.replace(inlineCommentMatch, '').trim(); | 		rule = rule.replace(inlineCommentMatch, '').trim(); | ||||||
| 		return rule.length && !rule.startsWith('#') ? rule : null; | 		return rule.length && !rule.startsWith('#') ? rule : null; | ||||||
| 	}).filter(Boolean); | 	}).filter(Boolean); | ||||||
| @@ -112,7 +112,7 @@ Blacklist.validate = function (rules) { | |||||||
| 	rules = uniqRules; | 	rules = uniqRules; | ||||||
|  |  | ||||||
| 	// Filter out invalid rules | 	// Filter out invalid rules | ||||||
| 	rules = rules.filter(function (rule) { | 	rules = rules.filter((rule) => { | ||||||
| 		var addr; | 		var addr; | ||||||
| 		var isRange = false; | 		var isRange = false; | ||||||
| 		try { | 		try { | ||||||
|   | |||||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user