Skip to content

Node.js based forum software built for the modern web

Resolve merge conflicts, minify only `.js` files

Peter Jaszkowiakdd2b93082439
diff --cc Gruntfile.js
index 3a2a4cd4e7,f3c4f1723e..c97795e743
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@@ -2,8 -2,7 +2,9 @@@
var fork = require('child_process').fork;
var env = process.env;
-var worker, updateWorker, initWorker;
+var worker;
+var updateWorker;
++var initWorker;
var incomplete = [];
var running = 0;
@@@ -44,12 -44,16 +46,14 @@@ module.exports = function (grunt)
if (updateWorker) {
updateWorker.kill('SIGKILL');
}
- updateWorker = fork('app.js', updateArgs, {
- env: env
- });
- ++running;
+ updateWorker = fork('app.js', updateArgs, { env: env });
+ running += 1;
updateWorker.on('exit', function () {
- --running;
+ running -= 1;
if (running === 0) {
- worker = fork('app.js', args, { env: env });
+ worker = fork('app.js', args, {
- env: env
++ env: env,
+ });
worker.on('message', function () {
if (incomplete.length) {
incomplete = [];
@@@ -131,15 -135,24 +135,24 @@@
grunt.loadNpmTasks('grunt-contrib-watch');
+ grunt.registerTask('default', ['watch']);
+ env.NODE_ENV = 'development';
+
if (grunt.option('skip')) {
- grunt.registerTask('default', ['watch:serverUpdated']);
+ worker = fork('app.js', args, {
- env: env
++ env: env,
+ });
} else {
- grunt.registerTask('default', ['watch']);
- }
-
+ initWorker = fork('app.js', initArgs, {
- env: env
++ env: env,
+ });
- env.NODE_ENV = 'development';
+ initWorker.on('exit', function () {
+ worker = fork('app.js', args, {
- env: env
++ env: env,
+ });
+ });
+ }
- worker = fork('app.js', args, { env: env });
grunt.event.on('watch', update);
};
diff --cc public/.eslintrc
index 6e7ddc57e0,0000000000..7c80ae2ec1
mode 100644,000000..100644
--- a/public/.eslintrc
+++ b/public/.eslintrc
@@@ -1,22 -1,0 +1,58 @@@
+{
+ "globals": {
+ "app": true,
+ "io": true,
+ "socket": true,
+ "ajaxify": true,
+ "config": true,
+ "RELATIVE_PATH": true,
+ "utils": true,
+ "overrides": true,
+ "componentHandler": true,
+ "bootbox": true,
+ "templates": true,
+ "Visibility": true,
- "Tinycon": true
++ "Tinycon": true,
++ "Promise": true
+ },
+ "env": {
+ "jquery": true,
+ "amd": true,
- "browser": true
++ "browser": true,
++ "es6": false
++ },
++ "rules": {
++ "no-dupe-class-members": "off",
++ "no-var": "off",
++ "object-shorthand": "off",
++ "prefer-arrow-callback": "off",
++ "prefer-spread": "off",
++ "prefer-reflect": "off",
++ "prefer-template": "off"
++ },
++ "parserOptions": {
++ "ecmaVersion": 5,
++ "ecmaFeatures": {
++ "arrowFunctions": false,
++ "classes": false,
++ "defaultParams": false,
++ "destructuring": false,
++ "experimentalObjectRestSpread": false,
++ "blockBindings": false,
++ "forOf": false,
++ "generators": false,
++ "globalReturn": false,
++ "jsx": false,
++ "modules": false,
++ "objectLiteralComputedProperties": false,
++ "objectLiteralDuplicateProperties": false,
++ "objectLiteralShorthandMethods": false,
++ "objectLiteralShorthandProperties": false,
++ "impliedStrict": false,
++ "restParams": false,
++ "spread": false,
++ "superInFunctions": false,
++ "templateStrings": false
++ }
+ }
+}
diff --cc public/src/admin/general/sounds.js
index ae239034b9,259b21f657..fc5f0aa7ee
--- a/public/src/admin/general/sounds.js
+++ b/public/src/admin/general/sounds.js
@@@ -1,7 -1,7 +1,7 @@@
-"use strict";
-/* global app, define, socket */
+'use strict';
+
- define('admin/general/sounds', ['sounds', 'settings'], function (Sounds, Settings) {
+ define('admin/general/sounds', ['sounds', 'settings', 'admin/settings'], function (Sounds, Settings, AdminSettings) {
var SoundsAdmin = {};
SoundsAdmin.init = function () {
diff --cc public/src/admin/manage/group.js
index 8b77b2bf52,05337f9f97..a4ed2eab7c
--- a/public/src/admin/manage/group.js
+++ b/public/src/admin/manage/group.js
@@@ -5,18 -5,18 +5,18 @@@ define('admin/manage/group',
'forum/groups/memberlist',
'iconSelect',
'admin/modules/colorpicker',
- 'translator'
+ 'translator',
], function (memberList, iconSelect, colorpicker, translator) {
- var Groups = {};
+ var Groups = {};
Groups.init = function () {
- var groupDetailsSearch = $('#group-details-search'),
- groupDetailsSearchResults = $('#group-details-search-results'),
- groupIcon = $('#group-icon'),
- changeGroupUserTitle = $('#change-group-user-title'),
- changeGroupLabelColor = $('#change-group-label-color'),
- groupLabelPreview = $('#group-label-preview'),
- searchDelay;
+ var groupDetailsSearch = $('#group-details-search');
+ var groupDetailsSearchResults = $('#group-details-search-results');
+ var groupIcon = $('#group-icon');
+ var changeGroupUserTitle = $('#change-group-user-title');
+ var changeGroupLabelColor = $('#change-group-label-color');
+ var groupLabelPreview = $('#group-label-preview');
+ var searchDelay;
var groupName = ajaxify.data.group.name;
@@@ -37,23 -38,26 +37,26 @@@
}
searchDelay = setTimeout(function () {
- var searchText = groupDetailsSearch.val(),
- foundUser;
+ var searchText = groupDetailsSearch.val();
+ var foundUser;
- socket.emit('admin.user.search', { query: searchText }, function (err, results) {
+ socket.emit('admin.user.search', {
- query: searchText
++ query: searchText,
+ }, function (err, results) {
if (!err && results && results.users.length > 0) {
- var numResults = results.users.length,
- x;
+ var numResults = results.users.length;
+ var x;
if (numResults > 20) {
numResults = 20;
}
groupDetailsSearchResults.empty();
- for (x = 0; x < numResults; x++) {
+ for (x = 0; x < numResults; x += 1) {
foundUser = $('<li />');
foundUser
- .attr({ title: results.users[x].username,
+ .attr({
+ title: results.users[x].username,
'data-uid': results.users[x].uid,
'data-username': results.users[x].username,
'data-userslug': results.users[x].userslug,
@@@ -92,11 -96,16 +95,16 @@@
username: userLabel.attr('data-username'),
userslug: userLabel.attr('data-userslug'),
picture: userLabel.attr('data-picture'),
- "icon:bgColor": userLabel.attr('data-usericon-bgColor'),
- "icon:text": userLabel.attr('data-usericon-text')
+ 'icon:bgColor': userLabel.attr('data-usericon-bgColor'),
+ 'icon:text': userLabel.attr('data-usericon-text'),
};
- templates.parse('partials/groups/memberlist', 'members', { group: { isOwner: ajaxify.data.group.isOwner, members: [member] } }, function (html) {
+ templates.parse('admin/partials/groups/memberlist', 'members', {
+ group: {
+ isOwner: ajaxify.data.group.isOwner,
- members: [member]
- }
++ members: [member],
++ },
+ }, function (html) {
translator.translate(html, function (html) {
$('[component="groups/members"] tbody').prepend(html);
});
diff --cc public/src/admin/manage/tags.js
index e20bd72276,9ead604c3f..717d4bba1d
--- a/public/src/admin/manage/tags.js
+++ b/public/src/admin/manage/tags.js
@@@ -61,12 -61,16 +61,16 @@@ define('admin/manage/tags',
}
timeoutId = setTimeout(function () {
- socket.emit('topics.searchAndLoadTags', { query: $('#tag-search').val() }, function (err, result) {
+ socket.emit('topics.searchAndLoadTags', {
- query: $('#tag-search').val()
++ query: $('#tag-search').val(),
+ }, function (err, result) {
if (err) {
return app.alertError(err.message);
}
- app.parseAndTranslate('admin/manage/tags', 'tags', { tags: result.tags }, function (html) {
+ app.parseAndTranslate('admin/manage/tags', 'tags', {
- tags: result.tags
++ tags: result.tags,
+ }, function (html) {
$('.tag-list').html(html);
utils.makeNumbersHumanReadable(html.find('.human-readable-number'));
timeoutId = 0;
@@@ -85,8 -89,8 +89,8 @@@
return;
}
- var firstTag = $(tagsToModify[0]),
- title = tagsToModify.length > 1 ? '[[admin/manage/tags:alerts.editing-multiple]]' : '[[admin/manage/tags:alerts.editing-x, ' + firstTag.find('.tag-item').attr('data-tag') + ']]';
+ var firstTag = $(tagsToModify[0]);
- var title = tagsToModify.length > 1 ? '[[admin/manage/tags:alerts.editing-multiple]]' : '[[admin/manage/tags:alerts.editing-x, ' + firstTag.find('.tag-item').text() + ']]';
++ var title = tagsToModify.length > 1 ? '[[admin/manage/tags:alerts.editing-multiple]]' : '[[admin/manage/tags:alerts.editing-x, ' + firstTag.find('.tag-item').attr('data-tag') + ']]';
var modal = bootbox.dialog({
title: title,
@@@ -133,7 -137,9 +137,9 @@@
tagsToDelete.each(function (index, el) {
tags.push($(el).attr('data-tag'));
});
- socket.emit('admin.tags.deleteTags', { tags: tags }, function (err) {
+ socket.emit('admin.tags.deleteTags', {
- tags: tags
++ tags: tags,
+ }, function (err) {
if (err) {
return app.alertError(err.message);
}
diff --cc public/src/client/account/edit.js
index 4de3d61be3,86b9dcafe6..20e85bb46b
--- a/public/src/client/account/edit.js
+++ b/public/src/client/account/edit.js
@@@ -69,8 -71,11 +69,10 @@@ define('forum/account/edit', ['forum/ac
}
function handleImageChange() {
-
$('#changePictureBtn').on('click', function () {
- socket.emit('user.getProfilePictures', { uid: ajaxify.data.uid }, function (err, pictures) {
+ socket.emit('user.getProfilePictures', {
- uid: ajaxify.data.uid
++ uid: ajaxify.data.uid,
+ }, function (err, pictures) {
if (err) {
return app.alertError(err.message);
}
@@@ -216,9 -222,12 +218,12 @@@
paramName: 'uid',
paramValue: ajaxify.data.theirid,
fileSize: ajaxify.data.maximumProfileImageSize,
+ allowSkippingCrop: false,
+ restrictImageDimension: true,
+ imageDimension: ajaxify.data.profileImageDimension,
title: '[[user:upload_picture]]',
description: '[[user:upload_a_picture]]',
- accept: '.png,.jpg,.bmp'
+ accept: '.png,.jpg,.bmp',
}, function (url) {
onUploadComplete(url);
});
@@@ -258,7 -270,9 +266,9 @@@
});
modal.find('[data-action="remove-uploaded"]').on('click', function () {
- socket.emit('user.removeUploadedPicture', { uid: ajaxify.data.theirid }, function (err) {
+ socket.emit('user.removeUploadedPicture', {
- uid: ajaxify.data.theirid
++ uid: ajaxify.data.theirid,
+ }, function (err) {
modal.modal('hide');
if (err) {
return app.alertError(err.message);
diff --cc public/src/client/account/header.js
index 33756e5b6c,63869af05b..1ff436c7ee
--- a/public/src/client/account/header.js
+++ b/public/src/client/account/header.js
@@@ -83,10 -83,12 +83,12 @@@ define('forum/account/header',
pictureCropper.show({
title: '[[user:upload_cover_picture]]',
socketMethod: 'user.updateCover',
- aspectRatio: '16 / 9',
+ aspectRatio: NaN,
+ allowSkippingCrop: true,
+ restrictImageDimension: false,
paramName: 'uid',
paramValue: ajaxify.data.theirid,
- accept: '.png,.jpg,.bmp'
+ accept: '.png,.jpg,.bmp',
}, function (imageUrlOnServer) {
components.get('account/cover').css('background-image', 'url(' + imageUrlOnServer + '?' + config['cache-buster'] + ')');
});
@@@ -129,9 -131,13 +131,13 @@@
data[cur.name] = cur.value;
return data;
}, {});
- var until = parseInt(formData.length, 10) ? (Date.now() + formData.length * 1000 * 60 * 60 * (parseInt(formData.unit, 10) ? 24 : 1)) : 0;
+ var until = parseInt(formData.length, 10) ? (Date.now() + (formData.length * 1000 * 60 * 60 * (parseInt(formData.unit, 10) ? 24 : 1))) : 0;
- socket.emit('user.banUsers', { uids: [ajaxify.data.theirid], until: until, reason: formData.reason || '' }, function (err) {
+ socket.emit('user.banUsers', {
+ uids: [ajaxify.data.theirid],
+ until: until,
- reason: formData.reason || ''
++ reason: formData.reason || '',
+ }, function (err) {
if (err) {
return app.alertError(err.message);
}
diff --cc public/src/client/groups/details.js
index e334f70ec5,6d0559add3..4f7a11a892
--- a/public/src/client/groups/details.js
+++ b/public/src/client/groups/details.js
@@@ -33,9 -34,11 +33,11 @@@ define('forum/groups/details',
pictureCropper.show({
title: '[[groups:upload-group-cover]]',
socketMethod: 'groups.cover.update',
- aspectRatio: '16 / 9',
+ aspectRatio: NaN,
+ allowSkippingCrop: true,
+ restrictImageDimension: false,
paramName: 'groupName',
- paramValue: groupName
+ paramValue: groupName,
}, function (imageUrlOnServer) {
components.get('groups/cover').css('background-image', 'url(' + imageUrlOnServer + ')');
});
diff --cc public/src/modules/notifications.js
index 22198c0db7,f9972ca5a9..ecbfaadd1b
--- a/public/src/modules/notifications.js
+++ b/public/src/modules/notifications.js
@@@ -1,7 -1,8 +1,7 @@@
'use strict';
-/* globals define, socket, app, ajaxify, templates, Tinycon*/
- define('notifications', ['sounds', 'translator', 'components'], function (sound, translator, components) {
+ define('notifications', ['sounds', 'translator', 'components'], function (sounds, translator, components) {
var Notifications = {};
var unreadNotifs = {};
diff --cc public/src/modules/pictureCropper.js
index 2b6172f82b,60dd073532..0ed62d3d8c
--- a/public/src/modules/pictureCropper.js
+++ b/public/src/modules/pictureCropper.js
@@@ -43,9 -44,32 +43,32 @@@ define('pictureCropper', ['translator'
var cropperTool = new cropper.default(img, {
aspectRatio: data.aspectRatio,
viewMode: 1,
+ cropmove: function () {
+ if (data.restrictImageDimension) {
+ if (cropperTool.cropBoxData.width > data.imageDimension) {
+ cropperTool.setCropBoxData({
- width: data.imageDimension
++ width: data.imageDimension,
+ });
+ }
+ if (cropperTool.cropBoxData.height > data.imageDimension) {
+ cropperTool.setCropBoxData({
- height: data.imageDimension
++ height: data.imageDimension,
+ });
+ }
+ }
+ },
ready: function () {
+ if (data.restrictImageDimension) {
+ var origDimension = (img.width < img.height) ? img.width : img.height;
+ var dimension = (origDimension > data.imageDimension) ? data.imageDimension : origDimension;
+ cropperTool.setCropBoxData({
+ width: dimension,
- height: dimension
++ height: dimension,
+ });
+ }
+
cropperModal.find('.rotate').on('click', function () {
- var degrees = this.getAttribute("data-degrees");
+ var degrees = this.getAttribute('data-degrees');
cropperTool.rotate(degrees);
});
@@@ -135,8 -155,11 +158,11 @@@
imageType: imageType,
socketMethod: data.socketMethod,
aspectRatio: data.aspectRatio,
+ allowSkippingCrop: data.allowSkippingCrop,
+ restrictImageDimension: data.restrictImageDimension,
+ imageDimension: data.imageDimension,
paramName: data.paramName,
- paramValue: data.paramValue
+ paramValue: data.paramValue,
}, callback);
}, false);
diff --cc public/src/modules/sounds.js
index f3d07acb6c,26d64079ca..e81ee889f3
--- a/public/src/modules/sounds.js
+++ b/public/src/modules/sounds.js
@@@ -1,19 -1,15 +1,15 @@@
-"use strict";
-/* global app, define, socket, config */
+'use strict';
+
- define('sounds', ['buzz'], function (buzz) {
+ define('sounds', function () {
var Sounds = {};
- var loadedSounds = {};
- var eventSoundMapping;
- var files;
+ var fileMap;
+ var soundMap;
+ var cache = {};
- socket.on('event:sounds.reloadMapping', function () {
- Sounds.reloadMapping();
- });
-
- Sounds.reloadMapping = function () {
- socket.emit('modules.sounds.getMapping', function (err, mapping) {
+ Sounds.loadMap = function loadMap(callback) {
+ socket.emit('modules.sounds.getUserSoundMap', function (err, map) {
if (err) {
return app.alertError(err.message);
}
@@@ -22,69 -21,74 +21,75 @@@
};
function loadData(callback) {
- socket.emit('modules.sounds.getData', function (err, data) {
- if (err) {
- return app.alertError('[sounds] Could not load sound mapping!');
- }
- eventSoundMapping = data.mapping;
- files = data.files;
- callback();
- });
- }
-
- function isSoundLoaded(fileName) {
- return loadedSounds[fileName];
- }
-
- function loadFile(fileName, callback) {
- function createSound() {
- if (files && files[fileName]) {
- loadedSounds[fileName] = new buzz.sound(files[fileName]);
+ var outstanding = 2;
+ function after() {
+ outstanding -= 1;
+ if (outstanding === 0 && callback) {
+ callback();
}
- callback();
}
-
- if (isSoundLoaded(fileName)) {
- return callback();
+ if (fileMap) {
+ outstanding -= 1;
+ } else {
- $.getJSON(config.relative_path + '/assets/sounds/fileMap.json', function (map) {
++ $.getJSON(config.relative_path + '/assets/sounds/fileMap.json', function (map) {
+ fileMap = map;
+ after();
+ });
}
- if (!files || !files[fileName]) {
- return loadData(createSound);
- }
- createSound();
+ Sounds.loadMap(after);
}
- Sounds.play = function (name) {
- function play() {
- Sounds.playFile(eventSoundMapping[name]);
+ Sounds.playSound = function playSound(soundName) {
+ if (!soundMap || !fileMap) {
+ return loadData(after);
}
- if (!eventSoundMapping) {
- return loadData(play);
+ function after() {
+ if (!fileMap[soundName]) {
+ return;
+ }
- var audio = cache[soundName] = cache[soundName] || new Audio(config.relative_path + '/assets/sounds/' + fileMap[soundName]);
++ var audio = cache[soundName] || new Audio(config.relative_path + '/assets/sounds/' + fileMap[soundName]);
++ cache[soundName] = audio;
+ audio.pause();
- audio.currentTime = 0;
++ audio.currentTime = 0;
+ audio.play();
}
- play();
+ after();
};
- Sounds.playFile = function (fileName) {
- if (!fileName) {
- return;
- }
+ Sounds.play = function play(type, id) {
+ function after() {
+ if (!soundMap[type]) {
+ return;
+ }
-
++
+ if (id) {
+ var item = 'sounds.handled:' + id;
+ if (sessionStorage.getItem(item)) {
+ return;
+ }
+ sessionStorage.setItem(item, true);
- function play() {
- if (loadedSounds[fileName]) {
- loadedSounds[fileName].play();
- } else {
- app.alertError('[sounds] Not found: ' + fileName);
+ setTimeout(function () {
+ sessionStorage.removeItem(item);
+ }, 5000);
}
+
+ Sounds.playSound(soundMap[type]);
}
- if (isSoundLoaded(fileName)) {
- play();
- } else {
- loadFile(fileName, play);
+ if (!soundMap || !fileMap) {
+ return loadData(after);
}
+
+ after();
};
+ socket.on('event:sounds.reloadMapping', function () {
+ Sounds.loadMap();
+ });
+
return Sounds;
});
diff --cc src/controllers/accounts/edit.js
index 7006672853,58409060e4..25f1112556
--- a/src/controllers/accounts/edit.js
+++ b/src/controllers/accounts/edit.js
@@@ -25,8 -25,9 +25,9 @@@ editController.get = function (req, res
userData.maximumSignatureLength = parseInt(meta.config.maximumSignatureLength, 10) || 255;
userData.maximumAboutMeLength = parseInt(meta.config.maximumAboutMeLength, 10) || 1000;
userData.maximumProfileImageSize = parseInt(meta.config.maximumProfileImageSize, 10);
- userData.allowProfileImageUploads = parseInt(meta.config.allowProfileImageUploads) === 1;
+ userData.allowProfileImageUploads = parseInt(meta.config.allowProfileImageUploads, 10) === 1;
userData.allowAccountDelete = parseInt(meta.config.allowAccountDelete, 10) === 1;
+ userData.profileImageDimension = parseInt(meta.config.profileImageDimension, 10) || 128;
userData.groups = userData.groups.filter(function (group) {
return group && group.userTitleEnabled && !groups.isPrivilegeGroup(group.name) && group.name !== 'registered-users';
@@@ -36,7 -37,12 +37,15 @@@
});
userData.title = '[[pages:account/edit, ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{ text: userData.username, url: '/user/' + userData.userslug }, { text: '[[user:edit]]' }]);
- userData.breadcrumbs = helpers.buildBreadcrumbs([{
- text: userData.username,
- url: '/user/' + userData.userslug
- }, {
- text: '[[user:edit]]'
- }]);
++ userData.breadcrumbs = helpers.buildBreadcrumbs([
++ {
++ text: userData.username,
++ url: '/user/' + userData.userslug,
++ },
++ {
++ text: '[[user:edit]]',
++ },
++ ]);
userData.editButtons = [];
plugins.fireHook('filter:user.account.edit', userData, function (err, userData) {
@@@ -75,11 -81,15 +84,19 @@@ function renderRoute(name, req, res, ne
}
userData.title = '[[pages:account/edit/' + name + ', ' + userData.username + ']]';
- userData.breadcrumbs = helpers.buildBreadcrumbs([{
- text: userData.username,
- url: '/user/' + userData.userslug
- }, {
- text: '[[user:edit]]',
- url: '/user/' + userData.userslug + '/edit'
- }, {
- text: '[[user:' + name + ']]'
- }]);
+ userData.breadcrumbs = helpers.buildBreadcrumbs([
- { text: userData.username, url: '/user/' + userData.userslug },
- { text: '[[user:edit]]', url: '/user/' + userData.userslug + '/edit' },
- { text: '[[user:' + name + ']]' },
++ {
++ text: userData.username,
++ url: '/user/' + userData.userslug,
++ },
++ {
++ text: '[[user:edit]]',
++ url: '/user/' + userData.userslug + '/edit',
++ },
++ {
++ text: '[[user:' + name + ']]',
++ },
+ ]);
res.render('account/edit/' + name, userData);
});
@@@ -139,7 -149,10 +156,10 @@@ editController.uploadPicture = functio
return next(err);
}
- res.json([{ name: userPhoto.name, url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url }]);
+ res.json([{
+ name: userPhoto.name,
- url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url
++ url: image.url.startsWith('http') ? image.url : nconf.get('relative_path') + image.url,
+ }]);
});
};
@@@ -154,7 -167,9 +174,9 @@@ editController.uploadCoverPicture = fun
return next(err);
}
- res.json([{ url: image.url }]);
+ res.json([{
- url: image.url
++ url: image.url,
+ }]);
});
};
diff --cc src/controllers/accounts/settings.js
index 0644dad9e8,68cef8be5f..edd5d58282
--- a/src/controllers/accounts/settings.js
+++ b/src/controllers/accounts/settings.js
@@@ -37,12 -37,9 +37,9 @@@ settingsController.get = function (req
homePageRoutes: function (next) {
getHomePageRoutes(next);
},
- sounds: function (next) {
- meta.sounds.getFiles(next);
- },
soundsMapping: function (next) {
- meta.sounds.getMapping(userData.uid, next);
+ meta.sounds.getUserSoundMap(userData.uid, next);
- }
+ },
}, next);
},
function (results, next) {
@@@ -50,16 -47,44 +47,44 @@@
userData.languages = results.languages;
userData.homePageRoutes = results.homePageRoutes;
- var soundSettings = {
- notificationSound: 'notification',
- incomingChatSound: 'chat-incoming',
- outgoingChatSound: 'chat-outgoing',
+ var types = [
+ 'notification',
+ 'chat-incoming',
+ 'chat-outgoing',
+ ];
+ var aliases = {
- 'notification': 'notificationSound',
++ notification: 'notificationSound',
+ 'chat-incoming': 'incomingChatSound',
+ 'chat-outgoing': 'outgoingChatSound',
};
- Object.keys(soundSettings).forEach(function (setting) {
- userData[setting] = Object.keys(results.sounds).map(function (name) {
- return { name: name, selected: name === results.soundsMapping[soundSettings[setting]] };
+ types.forEach(function (type) {
+ var soundpacks = plugins.soundpacks.map(function (pack) {
+ var sounds = Object.keys(pack.sounds).map(function (soundName) {
+ var value = pack.name + ' | ' + soundName;
+ return {
+ name: soundName,
+ value: value,
+ selected: value === results.soundsMapping[type],
+ };
+ });
+
+ return {
+ name: pack.name,
+ sounds: sounds,
+ };
});
+
+ userData[type + '-sound'] = soundpacks;
+ // fallback
+ userData[aliases[type]] = soundpacks.concat.apply([], soundpacks.map(function (pack) {
+ return pack.sounds.map(function (sound) {
+ return {
+ name: sound.value,
+ selected: sound.selected,
+ };
+ });
+ }));
});
plugins.fireHook('filter:user.customSettings', { settings: results.settings, customSettings: [], uid: req.uid }, next);
diff --cc src/controllers/admin/dashboard.js
index 63ccc5eb7d,2ffbea0e98..70149e580e
--- a/src/controllers/admin/dashboard.js
+++ b/src/controllers/admin/dashboard.js
@@@ -25,13 -25,21 +25,21 @@@ dashboardController.get = function (req
{
done: plugins.hasListeners('filter:search.query'),
doneText: '[[admin/general/dashboard:search-plugin-installed]]',
- notDoneText:'[[admin/general/dashboard:search-plugin-not-installed]]',
+ notDoneText: '[[admin/general/dashboard:search-plugin-not-installed]]',
tooltip: '[[admin/general/dashboard:search-plugin-tooltip]]',
- link:'/admin/extend/plugins'
- }
+ link: '/admin/extend/plugins',
+ },
];
+
+ if (global.env !== 'production') {
+ notices.push({
+ done: false,
- notDoneText: '[[admin/general/dashboard:running-in-development]]'
++ notDoneText: '[[admin/general/dashboard:running-in-development]]',
+ });
+ }
+
plugins.fireHook('filter:admin.notices', notices, next);
- }
+ },
}, function (err, results) {
if (err) {
return next(err);
diff --cc src/controllers/admin/sounds.js
index 97dac0099a,b042048313..bc4730a865
--- a/src/controllers/admin/sounds.js
+++ b/src/controllers/admin/sounds.js
@@@ -9,16 -10,37 +10,37 @@@ soundsController.get = function (req, r
if (err) {
return next(err);
}
-
+
- sounds = Object.keys(sounds).map(function (name) {
- return {
- name: name,
- };
- });
+ settings = settings || {};
+
+ var types = [
+ 'notification',
+ 'chat-incoming',
+ 'chat-outgoing',
+ ];
+ var output = {};
+
+ types.forEach(function (type) {
+ var soundpacks = plugins.soundpacks.map(function (pack) {
+ var sounds = Object.keys(pack.sounds).map(function (soundName) {
+ var value = pack.name + ' | ' + soundName;
+ return {
+ name: soundName,
+ value: value,
+ selected: value === settings[type],
+ };
+ });
- res.render('admin/general/sounds', {
- sounds: sounds,
+ return {
+ name: pack.name,
+ sounds: sounds,
+ };
+ });
+
+ output[type + '-sound'] = soundpacks;
});
+
+ res.render('admin/general/sounds', output);
});
};
diff --cc src/groups/cover.js
index d7dd9a8b79,8f18c60ad7..a7d7550fa0
--- a/src/groups/cover.js
+++ b/src/groups/cover.js
@@@ -1,10 -1,10 +1,7 @@@
'use strict';
var async = require('async');
--var nconf = require('nconf');
--var path = require('path');
var fs = require('fs');
--var crypto = require('crypto');
var Jimp = require('jimp');
var mime = require('mime');
var winston = require('winston');
diff --cc src/image.js
index 82d8886895,7b428f2331..1609993731
--- a/src/image.js
+++ b/src/image.js
@@@ -65,11 -70,8 +70,8 @@@ image.resizeImage = function (data, cal
}
},
function (image, next) {
- if (data.write === false) {
- return next();
- }
image.write(data.target || data.path, next);
- }
+ },
], function (err) {
callback(err);
});
@@@ -81,9 -83,9 +83,9 @@@ image.normalise = function (path, exten
if (plugins.hasListeners('filter:image.normalise')) {
plugins.fireHook('filter:image.normalise', {
path: path,
- extension: extension
+ extension: extension,
}, function (err) {
- callback(err);
+ callback(err, path + '.png');
});
} else {
new Jimp(path, function (err, image) {
@@@ -116,3 -118,28 +118,28 @@@ image.convertImageToBase64 = function (
callback(err, data ? data.toString('base64') : null);
});
};
+
+ image.mimeFromBase64 = function (imageData) {
+ return imageData.slice(5, imageData.indexOf('base64') - 1);
+ };
+
+ image.extensionFromBase64 = function (imageData) {
+ return file.typeToExtension(image.mimeFromBase64(imageData));
+ };
+
+ image.writeImageDataToTempFile = function (imageData, callback) {
+ var filename = crypto.createHash('md5').update(imageData).digest('hex');
+
+ var type = image.mimeFromBase64(imageData);
+ var extension = file.typeToExtension(type);
+
+ var filepath = path.join(os.tmpdir(), filename + extension);
+
+ var buffer = new Buffer(imageData.slice(imageData.indexOf('base64') + 7), 'base64');
+
+ fs.writeFile(filepath, buffer, {
- encoding: 'base64'
++ encoding: 'base64',
+ }, function (err) {
+ callback(err, filepath);
+ });
-};
++};
diff --cc src/messaging/notifications.js
index 674fa77c3a,2eeb562b5c..eb7a1a1a74
--- a/src/messaging/notifications.js
+++ b/src/messaging/notifications.js
@@@ -11,74 -11,78 +11,78 @@@ var meta = require('../meta')
var sockets = require('../socket.io');
module.exports = function (Messaging) {
-
Messaging.notifyQueue = {}; // Only used to notify a user of a new chat message, see Messaging.notifyUser
- Messaging.notifyUsersInRoom = function (fromUid, roomId, messageObj) {
- Messaging.getUidsInRoom(roomId, 0, -1, function (err, uids) {
- if (err) {
- return;
- }
-
- var data = {
- roomId: roomId,
- fromUid: fromUid,
- message: messageObj,
- };
- uids.forEach(function (uid) {
- data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0;
- Messaging.pushUnreadCount(uid);
- sockets.in('uid_' + uid).emit('event:chats.receive', data);
- });
+ Messaging.notificationSendDelay = 1000 * 60;
- // Delayed notifications
- var queueObj = Messaging.notifyQueue[fromUid + ':' + roomId];
- if (queueObj) {
- queueObj.message.content += '\n' + messageObj.content;
- clearTimeout(queueObj.timeout);
- } else {
- queueObj = {
+ Messaging.notifyUsersInRoom = function (fromUid, roomId, messageObj) {
+ async.waterfall([
+ function (next) {
+ Messaging.getUidsInRoom(roomId, 0, -1, next);
+ },
+ function (uids, next) {
+ var data = {
+ roomId: roomId,
+ fromUid: fromUid,
- message: messageObj
+ message: messageObj,
};
- Messaging.notifyQueue[fromUid + ':' + roomId] = queueObj;
- }
- queueObj.timeout = setTimeout(function () {
- sendNotifications(fromUid, uids, roomId, queueObj.message, function (err) {
- if (!err) {
- delete Messaging.notifyQueue[fromUid + ':' + roomId];
- }
+ uids.forEach(function (uid) {
- data.self = parseInt(uid, 10) === parseInt(fromUid) ? 1 : 0;
++ data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0;
+ Messaging.pushUnreadCount(uid);
+ sockets.in('uid_' + uid).emit('event:chats.receive', data);
});
- }, 1000 * 60); // wait 60s before sending
- });
- };
- function sendNotifications(fromuid, uids, roomId, messageObj, callback) {
- user.isOnline(uids, function (err, isOnline) {
- if (err) {
- return callback(err);
- }
+ // Delayed notifications
+ var queueObj = Messaging.notifyQueue[fromUid + ':' + roomId];
+ if (queueObj) {
+ queueObj.message.content += '\n' + messageObj.content;
+ clearTimeout(queueObj.timeout);
+ } else {
- queueObj = Messaging.notifyQueue[fromUid + ':' + roomId] = {
- message: messageObj
++ queueObj = {
++ message: messageObj,
+ };
++ Messaging.notifyQueue[fromUid + ':' + roomId] = queueObj;
+ }
- uids = uids.filter(function (uid, index) {
- return !isOnline[index] && parseInt(fromuid, 10) !== parseInt(uid, 10);
- });
+ queueObj.timeout = setTimeout(function () {
+ sendNotifications(fromUid, uids, roomId, queueObj.message);
+ }, Messaging.notificationSendDelay);
+ next();
- }
++ },
+ ]);
+ };
- if (!uids.length) {
- return callback();
- }
+ function sendNotifications(fromuid, uids, roomId, messageObj) {
+ async.waterfall([
+ function (next) {
+ user.isOnline(uids, next);
+ },
+ function (isOnline, next) {
+ uids = uids.filter(function (uid, index) {
+ return !isOnline[index] && parseInt(fromuid, 10) !== parseInt(uid, 10);
+ });
- notifications.create({
- bodyShort: '[[notifications:new_message_from, ' + messageObj.fromUser.username + ']]',
- bodyLong: messageObj.content,
- nid: 'chat_' + fromuid + '_' + roomId,
- from: fromuid,
- path: '/chats/' + messageObj.roomId,
- }, function (err, notification) {
- if (!err && notification) {
- notifications.push(notification, uids, callback);
+ if (!uids.length) {
+ return;
}
- });
- sendNotificationEmails(uids, messageObj);
+ notifications.create({
+ bodyShort: '[[notifications:new_message_from, ' + messageObj.fromUser.username + ']]',
+ bodyLong: messageObj.content,
+ nid: 'chat_' + fromuid + '_' + roomId,
+ from: fromuid,
- path: '/chats/' + messageObj.roomId
++ path: '/chats/' + messageObj.roomId,
+ }, next);
- }
++ },
+ ], function (err, notification) {
+ if (!err) {
+ delete Messaging.notifyQueue[fromuid + ':' + roomId];
+ if (notification) {
+ notifications.push(notification, uids);
+ }
+ sendNotificationEmails(uids, messageObj);
+ }
});
}
@@@ -87,38 -91,38 +91,39 @@@
return;
}
- async.parallel({
- userData: function (next) {
- user.getUsersFields(uids, ['uid', 'username', 'userslug'], next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ userData: function (next) {
+ user.getUsersFields(uids, ['uid', 'username', 'userslug'], next);
+ },
+ userSettings: function (next) {
+ user.getMultipleUserSettings(uids, next);
- }
++ },
+ }, next);
},
- userSettings: function (next) {
- user.getMultipleUserSettings(uids, next);
++
+ function (results, next) {
+ results.userData = results.userData.filter(function (userData, index) {
+ return userData && results.userSettings[index] && results.userSettings[index].sendChatNotifications;
+ });
+ async.each(results.userData, function (userData, next) {
+ emailer.send('notif_chat', userData.uid, {
+ subject: '[[email:notif.chat.subject, ' + messageObj.fromUser.username + ']]',
+ summary: '[[notifications:new_message_from, ' + messageObj.fromUser.username + ']]',
+ message: messageObj,
+ site_title: meta.config.title || 'NodeBB',
+ url: nconf.get('url'),
+ roomId: messageObj.roomId,
+ username: userData.username,
- userslug: userData.userslug
++ userslug: userData.userslug,
+ }, next);
+ }, next);
- }
+ },
- }, function (err, results) {
+ ], function (err) {
if (err) {
return winston.error(err);
}
-
- results.userData = results.userData.filter(function (userData, index) {
- return userData && results.userSettings[index] && results.userSettings[index].sendChatNotifications;
- });
-
- async.each(results.userData, function (userData, next) {
- emailer.send('notif_chat', userData.uid, {
- subject: '[[email:notif.chat.subject, ' + messageObj.fromUser.username + ']]',
- summary: '[[notifications:new_message_from, ' + messageObj.fromUser.username + ']]',
- message: messageObj,
- site_title: meta.config.title || 'NodeBB',
- url: nconf.get('url'),
- roomId: messageObj.roomId,
- username: userData.username,
- userslug: userData.userslug,
- }, next);
- }, function (err) {
- if (err) {
- winston.error(err);
- }
- });
});
}
-};
+};
diff --cc src/meta/blacklist.js
index 2c17c488b1,a078b89815..31ce06af8c
--- a/src/meta/blacklist.js
+++ b/src/meta/blacklist.js
@@@ -3,16 -3,19 +3,19 @@@
var ip = require('ip');
var winston = require('winston');
var async = require('async');
+
var db = require('../database');
+ var pubsub = require('../pubsub');
var Blacklist = {
- _rules: []
+ _rules: [],
};
Blacklist.load = function (callback) {
+ callback = callback || function () {};
async.waterfall([
- async.apply(db.get, 'ip-blacklist-rules'),
- async.apply(Blacklist.validate),
- async.apply(Blacklist.get),
- async.apply(Blacklist.validate)
++ Blacklist.get,
++ Blacklist.validate,
], function (err, rules) {
if (err) {
return callback(err);
@@@ -33,13 -36,18 +36,18 @@@
});
};
+ pubsub.on('blacklist:reload', Blacklist.load);
+
Blacklist.save = function (rules, callback) {
- db.set('ip-blacklist-rules', rules, function (err) {
- if (err) {
- return callback(err);
- }
- Blacklist.load(callback);
- });
+ async.waterfall([
+ function (next) {
+ db.set('ip-blacklist-rules', rules, next);
+ },
+ function (next) {
+ Blacklist.load(next);
+ pubsub.publish('blacklist:reload');
- }
++ },
+ ], callback);
};
Blacklist.get = function (callback) {
diff --cc src/meta/build.js
index cdebd8572e,29cfbc45be..9ba5ec89bf
--- a/src/meta/build.js
+++ b/src/meta/build.js
@@@ -52,7 -52,7 +52,7 @@@ exports.buildTargets = function (target
var step = function (startTime, target, next, err) {
if (err) {
-- winston.error('Build failed: ' + err.message);
++ winston.error('Build failed: ' + err.stack);
process.exit(1);
}
winston.info('[build] ' + target + ' => Completed in ' + ((Date.now() - startTime) / 1000) + 's');
@@@ -71,10 -71,10 +71,10 @@@
winston.info('[build] Building javascript');
var startTime = Date.now();
async.series([
- meta.js.linkModules,
+ meta.js.buildModules,
meta.js.linkStatics,
async.apply(meta.js.minify, 'nodebb.min.js'),
- async.apply(meta.js.minify, 'acp.min.js')
+ async.apply(meta.js.minify, 'acp.min.js'),
], step.bind(this, startTime, 'js', next));
} else {
setImmediate(next);
@@@ -83,41 -83,47 +83,47 @@@
function (next) {
async.eachSeries(targets, function (target, next) {
var startTime;
- switch(target) {
- case 'js':
- setImmediate(next);
- break;
- case 'clientCSS':
- winston.info('[build] Building client-side CSS');
- startTime = Date.now();
- meta.css.minify('client', step.bind(this, startTime, target, next));
- break;
-
- case 'acpCSS':
- winston.info('[build] Building admin control panel CSS');
- startTime = Date.now();
- meta.css.minify('admin', step.bind(this, startTime, target, next));
- break;
-
- case 'tpl':
- winston.info('[build] Building templates');
- startTime = Date.now();
- meta.templates.compile(step.bind(this, startTime, target, next));
- break;
-
- case 'lang':
- winston.info('[build] Building language files');
- startTime = Date.now();
- meta.languages.build(step.bind(this, startTime, target, next));
- break;
-
- case 'sound':
- winston.info('[build] Linking sound files');
- startTime = Date.now();
- meta.sounds.build(step.bind(this, startTime, target, next));
- break;
-
- default:
- winston.warn('[build] Unknown build target: \'' + target + '\'');
- setImmediate(next);
- break;
+ switch (target) {
+ case 'js':
+ setImmediate(next);
+ break;
+ case 'clientCSS':
+ winston.info('[build] Building client-side CSS');
+ startTime = Date.now();
+ meta.css.minify('client', step.bind(this, startTime, target, next));
+ break;
+
+ case 'acpCSS':
+ winston.info('[build] Building admin control panel CSS');
+ startTime = Date.now();
+ meta.css.minify('admin', step.bind(this, startTime, target, next));
+ break;
+
+ case 'tpl':
+ winston.info('[build] Building templates');
+ startTime = Date.now();
+ meta.templates.compile(step.bind(this, startTime, target, next));
+ break;
+
+ case 'lang':
+ winston.info('[build] Building language files');
+ startTime = Date.now();
+ meta.languages.build(step.bind(this, startTime, target, next));
+ break;
+
++ case 'sound':
++ winston.info('[build] Linking sound files');
++ startTime = Date.now();
++ meta.sounds.build(step.bind(this, startTime, target, next));
++ break;
++
+ default:
+ winston.warn('[build] Unknown build target: \'' + target + '\'');
+ setImmediate(next);
+ break;
}
}, next);
- }
+ },
], function (err) {
if (err) {
winston.error('[build] Encountered error during build step: ' + err.message);
diff --cc src/meta/js.js
index 18701349f8,90f757361a..679236d9c8
--- a/src/meta/js.js
+++ b/src/meta/js.js
@@@ -12,7 -13,10 +13,9 @@@ var file = require('../file')
var plugins = require('../plugins');
var utils = require('../../public/src/utils');
+ var minifierPath = path.join(__dirname, 'minifier.js');
+
module.exports = function (Meta) {
-
Meta.js = {
target: {},
scripts: {
@@@ -75,38 -79,133 +78,137 @@@
'public/src/modules/taskbar.js',
'public/src/modules/helpers.js',
'public/src/modules/sounds.js',
- 'public/src/modules/string.js'
+ 'public/src/modules/string.js',
],
- // modules listed below are routed through express (/src/modules) so they can be defined anonymously
+ // modules listed below are built (/src/modules) so they can be defined anonymously
modules: {
- "Chart.js": './node_modules/chart.js/dist/Chart.min.js',
- "mousetrap.js": './node_modules/mousetrap/mousetrap.min.js',
- "jqueryui.js": 'public/vendor/jquery/js/jquery-ui.js',
- "buzz.js": 'public/vendor/buzz/buzz.js',
- "cropper.js": './node_modules/cropperjs/dist/cropper.min.js'
- }
- }
+ 'Chart.js': './node_modules/chart.js/dist/Chart.min.js',
+ 'mousetrap.js': './node_modules/mousetrap/mousetrap.min.js',
+ 'jqueryui.js': 'public/vendor/jquery/js/jquery-ui.js',
+ 'buzz.js': 'public/vendor/buzz/buzz.js',
+ 'cropper.js': './node_modules/cropperjs/dist/cropper.min.js',
+ },
+ },
};
- Meta.js.linkModules = function (callback) {
- rimraf(path.join(__dirname, '../../build/public/src/modules'), function (err) {
- if (err) {
- return callback(err);
- }
- async.eachLimit(Object.keys(Meta.js.scripts.modules), 1000, function (relPath, next) {
- var filePath = path.join(__dirname, '../../', Meta.js.scripts.modules[relPath]);
- var destPath = path.join(__dirname, '../../build/public/src/modules', relPath);
+ function minifyModules(modules, callback) {
+ async.eachLimit(modules, 500, function (mod, next) {
+ var filePath = mod.filePath;
+ var destPath = mod.destPath;
+ var minified;
- mkdirp(path.dirname(destPath), function (err) {
- if (err) {
- return next(err);
- }
+ async.parallel([
+ function (cb) {
+ mkdirp(path.dirname(destPath), cb);
+ },
+ function (cb) {
+ fs.readFile(filePath, function (err, buffer) {
+ if (err) {
+ return cb(err);
+ }
+ try {
+ minified = uglifyjs.minify(buffer.toString(), {
+ fromString: true,
+ compress: false,
+ });
+ } catch (e) {
+ return cb(e);
+ }
+
+ cb();
+ });
- }
++ },
+ ], function (err) {
+ if (err) {
+ return next(err);
+ }
+
+ fs.writeFile(destPath, minified.code, next);
+ });
+ }, callback);
- };
++ }
+
+ function linkModules(callback) {
+ var modules = Meta.js.scripts.modules;
+
+ async.eachLimit(Object.keys(modules), 1000, function (relPath, next) {
+ var filePath = path.join(__dirname, '../../', modules[relPath]);
+ var destPath = path.join(__dirname, '../../build/public/src/modules', relPath);
+
+ mkdirp(path.dirname(destPath), function (err) {
+ if (err) {
+ return next(err);
+ }
+
+ file.link(filePath, destPath, next);
+ });
+ }, callback);
- };
++ }
+
+ var moduleDirs = ['modules', 'admin', 'client'];
- file.link(filePath, destPath, next);
+ function getModuleList(callback) {
+ var modules = Object.keys(Meta.js.scripts.modules).map(function (relPath) {
+ return {
+ filePath: path.join(__dirname, '../../', Meta.js.scripts.modules[relPath]),
+ destPath: path.join(__dirname, '../../build/public/src/modules', relPath),
+ };
+ });
+
+ var dirs = moduleDirs.map(function (dir) {
+ return path.join(__dirname, '../../public/src', dir);
+ });
+
+ async.each(dirs, function (dir, next) {
+ utils.walk(dir, function (err, files) {
+ if (err) {
+ return next(err);
+ }
+
- modules = modules.concat(files.map(function (filePath) {
++ var mods = files.filter(function (filePath) {
++ return path.extname(filePath) === '.js';
++ }).map(function (filePath) {
+ return {
+ filePath: filePath,
+ destPath: path.join(__dirname, '../../build/public/src', path.relative(path.dirname(dir), filePath)),
+ };
- }));
+ });
- }, callback);
++
++ modules = modules.concat(mods);
+
+ next();
+ });
+ }, function (err) {
+ callback(err, modules);
+ });
+ }
+
+ function clearModules(callback) {
+ var builtPaths = moduleDirs.map(function (p) {
+ return '../../build/public/src/' + p;
+ });
+ async.each(builtPaths, function (builtPath, next) {
+ rimraf(path.join(__dirname, builtPath), next);
+ }, function (err) {
+ callback(err);
});
+ }
+
+ Meta.js.buildModules = function (callback) {
+ async.waterfall([
+ clearModules,
+ function (next) {
+ if (global.env === 'development') {
+ return linkModules(callback);
+ }
+
+ getModuleList(next);
+ },
+ function (modules, next) {
+ minifyModules(modules, next);
- }
++ },
+ ], callback);
};
Meta.js.linkStatics = function (callback) {
@@@ -133,8 -232,7 +235,8 @@@
winston.verbose('[meta/js] Minifying ' + target);
var forkProcessParams = setupDebugging();
- var minifier = fork('minifier.js', [], forkProcessParams);
- var minifier = Meta.js.minifierProc = fork(minifierPath, [], forkProcessParams);
++ var minifier = fork(minifierPath, [], forkProcessParams);
+ Meta.js.minifierProc = minifier;
Meta.js.target[target] = {};
diff --cc src/meta/minifier.js
index a68aca8fde,5c47bc3e4e..6152112c59
--- a/src/meta/minifier.js
+++ b/src/meta/minifier.js
@@@ -3,10 -3,10 +3,10 @@@
var uglifyjs = require('uglify-js');
var async = require('async');
var fs = require('fs');
- var file = require('./src/file');
+ var file = require('../file');
var Minifier = {
- js: {}
+ js: {},
};
/* Javascript */
diff --cc src/meta/sounds.js
index 0205e56396,00bcbc2410..af6cbe3a2a
--- a/src/meta/sounds.js
+++ b/src/meta/sounds.js
@@@ -10,8 -8,12 +8,13 @@@ var async = require('async')
var file = require('../file');
var plugins = require('../plugins');
+ var user = require('../user');
var db = require('../database');
++
+ var soundsPath = path.join(__dirname, '../../build/public/sounds');
+ var uploadsPath = path.join(__dirname, '../../public/uploads/sounds');
+
module.exports = function (Meta) {
Meta.sounds = {};
diff --cc src/middleware/header.js
index 1928169ae6,0c33e621e5..accbbf2fe6
--- a/src/middleware/header.js
+++ b/src/middleware/header.js
@@@ -58,115 -59,122 +58,123 @@@ module.exports = function (middleware)
};
templateValues.configJSON = JSON.stringify(res.locals.config);
+
- async.parallel({
- scripts: function (next) {
- plugins.fireHook('filter:scripts.get', [], next);
- },
- isAdmin: function (next) {
- user.isAdministrator(req.uid, next);
- },
- isGlobalMod: function (next) {
- user.isGlobalModerator(req.uid, next);
- },
- isModerator: function (next) {
- user.isModeratorOfAnyCategory(req.uid, next);
- },
- user: function (next) {
- var userData = {
- uid: 0,
- username: '[[global:guest]]',
- userslug: '',
- email: '',
- picture: meta.config.defaultAvatar,
- status: 'offline',
- reputation: 0,
- 'email:confirmed': false,
- };
- if (req.uid) {
- user.getUserFields(req.uid, Object.keys(userData), next);
- } else {
- next(null, userData);
- }
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ scripts: function (next) {
+ plugins.fireHook('filter:scripts.get', [], next);
+ },
+ isAdmin: function (next) {
+ user.isAdministrator(req.uid, next);
+ },
+ isGlobalMod: function (next) {
+ user.isGlobalModerator(req.uid, next);
+ },
+ isModerator: function (next) {
+ user.isModeratorOfAnyCategory(req.uid, next);
+ },
+ user: function (next) {
+ var userData = {
+ uid: 0,
+ username: '[[global:guest]]',
+ userslug: '',
+ email: '',
+ picture: meta.config.defaultAvatar,
+ status: 'offline',
+ reputation: 0,
- 'email:confirmed': false
++ 'email:confirmed': false,
+ };
+ if (req.uid) {
+ user.getUserFields(req.uid, Object.keys(userData), next);
+ } else {
+ next(null, userData);
+ }
+ },
+ isEmailConfirmSent: function (next) {
+ if (!meta.config.requireEmailConfirmation || !req.uid) {
+ return next(null, false);
+ }
+ db.get('uid:' + req.uid + ':confirm:email:sent', next);
+ },
+ navigation: async.apply(navigation.get),
+ tags: async.apply(meta.tags.parse, res.locals.metaTags, res.locals.linkTags),
+ banned: async.apply(user.isBanned, req.uid),
- banReason: async.apply(user.getBannedReason, req.uid)
++ banReason: async.apply(user.getBannedReason, req.uid),
+ }, next);
},
- isEmailConfirmSent: function (next) {
- if (!meta.config.requireEmailConfirmation || !req.uid) {
- return next(null, false);
+ function (results, next) {
+ if (results.banned) {
+ req.logout();
+ return res.redirect('/?banned=' + (results.banReason || 'no-reason'));
}
- db.get('uid:' + req.uid + ':confirm:email:sent', next);
- },
- navigation: async.apply(navigation.get),
- tags: async.apply(meta.tags.parse, res.locals.metaTags, res.locals.linkTags),
- banned: async.apply(user.isBanned, req.uid),
- banReason: async.apply(user.getBannedReason, req.uid),
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- if (results.banned) {
- req.logout();
- return res.redirect('/?banned=' + (results.banReason || 'no-reason'));
- }
-
- results.user.isAdmin = results.isAdmin;
- results.user.isGlobalMod = results.isGlobalMod;
- results.user.isMod = !!results.isModerator;
- results.user.uid = parseInt(results.user.uid, 10);
- results.user.email = String(results.user.email).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
- results.user['email:confirmed'] = parseInt(results.user['email:confirmed'], 10) === 1;
- results.user.isEmailConfirmSent = !!results.isEmailConfirmSent;
-
- if (res.locals.config && parseInt(meta.config.disableCustomUserSkins, 10) !== 1 && res.locals.config.bootswatchSkin !== 'default') {
- templateValues.bootswatchCSS = '//maxcdn.bootstrapcdn.com/bootswatch/latest/' + res.locals.config.bootswatchSkin + '/bootstrap.min.css';
- }
-
- templateValues.browserTitle = controllers.helpers.buildTitle(data.title);
- templateValues.navigation = results.navigation;
- templateValues.metaTags = results.tags.meta;
- templateValues.linkTags = results.tags.link;
- templateValues.isAdmin = results.user.isAdmin;
- templateValues.isGlobalMod = results.user.isGlobalMod;
- templateValues.showModMenu = results.user.isAdmin || results.user.isGlobalMod || results.user.isMod;
- templateValues.user = results.user;
- templateValues.userJSON = JSON.stringify(results.user);
- templateValues.useCustomCSS = parseInt(meta.config.useCustomCSS, 10) === 1 && meta.config.customCSS;
- templateValues.customCSS = templateValues.useCustomCSS ? (meta.config.renderedCustomCSS || '') : '';
- templateValues.useCustomJS = parseInt(meta.config.useCustomJS, 10) === 1;
- templateValues.customJS = templateValues.useCustomJS ? meta.config.customJS : '';
- templateValues.maintenanceHeader = parseInt(meta.config.maintenanceMode, 10) === 1 && !results.isAdmin;
- templateValues.defaultLang = meta.config.defaultLang || 'en-GB';
- templateValues.privateUserInfo = parseInt(meta.config.privateUserInfo, 10) === 1;
- templateValues.privateTagListing = parseInt(meta.config.privateTagListing, 10) === 1;
-
- templateValues.template = { name: res.locals.template };
- templateValues.template[res.locals.template] = true;
-
- templateValues.scripts = results.scripts.map(function (script) {
- return { src: script };
- });
- if (req.route && req.route.path === '/') {
- modifyTitle(templateValues);
- }
+ results.user.isAdmin = results.isAdmin;
+ results.user.isGlobalMod = results.isGlobalMod;
+ results.user.isMod = !!results.isModerator;
+ results.user.uid = parseInt(results.user.uid, 10);
+ results.user.email = String(results.user.email).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+ results.user['email:confirmed'] = parseInt(results.user['email:confirmed'], 10) === 1;
+ results.user.isEmailConfirmSent = !!results.isEmailConfirmSent;
- plugins.fireHook('filter:middleware.renderHeader', { templateValues: templateValues, req: req, res: res }, function (err, data) {
- if (err) {
- return callback(err);
+ if (res.locals.config && parseInt(meta.config.disableCustomUserSkins, 10) !== 1 && res.locals.config.bootswatchSkin !== 'default') {
+ templateValues.bootswatchCSS = '//maxcdn.bootstrapcdn.com/bootswatch/latest/' + res.locals.config.bootswatchSkin + '/bootstrap.min.css';
}
- req.app.render('header', data.templateValues, callback);
- });
- });
+ templateValues.browserTitle = controllers.helpers.buildTitle(data.title);
+ templateValues.navigation = results.navigation;
+ templateValues.metaTags = results.tags.meta;
+ templateValues.linkTags = results.tags.link;
+ templateValues.isAdmin = results.user.isAdmin;
+ templateValues.isGlobalMod = results.user.isGlobalMod;
+ templateValues.showModMenu = results.user.isAdmin || results.user.isGlobalMod || results.user.isMod;
+ templateValues.user = results.user;
+ templateValues.userJSON = JSON.stringify(results.user);
+ templateValues.useCustomCSS = parseInt(meta.config.useCustomCSS, 10) === 1 && meta.config.customCSS;
+ templateValues.customCSS = templateValues.useCustomCSS ? (meta.config.renderedCustomCSS || '') : '';
+ templateValues.useCustomJS = parseInt(meta.config.useCustomJS, 10) === 1;
+ templateValues.customJS = templateValues.useCustomJS ? meta.config.customJS : '';
+ templateValues.maintenanceHeader = parseInt(meta.config.maintenanceMode, 10) === 1 && !results.isAdmin;
+ templateValues.defaultLang = meta.config.defaultLang || 'en-GB';
+ templateValues.privateUserInfo = parseInt(meta.config.privateUserInfo, 10) === 1;
+ templateValues.privateTagListing = parseInt(meta.config.privateTagListing, 10) === 1;
+
- templateValues.template = {name: res.locals.template};
++ templateValues.template = { name: res.locals.template };
+ templateValues.template[res.locals.template] = true;
+
+ templateValues.scripts = results.scripts.map(function (script) {
- return {src: script};
++ return { src: script };
+ });
+
+ if (req.route && req.route.path === '/') {
+ modifyTitle(templateValues);
+ }
+
+ plugins.fireHook('filter:middleware.renderHeader', {
- req: req,
++ req: req,
+ res: res,
- templateValues: templateValues
- }, next);
++ templateValues: templateValues,
++ }, next);
+ },
+ function (data, next) {
+ req.app.render('header', data.templateValues, next);
- }
++ },
+ ], callback);
};
middleware.renderFooter = function (req, res, data, callback) {
- plugins.fireHook('filter:middleware.renderFooter', { templateValues: data, req: req, res: res }, function (err, data) {
- if (err) {
- return callback(err);
- }
- req.app.render('footer', data.templateValues, callback);
- });
+ async.waterfall([
+ function (next) {
+ plugins.fireHook('filter:middleware.renderFooter', {
+ req: req,
+ res: res,
- templateValues: data,
++ templateValues: data,
+ }, next);
+ },
+ function (data, next) {
+ req.app.render('footer', data.templateValues, next);
- }
++ },
+ ], callback);
};
function modifyTitle(obj) {
diff --cc src/navigation/admin.js
index b186e332eb,ab1c5aff42..0917e9e524
--- a/src/navigation/admin.js
+++ b/src/navigation/admin.js
@@@ -1,6 -1,5 +1,5 @@@
-"use strict";
+'use strict';
-
var async = require('async');
var plugins = require('../plugins');
var db = require('../database');
diff --cc src/plugins/load.js
index 49e4b26e2a,c6a9429667..3c1c61df73
--- a/src/plugins/load.js
+++ b/src/plugins/load.js
@@@ -57,9 -58,10 +58,10 @@@ module.exports = function (Plugins)
async.apply(mapClientSideScripts, pluginData),
async.apply(mapClientModules, pluginData),
async.apply(mapStaticDirectories, pluginData, pluginData.path),
+ async.apply(mapSoundpack, pluginData),
], next);
}, next);
- }
+ },
], callback);
};
diff --cc src/socket.io/index.js
index d6907538fd,01a520585d..253f5628e1
--- a/src/socket.io/index.js
+++ b/src/socket.io/index.js
@@@ -33,8 -33,30 +33,30 @@@ Sockets.init = function (server)
io.on('connection', onConnection);
+ /*
+ * Restrict socket.io listener to cookie domain. If none is set, infer based on url.
+ * Production only so you don't get accidentally locked out.
+ * Can be overridden via config (socket.io:origins)
+ */
+ if (process.env.NODE_ENV !== 'development') {
+ var domain = nconf.get('cookieDomain');
+ var parsedUrl = url.parse(nconf.get('url'));
+ var override = nconf.get('socket.io:origins');
+ if (!domain) {
+ domain = parsedUrl.hostname; // cookies don't provide isolation by port: http://stackoverflow.com/a/16328399/122353
+ }
+
+ if (!override) {
+ io.origins(parsedUrl.protocol + '//' + domain + ':*');
+ winston.info('[socket.io] Restricting access to origin: ' + parsedUrl.protocol + '//' + domain + ':*');
+ } else {
+ io.origins(override);
+ winston.info('[socket.io] Restricting access to origin: ' + override);
+ }
+ }
+
io.listen(server, {
- transports: nconf.get('socket.io:transports')
+ transports: nconf.get('socket.io:transports'),
});
Sockets.server = io;
diff --cc src/socket.io/posts.js
index 0a31f8427b,8ded335780..b4b5ac40cd
--- a/src/socket.io/posts.js
+++ b/src/socket.io/posts.js
@@@ -1,6 -1,6 +1,6 @@@
-"use strict";
+'use strict';
- var async = require('async');
+ var async = require('async');
var posts = require('../posts');
var privileges = require('../privileges');
@@@ -31,25 -31,26 +31,26 @@@ SocketPosts.reply = function (socket, d
data.req = websockets.reqFromSocket(socket);
data.timestamp = Date.now();
- topics.reply(data, function (err, postData) {
- if (err) {
- return callback(err);
- }
-
- var result = {
- posts: [postData],
- 'reputation:disabled': parseInt(meta.config['reputation:disabled'], 10) === 1,
- 'downvote:disabled': parseInt(meta.config['downvote:disabled'], 10) === 1,
- };
+ async.waterfall([
+ function (next) {
+ topics.reply(data, next);
+ },
+ function (postData, next) {
+ var result = {
+ posts: [postData],
+ 'reputation:disabled': parseInt(meta.config['reputation:disabled'], 10) === 1,
+ 'downvote:disabled': parseInt(meta.config['downvote:disabled'], 10) === 1,
+ };
- callback(null, postData);
+ next(null, postData);
- websockets.in('uid_' + socket.uid).emit('event:new_post', result);
+ websockets.in('uid_' + socket.uid).emit('event:new_post', result);
- user.updateOnlineUsers(socket.uid);
+ user.updateOnlineUsers(socket.uid);
- socketHelpers.notifyNew(socket.uid, 'newPost', result);
- });
+ socketHelpers.notifyNew(socket.uid, 'newPost', result);
- }
++ },
+ ], callback);
};
SocketPosts.getRawPost = function (socket, pid, callback) {
diff --cc src/socket.io/user.js
index bef5eb9d77,060c9e7b2e..f7208b116a
--- a/src/socket.io/user.js
+++ b/src/socket.io/user.js
@@@ -287,19 -291,15 +291,15 @@@ SocketUser.invite = function (socket, e
user.getInvitesNumber(socket.uid, next);
},
function (invites, next) {
- if (!admin && invites > max) {
+ if (!isAdmin && invites >= max) {
return next(new Error('[[error:invite-maximum-met, ' + invites + ', ' + max + ']]'));
}
- next();
- },
- function (next) {
+
user.sendInvitationEmail(socket.uid, email, next);
- }
+ },
- ], callback);
- } else {
- user.sendInvitationEmail(socket.uid, email, callback);
- }
- });
+ ], next);
- }
++ },
+ ], callback);
};
SocketUser.getUserByUID = function (socket, uid, callback) {
diff --cc src/topics/posts.js
index 65c180d784,97b6f71162..909de0caa4
--- a/src/topics/posts.js
+++ b/src/topics/posts.js
@@@ -27,23 -28,23 +27,23 @@@ module.exports = function (Topics)
};
Topics.getTopicPosts = function (tid, set, start, stop, uid, reverse, callback) {
- callback = callback || function () {};
- async.parallel({
- posts: function (next) {
- posts.getPostsFromSet(set, start, stop, uid, reverse, next);
- },
- postCount: function (next) {
- Topics.getTopicField(tid, 'postcount', next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ posts: function (next) {
+ posts.getPostsFromSet(set, start, stop, uid, reverse, next);
+ },
+ postCount: function (next) {
+ Topics.getTopicField(tid, 'postcount', next);
- }
++ },
+ }, next);
},
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
+ function (results, next) {
+ Topics.calculatePostIndices(results.posts, start, stop, results.postCount, reverse);
- Topics.calculatePostIndices(results.posts, start, stop, results.postCount, reverse);
-
- Topics.addPostData(results.posts, uid, callback);
- });
+ Topics.addPostData(results.posts, uid, next);
- }
++ },
+ ], callback);
};
Topics.addPostData = function (postData, uid, callback) {
@@@ -83,63 -77,64 +76,63 @@@
users.forEach(function (user, index) {
userData[uids[index]] = user;
});
-
next(null, userData);
- });
- },
- editors: function (next) {
- var editors = [];
- for (var i = 0; i < postData.length; i += 1) {
- if (postData[i] && postData[i].editor && editors.indexOf(postData[i].editor) === -1) {
- editors.push(postData[i].editor);
- }
-- }
++ },
+ ], callback);
+ }
- user.getUsersFields(editors, ['uid', 'username', 'userslug'], function (err, editors) {
- if (err) {
- return next(err);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ bookmarks: function (next) {
+ posts.hasBookmarked(pids, uid, next);
+ },
+ voteData: function (next) {
+ posts.getVoteStatusByPostIDs(pids, uid, next);
+ },
+ userData: function (next) {
+ getPostUserData('uid', function (uids, next) {
+ posts.getUserInfoForPosts(uids, uid, next);
+ }, next);
-
+ },
+ editors: function (next) {
+ getPostUserData('editor', function (uids, next) {
+ user.getUsersFields(uids, ['uid', 'username', 'userslug'], next);
+ }, next);
+ },
+ parents: function (next) {
+ Topics.addParentPosts(postData, next);
- }
++ },
+ }, next);
+ },
+ function (results, next) {
+ postData.forEach(function (postObj, i) {
+ if (postObj) {
+ postObj.deleted = parseInt(postObj.deleted, 10) === 1;
+ postObj.user = parseInt(postObj.uid, 10) ? results.userData[postObj.uid] : _.clone(results.userData[postObj.uid]);
+ postObj.editor = postObj.editor ? results.editors[postObj.editor] : null;
+ postObj.bookmarked = results.bookmarks[i];
+ postObj.upvoted = results.voteData.upvotes[i];
+ postObj.downvoted = results.voteData.downvotes[i];
+ postObj.votes = postObj.votes || 0;
+ postObj.replies = postObj.replies || 0;
+ postObj.selfPost = !!parseInt(uid, 10) && parseInt(uid, 10) === parseInt(postObj.uid, 10);
+
+ // Username override for guests, if enabled
+ if (parseInt(meta.config.allowGuestHandles, 10) === 1 && parseInt(postObj.uid, 10) === 0 && postObj.handle) {
+ postObj.user.username = validator.escape(String(postObj.handle));
+ }
}
- var editorData = {};
- editors.forEach(function (editor) {
- editorData[editor.uid] = editor;
- });
- next(null, editorData);
});
+ plugins.fireHook('filter:topics.addPostData', {
+ posts: postData,
- uid: uid
++ uid: uid,
+ }, next);
},
- parents: function (next) {
- Topics.addParentPosts(postData, next);
+ function (data, next) {
+ next(null, data.posts);
- }
+ },
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
-
- postData.forEach(function (postObj, i) {
- if (postObj) {
- postObj.deleted = parseInt(postObj.deleted, 10) === 1;
- postObj.user = parseInt(postObj.uid, 10) ? results.userData[postObj.uid] : _.clone(results.userData[postObj.uid]);
- postObj.editor = postObj.editor ? results.editors[postObj.editor] : null;
- postObj.bookmarked = results.bookmarks[i];
- postObj.upvoted = results.voteData.upvotes[i];
- postObj.downvoted = results.voteData.downvotes[i];
- postObj.votes = postObj.votes || 0;
- postObj.replies = postObj.replies || 0;
- postObj.selfPost = !!parseInt(uid, 10) && parseInt(uid, 10) === parseInt(postObj.uid, 10);
-
- // Username override for guests, if enabled
- if (parseInt(meta.config.allowGuestHandles, 10) === 1 && parseInt(postObj.uid, 10) === 0 && postObj.handle) {
- postObj.user.username = validator.escape(String(postObj.handle));
- }
- }
- });
-
- plugins.fireHook('filter:topics.addPostData', {
- posts: postData,
- uid: uid,
- }, function (err, data) {
- callback(err, data ? data.posts : null);
- });
- });
+ ], callback);
};
Topics.modifyPostsByPrivilege = function (topicData, topicPrivileges) {
@@@ -172,7 -167,9 +165,9 @@@
async.apply(posts.getPostsFields, parentPids, ['uid']),
function (_parentPosts, next) {
parentPosts = _parentPosts;
- var parentUids = parentPosts.map(function (postObj) { return parseInt(postObj.uid, 10); }).filter(function (uid, idx, users) {
- var parentUids = parentPosts.map(function (postObj) {
- return parseInt(postObj.uid, 10);
++ var parentUids = parentPosts.map(function (postObj) {
++ return parseInt(postObj.uid, 10);
+ }).filter(function (uid, idx, users) {
return users.indexOf(uid) === idx;
});
@@@ -252,10 -249,10 +247,10 @@@
if (!isDeleted) {
latestPid = pids[0];
}
- ++index;
+ index += 1;
- next();
- });
- });
+ _next();
- }
++ },
+ ], next);
},
function () {
return isDeleted && !done;
@@@ -317,22 -314,24 +312,24 @@@
};
Topics.getPids = function (tid, callback) {
- async.parallel({
- mainPid: function (next) {
- Topics.getTopicField(tid, 'mainPid', next);
+ async.waterfall([
+ function (next) {
+ async.parallel({
+ mainPid: function (next) {
+ Topics.getTopicField(tid, 'mainPid', next);
+ },
+ pids: function (next) {
+ db.getSortedSetRange('tid:' + tid + ':posts', 0, -1, next);
- }
++ },
+ }, next);
},
- pids: function (next) {
- db.getSortedSetRange('tid:' + tid + ':posts', 0, -1, next);
+ function (results, next) {
+ if (results.mainPid) {
+ results.pids = [results.mainPid].concat(results.pids);
+ }
+ next(null, results.pids);
- }
+ },
- }, function (err, results) {
- if (err) {
- return callback(err);
- }
- if (results.mainPid) {
- results.pids = [results.mainPid].concat(results.pids);
- }
- callback(null, results.pids);
- });
+ ], callback);
};
Topics.increasePostCount = function (tid, callback) {
@@@ -349,12 -348,14 +346,14 @@@
function incrementFieldAndUpdateSortedSet(tid, field, by, set, callback) {
callback = callback || function () {};
- db.incrObjectFieldBy('topic:' + tid, field, by, function (err, value) {
- if (err) {
- return callback(err);
- }
- db.sortedSetAdd(set, value, tid, callback);
- });
+ async.waterfall([
+ function (next) {
+ db.incrObjectFieldBy('topic:' + tid, field, by, next);
+ },
+ function (value, next) {
+ db.sortedSetAdd(set, value, tid, next);
- }
++ },
+ ], callback);
}
Topics.getTitleByPid = function (pid, callback) {
@@@ -362,21 -363,25 +361,25 @@@
};
Topics.getTopicFieldByPid = function (field, pid, callback) {
- posts.getPostField(pid, 'tid', function (err, tid) {
- if (err) {
- return callback(err);
- }
- Topics.getTopicField(tid, field, callback);
- });
+ async.waterfall([
+ function (next) {
+ posts.getPostField(pid, 'tid', next);
+ },
+ function (tid, next) {
+ Topics.getTopicField(tid, field, next);
- }
++ },
+ ], callback);
};
Topics.getTopicDataByPid = function (pid, callback) {
- posts.getPostField(pid, 'tid', function (err, tid) {
- if (err) {
- return callback(err);
- }
- Topics.getTopicData(tid, callback);
- });
+ async.waterfall([
+ function (next) {
+ posts.getPostField(pid, 'tid', next);
+ },
+ function (tid, next) {
+ Topics.getTopicData(tid, next);
- }
++ },
+ ], callback);
};
Topics.getPostCount = function (tid, callback) {
diff --cc src/user/invite.js
index 7e1b8c9866,043bf62a7b..4e41b824a5
--- a/src/user/invite.js
+++ b/src/user/invite.js
@@@ -130,12 -129,12 +128,12 @@@ module.exports = function (User)
return next(new Error('[[error:invalid-username]]'));
}
async.parallel([
- function deleteFromReferenceList(next) {
- db.setRemove('invitation:uid:' + invitedByUid, email, next);
+ function (next) {
+ deleteFromReferenceList(invitedByUid, email, next);
},
- function deleteInviteKey(next) {
+ function (next) {
db.delete('invitation:email:' + email, next);
- }
+ },
], function (err) {
next(err);
});
@@@ -145,6 -144,37 +143,36 @@@
User.deleteInvitationKey = function (email, callback) {
callback = callback || function () {};
- db.delete('invitation:email:' + email, callback);
+
+ async.waterfall([
+ function (next) {
+ User.getInvitingUsers(next);
+ },
+ function (uids, next) {
+ async.each(uids, function (uid, next) {
+ deleteFromReferenceList(uid, email, next);
+ }, next);
+ },
+ function (next) {
+ db.delete('invitation:email:' + email, next);
- }
++ },
+ ], callback);
};
+
+ function deleteFromReferenceList(uid, email, callback) {
+ async.waterfall([
+ function (next) {
+ db.setRemove('invitation:uid:' + uid, email, next);
+ },
+ function (next) {
+ db.setCount('invitation:uid:' + uid, next);
+ },
+ function (count, next) {
+ if (count === 0) {
+ return db.setRemove('invitation:uids', uid, next);
+ }
+ setImmediate(next);
- }
++ },
+ ], callback);
+ }
-
};
diff --cc src/user/picture.js
index 1fc3b05ffd,09b7d636e8..be489364b9
--- a/src/user/picture.js
+++ b/src/user/picture.js
@@@ -17,78 -14,9 +14,8 @@@ var meta = require('../meta')
var db = require('../database');
module.exports = function (User) {
-
User.uploadPicture = function (uid, picture, callback) {
- var uploadSize = parseInt(meta.config.maximumProfileImageSize, 10) || 256;
- var extension = path.extname(picture.name);
- var updateUid = uid;
- var imageDimension = parseInt(meta.config.profileImageDimension, 10) || 128;
- var convertToPNG = parseInt(meta.config['profile:convertProfileImageToPNG'], 10) === 1;
- var keepAllVersions = parseInt(meta.config['profile:keepAllUserImages'], 10) === 1;
- var uploadedImage;
-
- if (parseInt(meta.config.allowProfileImageUploads, 10) !== 1) {
- return callback(new Error('[[error:profile-image-uploads-disabled]]'));
- }
-
- if (picture.size > uploadSize * 1024) {
- return callback(new Error('[[error:file-too-big, ' + uploadSize + ']]'));
- }
-
- if (!extension) {
- return callback(new Error('[[error:invalid-image-extension]]'));
- }
-
- async.waterfall([
- function (next) {
- if (plugins.hasListeners('filter:uploadImage')) {
- return plugins.fireHook('filter:uploadImage', {
- image: picture,
- uid: updateUid,
- }, next);
- }
-
- var filename = updateUid + '-profileimg' + (keepAllVersions ? '-' + Date.now() : '') + (convertToPNG ? '.png' : extension);
-
- async.waterfall([
- function (next) {
- file.isFileTypeAllowed(picture.path, next);
- },
- function (next) {
- image.resizeImage({
- path: picture.path,
- extension: extension,
- width: imageDimension,
- height: imageDimension,
- write: false,
- }, next);
- },
- function (next) {
- if (!convertToPNG) {
- return next();
- }
- async.series([
- async.apply(image.normalise, picture.path, extension),
- async.apply(fs.rename, picture.path + '.png', picture.path),
- ], function (err) {
- next(err);
- });
- },
- function (next) {
- file.saveFileToLocal(filename, 'profile', picture.path, next);
- },
- ], next);
- },
- function (_image, next) {
- uploadedImage = _image;
- User.setUserFields(updateUid, {
- uploadedpicture: uploadedImage.url,
- picture: uploadedImage.url,
- }, next);
- },
- function (next) {
- next(null, uploadedImage);
- },
- ], callback);
- User.uploadCroppedPicture({uid: uid, file: picture}, callback);
++ User.uploadCroppedPicture({ uid: uid, file: picture }, callback);
};
User.uploadFromUrl = function (uid, url, callback) {
@@@ -138,10 -66,11 +65,10 @@@
};
User.updateCoverPicture = function (data, callback) {
-
var url;
- var image = {
+ var picture = {
name: 'profileCover',
- uid: data.uid
+ uid: data.uid,
};
if (!data.imageData && data.position) {
@@@ -181,53 -112,80 +110,79 @@@
} else {
setImmediate(next);
}
- }
+ },
], function (err) {
- deleteFile(image.path);
+ deleteFile(picture.path);
callback(err, {
- url: url
+ url: url,
});
});
};
User.uploadCroppedPicture = function (data, callback) {
- var url;
- var image = {
- name: 'profileAvatar',
- uid: data.uid,
- };
-
- if (parseInt(meta.config.allowProfileImageUploads) !== 1) {
++ if (parseInt(meta.config.allowProfileImageUploads, 10) !== 1) {
+ return callback(new Error('[[error:profile-image-uploads-disabled]]'));
+ }
- if (!data.imageData) {
+ if (!data.imageData && !data.file) {
return callback(new Error('[[error:invalid-data]]'));
}
+ var size = data.file ? data.file.size : data.imageData.length;
+ var uploadSize = parseInt(meta.config.maximumProfileImageSize, 10) || 256;
+ if (size > uploadSize * 1024) {
+ return callback(new Error('[[error:file-too-big, ' + meta.config.maximumProfileImageSize + ']]'));
+ }
+
+ var type = data.file ? data.file.type : image.mimeFromBase64(data.imageData);
+ var extension = file.typeToExtension(type);
+ if (!extension) {
+ return callback(new Error('[[error:invalid-image-extension]]'));
+ }
+
+ var uploadedImage;
+
+ var picture = {
+ name: 'profileAvatar',
- uid: data.uid
++ uid: data.uid,
+ };
+
async.waterfall([
function (next) {
- var size = data.imageData.length;
- var uploadSize = parseInt(meta.config.maximumProfileImageSize, 10) || 256;
- if (size > uploadSize * 1024) {
- return next(new Error('[[error:file-too-big, ' + meta.config.maximumProfileImageSize + ']]'));
+ if (data.file) {
+ return setImmediate(next, null, data.file.path);
}
-
- saveImageDataToTempFile(data.imageData, next);
+ image.writeImageDataToTempFile(data.imageData, next);
},
function (path, next) {
- image.path = path;
-
- uploadProfileOrCover('profileavatar', image, data.imageData, next);
+ convertToPNG(path, extension, next);
},
- function (uploadData, next) {
- url = uploadData.url;
+ function (path, next) {
+ picture.path = path;
+
+ var imageDimension = parseInt(meta.config.profileImageDimension, 10) || 128;
+ image.resizeImage({
+ path: picture.path,
+ extension: extension,
+ width: imageDimension,
- height: imageDimension
++ height: imageDimension,
+ }, next);
+ },
+ function (next) {
+ var filename = generateProfileImageFilename(data.uid, 'profileavatar', extension);
+ uploadProfileOrCover(filename, picture, next);
+ },
+ function (_uploadedImage, next) {
+ uploadedImage = _uploadedImage;
+
User.setUserFields(data.uid, {
- uploadedpicture: url,
- picture: url,
+ uploadedpicture: uploadedImage.url,
- picture: uploadedImage.url
++ picture: uploadedImage.url,
}, next);
- }
+ },
], function (err) {
- deleteFile(image.path);
- callback(err, {
- url: url,
- });
+ deleteFile(picture.path);
+ callback(err, uploadedImage);
});
};
@@@ -248,10 -208,10 +205,10 @@@
if (plugins.hasListeners('filter:uploadImage')) {
return plugins.fireHook('filter:uploadImage', {
image: image,
- uid: image.uid
+ uid: image.uid,
}, callback);
}
- var filename = generateProfileImageFilename(image.uid, type, imageData);
+
saveFileToLocal(filename, image, callback);
}
@@@ -273,9 -232,10 +229,10 @@@
function (upload, next) {
next(null, {
url: nconf.get('relative_path') + upload.url,
+ path: upload.path,
- name: image.name
+ name: image.name,
});
- }
+ },
], callback);
}
diff --cc src/webserver.js
index dbc65a36ec,9b3e816c5d..ee8ebc57df
--- a/src/webserver.js
+++ b/src/webserver.js
@@@ -103,11 -103,11 +103,11 @@@ function initializeNodeBB(callback)
},
function (next) {
async.series([
- async.apply(meta.sounds.init),
- async.apply(languages.init),
- async.apply(meta.blacklist.load),
+ meta.sounds.addUploads,
+ languages.init,
+ meta.blacklist.load,
], next);
- }
+ },
], callback);
}
diff --cc test/blacklist.js
index 0000000000,0ffc0f78a1..72f5e1e813
mode 000000,100644..100644
--- a/test/blacklist.js
+++ b/test/blacklist.js
@@@ -1,0 -1,79 +1,79 @@@
+ 'use strict';
-/*global require, after, before*/
++
++/* global require, after, before*/
+
+
+ var async = require('async');
+ var assert = require('assert');
+
+ var db = require('./mocks/databasemock');
+ var groups = require('../src/groups');
+ var user = require('../src/user');
+ var blacklist = require('../src/meta/blacklist');
+
+ describe('blacklist', function () {
-
+ var adminUid;
+
+ before(function (done) {
+ groups.resetCache();
- user.create({username: 'admin'}, function (err, uid) {
++ user.create({ username: 'admin' }, function (err, uid) {
+ assert.ifError(err);
+ adminUid = uid;
+ groups.join('administrators', adminUid, done);
+ });
+ });
+
+ var socketBlacklist = require('../src/socket.io/blacklist');
+ var rules = '1.1.1.1\n2.2.2.2\n::ffff:0:2.2.2.2\n127.0.0.1\n192.168.100.0/22';
+
+ it('should validate blacklist', function (done) {
- socketBlacklist.validate({uid: adminUid}, {
- rules: rules
++ socketBlacklist.validate({ uid: adminUid }, {
++ rules: rules,
+ }, function (err, data) {
+ assert.ifError(err);
+ done();
+ });
+ });
+
+ it('should error if not admin', function (done) {
- socketBlacklist.save({uid: 0}, rules, function (err) {
++ socketBlacklist.save({ uid: 0 }, rules, function (err) {
+ assert.equal(err.message, '[[error:no-privileges]]');
+ done();
+ });
+ });
+
+ it('should save blacklist', function (done) {
- socketBlacklist.save({uid: adminUid}, rules, function (err) {
++ socketBlacklist.save({ uid: adminUid }, rules, function (err) {
+ assert.ifError(err);
+ done();
+ });
+ });
+
+ it('should pass ip test against blacklist async', function (done) {
+ blacklist.test('3.3.3.3', function (err) {
+ assert.ifError(err);
+ done();
+ });
+ });
+
+ it('should pass ip test against blacklist sync', function (done) {
+ assert(!blacklist.test('3.3.3.3'));
+ done();
+ });
+
+ it('should fail ip test against blacklist async', function (done) {
+ blacklist.test('1.1.1.1', function (err) {
+ assert.equal(err.message, '[[error:blacklisted-ip]]');
+ done();
+ });
+ });
+
+ it('should fail ip test against blacklist sync', function (done) {
+ assert(blacklist.test('1.1.1.1'));
+ done();
+ });
+
+ after(function (done) {
+ db.emptydb(done);
+ });
+ });
diff --cc test/build.js
index 8422887762,5fe95561ba..3b6890ebe6
--- a/test/build.js
+++ b/test/build.js
@@@ -5,7 -5,9 +5,8 @@@ var assert = require('assert')
var db = require('./mocks/databasemock');
describe('Build', function () {
-
it('should build all assets', function (done) {
+ this.timeout(50000);
var build = require('../src/meta/build');
build.buildAll(function (err) {
assert.ifError(err);
diff --cc test/controllers.js
index 6c10e24b26,42070e4c36..c456d3fd69
--- a/test/controllers.js
+++ b/test/controllers.js
@@@ -27,8 -28,14 +27,14 @@@ describe('Controllers', function ()
}, next);
},
user: function (next) {
- user.create({username: 'foo', password: 'barbar'}, next);
+ user.create({ username: 'foo', password: 'barbar' }, next);
},
+ navigation: function (next) {
+ var navigation = require('../src/navigation/admin');
+ var data = require('../install/data/navigation.json');
+
+ navigation.save(data, next);
- }
++ },
}, function (err, results) {
if (err) {
return done(err);
diff --cc test/groups.js
index 8e70341e00,ff9ad3b013..71a7bbca5a
--- a/test/groups.js
+++ b/test/groups.js
@@@ -705,10 -707,10 +705,10 @@@ describe('Groups', function ()
describe('groups cover', function () {
var socketGroups = require('../src/socket.io/groups');
var regularUid;
- var logoPath = path.join(__dirname, '../public/logo.png');
- var imagePath = path.join(__dirname, '../public/groupcover.png');
+ var logoPath = path.join(__dirname, '../test/files/test.png');
+ var imagePath = path.join(__dirname, '../test/files/groupcover.png');
before(function (done) {
- User.create({username: 'regularuser', password: '123456'}, function (err, uid) {
+ User.create({ username: 'regularuser', password: '123456' }, function (err, uid) {
assert.ifError(err);
regularUid = uid;
async.series([
diff --cc test/messaging.js
index 879bdda209,12922f9e1d..4fbaad717f
--- a/test/messaging.js
+++ b/test/messaging.js
@@@ -121,11 -121,33 +121,33 @@@ describe('Messaging Library', function
});
});
+ it('should notify offline users of message', function (done) {
+ Messaging.notificationSendDelay = 100;
+
+ db.sortedSetAdd('users:online', Date.now() - 350000, herpUid, function (err) {
+ assert.ifError(err);
- socketModules.chats.send({uid: fooUid}, {roomId: roomId, message: 'second chat message'}, function (err) {
++ socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'second chat message' }, function (err) {
+ assert.ifError(err);
+ setTimeout(function () {
+ User.notifications.get(herpUid, function (err, data) {
+ assert.ifError(err);
+ assert(data.unread[0]);
+ var notification = data.unread[0];
+ assert.equal(notification.bodyShort, '[[notifications:new_message_from, foo]]');
+ assert.equal(notification.nid, 'chat_' + fooUid + '_' + roomId);
+ assert.equal(notification.path, '/chats/' + roomId);
+ done();
+ });
+ }, 1500);
+ });
+ });
+ });
+
it('should get messages from room', function (done) {
- socketModules.chats.getMessages({uid: fooUid}, {
+ socketModules.chats.getMessages({ uid: fooUid }, {
uid: fooUid,
roomId: roomId,
- start: 0
+ start: 0,
}, function (err, messages) {
assert.ifError(err);
assert(Array.isArray(messages));
diff --cc test/posts.js
index 2c21178801,42ebbde345..39c66701eb
--- a/test/posts.js
+++ b/test/posts.js
@@@ -754,6 -755,144 +754,143 @@@ describe('Post\'s', function ()
});
});
+ describe('socket methods', function () {
-
+ var pid;
+ before(function (done) {
+ topics.reply({
+ uid: voterUid,
+ tid: topicData.tid,
+ timestamp: Date.now(),
- content: 'raw content'
++ content: 'raw content',
+ }, function (err, postData) {
+ assert.ifError(err);
+ pid = postData.pid;
+ privileges.categories.rescind(['read'], cid, 'guests', done);
+ });
+ });
+
+ var socketPosts = require('../src/socket.io/posts');
+ it('should error with invalid data', function (done) {
- socketPosts.reply({uid: 0}, null, function (err) {
++ socketPosts.reply({ uid: 0 }, null, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should error with invalid tid', function (done) {
- socketPosts.reply({uid: 0}, {tid: 0, content: 'derp'}, function (err) {
++ socketPosts.reply({ uid: 0 }, { tid: 0, content: 'derp' }, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should fail to get raw post because of privilege', function (done) {
- socketPosts.getRawPost({uid: 0}, pid, function (err) {
++ socketPosts.getRawPost({ uid: 0 }, pid, function (err) {
+ assert.equal(err.message, '[[error:no-privileges]]');
+ done();
+ });
+ });
+
+ it('should fail to get raw post because post is deleted', function (done) {
+ posts.setPostField(pid, 'deleted', 1, function (err) {
+ assert.ifError(err);
- socketPosts.getRawPost({uid: voterUid}, pid, function (err) {
++ socketPosts.getRawPost({ uid: voterUid }, pid, function (err) {
+ assert.equal(err.message, '[[error:no-post]]');
+ done();
+ });
+ });
+ });
+
+ it('should get raw post content', function (done) {
+ posts.setPostField(pid, 'deleted', 0, function (err) {
+ assert.ifError(err);
- socketPosts.getRawPost({uid: voterUid}, pid, function (err, postContent) {
++ socketPosts.getRawPost({ uid: voterUid }, pid, function (err, postContent) {
+ assert.ifError(err);
+ assert.equal(postContent, 'raw content');
+ done();
+ });
+ });
+ });
+
+ it('should get post', function (done) {
- socketPosts.getPost({uid: voterUid}, pid, function (err, postData) {
++ socketPosts.getPost({ uid: voterUid }, pid, function (err, postData) {
+ assert.ifError(err);
+ assert(postData);
+ done();
+ });
+ });
+
+ it('shold error with invalid data', function (done) {
- socketPosts.loadMoreBookmarks({uid: voterUid}, {uid: voterUid, after: null}, function (err, postData) {
++ socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: null }, function (err, postData) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should load more bookmarks', function (done) {
- socketPosts.loadMoreBookmarks({uid: voterUid}, {uid: voterUid, after: 0}, function (err, data) {
++ socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) {
+ assert.ifError(err);
+ assert(data);
+ done();
+ });
+ });
+
+ it('should load more user posts', function (done) {
- socketPosts.loadMoreUserPosts({uid: voterUid}, {uid: voterUid, after: 0}, function (err, data) {
++ socketPosts.loadMoreUserPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) {
+ assert.ifError(err);
+ assert(data);
+ done();
+ });
+ });
+
+ it('should load more best posts', function (done) {
- socketPosts.loadMoreBestPosts({uid: voterUid}, {uid: voterUid, after: 0}, function (err, data) {
++ socketPosts.loadMoreBestPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) {
+ assert.ifError(err);
+ assert(data);
+ done();
+ });
+ });
+
+ it('should load more up voted posts', function (done) {
- socketPosts.loadMoreUpVotedPosts({uid: voterUid}, {uid: voterUid, after: 0}, function (err, data) {
++ socketPosts.loadMoreUpVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) {
+ assert.ifError(err);
+ assert(data);
+ done();
+ });
+ });
+
+ it('should load more down voted posts', function (done) {
- socketPosts.loadMoreDownVotedPosts({uid: voterUid}, {uid: voterUid, after: 0}, function (err, data) {
++ socketPosts.loadMoreDownVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) {
+ assert.ifError(err);
+ assert(data);
+ done();
+ });
+ });
+
+ it('should get post category', function (done) {
- socketPosts.getCategory({uid: voterUid}, pid, function (err, postCid) {
++ socketPosts.getCategory({ uid: voterUid }, pid, function (err, postCid) {
+ assert.ifError(err);
+ assert.equal(cid, postCid);
+ done();
+ });
+ });
+
+ it('should error with invalid data', function (done) {
- socketPosts.getPidIndex({uid: voterUid}, null, function (err) {
++ socketPosts.getPidIndex({ uid: voterUid }, null, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should get pid index', function (done) {
- socketPosts.getPidIndex({uid: voterUid}, {pid: pid, tid: topicData.tid, topicPostSort: 'oldest-to-newest'}, function (err, index) {
++ socketPosts.getPidIndex({ uid: voterUid }, { pid: pid, tid: topicData.tid, topicPostSort: 'oldest-to-newest' }, function (err, index) {
+ assert.ifError(err);
+ assert.equal(index, 2);
+ done();
+ });
+ });
+ });
+
after(function (done) {
db.emptydb(done);
});
diff --cc test/topics.js
index 40a6a8bed4,9f430c995a..911d8bb216
--- a/test/topics.js
+++ b/test/topics.js
@@@ -129,8 -130,15 +129,15 @@@ describe('Topic\'s', function ()
});
});
+ it('should error if pid is not a number', function (done) {
- socketPosts.getReplies({uid: 0}, 'abc', function (err) {
++ socketPosts.getReplies({ uid: 0 }, 'abc', function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
it('should fail to create new reply with invalid user id', function (done) {
- topics.reply({uid: null, content: 'test post', tid: newTopic.tid}, function (err) {
+ topics.reply({ uid: null, content: 'test post', tid: newTopic.tid }, function (err) {
assert.equal(err.message, '[[error:no-privileges]]');
done();
});
@@@ -174,12 -182,27 +181,27 @@@
});
});
- describe('.getTopicData', function () {
- it('should not receive errors', function (done) {
- topics.getTopicData(newTopic.tid, done);
-
++
+ it('should not receive errors', function (done) {
+ topics.getTopicData(newTopic.tid, done);
+ });
+
+ it('should get topic title by pid', function (done) {
+ topics.getTitleByPid(newPost.pid, function (err, title) {
+ assert.ifError(err);
+ assert.equal(title, topic.title);
+ done();
+ });
+ });
+
+ it('should get topic data by pid', function (done) {
+ topics.getTopicDataByPid(newPost.pid, function (err, data) {
+ assert.ifError(err);
+ assert.equal(data.tid, newTopic.tid);
+ done();
});
});
-
+
describe('.getTopicWithPosts', function () {
it('should get a topic with posts and other data', function (done) {
topics.getTopicData(newTopic.tid, function (err, topicData) {
diff --cc test/uploads.js
index 17408a4170,f8a3738c8f..513f333884
--- a/test/uploads.js
+++ b/test/uploads.js
@@@ -77,7 -78,7 +77,7 @@@ describe('Upload Controllers', functio
});
it('should upload an image to a post', function (done) {
- helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../public/logo.png'), { cid: cid }, jar, csrf_token, function (err, res, body) {
- helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../test/files/test.png'), {cid: cid}, jar, csrf_token, function (err, res, body) {
++ helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../test/files/test.png'), { cid: cid }, jar, csrf_token, function (err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert(Array.isArray(body));
@@@ -90,7 -91,7 +90,7 @@@
it('should upload a file to a post', function (done) {
meta.config.allowFileUploads = 1;
- helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../public/503.html'), { cid: cid }, jar, csrf_token, function (err, res, body) {
- helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../test/files/503.html'), {cid: cid}, jar, csrf_token, function (err, res, body) {
++ helpers.uploadFile(nconf.get('url') + '/api/post/upload', path.join(__dirname, '../test/files/503.html'), { cid: cid }, jar, csrf_token, function (err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert(Array.isArray(body));
@@@ -126,7 -128,7 +126,7 @@@
});
it('should upload category image', function (done) {
- helpers.uploadFile(nconf.get('url') + '/api/admin/category/uploadpicture', path.join(__dirname, '../public/logo.png'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, function (err, res, body) {
- helpers.uploadFile(nconf.get('url') + '/api/admin/category/uploadpicture', path.join(__dirname, '../test/files/test.png'), {params: JSON.stringify({cid: cid})}, jar, csrf_token, function (err, res, body) {
++ helpers.uploadFile(nconf.get('url') + '/api/admin/category/uploadpicture', path.join(__dirname, '../test/files/test.png'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, function (err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert(Array.isArray(body));
diff --cc test/user.js
index 96ceb20bd6,70334d04e1..00794b3d0e
--- a/test/user.js
+++ b/test/user.js
@@@ -508,27 -511,32 +509,34 @@@ describe('User', function ()
});
it('should upload profile picture', function (done) {
- var path = require('path');
- var picture = {
- path: path.join(nconf.get('base_dir'), 'public', 'logo.png'),
- size: 7189,
- name: 'logo.png',
- };
- User.uploadPicture(uid, picture, function (err, uploadedPicture) {
- assert.ifError(err);
- assert.equal(uploadedPicture.url, '/assets/uploads/profile/' + uid + '-profileimg.png');
- assert.equal(uploadedPicture.path, path.join(nconf.get('base_dir'), 'public', 'uploads', 'profile', uid + '-profileimg.png'));
- done();
- });
+ helpers.copyFile(
+ path.join(nconf.get('base_dir'), 'test/files/test.png'),
- path.join(nconf.get('base_dir'), 'test/files/test_copy.png'), function (err) {
- assert.ifError(err);
- var picture = {
- path: path.join(nconf.get('base_dir'), 'test/files/test_copy.png'),
- size: 7189,
- name: 'test_copy.png',
- type: 'image/png'
- };
- User.uploadPicture(uid, picture, function (err, uploadedPicture) {
++ path.join(nconf.get('base_dir'), 'test/files/test_copy.png'),
++ function (err) {
+ assert.ifError(err);
- assert.equal(uploadedPicture.url, '/assets/uploads/profile/' + uid + '-profileavatar.png');
- assert.equal(uploadedPicture.path, path.join(nconf.get('base_dir'), 'public', 'uploads', 'profile', uid + '-profileavatar.png'));
- done();
- });
- });
++ var picture = {
++ path: path.join(nconf.get('base_dir'), 'test/files/test_copy.png'),
++ size: 7189,
++ name: 'test_copy.png',
++ type: 'image/png',
++ };
++ User.uploadPicture(uid, picture, function (err, uploadedPicture) {
++ assert.ifError(err);
++ assert.equal(uploadedPicture.url, '/assets/uploads/profile/' + uid + '-profileavatar.png');
++ assert.equal(uploadedPicture.path, path.join(nconf.get('base_dir'), 'public', 'uploads', 'profile', uid + '-profileavatar.png'));
++ done();
++ });
++ }
++ );
});
it('should return error if profile image uploads disabled', function (done) {
meta.config.allowProfileImageUploads = 0;
- var path = require('path');
var picture = {
- path: path.join(nconf.get('base_dir'), 'public', 'logo.png'),
+ path: path.join(nconf.get('base_dir'), 'test/files/test.png'),
size: 7189,
- name: 'logo.png',
+ name: 'test.png',
- type: 'image/png'
++ type: 'image/png',
};
User.uploadPicture(uid, picture, function (err) {
assert.equal(err.message, '[[error:profile-image-uploads-disabled]]');
@@@ -538,11 -546,11 +546,11 @@@
it('should return error if profile image is too big', function (done) {
meta.config.allowProfileImageUploads = 1;
- var path = require('path');
var picture = {
- path: path.join(nconf.get('base_dir'), 'public', 'logo.png'),
+ path: path.join(nconf.get('base_dir'), 'test/files/test.png'),
size: 265000,
- name: 'logo.png',
+ name: 'test.png',
- type: 'image/png'
++ type: 'image/png',
};
User.uploadPicture(uid, picture, function (err) {
assert.equal(err.message, '[[error:file-too-big, 256]]');
@@@ -550,12 -558,11 +558,11 @@@
});
});
- it('should return error if profile image file has no extension', function (done) {
- var path = require('path');
+ it('should return error if profile image has no mime type', function (done) {
var picture = {
- path: path.join(nconf.get('base_dir'), 'public', 'logo.png'),
+ path: path.join(nconf.get('base_dir'), 'test/files/test.png'),
size: 7189,
- name: 'logo',
- name: 'test'
++ name: 'test',
};
User.uploadPicture(uid, picture, function (err) {
assert.equal(err.message, '[[error:invalid-image-extension]]');
@@@ -604,20 -609,29 +609,29 @@@
});
});
+ it('should error with invalid data', function (done) {
+ var socketUser = require('../src/socket.io/user');
+
- socketUser.uploadProfileImageFromUrl({uid: uid}, {uid: uid, url: ''}, function (err) {
++ socketUser.uploadProfileImageFromUrl({ uid: uid }, { uid: uid, url: '' }, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
it('should upload picture when uploading from url', function (done) {
- var url = nconf.get('url') + '/logo.png';
+ var socketUser = require('../src/socket.io/user');
+ var url = nconf.get('url') + '/assets/logo.png';
meta.config.maximumProfileImageSize = '';
function filterMethod(data, callback) {
- data.foo += 5;
- callback(null, {url: url});
+ callback(null, { url: url });
}
- plugins.registerHook('test-plugin', {hook: 'filter:uploadImage', method: filterMethod});
+ plugins.registerHook('test-plugin', { hook: 'filter:uploadImage', method: filterMethod });
- User.uploadFromUrl(uid, url, function (err, uploadedPicture) {
- socketUser.uploadProfileImageFromUrl({uid: uid}, {uid: uid, url: url}, function (err, uploadedPicture) {
++ socketUser.uploadProfileImageFromUrl({ uid: uid }, { uid: uid, url: url }, function (err, uploadedPicture) {
assert.ifError(err);
- assert.equal(uploadedPicture.url, url);
+ assert.equal(uploadedPicture, url);
done();
});
});
@@@ -991,6 -1007,153 +1005,153 @@@
});
});
+ describe('invites', function () {
+ var socketUser = require('../src/socket.io/user');
+ var inviterUid;
+
+ before(function (done) {
+ User.create({
+ username: 'inviter',
- email: '[email protected]'
++ email: '[email protected]',
+ }, function (err, uid) {
+ assert.ifError(err);
+ inviterUid = uid;
+ done();
+ });
+ });
+
+ it('should error with invalid data', function (done) {
- socketUser.invite({uid: inviterUid}, null, function (err) {
++ socketUser.invite({ uid: inviterUid }, null, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should eror if forum is not invite only', function (done) {
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.equal(err.message, '[[error:forum-not-invite-only]]');
+ done();
+ });
+ });
+
+ it('should error if user is not admin and type is admin-invite-only', function (done) {
+ meta.config.registrationType = 'admin-invite-only';
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.equal(err.message, '[[error:no-privileges]]');
+ done();
+ });
+ });
+
+ it('should send invitation email', function (done) {
+ meta.config.registrationType = 'invite-only';
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.ifError(err);
+ done();
+ });
+ });
+
+ it('should error if ouf of invitations', function (done) {
+ meta.config.maximumInvites = 1;
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.equal(err.message, '[[error:invite-maximum-met, ' + 1 + ', ' + 1 + ']]');
+ meta.config.maximumInvites = 5;
+ done();
+ });
+ });
+
+ it('should error if email exists', function (done) {
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.equal(err.message, '[[error:email-taken]]');
+ done();
+ });
+ });
+
+ it('should send invitation email', function (done) {
- socketUser.invite({uid: inviterUid}, '[email protected]', function (err) {
++ socketUser.invite({ uid: inviterUid }, '[email protected]', function (err) {
+ assert.ifError(err);
+ done();
+ });
+ });
+
+ it('should get user\'s invites', function (done) {
+ User.getInvites(inviterUid, function (err, data) {
+ assert.ifError(err);
+ assert.notEqual(data.indexOf('[email protected]'), -1);
+ assert.notEqual(data.indexOf('[email protected]'), -1);
+ done();
+ });
+ });
+
+ it('should get all invites', function (done) {
+ User.getAllInvites(function (err, data) {
+ assert.ifError(err);
+ assert.equal(data[0].uid, inviterUid);
+ assert.notEqual(data[0].invitations.indexOf('[email protected]'), -1);
+ assert.notEqual(data[0].invitations.indexOf('[email protected]'), -1);
+ done();
+ });
+ });
+
+ it('should fail to verify invitation with invalid data', function (done) {
- User.verifyInvitation({token: '', email: ''}, function (err) {
++ User.verifyInvitation({ token: '', email: '' }, function (err) {
+ assert.equal(err.message, '[[error:invalid-data]]');
+ done();
+ });
+ });
+
+ it('should fail to verify invitation with invalid email', function (done) {
- User.verifyInvitation({token: 'test', email: '[email protected]'}, function (err) {
++ User.verifyInvitation({ token: 'test', email: '[email protected]' }, function (err) {
+ assert.equal(err.message, '[[error:invalid-token]]');
+ done();
+ });
+ });
+
+ it('should verify installation with no errors', function (done) {
- db.get('invitation:email:' + '[email protected]', function (err, token) {
++ var email = '[email protected]';
++ db.get('invitation:email:' + email, function (err, token) {
+ assert.ifError(err);
- User.verifyInvitation({token: token, email: '[email protected]'}, function (err) {
++ User.verifyInvitation({ token: token, email: '[email protected]' }, function (err) {
+ assert.ifError(err);
+ done();
+ });
+ });
+ });
+
+ it('should error with invalid username', function (done) {
+ User.deleteInvitation('doesnotexist', '[email protected]', function (err) {
+ assert.equal(err.message, '[[error:invalid-username]]');
+ done();
+ });
+ });
+
+ it('should delete invitation', function (done) {
+ var socketAdmin = require('../src/socket.io/admin');
- socketAdmin.user.deleteInvitation({uid: inviterUid}, {invitedBy: 'inviter', email: '[email protected]'}, function (err) {
++ socketAdmin.user.deleteInvitation({ uid: inviterUid }, { invitedBy: 'inviter', email: '[email protected]' }, function (err) {
+ assert.ifError(err);
+ db.isSetMember('invitation:uid:' + inviterUid, '[email protected]', function (err, isMember) {
+ assert.ifError(err);
+ assert.equal(isMember, false);
+ done();
+ });
+ });
+ });
+
+ it('should delete invitation key', function (done) {
+ User.deleteInvitationKey('[email protected]', function (err) {
+ assert.ifError(err);
+ db.isSetMember('invitation:uid:' + inviterUid, '[email protected]', function (err, isMember) {
+ assert.ifError(err);
+ assert.equal(isMember, false);
+ db.isSetMember('invitation:uids', inviterUid, function (err, isMember) {
+ assert.ifError(err);
+ assert.equal(isMember, false);
+ done();
+ });
+ });
+ });
+ });
-
+ });
+
after(function (done) {
db.emptydb(done);