formatting - server side core

v1.18.x
psychobunny 12 years ago
parent c44461e33f
commit aea3181d27

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
posts = require('./posts.js'),
utils = require('./../public/src/utils.js'),
user = require('./user.js'),
@ -10,7 +10,7 @@ var RDB = require('./redis.js'),
Categories.create = function(data, callback) {
RDB.incr('global:next_category_id', function(err, cid) {
if(err)
if (err)
return callback(err, null);
var slug = cid + '/' + utils.slugify(data.name);
@ -57,16 +57,16 @@ var RDB = require('./redis.js'),
active_users = results[1];
var categoryData = {
'category_name' : category_name,
'category_name': category_name,
'category_description': category_description,
'disabled': disabled,
'show_sidebar' : 'show',
'show_sidebar': 'show',
'show_topic_button': 'inline-block',
'no_topics_message': 'hidden',
'topic_row_size': 'col-md-9',
'category_id': category_id,
'active_users': [],
'topics' : [],
'topics': [],
'twitter-intent-url': 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug) + '&text=' + encodeURIComponent(category_name),
'facebook-share-url': 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug),
'google-share-url': 'https://plus.google.com/share?url=' + encodeURIComponent(nconf.get('url') + 'category/' + category_slug)
@ -102,7 +102,7 @@ var RDB = require('./redis.js'),
categoryData.moderator_block_class = results[1].length > 0 ? '' : 'none';
categoryData.moderators = results[1];
categoryData.active_users = results[2];
categoryData.show_sidebar = categoryData.topics.length > 0 ? 'show':'hidden';
categoryData.show_sidebar = categoryData.topics.length > 0 ? 'show' : 'hidden';
callback(null, categoryData);
});
}
@ -136,8 +136,8 @@ var RDB = require('./redis.js'),
Categories.getModerators = function(cid, callback) {
RDB.smembers('cid:' + cid + ':moderators', function(err, mods) {
if(!err) {
if(mods && mods.length) {
if (!err) {
if (mods && mods.length) {
user.getMultipleUserFields(mods, ['username'], function(err, moderators) {
callback(err, moderators);
});
@ -155,14 +155,14 @@ var RDB = require('./redis.js'),
Categories.privileges = function(cid, uid, callback) {
function isModerator(next) {
user.isModerator(uid, cid, function(isMod) {
next(null, isMod);
});
next(null, isMod);
});
}
function isAdministrator(next) {
user.isAdministrator(uid, function(isAdmin) {
next(null, isAdmin);
});
next(null, isAdmin);
});
}
async.parallel([isModerator, isAdministrator], function(err, results) {
@ -179,8 +179,8 @@ var RDB = require('./redis.js'),
topics.hasReadTopics(tids, uid, function(hasRead) {
var allread = true;
for (var i=0, ii=tids.length; i<ii; i++) {
if(hasRead[i] === 0) {
for (var i = 0, ii = tids.length; i < ii; i++) {
if (hasRead[i] === 0) {
allread = false;
break;
}
@ -197,7 +197,7 @@ var RDB = require('./redis.js'),
Categories.hasReadCategories = function(cids, uid, callback) {
var batch = RDB.multi();
for (var i=0, ii=cids.length; i<ii; i++) {
for (var i = 0, ii = cids.length; i < ii; i++) {
batch.sismember('cid:' + cids[i] + ':read_by_uid', uid);
}
@ -215,9 +215,9 @@ var RDB = require('./redis.js'),
};
Categories.getRecentReplies = function(cid, count, callback) {
RDB.zrevrange('categories:recent_posts:cid:' + cid, 0, (count<10)?10:count, function(err, pids) {
RDB.zrevrange('categories:recent_posts:cid:' + cid, 0, (count < 10) ? 10 : count, function(err, pids) {
if(err) {
if (err) {
winston.err(err);
callback([]);
return;
@ -229,7 +229,7 @@ var RDB = require('./redis.js'),
}
posts.getPostSummaryByPids(pids, function(err, postData) {
if(postData.length > count) {
if (postData.length > count) {
postData = postData.slice(0, count);
}
callback(postData);
@ -246,9 +246,9 @@ var RDB = require('./redis.js'),
}
topics.getPids(tid, function(err, pids) {
if(!err) {
if (!err) {
async.each(pids, movePost, function(err) {
if(!err) {
if (!err) {
callback(null, 1);
} else {
winston.err(err);
@ -267,15 +267,15 @@ var RDB = require('./redis.js'),
Categories.addActiveUser(cid, uid);
Categories.isUserActiveIn(oldCid, uid, function(err, active) {
if(!err && !active) {
if (!err && !active) {
Categories.removeActiveUser(oldCid, uid);
}
});
}
topics.getUids(tid, function(err, uids) {
if(!err && uids) {
for(var i=0; i<uids.length; ++i) {
if (!err && uids) {
for (var i = 0; i < uids.length; ++i) {
updateUser(uids[i]);
}
}
@ -295,7 +295,7 @@ var RDB = require('./redis.js'),
Categories.getCategoryFields = function(cid, fields, callback) {
RDB.hmgetObject('category:' + cid, fields, function(err, data) {
if(err === null)
if (err === null)
callback(data);
else
winston.err(err);
@ -312,7 +312,9 @@ var RDB = require('./redis.js'),
Categories.getCategories = function(cids, callback, current_user) {
if (!cids || !Array.isArray(cids) || cids.length === 0) {
callback({'categories' : []});
callback({
'categories': []
});
return;
}
@ -321,7 +323,7 @@ var RDB = require('./redis.js'),
function getCategory(cid, callback) {
Categories.getCategoryData(cid, function(err, categoryData) {
if(err) {
if (err) {
callback(err);
return;
}
@ -331,18 +333,20 @@ var RDB = require('./redis.js'),
categories.push(categoryData);
callback(null);
}) ;
});
});
}
async.eachSeries(cids, getCategory, function(err) {
if(err) {
if (err) {
winston.err(err);
callback(null);
return;
}
callback({'categories': categories});
callback({
'categories': categories
});
});
};
@ -350,14 +354,14 @@ var RDB = require('./redis.js'),
Categories.isUserActiveIn = function(cid, uid, callback) {
RDB.lrange('uid:' + uid + ':posts', 0, -1, function(err, pids) {
if(err)
if (err)
return callback(err, null);
function getPostCategory(pid, callback) {
posts.getPostField(pid, 'tid', function(tid) {
topics.getTopicField(tid, 'cid', function(err, postCid) {
if(err)
if (err)
return callback(err, null);
return callback(null, postCid);
@ -374,16 +378,16 @@ var RDB = require('./redis.js'),
},
function(callback) {
getPostCategory(pids[index], function(err, postCid) {
if(err)
if (err)
return callback(err);
if(postCid === cid)
if (postCid === cid)
active = true;
++index;
callback(null);
});
},
function(err) {
if(err)
if (err)
return callback(err, null);
callback(null, active);

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
posts = require('./posts.js'),
user = require('./user.js');
@ -32,7 +32,10 @@ var RDB = require('./redis.js'),
}
if (room_id) {
io.sockets.in(room_id).emit('event:rep_up', {uid: uid !== postData.uid ? postData.uid : 0, pid: pid});
io.sockets. in (room_id).emit('event:rep_up', {
uid: uid !== postData.uid ? postData.uid : 0,
pid: pid
});
}
socket.emit('api:posts.favourite', {
@ -71,7 +74,10 @@ var RDB = require('./redis.js'),
}
if (room_id) {
io.sockets.in(room_id).emit('event:rep_down', {uid: uid !== uid_of_poster ? uid_of_poster : 0, pid: pid});
io.sockets. in (room_id).emit('event:rep_down', {
uid: uid !== uid_of_poster ? uid_of_poster : 0,
pid: pid
});
}
socket.emit('api:posts.unfavourite', {
@ -95,12 +101,12 @@ var RDB = require('./redis.js'),
var loaded = 0;
var data = {};
for (var i=0, ii=pids.length; i<ii; i++) {
for (var i = 0, ii = pids.length; i < ii; i++) {
(function(post_id) {
Favourites.hasFavourited(post_id, uid, function(hasFavourited) {
data[post_id] = hasFavourited;
loaded ++;
loaded++;
if (loaded === pids.length)
callback(data);
});

@ -1,5 +1,5 @@
(function(Feed) {
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
schema = require('./schema.js'),
posts = require('./posts.js'),
topics = require('./topics.js'),
@ -15,10 +15,10 @@
};
Feed.saveFeed = function(location, feed, callback) {
var savePath = path.join(__dirname, '../', location);
var savePath = path.join(__dirname, '../', location);
fs.writeFile(savePath, feed.xml(), function (err) {
if(err) return winston.err(err);
fs.writeFile(savePath, feed.xml(), function(err) {
if (err) return winston.err(err);
if (callback) callback(err);
});
@ -30,15 +30,15 @@
topics.getTopicWithPosts(tid, 0, 0, -1, function(err, topicData) {
if (err) return callback(new Error('topic-invalid'));
var feed = new rss({
title: topicData.topic_name,
description: topicData.main_posts[0].content,
feed_url: Feed.defaults.baseUrl + '/topics/' + tid + '.rss',
site_url: nconf.get('url') + 'topic/' + topicData.slug,
image_url: topicData.main_posts[0].picture,
author: topicData.main_posts[0].username,
ttl: Feed.defaults.ttl
}),
var feed = new rss({
title: topicData.topic_name,
description: topicData.main_posts[0].content,
feed_url: Feed.defaults.baseUrl + '/topics/' + tid + '.rss',
site_url: nconf.get('url') + 'topic/' + topicData.slug,
image_url: topicData.main_posts[0].picture,
author: topicData.main_posts[0].username,
ttl: Feed.defaults.ttl
}),
topic_posts = topicData.main_posts.concat(topicData.posts),
title, postData, dateStamp;
@ -73,13 +73,13 @@
categories.getCategoryById(cid, 0, function(err, categoryData) {
if (err) return callback(new Error('category-invalid'));
var feed = new rss({
title: categoryData.category_name,
description: categoryData.category_description,
feed_url: Feed.defaults.baseUrl + '/categories/' + cid + '.rss',
site_url: nconf.get('url') + 'category/' + categoryData.category_id,
ttl: Feed.defaults.ttl
}),
var feed = new rss({
title: categoryData.category_name,
description: categoryData.category_description,
feed_url: Feed.defaults.baseUrl + '/categories/' + cid + '.rss',
site_url: nconf.get('url') + 'category/' + categoryData.category_id,
ttl: Feed.defaults.ttl
}),
topics = categoryData.topics,
title, topicData, dateStamp;

@ -1,4 +1,4 @@
var async = require('async'),
var async = require('async'),
User = require('./user'),
RDB = RDB || require('./redis'),
Groups = {
@ -68,9 +68,9 @@ var async = require('async'),
description: description,
deleted: '0'
})
.exec(function(err) {
Groups.get(gid, {}, callback);
});
.exec(function(err) {
Groups.get(gid, {}, callback);
});
});
} else callback(new Error('group-exists'))
});

@ -1,33 +1,33 @@
var request = require('request');
(function(imgur) {
var clientID = '';
imgur.upload = function(image, type, callback) {
var options = {
url: 'https://api.imgur.com/3/upload.json',
headers: {
'Authorization': 'Client-ID ' + clientID
}
}
};
var post = request.post(options, function(err, req, body) {
try{
try {
callback(err, JSON.parse(body));
} catch(e) {
} catch (e) {
callback(err, body);
}
});
var upload = post.form({type:type, image:image});
var upload = post.form({
type: type,
image: image
});
}
imgur.setClientID = function(id) {
clientID = id;
}
}(exports));
}
}(exports));

@ -1,4 +1,4 @@
var async = require('async'),
var async = require('async'),
utils = require('../public/src/utils.js'),
fs = require('fs'),
url = require('url'),
@ -8,46 +8,38 @@ var async = require('async'),
reds = require('reds'),
install = {
questions: [
{
name: 'base_url',
description: 'URL of this installation',
'default': 'http://localhost',
pattern: /^http(?:s)?:\/\//,
message: 'Base URL must begin with \'http://\' or \'https://\'',
},
{
name: 'port',
description: 'Port number of your NodeBB',
'default': 4567
},
{
name: 'use_port',
description: 'Use a port number to access NodeBB?',
'default': 'y',
pattern: /y[es]*|n[o]?/,
message: 'Please enter \'yes\' or \'no\'',
},
{
name: 'secret',
description: 'Please enter a NodeBB secret',
'default': utils.generateUUID()
},
{
name: 'redis:host',
description: 'Host IP or address of your Redis instance',
'default': '127.0.0.1'
},
{
name: 'redis:port',
description: 'Host port of your Redis instance',
'default': 6379
},
{
name: 'redis:password',
description: 'Password of your Redis database'
}
],
questions: [{
name: 'base_url',
description: 'URL of this installation',
'default': 'http://localhost',
pattern: /^http(?:s)?:\/\//,
message: 'Base URL must begin with \'http://\' or \'https://\'',
}, {
name: 'port',
description: 'Port number of your NodeBB',
'default': 4567
}, {
name: 'use_port',
description: 'Use a port number to access NodeBB?',
'default': 'y',
pattern: /y[es]*|n[o]?/,
message: 'Please enter \'yes\' or \'no\'',
}, {
name: 'secret',
description: 'Please enter a NodeBB secret',
'default': utils.generateUUID()
}, {
name: 'redis:host',
description: 'Host IP or address of your Redis instance',
'default': '127.0.0.1'
}, {
name: 'redis:port',
description: 'Host port of your Redis instance',
'default': 6379
}, {
name: 'redis:password',
description: 'Password of your Redis database'
}],
setup: function(callback) {
async.series([
function(next) {
@ -96,16 +88,29 @@ var async = require('async'),
function(next) {
// Applying default database configs
winston.info('Populating database with default configs, if not already set...')
var meta = require('./meta'),
defaults = [
{ field: 'postDelay', value: 10000 },
{ field: 'minimumPostLength', value: 8 },
{ field: 'minimumTitleLength', value: 3 },
{ field: 'minimumUsernameLength', value: 2 },
{ field: 'maximumUsernameLength', value: 16 },
{ field: 'minimumPasswordLength', value: 6 },
{ field: 'imgurClientID', value: '' }
];
var meta = require('./meta'),
defaults = [{
field: 'postDelay',
value: 10000
}, {
field: 'minimumPostLength',
value: 8
}, {
field: 'minimumTitleLength',
value: 3
}, {
field: 'minimumUsernameLength',
value: 2
}, {
field: 'maximumUsernameLength',
value: 16
}, {
field: 'minimumPasswordLength',
value: 6
}, {
field: 'imgurClientID',
value: ''
}];
async.each(defaults, function(configObj, next) {
meta.configs.setOnEmpty(configObj.field, configObj.value, next);
@ -115,7 +120,7 @@ var async = require('async'),
},
function(next) {
// Check if an administrator needs to be created
var Groups = require('./groups');
var Groups = require('./groups');
Groups.getGidFromName('Administrators', function(err, gid) {
if (err) return next(err.message);
@ -132,7 +137,7 @@ var async = require('async'),
},
function(next) {
// Categories
var Categories = require('./categories'),
var Categories = require('./categories'),
admin = {
categories: require('./admin/categories')
};
@ -159,13 +164,13 @@ var async = require('async'),
},
function(next) {
// Default plugins
var Plugins = require('./plugins');
var Plugins = require('./plugins');
winston.info('Enabling default plugins');
var defaultEnabled = [
'nodebb-plugin-markdown', 'nodebb-plugin-mentions'
];
var defaultEnabled = [
'nodebb-plugin-markdown', 'nodebb-plugin-mentions'
];
async.each(defaultEnabled, function(pluginId, next) {
Plugins.isActive(pluginId, function(err, active) {
@ -185,31 +190,27 @@ var async = require('async'),
});
},
createAdmin: function(callback) {
var User = require('./user'),
var User = require('./user'),
Groups = require('./groups');
winston.warn('No administrators have been detected, running initial user setup');
var questions = [
{
name: 'username',
description: 'Administrator username',
required: true,
type: 'string'
},
{
name: 'email',
description: 'Administrator email address',
pattern: /.+@.+/,
required: true
},
{
name: 'password',
description: 'Password',
required: true,
hidden: true,
type: 'string'
}
],
var questions = [{
name: 'username',
description: 'Administrator username',
required: true,
type: 'string'
}, {
name: 'email',
description: 'Administrator email address',
pattern: /.+@.+/,
required: true
}, {
name: 'password',
description: 'Password',
required: true,
hidden: true,
type: 'string'
}],
getAdminInfo = function(callback) {
prompt.get(questions, function(err, results) {
if (!results) return callback(new Error('aborted'));
@ -251,9 +252,11 @@ var async = require('async'),
], function(err) {
winston.info('Configuration Saved OK');
nconf.file({ file: path.join(__dirname, '..', 'config.json') });
nconf.file({
file: path.join(__dirname, '..', 'config.json')
});
var RDB = require('./redis');
var RDB = require('./redis');
reds.createClient = function() {
return reds.client || (reds.client = RDB);
}

@ -1,11 +1,10 @@
var user = require('./user.js'),
bcrypt = require('bcrypt'),
RDB = require('./redis.js'),
path = require('path'),
winston = require('winston');
(function(Login){
(function(Login) {
Login.loginViaLocal = function(username, password, next) {
if (!username || !password) {
@ -24,9 +23,9 @@ var user = require('./user.js'),
}
user.getUserFields(uid, ['password', 'banned'], function(err, userData) {
if(err) return next(err);
if (err) return next(err);
if(userData.banned && userData.banned === '1') {
if (userData.banned && userData.banned === '1') {
return next({
status: "error",
message: "user-banned"
@ -34,14 +33,18 @@ var user = require('./user.js'),
}
bcrypt.compare(password, userData.password, function(err, res) {
if(err) {
if (err) {
winston.err(err.message);
next(new Error('bcrypt compare error'));
return;
}
if (res) {
next(null, { user: { uid: uid } });
next(null, {
user: {
uid: uid
}
});
} else {
next(new Error('invalid-password'));
}
@ -70,7 +73,7 @@ var user = require('./user.js'),
// Save their photo, if present
if (photos && photos.length > 0) {
var photoUrl = photos[0].value;
var photoUrl = photos[0].value;
photoUrl = path.dirname(photoUrl) + '/' + path.basename(photoUrl, path.extname(photoUrl)).slice(0, -6) + 'bigger' + path.extname(photoUrl);
user.setUserField(uid, 'uploadedpicture', photoUrl);
user.setUserField(uid, 'picture', photoUrl);
@ -157,5 +160,4 @@ var user = require('./user.js'),
});
}
}(exports));
}(exports));

@ -1,4 +1,3 @@
var RDB = require('./redis'),
async = require('async');
@ -15,7 +14,7 @@ var RDB = require('./redis'),
var uids = sortUids(fromuid, touid);
RDB.incr('global:next_message_id', function(err, mid) {
if(err)
if (err)
return callback(err, null);
var message = {
@ -36,10 +35,10 @@ var RDB = require('./redis'),
var uids = sortUids(fromuid, touid);
RDB.lrange('messages:' + uids[0] + ':' + uids[1], 0, -1, function(err, mids) {
if(err)
if (err)
return callback(err, null);
if(!mids || !mids.length) {
if (!mids || !mids.length) {
return callback(null, []);
}
@ -50,10 +49,10 @@ var RDB = require('./redis'),
function getMessage(mid, next) {
RDB.hgetall('message:' + mid, function(err, message) {
if(err)
if (err)
return next(err);
if(message.fromuid === fromuid)
if (message.fromuid === fromuid)
message.content = 'You : ' + message.content;
else
message.content = tousername + ' : ' + message.content;
@ -64,7 +63,7 @@ var RDB = require('./redis'),
}
async.eachSeries(mids, getMessage, function(err) {
if(err)
if (err)
return callback(err, null);
callback(null, messages);

@ -35,7 +35,7 @@ var utils = require('./../public/src/utils.js'),
},
set: function(field, value, callback) {
RDB.hset('config', field, value, function(err, res) {
if(callback)
if (callback)
callback(err, res);
});
},
@ -52,7 +52,7 @@ var utils = require('./../public/src/utils.js'),
Meta.themes = {
get: function(callback) {
var themePath = path.join(__dirname, '../node_modules');
var themePath = path.join(__dirname, '../node_modules');
fs.readdir(themePath, function(err, files) {
async.filter(files, function(file, next) {
fs.stat(path.join(themePath, file), function(err, fileStat) {
@ -62,11 +62,11 @@ var utils = require('./../public/src/utils.js'),
});
}, function(themes) {
async.map(themes, function(theme, next) {
var config = path.join(themePath, theme, 'theme.json');
var config = path.join(themePath, theme, 'theme.json');
if (fs.existsSync(config)) {
fs.readFile(config, function(err, file) {
var configObj = JSON.parse(file.toString());
var configObj = JSON.parse(file.toString());
if (!configObj.screenshot) configObj.screenshot = nconf.get('relative_path') + '/images/themes/default.png';
next(err, configObj);
});
@ -84,7 +84,7 @@ var utils = require('./../public/src/utils.js'),
Meta.title = {
build: function(urlFragment, current_user, callback) {
var self = this,
var self = this,
user = require('./user');
async.parallel({
@ -95,7 +95,7 @@ var utils = require('./../public/src/utils.js'),
user.notifications.getUnreadCount(current_user, next);
}
}, function(err, values) {
var title;
var title;
if (err) title = Meta.config.title || 'NodeBB';
else title = (values.title ? values.title + ' | ' : '') + (Meta.config.title || 'NodeBB');
@ -113,13 +113,13 @@ var utils = require('./../public/src/utils.js'),
} else if (urlFragment === 'users') {
callback(null, 'Registered Users');
} else if (/^category\/\d+\/?/.test(urlFragment)) {
var cid = urlFragment.match(/category\/(\d+)/)[1];
var cid = urlFragment.match(/category\/(\d+)/)[1];
require('./categories').getCategoryField(cid, 'name', function(err, name) {
callback(null, name);
});
} else if (/^topic\/\d+\/?/.test(urlFragment)) {
var tid = urlFragment.match(/topic\/(\d+)/)[1];
var tid = urlFragment.match(/topic\/(\d+)/)[1];
require('./topics').getTopicField(tid, 'title', function(err, title) {
callback(null, title);
@ -129,5 +129,4 @@ var utils = require('./../public/src/utils.js'),
}
}(exports));
}(exports));

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
async = require('async'),
utils = require('../public/src/utils.js'),
@ -35,25 +35,25 @@ var RDB = require('./redis.js'),
'path', path || null,
'datetime', Date.now(),
'uniqueId', uniqueId || utils.generateUUID(),
function(err, status) {
if (status === 'OK') callback(nid);
});
function(err, status) {
if (status === 'OK') callback(nid);
});
});
},
push: function(nid, uids, callback) {
if (!Array.isArray(uids)) uids = [uids];
var numUids = uids.length,
var numUids = uids.length,
x;
notifications.get(nid, function(notif_data) {
for(x=0;x<numUids;x++) {
for (x = 0; x < numUids; x++) {
if (parseInt(uids[x]) > 0) {
(function(uid) {
notifications.remove_by_uniqueId(notif_data.uniqueId, uid, function() {
RDB.zadd('uid:' + uid + ':notifications:unread', notif_data.score, nid);
RDB.set('uid:' + uid + ':notifications:flag', 1);
global.io.sockets.in('uid_' + uid).emit('event:new_notification');
global.io.sockets. in ('uid_' + uid).emit('event:new_notification');
if (callback) callback(true);
});
})(uids[x]);

@ -1,4 +1,4 @@
var fs = require('fs'),
var fs = require('fs'),
path = require('path'),
RDB = require('./redis.js'),
async = require('async'),
@ -16,7 +16,7 @@ var fs = require('fs'),
if (this.initialized) return;
if (global.env === 'development') winston.info('[plugins] Initializing plugins system');
var _self = this;
var _self = this;
// Read the list of activated plugins and require their libraries
async.waterfall([
@ -27,13 +27,13 @@ var fs = require('fs'),
if (plugins && Array.isArray(plugins) && plugins.length > 0) {
async.each(plugins, function(plugin, next) {
// TODO: Update this check to also check node_modules
var pluginPath = path.join(__dirname, '../plugins/', plugin),
var pluginPath = path.join(__dirname, '../plugins/', plugin),
modulePath = path.join(__dirname, '../node_modules/', plugin);
if (fs.existsSync(pluginPath)) _self.loadPlugin(pluginPath, next);
else if (fs.existsSync(modulePath)) _self.loadPlugin(modulePath, next);
else {
if (global.env === 'development') winston.warn('[plugins] Plugin \'' + plugin + '\' not found');
next(); // Ignore this plugin silently
next(); // Ignore this plugin silently
}
}, next);
} else next();
@ -41,7 +41,7 @@ var fs = require('fs'),
function(next) {
if (global.env === 'development') winston.info('[plugins] Sorting hooks to fire in priority sequence');
Object.keys(_self.loadedHooks).forEach(function(hook) {
var hooks = _self.loadedHooks[hook];
var hooks = _self.loadedHooks[hook];
hooks = hooks.sort(function(a, b) {
return a[3] - b[3];
});
@ -65,12 +65,12 @@ var fs = require('fs'),
},
initialized: false,
loadPlugin: function(pluginPath, callback) {
var _self = this;
var _self = this;
fs.readFile(path.join(pluginPath, 'plugin.json'), function(err, data) {
if (err) return callback(err);
var pluginData = JSON.parse(data),
var pluginData = JSON.parse(data),
libraryPath, staticDir;
async.parallel([
@ -119,30 +119,30 @@ var fs = require('fs'),
`data.callbacked`, whether or not the hook expects a callback (true), or a return (false). Only used for filters. (Default: false)
`data.priority`, the relative priority of the method when it is eventually called (default: 10)
*/
var _self = this;
var _self = this;
if (data.hook && data.method) {
// Assign default priority of 10 if none is passed-in
if (!data.priority) data.priority = 10;
_self.loadedHooks[data.hook] = _self.loadedHooks[data.hook] || [];
_self.loadedHooks[data.hook].push([id, data.method, !!data.callbacked, data.priority]);
_self.loadedHooks[data.hook].push([id, data.method, !! data.callbacked, data.priority]);
if (global.env === 'development') winston.info('[plugins] Hook registered: ' + data.hook + ' will call ' + id);
callback();
} else return;
},
fireHook: function(hook, args, callback) {
var _self = this
hookList = this.loadedHooks[hook];
var _self = this
hookList = this.loadedHooks[hook];
if (hookList && Array.isArray(hookList)) {
if (global.env === 'development') winston.info('[plugins] Firing hook: \'' + hook + '\'');
var hookType = hook.split(':')[0];
switch(hookType) {
var hookType = hook.split(':')[0];
switch (hookType) {
case 'filter':
// Filters only take one argument, so only args[0] will be passed in
var returnVal = (Array.isArray(args) ? args[0] : args);
var returnVal = (Array.isArray(args) ? args[0] : args);
async.eachSeries(hookList, function(hookObj, next) {
if (hookObj[2]) {
@ -163,7 +163,7 @@ var fs = require('fs'),
callback(returnVal);
});
break;
break;
case 'action':
async.each(hookList, function(hookObj) {
if (
@ -176,14 +176,14 @@ var fs = require('fs'),
if (global.env === 'development') winston.info('[plugins] Expected method \'' + hookObj[1] + '\' in plugin \'' + hookObj[0] + '\' not found, skipping.');
}
});
break;
break;
default:
// Do nothing...
break;
break;
}
} else {
// Otherwise, this hook contains no methods
var returnVal = (Array.isArray(args) ? args[0] : args);
var returnVal = (Array.isArray(args) ? args[0] : args);
if (callback) callback(returnVal);
}
},
@ -214,9 +214,9 @@ var fs = require('fs'),
},
showInstalled: function(callback) {
// TODO: Also check /node_modules
var _self = this;
localPluginPath = path.join(__dirname, '../plugins'),
npmPluginPath = path.join(__dirname, '../node_modules');
var _self = this;
localPluginPath = path.join(__dirname, '../plugins'),
npmPluginPath = path.join(__dirname, '../node_modules');
async.waterfall([
function(next) {
@ -233,7 +233,7 @@ var fs = require('fs'),
dirs[0] = dirs[0].map(function(file) {
return path.join(localPluginPath, file);
}).filter(function(file) {
var stats = fs.statSync(file);
var stats = fs.statSync(file);
if (stats.isDirectory()) return true;
else return false;
});
@ -241,8 +241,8 @@ var fs = require('fs'),
dirs[1] = dirs[1].map(function(file) {
return path.join(npmPluginPath, file);
}).filter(function(file) {
var stats = fs.statSync(file);
if (stats.isDirectory() && file.substr(npmPluginPath.length+1, 14) === 'nodebb-plugin-') return true;
var stats = fs.statSync(file);
if (stats.isDirectory() && file.substr(npmPluginPath.length + 1, 14) === 'nodebb-plugin-') return true;
else return false;
});
@ -250,17 +250,17 @@ var fs = require('fs'),
});
},
function(files, next) {
var plugins = [];
var plugins = [];
async.each(files, function(file, next) {
var configPath;
var configPath;
async.waterfall([
function(next) {
fs.readFile(path.join(file, 'plugin.json'), next);
},
function(configJSON, next) {
var config = JSON.parse(configJSON);
var config = JSON.parse(configJSON);
_self.isActive(config.id, function(err, active) {
if (err) next(new Error('no-active-state'));
@ -272,7 +272,7 @@ var fs = require('fs'),
});
}
], function(err, config) {
if (err) return next(); // Silently fail
if (err) return next(); // Silently fail
plugins.push(config);
next();

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
posts = require('./posts.js'),
topics = require('./topics'),
threadTools = require('./threadTools.js'),
@ -57,7 +57,7 @@ var RDB = require('./redis.js'),
}
PostTools.edit = function(uid, pid, title, content, images) {
var success = function() {
var success = function() {
posts.setPostField(pid, 'content', content);
posts.setPostField(pid, 'edited', Date.now());
posts.setPostField(pid, 'editor', uid);
@ -82,7 +82,10 @@ var RDB = require('./redis.js'),
});
}
next(null, {tid:tid, isMainPost:isMainPost});
next(null, {
tid: tid,
isMainPost: isMainPost
});
});
});
},
@ -90,12 +93,12 @@ var RDB = require('./redis.js'),
PostTools.toHTML(content, next);
}
], function(err, results) {
io.sockets.in('topic_' + results[1].tid).emit('event:post_edited', {
io.sockets. in ('topic_' + results[1].tid).emit('event:post_edited', {
pid: pid,
title: title,
isMainPost: results[1].isMainPost,
content: results[2],
uploadedImages:results[0]
uploadedImages: results[0]
});
});
};
@ -117,13 +120,13 @@ var RDB = require('./redis.js'),
postSearch.remove(pid);
posts.getPostFields(pid, ['tid', 'uid'], function(postData) {
RDB.hincrby('topic:'+postData.tid, 'postcount', -1);
RDB.hincrby('topic:' + postData.tid, 'postcount', -1);
user.decrementUserFieldBy(postData.uid, 'postcount', 1, function(err, postcount) {
RDB.zadd('users:postcount', postcount, postData.uid);
});
io.sockets.in('topic_' + postData.tid).emit('event:post_deleted', {
io.sockets. in ('topic_' + postData.tid).emit('event:post_deleted', {
pid: pid
});
@ -153,35 +156,35 @@ var RDB = require('./redis.js'),
PostTools.restore = function(uid, pid) {
var success = function() {
posts.setPostField(pid, 'deleted', 0);
posts.setPostField(pid, 'deleted', 0);
posts.getPostFields(pid, ['tid', 'uid', 'content'], function(postData) {
RDB.hincrby('topic:'+postData.tid, 'postcount', 1);
posts.getPostFields(pid, ['tid', 'uid', 'content'], function(postData) {
RDB.hincrby('topic:' + postData.tid, 'postcount', 1);
user.incrementUserFieldBy(postData.uid, 'postcount', 1);
user.incrementUserFieldBy(postData.uid, 'postcount', 1);
io.sockets.in('topic_' + postData.tid).emit('event:post_restored', {
pid: pid
});
io.sockets. in ('topic_' + postData.tid).emit('event:post_restored', {
pid: pid
});
threadTools.get_latest_undeleted_pid(postData.tid, function(err, pid) {
posts.getPostField(pid, 'timestamp', function(timestamp) {
topics.updateTimestamp(postData.tid, timestamp);
});
threadTools.get_latest_undeleted_pid(postData.tid, function(err, pid) {
posts.getPostField(pid, 'timestamp', function(timestamp) {
topics.updateTimestamp(postData.tid, timestamp);
});
});
// Restore topic if it is the only post
topics.getTopicField(postData.tid, 'postcount', function(err, count) {
if (count === '1') {
threadTools.restore(postData.tid, uid);
}
});
// Restore topic if it is the only post
topics.getTopicField(postData.tid, 'postcount', function(err, count) {
if (count === '1') {
threadTools.restore(postData.tid, uid);
}
});
Feed.updateTopic(postData.tid);
Feed.updateTopic(postData.tid);
postSearch.index(postData.content, pid);
});
};
postSearch.index(postData.content, pid);
});
};
PostTools.privileges(pid, uid, function(privileges) {
if (privileges.editable) {
@ -193,11 +196,11 @@ var RDB = require('./redis.js'),
PostTools.toHTML = function(raw, callback) {
raw = raw || '';
plugins.fireHook('filter:post.parse', raw, function(parsed) {
var cheerio = require('cheerio');
var cheerio = require('cheerio');
if (parsed && parsed.length > 0) {
var parsedContentDOM = cheerio.load(parsed);
var domain = nconf.get('url');
var parsedContentDOM = cheerio.load(parsed);
var domain = nconf.get('url');
parsedContentDOM('a').each(function() {
this.attr('rel', 'nofollow');

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
utils = require('./../public/src/utils.js'),
schema = require('./schema.js'),
user = require('./user.js'),
@ -34,7 +34,7 @@ var RDB = require('./redis.js'),
Posts.addUserInfoToPost = function(post, callback) {
user.getUserFields(post.uid, ['username', 'userslug', 'reputation', 'postcount', 'picture', 'signature', 'banned'], function(err, userData) {
if(err) return callback();
if (err) return callback();
postTools.toHTML(userData.signature, function(err, signature) {
post.username = userData.username || 'anonymous';
@ -42,12 +42,12 @@ var RDB = require('./redis.js'),
post.user_rep = userData.reputation || 0;
post.user_postcount = userData.postcount || 0;
post.user_banned = userData.banned || '0';
post.picture = userData.picture || require('gravatar').url('', {}, https=nconf.get('https'));
post.picture = userData.picture || require('gravatar').url('', {}, https = nconf.get('https'));
post.signature = signature;
if(post.editor !== '') {
if (post.editor !== '') {
user.getUserFields(post.editor, ['username', 'userslug'], function(err, editorData) {
if(err) return callback();
if (err) return callback();
post.editorname = editorData.username;
post.editorslug = editorData.userslug;
@ -104,7 +104,7 @@ var RDB = require('./redis.js'),
}
async.eachSeries(pids, getPostSummary, function(err) {
if(!err) {
if (!err) {
callback(null, posts);
} else {
callback(err, null);
@ -120,22 +120,20 @@ var RDB = require('./redis.js'),
Posts.getPostData = function(pid, callback) {
RDB.hgetall('post:' + pid, function(err, data) {
if(err === null) {
if (err === null) {
plugins.fireHook('filter:post.get', data, function(data) {
callback(data);
});
}
else
} else
console.log(err);
});
}
Posts.getPostFields = function(pid, fields, callback) {
RDB.hmgetObject('post:' + pid, fields, function(err, data) {
if(err === null) {
if (err === null) {
callback(data);
}
else {
} else {
console.log(err);
}
});
@ -143,7 +141,7 @@ var RDB = require('./redis.js'),
Posts.getPostField = function(pid, field, callback) {
RDB.hget('post:' + pid, field, function(err, data) {
if(err === null)
if (err === null)
callback(data);
else
console.log(err);
@ -158,18 +156,18 @@ var RDB = require('./redis.js'),
Posts.getPostsByPids = function(pids, callback) {
var posts = [];
async.eachSeries(pids, function (pid, callback) {
async.eachSeries(pids, function(pid, callback) {
Posts.getPostData(pid, function(postData) {
if(postData) {
if (postData) {
postData.relativeTime = utils.relativeTime(postData.timestamp);
postData.post_rep = postData.reputation;
postData['edited-class'] = postData.editor !== '' ? '' : 'none';
postData['relativeEditTime'] = postData.edited !== '0' ? utils.relativeTime(postData.edited) : '';
if(postData.uploadedImages) {
if (postData.uploadedImages) {
try {
postData.uploadedImages = JSON.parse(postData.uploadedImages);
} catch(err) {
} catch (err) {
postData.uploadedImages = [];
winston.err(err);
}
@ -185,7 +183,7 @@ var RDB = require('./redis.js'),
}
});
}, function(err) {
if(!err) {
if (!err) {
callback(null, posts);
} else {
callback(err, null);
@ -220,14 +218,14 @@ var RDB = require('./redis.js'),
Posts.emitTooManyPostsAlert = function(socket) {
socket.emit('event:alert', {
title: 'Too many posts!',
message: 'You can only post every '+ meta.config.postDelay/1000 + ' seconds.',
message: 'You can only post every ' + meta.config.postDelay / 1000 + ' seconds.',
type: 'danger',
timeout: 2000
});
}
Posts.reply = function(tid, uid, content, images, callback) {
if(content) {
if (content) {
content = content.trim();
}
@ -237,7 +235,7 @@ var RDB = require('./redis.js'),
}
user.getUserField(uid, 'lastposttime', function(lastposttime) {
if(Date.now() - lastposttime < meta.config.postDelay) {
if (Date.now() - lastposttime < meta.config.postDelay) {
callback(new Error('too-many-posts'), null);
return;
}
@ -256,10 +254,12 @@ var RDB = require('./redis.js'),
threadTools.notify_followers(tid, uid);
Posts.addUserInfoToPost(postData, function() {
var socketData = { posts: [postData] };
io.sockets.in('topic_' + tid).emit('event:new_post', socketData);
io.sockets.in('recent_posts').emit('event:new_post', socketData);
io.sockets.in('users/' + uid).emit('event:new_post', socketData);
var socketData = {
posts: [postData]
};
io.sockets. in ('topic_' + tid).emit('event:new_post', socketData);
io.sockets. in ('recent_posts').emit('event:new_post', socketData);
io.sockets. in ('users/' + uid).emit('event:new_post', socketData);
});
callback(null, 'Reply successful');
@ -333,7 +333,7 @@ var RDB = require('./redis.js'),
async.parallel({
uploadedImages: function(next) {
Posts.uploadPostImages(postData.pid, images, function(err, uploadedImages) {
if(err) {
if (err) {
winston.error('Uploading images failed!', err.stack);
next(null, []);
} else {
@ -369,21 +369,26 @@ var RDB = require('./redis.js'),
var imgur = require('./imgur');
imgur.setClientID(meta.config.imgurClientID);
if(!images)
if (!images)
return callback(null, []);
var uploadedImages = images.filter(function(image) { return !!image.url; });
var uploadedImages = images.filter(function(image) {
return !!image.url;
});
function uploadImage(image, next) {
if(!image.data)
if (!image.data)
return next(null);
imgur.upload(image.data, 'base64', function(err, data) {
if(err) {
if (err) {
next(err);
} else {
if(data.success) {
var img= {url:data.data.link, name:image.name};
if (data.success) {
var img = {
url: data.data.link,
name: image.name
};
uploadedImages.push(img);
next(null);
} else {
@ -395,7 +400,7 @@ var RDB = require('./redis.js'),
}
async.each(images, uploadImage, function(err) {
if(!err) {
if (!err) {
Posts.setPostField(pid, 'uploadedImages', JSON.stringify(uploadedImages));
callback(null, uploadedImages);
} else {
@ -409,28 +414,26 @@ var RDB = require('./redis.js'),
user.getPostIds(uid, start, end, function(pids) {
if(pids && pids.length) {
if (pids && pids.length) {
Posts.getPostsByPids(pids, function(err, posts) {
callback(posts);
});
}
else
} else
callback([]);
});
}
Posts.getTopicPostStats = function(socket) {
RDB.mget(['totaltopiccount', 'totalpostcount'], function(err, data) {
if(err === null) {
if (err === null) {
var stats = {
topics: data[0]?data[0]:0,
posts: data[1]?data[1]:0
topics: data[0] ? data[0] : 0,
posts: data[1] ? data[1] : 0
};
socket.emit('post.stats', stats);
}
else
} else
console.log(err);
});
}
@ -442,7 +445,7 @@ var RDB = require('./redis.js'),
Posts.getPostField(pid, 'content', function(content) {
postSearch.remove(pid, function() {
if(content && content.length) {
if (content && content.length) {
postSearch.index(content, pid);
}
callback(null);
@ -451,7 +454,7 @@ var RDB = require('./redis.js'),
}
async.each(pids, reIndex, function(err) {
if(err) {
if (err) {
callback(err, null);
} else {
callback(null, 'Posts reindexed');
@ -461,11 +464,11 @@ var RDB = require('./redis.js'),
Posts.getFavourites = function(uid, callback) {
RDB.zrevrange('uid:' + uid + ':favourites', 0, -1, function(err, pids) {
if(err)
if (err)
return callback(err, null);
Posts.getPostSummaryByPids(pids, function(err, posts) {
if(err)
if (err)
return callback(err, null);
callback(null, posts);

@ -5,7 +5,7 @@
RedisDB.exports = redis.createClient(nconf.get('redis:port'), nconf.get('redis:host'));
if(nconf.get('redis:password')) {
if (nconf.get('redis:password')) {
RedisDB.exports.auth(nconf.get('redis:password'));
}
@ -20,8 +20,8 @@
/*
* A possibly more efficient way of doing multiple sismember calls
*/
* A possibly more efficient way of doing multiple sismember calls
*/
RedisDB.exports.sismembers = function(key, needles, callback) {
var tempkey = key + ':temp:' + utils.generateUUID();
RedisDB.exports.sadd(tempkey, needles, function() {
@ -35,18 +35,17 @@
/*
* gets fields of a hash as an object instead of an array
*/
RedisDB.exports.hmgetObject = function (key, fields, callback) {
RedisDB.exports.hmgetObject = function(key, fields, callback) {
RedisDB.exports.hmget(key, fields, function(err, data) {
if(err === null) {
if (err === null) {
var returnData = {};
for(var i=0, ii=fields.length; i<ii; ++i) {
for (var i = 0, ii = fields.length; i < ii; ++i) {
returnData[fields[i]] = data[i];
}
callback(null, returnData);
}
else {
} else {
console.log(err);
callback(err, null);
}

@ -1,4 +1,4 @@
var path = require('path'),
var path = require('path'),
async = require('async'),
sm = require('sitemap'),
url = require('url'),
@ -6,14 +6,22 @@ var path = require('path'),
topics = require('./topics'),
sitemap = {
getStaticUrls: function(callback) {
callback(null, [
{ url: '', changefreq: 'weekly', priority: '0.6' },
{ url: 'recent', changefreq: 'daily', priority: '0.4' },
{ url: 'users', changefreq: 'daily', priority: '0.4' }
]);
callback(null, [{
url: '',
changefreq: 'weekly',
priority: '0.6'
}, {
url: 'recent',
changefreq: 'daily',
priority: '0.4'
}, {
url: 'users',
changefreq: 'daily',
priority: '0.4'
}]);
},
getDynamicUrls: function(callback) {
var returnUrls = [];
var returnUrls = [];
async.parallel([
function(next) {
@ -33,7 +41,7 @@ var path = require('path'),
}, 0);
},
function(next) {
var topicUrls = [];
var topicUrls = [];
topics.getAllTopics(null, null, function(topics) {
topics.forEach(function(topic) {
if (topic.deleted !== '1') {

@ -1,4 +1,4 @@
var RDB = require('./redis.js'),
var RDB = require('./redis.js'),
topics = require('./topics.js'),
categories = require('./categories.js'),
user = require('./user.js'),
@ -15,7 +15,7 @@ var RDB = require('./redis.js'),
ThreadTools.exists = function(tid, callback) {
RDB.sismember('topics:tid', tid, function(err, ismember) {
if (err) RDB.handle(err);
callback(!!ismember || false);
callback( !! ismember || false);
});
}
@ -52,7 +52,7 @@ var RDB = require('./redis.js'),
topics.setTopicField(tid, 'locked', 1);
if (socket) {
io.sockets.in('topic_' + tid).emit('event:topic_locked', {
io.sockets. in ('topic_' + tid).emit('event:topic_locked', {
tid: tid,
status: 'ok'
});
@ -72,7 +72,7 @@ var RDB = require('./redis.js'),
topics.setTopicField(tid, 'locked', 0);
if (socket) {
io.sockets.in('topic_' + tid).emit('event:topic_unlocked', {
io.sockets. in ('topic_' + tid).emit('event:topic_unlocked', {
tid: tid,
status: 'ok'
});
@ -95,7 +95,7 @@ var RDB = require('./redis.js'),
topicSearch.remove(tid);
io.sockets.in('topic_' + tid).emit('event:topic_deleted', {
io.sockets. in ('topic_' + tid).emit('event:topic_deleted', {
tid: tid,
status: 'ok'
});
@ -112,7 +112,7 @@ var RDB = require('./redis.js'),
topics.restore(tid);
ThreadTools.unlock(tid, uid);
io.sockets.in('topic_' + tid).emit('event:topic_restored', {
io.sockets. in ('topic_' + tid).emit('event:topic_restored', {
tid: tid,
status: 'ok'
});
@ -137,11 +137,11 @@ var RDB = require('./redis.js'),
topics.setTopicField(tid, 'pinned', 1);
topics.getTopicField(tid, 'cid', function(err, cid) {
RDB.zadd('categories:' + cid + ':tid', Math.pow(2,53), tid);
RDB.zadd('categories:' + cid + ':tid', Math.pow(2, 53), tid);
});
if (socket) {
io.sockets.in('topic_' + tid).emit('event:topic_pinned', {
io.sockets. in ('topic_' + tid).emit('event:topic_pinned', {
tid: tid,
status: 'ok'
});
@ -164,7 +164,7 @@ var RDB = require('./redis.js'),
RDB.zadd('categories:' + topicData.cid + ':tid', topicData.lastposttime, tid);
});
if (socket) {
io.sockets.in('topic_' + tid).emit('event:topic_unpinned', {
io.sockets. in ('topic_' + tid).emit('event:topic_unpinned', {
tid: tid,
status: 'ok'
});
@ -194,13 +194,13 @@ var RDB = require('./redis.js'),
topics.setTopicField(tid, 'cid', cid);
categories.moveRecentReplies(tid, oldCid, cid, function(err, data) {
if(err) {
if (err) {
winston.err(err);
}
});
categories.moveActiveUsers(tid, oldCid, cid, function(err, data) {
if(err) {
if (err) {
winston.err(err);
}
});
@ -212,7 +212,7 @@ var RDB = require('./redis.js'),
status: 'ok'
});
io.sockets.in('topic_' + tid).emit('event:topic_moved', {
io.sockets. in ('topic_' + tid).emit('event:topic_moved', {
tid: tid
});
} else {
@ -240,7 +240,9 @@ var RDB = require('./redis.js'),
status: 'ok',
follow: true
});
} else callback({ status: 'error' });
} else callback({
status: 'error'
});
}
});
} else {
@ -251,7 +253,9 @@ var RDB = require('./redis.js'),
status: 'ok',
follow: false
});
} else callback({ status: 'error' });
} else callback({
status: 'error'
});
}
});
}
@ -297,11 +301,11 @@ var RDB = require('./redis.js'),
posts.getPostsByTid(tid, 0, -1, function(posts) {
var numPosts = posts.length;
if(!numPosts)
if (!numPosts)
return callback(new Error('no-undeleted-pids-found'));
while(numPosts--) {
if(posts[numPosts].deleted !== '1') {
while (numPosts--) {
if (posts[numPosts].deleted !== '1') {
callback(null, posts[numPosts].pid);
return;
}

@ -1,5 +1,5 @@
var RDB = require('./redis.js')
schema = require('./schema.js'),
var RDB = require('./redis.js')
schema = require('./schema.js'),
posts = require('./posts.js'),
utils = require('./../public/src/utils.js'),
user = require('./user.js'),
@ -19,7 +19,7 @@ var RDB = require('./redis.js')
Topics.getTopicData = function(tid, callback) {
RDB.hgetall('topic:' + tid, function(err, data) {
if(err === null)
if (err === null)
callback(data);
else
console.log(err);
@ -37,12 +37,12 @@ var RDB = require('./redis.js')
Topics.getTopicPosts = function(tid, start, end, current_user, callback) {
posts.getPostsByTid(tid, start, end, function(postData) {
if(Array.isArray(postData) && !postData.length)
if (Array.isArray(postData) && !postData.length)
return callback([]);
function getFavouritesData(next) {
var pids = [];
for(var i=0; i<postData.length; ++i)
for (var i = 0; i < postData.length; ++i)
pids.push(postData[i].pid);
favourites.getFavouritesByPostIDs(pids, current_user, function(fav_data) {
@ -72,11 +72,11 @@ var RDB = require('./redis.js')
var fav_data = results[0],
privileges = results[2];
for(var i=0; i<postData.length; ++i) {
postData[i].fav_button_class = fav_data[postData[i].pid]? 'btn-warning' : '';
for (var i = 0; i < postData.length; ++i) {
postData[i].fav_button_class = fav_data[postData[i].pid] ? 'btn-warning' : '';
postData[i].fav_star_class = fav_data[postData[i].pid] ? 'icon-star' : 'icon-star-empty';
postData[i]['display_moderator_tools'] = (postData[i].uid == current_user || privileges.editable) ? 'show' : 'none';
postData[i].show_banned = postData[i].user_banned === '1'?'show':'hide';
postData[i].show_banned = postData[i].user_banned === '1' ? 'show' : 'hide';
}
callback(postData);
@ -94,18 +94,18 @@ var RDB = require('./redis.js')
var timestamp = Date.now();
var args = [ 'topics:recent', '+inf', timestamp - 86400000, 'WITHSCORES', 'LIMIT', start, end - start + 1];
var args = ['topics:recent', '+inf', timestamp - 86400000, 'WITHSCORES', 'LIMIT', start, end - start + 1];
RDB.zrevrangebyscore(args, function(err, tids) {
var latestTopics = {
'category_name' : 'Recent',
'show_sidebar' : 'hidden',
'show_topic_button' : 'hidden',
'no_topics_message' : 'hidden',
'category_name': 'Recent',
'show_sidebar': 'hidden',
'show_topic_button': 'hidden',
'no_topics_message': 'hidden',
'topic_row_size': 'col-md-12',
'category_id': false,
'topics' : []
'topics': []
};
if (!tids || !tids.length) {
@ -129,14 +129,16 @@ var RDB = require('./redis.js')
done = false;
async.whilst(
function () { return unreadTids.length < 21 && !done; },
function (callback) {
function() {
return unreadTids.length < 21 && !done;
},
function(callback) {
RDB.zrevrange('topics:recent', start, stop, function(err, tids) {
if(err)
if (err)
return callback(err);
if(tids && !tids.length) {
if (tids && !tids.length) {
done = true;
return callback(null);
}
@ -155,7 +157,7 @@ var RDB = require('./redis.js')
});
});
},
function (err) {
function(err) {
callback({
count: unreadTids.length
});
@ -166,13 +168,13 @@ var RDB = require('./redis.js')
Topics.getUnreadTopics = function(uid, start, stop, callback) {
var unreadTopics = {
'category_name' : 'Unread',
'show_sidebar' : 'hidden',
'show_topic_button' : 'hidden',
'category_name': 'Unread',
'show_sidebar': 'hidden',
'show_topic_button': 'hidden',
'show_markallread_button': 'show',
'no_topics_message' : 'hidden',
'no_topics_message': 'hidden',
'topic_row_size': 'col-md-12',
'topics' : []
'topics': []
};
function noUnreadTopics() {
@ -185,9 +187,9 @@ var RDB = require('./redis.js')
Topics.getTopicsByTids(topicIds, uid, function(topicData) {
unreadTopics.topics = topicData;
unreadTopics.nextStart = start + topicIds.length;
if(!topicData || topicData.length === 0)
if (!topicData || topicData.length === 0)
unreadTopics.no_topics_message = 'show';
if(uid === 0 || topicData.length === 0)
if (uid === 0 || topicData.length === 0)
unreadTopics.show_markallread_button = 'hidden';
callback(unreadTopics);
});
@ -197,18 +199,20 @@ var RDB = require('./redis.js')
done = false;
async.whilst(
function () { return unreadTids.length < 20 && !done; },
function (callback) {
function() {
return unreadTids.length < 20 && !done;
},
function(callback) {
RDB.zrevrange('topics:recent', start, stop, function(err, tids) {
if(err)
if (err)
return callback(err);
if(tids && !tids.length) {
if (tids && !tids.length) {
done = true;
return callback(null);
}
if(uid === 0) {
if (uid === 0) {
unreadTids.push.apply(unreadTids, tids);
callback(null);
} else {
@ -226,10 +230,10 @@ var RDB = require('./redis.js')
}
});
},
function (err) {
if(err)
function(err) {
if (err)
return callback([]);
if(unreadTids.length)
if (unreadTids.length)
sendUnreadTopics(unreadTids);
else
noUnreadTopics();
@ -242,7 +246,7 @@ var RDB = require('./redis.js')
var retrieved_topics = [];
if(!Array.isArray(tids) || tids.length === 0) {
if (!Array.isArray(tids) || tids.length === 0) {
callback(retrieved_topics);
return;
}
@ -266,6 +270,7 @@ var RDB = require('./redis.js')
}
// temporary. I don't think this call should belong here
function getPrivileges(next) {
categories.privileges(category_id, current_user, function(user_privs) {
next(null, user_privs);
@ -290,7 +295,7 @@ var RDB = require('./redis.js')
function loadTopic(tid, callback) {
Topics.getTopicData(tid, function(topicData) {
if(!topicData) {
if (!topicData) {
return callback(null);
}
@ -318,7 +323,7 @@ var RDB = require('./redis.js')
}
async.eachSeries(tids, loadTopic, function(err) {
if(!err) {
if (!err) {
callback(retrieved_topics);
}
});
@ -369,14 +374,14 @@ var RDB = require('./redis.js')
var main_posts = topicPosts.splice(0, 1);
callback(null, {
'topic_name':topicData.title,
'category_name':categoryData.name,
'category_slug':categoryData.slug,
'topic_name': topicData.title,
'category_name': categoryData.name,
'category_slug': categoryData.slug,
'locked': topicData.locked,
'deleted': topicData.deleted,
'pinned': topicData.pinned,
'slug': topicData.slug,
'postcount' : topicData.postcount,
'postcount': topicData.postcount,
'topic_id': tid,
'expose_tools': privileges.editable ? 1 : 0,
'posts': topicPosts,
@ -438,11 +443,13 @@ var RDB = require('./redis.js')
numTids, x;
// Sort into ascending order
tids.sort(function(a, b) { return a - b; });
tids.sort(function(a, b) {
return a - b;
});
// Eliminate everything after the "after" tid
if (after) {
for(x=0,numTids=tids.length;x<numTids;x++) {
for (x = 0, numTids = tids.length; x < numTids; x++) {
if (tids[x] >= after) {
tids = tids.slice(0, x);
break;
@ -457,7 +464,9 @@ var RDB = require('./redis.js')
}
// Sort into descending order
tids.sort(function(a, b) { return b - a; });
tids.sort(function(a, b) {
return b - a;
});
async.each(tids, function(tid, next) {
Topics.getTopicDataWithUsername(tid, function(topicData) {
@ -472,14 +481,14 @@ var RDB = require('./redis.js')
Topics.markAllRead = function(uid, callback) {
RDB.smembers('topics:tid', function(err, tids) {
if(err) {
if (err) {
console.log(err);
callback(err, null);
return;
}
if(tids && tids.length) {
for(var i=0; i<tids.length; ++i) {
if (tids && tids.length) {
for (var i = 0; i < tids.length; ++i) {
Topics.markAsRead(tids[i], uid);
}
}
@ -507,7 +516,7 @@ var RDB = require('./redis.js')
Topics.getTopicField(tid, 'cid', function(err, cid) {
categories.isTopicsRead(cid, uid, function(read) {
if(read) {
if (read) {
categories.markAsRead(cid, uid);
}
});
@ -525,7 +534,7 @@ var RDB = require('./redis.js')
Topics.hasReadTopics = function(tids, uid, callback) {
var batch = RDB.multi();
for (var i=0, ii=tids.length; i<ii; i++) {
for (var i = 0, ii = tids.length; i < ii; i++) {
batch.sismember(schema.topics(tids[i]).read_by_uid, uid);
}
@ -537,7 +546,7 @@ var RDB = require('./redis.js')
Topics.hasReadTopic = function(tid, uid, callback) {
RDB.sismember(schema.topics(tid).read_by_uid, uid, function(err, hasRead) {
if(err === null) {
if (err === null) {
callback(hasRead);
} else {
console.log(err);
@ -567,7 +576,7 @@ var RDB = require('./redis.js')
posts.getPostFields(pid, ['content', 'uid', 'timestamp'], function(postData) {
user.getUserFields(postData.uid, ['username', 'picture'], function(err, userData) {
if(err)
if (err)
return callback(err, null);
var stripped = postData.content,
@ -575,7 +584,7 @@ var RDB = require('./redis.js')
returnObj = {
"username": userData.username,
"picture": userData.picture,
"timestamp" : timestamp
"timestamp": timestamp
};
if (postData.content) {
@ -596,27 +605,27 @@ var RDB = require('./redis.js')
Topics.emitTitleTooShortAlert = function(socket) {
socket.emit('event:alert', {
type: 'danger',
timeout: 2000,
title: 'Title too short',
message: "Please enter a longer title. At least " + meta.config.minimumTitleLength + " characters.",
alert_id: 'post_error'
});
type: 'danger',
timeout: 2000,
title: 'Title too short',
message: "Please enter a longer title. At least " + meta.config.minimumTitleLength + " characters.",
alert_id: 'post_error'
});
}
Topics.post = function(uid, title, content, category_id, images, callback) {
if (!category_id)
throw new Error('Attempted to post without a category_id');
if(content)
if (content)
content = content.trim();
if(title)
if (title)
title = title.trim();
if (uid === 0) {
callback(new Error('not-logged-in'), null);
return;
} else if(!title || title.length < meta.config.minimumTitleLength) {
} else if (!title || title.length < meta.config.minimumTitleLength) {
callback(new Error('title-too-short'), null);
return;
} else if (!content || content.length < meta.config.miminumPostLength) {
@ -626,7 +635,7 @@ var RDB = require('./redis.js')
user.getUserField(uid, 'lastposttime', function(err, lastposttime) {
if (err) lastposttime = 0;
if(Date.now() - lastposttime < meta.config.postDelay) {
if (Date.now() - lastposttime < meta.config.postDelay) {
callback(new Error('too-many-posts'), null);
return;
}
@ -686,9 +695,11 @@ var RDB = require('./redis.js')
// Notify any users looking at the category that a new topic has arrived
Topics.getTopicForCategoryView(tid, uid, function(topicData) {
io.sockets.in('category_' + category_id).emit('event:new_topic', topicData);
io.sockets.in('recent_posts').emit('event:new_topic', topicData);
io.sockets.in('users/' + uid).emit('event:new_post', {posts:postData});
io.sockets. in ('category_' + category_id).emit('event:new_topic', topicData);
io.sockets. in ('recent_posts').emit('event:new_topic', topicData);
io.sockets. in ('users/' + uid).emit('event:new_post', {
posts: postData
});
});
callback(null, postData);
@ -739,7 +750,7 @@ var RDB = require('./redis.js')
function getUid(pid, next) {
posts.getPostField(pid, 'uid', function(uid) {
if(err)
if (err)
return next(err);
uids[uid] = 1;
next(null);
@ -747,7 +758,7 @@ var RDB = require('./redis.js')
}
async.each(pids, getUid, function(err) {
if(err)
if (err)
return callback(err, null);
callback(null, Object.keys(uids));
@ -777,11 +788,11 @@ var RDB = require('./redis.js')
Topics.reIndexTopic = function(tid, callback) {
Topics.getPids(tid, function(err, pids) {
if(err) {
if (err) {
callback(err);
} else {
posts.reIndexPids(pids, function(err) {
if(err) {
if (err) {
callback(err);
} else {
callback(null);
@ -793,12 +804,12 @@ var RDB = require('./redis.js')
Topics.reIndexAll = function(callback) {
RDB.smembers('topics:tid', function(err, tids) {
if(err) {
if (err) {
callback(err, null);
} else {
async.each(tids, Topics.reIndexTopic, function(err) {
if(err) {
if (err) {
callback(err, null);
} else {
callback(null, 'All topics reindexed.');

@ -6,32 +6,31 @@ var RDB = require('./redis.js'),
function upgradeCategory(cid, callback) {
RDB.type('categories:'+ cid +':tid', function(err, type) {
RDB.type('categories:' + cid + ':tid', function(err, type) {
if (type === 'set') {
RDB.smembers('categories:' + cid + ':tid', function(err, tids) {
function moveTopic(tid, callback) {
RDB.hget('topic:' + tid, 'timestamp', function(err, timestamp) {
if(err)
if (err)
return callback(err);
RDB.zadd('temp_categories:'+ cid + ':tid', timestamp, tid);
RDB.zadd('temp_categories:' + cid + ':tid', timestamp, tid);
callback(null);
});
}
async.each(tids, moveTopic, function(err) {
if(!err) {
if (!err) {
RDB.rename('temp_categories:' + cid + ':tid', 'categories:' + cid + ':tid');
callback(null);
}
else
} else
callback(err);
});
});
} else {
winston.info('category already upgraded '+ cid);
winston.info('category already upgraded ' + cid);
callback(null);
}
});
@ -39,54 +38,54 @@ function upgradeCategory(cid, callback) {
function upgradeUser(uid, callback) {
user.getUserFields(uid, ['joindate', 'postcount', 'reputation'], function(err, userData) {
if(err)
if (err)
return callback(err);
async.parallel([
function(next) {
if(userData.joindate)
if (userData.joindate)
RDB.zadd('users:joindate', userData.joindate, uid, next);
else
next(null);
},
function(next) {
if(userData.postcount)
if (userData.postcount)
RDB.zadd('users:postcount', userData.postcount, uid, next);
else
next(null);
},
function(next) {
if(userData.reputation)
if (userData.reputation)
RDB.zadd('users:reputation', userData.reputation, uid, next);
else
next(null);
}
], function(err, result) {
callback(err);
});
callback(err);
});
});
}
function upgradeUserHash(uid, callback) {
user.getUserFields(uid, ['username', 'userslug', 'email'], function(err, userData) {
if(err)
if (err)
return callback(err);
async.parallel([
function(next) {
if(userData.username)
if (userData.username)
RDB.hset('username:uid', userData.username, uid, next);
else
next(null);
},
function(next) {
if(userData.userslug)
if (userData.userslug)
RDB.hset('userslug:uid', userData.userslug, uid, next);
else
next(null);
},
function(next) {
if(userData.email)
if (userData.email)
RDB.hset('email:uid', userData.email, uid, next);
else
next(null);
@ -135,7 +134,7 @@ exports.upgrade = function() {
RDB.lrange('categories:cid', 0, -1, function(err, cids) {
async.each(cids, upgradeCategory, function(err) {
if(!err) {
if (!err) {
winston.info('upgraded categories');
next(null, null);
} else {
@ -151,7 +150,7 @@ exports.upgrade = function() {
RDB.lrange('userlist', 0, -1, function(err, uids) {
async.each(uids, upgradeUser, function(err) {
if(!err) {
if (!err) {
winston.info('upgraded users');
next(null, null);
} else {
@ -165,11 +164,11 @@ exports.upgrade = function() {
function upgradeUserHashes(next) {
winston.info('upgrading user hashes');
RDB.zrange('users:joindate', 0, -1, function(err, uids) {
if(err)
if (err)
return next(err);
async.each(uids, upgradeUserHash, function(err) {
if(!err) {
if (!err) {
winston.info('upgraded user hashes');
next(null, null);
} else {
@ -183,7 +182,7 @@ exports.upgrade = function() {
];
async.series(schema, function(err, results) {
if(!err)
if (!err)
winston.info('upgrade complete');
else
winston.err(err);

@ -38,7 +38,7 @@ var utils = require('./../public/src/utils.js'),
function(next) {
if (email !== undefined) {
User.isEmailAvailable(email, function(err, available) {
if(err)
if (err)
return next(err);
next(!available ? new Error('Email taken!') : null);
});
@ -53,19 +53,19 @@ var utils = require('./../public/src/utils.js'),
var gravatar = User.createGravatarURLFromEmail(email);
var timestamp = Date.now();
RDB.hmset('user:'+uid, {
RDB.hmset('user:' + uid, {
'uid': uid,
'username' : username,
'userslug' : userslug,
'username': username,
'userslug': userslug,
'fullname': '',
'location':'',
'birthday':'',
'website':'',
'email' : email || '',
'signature':'',
'joindate' : timestamp,
'location': '',
'birthday': '',
'website': '',
'email': email || '',
'signature': '',
'joindate': timestamp,
'picture': gravatar,
'gravatarpicture' : gravatar,
'gravatarpicture': gravatar,
'uploadedpicture': '',
'profileviews': 0,
'reputation': 0,
@ -87,7 +87,9 @@ var utils = require('./../public/src/utils.js'),
RDB.incr('usercount', function(err, count) {
RDB.handle(err);
if (typeof io !== 'undefined') io.sockets.emit('user.count', {count: count});
if (typeof io !== 'undefined') io.sockets.emit('user.count', {
count: count
});
});
RDB.zadd('users:joindate', timestamp, uid);
@ -96,7 +98,10 @@ var utils = require('./../public/src/utils.js'),
userSearch.index(username, uid);
if (typeof io !== 'undefined') io.sockets.emit('user.latest', {userslug: userslug, username: username});
if (typeof io !== 'undefined') io.sockets.emit('user.latest', {
userslug: userslug,
username: username
});
if (password !== undefined) {
User.hashPassword(password, function(err, hash) {
@ -109,8 +114,8 @@ var utils = require('./../public/src/utils.js'),
};
User.delete = function(uid, callback) {
RDB.exists('user:'+uid, function(err, exists) {
if(exists === 1) {
RDB.exists('user:' + uid, function(err, exists) {
if (exists === 1) {
console.log('deleting uid ' + uid);
User.getUserData(uid, function(err, data) {
@ -152,7 +157,7 @@ var utils = require('./../public/src/utils.js'),
}
User.getMultipleUserFields = function(uids, fields, callback) {
if(uids.length === 0) {
if (uids.length === 0) {
return callback(null, []);
}
@ -164,7 +169,7 @@ var utils = require('./../public/src/utils.js'),
function iterator(uid, next) {
User.getUserFields(uid, fields, function(err, userData) {
if(err)
if (err)
return next(err);
returnData.push(userData);
next(null);
@ -179,7 +184,7 @@ var utils = require('./../public/src/utils.js'),
User.getUserData = function(uid, callback) {
RDB.hgetall('user:' + uid, function(err, data) {
if(data && data['password']) {
if (data && data['password']) {
delete data['password'];
}
callback(err, data);
@ -195,28 +200,34 @@ var utils = require('./../public/src/utils.js'),
User.updateProfile = function(uid, data, callback) {
var fields = ['email', 'fullname', 'website', 'location', 'birthday', 'signature'];
var returnData = {success:false};
var returnData = {
success: false
};
function isSignatureValid(next) {
if(data['signature'] !== undefined && data['signature'].length > 150) {
next({error:'Signature can\'t be longer than 150 characters!'}, false);
if (data['signature'] !== undefined && data['signature'].length > 150) {
next({
error: 'Signature can\'t be longer than 150 characters!'
}, false);
} else {
next(null, true);
}
}
function isEmailAvailable(next) {
if(!data['email']) {
if (!data['email']) {
return next(null, true);
}
User.getUserField(uid, 'email', function(err, email) {
if(email !== data['email']) {
if (email !== data['email']) {
User.isEmailAvailable(data['email'], function(err, available) {
if(err)
if (err)
return next(err, null);
if(!available) {
next({error:'Email not available!'}, false);
if (!available) {
next({
error: 'Email not available!'
}, false);
} else {
next(null, true);
}
@ -228,11 +239,11 @@ var utils = require('./../public/src/utils.js'),
}
async.series([isSignatureValid, isEmailAvailable], function(err, results) {
if(err) {
if (err) {
callback(err, returnData);
} else {
async.each(fields, updateField, function(err) {
if(err) {
if (err) {
callback(err, returnData);
} else {
returnData.success = true;
@ -243,18 +254,18 @@ var utils = require('./../public/src/utils.js'),
});
function updateField(field, next) {
if(data[field] !== undefined) {
if(field === 'email') {
if (data[field] !== undefined) {
if (field === 'email') {
var gravatarpicture = User.createGravatarURLFromEmail(data[field]);
User.setUserField(uid, 'gravatarpicture', gravatarpicture);
User.getUserFields(uid, ['email', 'picture', 'uploadedpicture'], function(err, userData) {
if(err)
if (err)
return next(err);
RDB.hdel('email:uid', userData['email']);
RDB.hset('email:uid', data['email'], uid);
User.setUserField(uid, field, data[field]);
if(userData.picture !== userData.uploadedpicture) {
if (userData.picture !== userData.uploadedpicture) {
returnData.picture = gravatarpicture;
User.setUserField(uid, 'picture', gravatarpicture);
}
@ -262,7 +273,7 @@ var utils = require('./../public/src/utils.js'),
next(null);
});
return;
} else if(field === 'signature') {
} else if (field === 'signature') {
data[field] = utils.strip_tags(data[field]);
}
@ -282,13 +293,15 @@ var utils = require('./../public/src/utils.js'),
}
User.changePassword = function(uid, data, callback) {
if(!utils.isPasswordValid(data.newPassword)) {
return callback({error:'Invalid password!'});
if (!utils.isPasswordValid(data.newPassword)) {
return callback({
error: 'Invalid password!'
});
}
User.getUserField(uid, 'password', function(err, user_password) {
bcrypt.compare(data.currentPassword, user_password, function(err, res) {
if(err) {
if (err) {
return callback(err);
}
@ -299,7 +312,9 @@ var utils = require('./../public/src/utils.js'),
callback(null);
});
} else {
callback({error:'Your current password is not correct!'});
callback({
error: 'Your current password is not correct!'
});
}
});
});
@ -325,13 +340,13 @@ var utils = require('./../public/src/utils.js'),
var data = [];
RDB.zrevrange(set, start, stop, function(err, uids) {
if(err) {
if (err) {
return callback(err, null);
}
function iterator(uid, callback) {
User.getUserData(uid, function(err, userData) {
if(userData) {
if (userData) {
data.push(userData);
}
callback(null);
@ -356,11 +371,11 @@ var utils = require('./../public/src/utils.js'),
options.forcedefault = 'y';
}
return require('gravatar').url(email, options, https=nconf.get('https'));
return require('gravatar').url(email, options, https = nconf.get('https'));
}
User.hashPassword = function(password, callback) {
if(!password) {
if (!password) {
callback(password);
return;
}
@ -372,17 +387,17 @@ var utils = require('./../public/src/utils.js'),
User.reIndexAll = function(callback) {
User.getUsers('users:joindate', 0, -1, function(err, usersData) {
if(err) {
if (err) {
return callback(err, null);
}
function reIndexUser(uid, username) {
userSearch.remove(uid, function(){
userSearch.remove(uid, function() {
userSearch.index(username, uid);
})
}
for(var i=0; i<usersData.length; ++i) {
for (var i = 0; i < usersData.length; ++i) {
reIndexUser(usersData[i].uid, usersData[i].username);
}
callback(null, 1);
@ -390,17 +405,17 @@ var utils = require('./../public/src/utils.js'),
}
User.search = function(username, callback) {
if(!username) {
if (!username) {
callback([]);
return;
}
userSearch.query(query = username).type('or').end(function(err, uids) {
if(err) {
if (err) {
console.log(err);
return;
}
if(uids && uids.length) {
if (uids && uids.length) {
User.getDataForUsers(uids, function(userdata) {
callback(userdata);
});
@ -432,8 +447,8 @@ var utils = require('./../public/src/utils.js'),
User.getPostIds = function(uid, start, end, callback) {
RDB.lrange('uid:' + uid + ':posts', start, end, function(err, pids) {
if(!err) {
if(pids && pids.length)
if (!err) {
if (pids && pids.length)
callback(pids);
else
callback([]);
@ -444,15 +459,19 @@ var utils = require('./../public/src/utils.js'),
});
}
User.sendConfirmationEmail = function (email) {
User.sendConfirmationEmail = function(email) {
if (meta.config['email:host'] && meta.config['email:port'] && meta.config['email:from']) {
var confirm_code = utils.generateUUID(),
confirm_link = nconf.get('url') + 'confirm/' + confirm_code,
confirm_email = global.templates['emails/header'] + global.templates['emails/email_confirm'].parse({'CONFIRM_LINK': confirm_link}) + global.templates['emails/footer'],
confirm_email_plaintext = global.templates['emails/email_confirm_plaintext'].parse({ 'CONFIRM_LINK': confirm_link });
confirm_email = global.templates['emails/header'] + global.templates['emails/email_confirm'].parse({
'CONFIRM_LINK': confirm_link
}) + global.templates['emails/footer'],
confirm_email_plaintext = global.templates['emails/email_confirm_plaintext'].parse({
'CONFIRM_LINK': confirm_link
});
// Email confirmation code
var expiry_time = 60*60*2, // Expire after 2 hours
var expiry_time = 60 * 60 * 2, // Expire after 2 hours
email_key = 'email:' + email + ':confirm',
confirm_key = 'confirm:' + confirm_code + ':email';
@ -467,12 +486,10 @@ var utils = require('./../public/src/utils.js'),
from: meta.config.mailer.from,
to: email,
subject: '[NodeBB] Registration Email Verification',
attachment: [
{
data: confirm_email,
alternative: true
}
]
attachment: [{
data: confirm_email,
alternative: true
}]
});
emailjsServer.send(message, function(err, success) {
@ -485,9 +502,9 @@ var utils = require('./../public/src/utils.js'),
User.follow = function(uid, followid, callback) {
RDB.sadd('following:' + uid, followid, function(err, data) {
if(!err) {
if (!err) {
RDB.sadd('followers:' + followid, uid, function(err, data) {
if(!err) {
if (!err) {
callback(true);
} else {
console.log(err);
@ -502,9 +519,9 @@ var utils = require('./../public/src/utils.js'),
}
User.unfollow = function(uid, unfollowid, callback) {
RDB.srem('following:' + uid, unfollowid, function(err, data){
if(!err) {
RDB.srem('followers:' + unfollowid, uid, function(err, data){
RDB.srem('following:' + uid, unfollowid, function(err, data) {
if (!err) {
RDB.srem('followers:' + unfollowid, uid, function(err, data) {
callback(data);
});
} else {
@ -515,7 +532,7 @@ var utils = require('./../public/src/utils.js'),
User.getFollowing = function(uid, callback) {
RDB.smembers('following:' + uid, function(err, userIds) {
if(!err) {
if (!err) {
User.getDataForUsers(userIds, callback);
} else {
console.log(err);
@ -525,7 +542,7 @@ var utils = require('./../public/src/utils.js'),
User.getFollowers = function(uid, callback) {
RDB.smembers('followers:' + uid, function(err, userIds) {
if(!err) {
if (!err) {
User.getDataForUsers(userIds, callback);
} else {
console.log(err);
@ -535,7 +552,7 @@ var utils = require('./../public/src/utils.js'),
User.getFollowingCount = function(uid, callback) {
RDB.smembers('following:' + uid, function(err, userIds) {
if(!err) {
if (!err) {
callback(userIds.length);
} else {
console.log(err);
@ -549,7 +566,7 @@ var utils = require('./../public/src/utils.js'),
// either go with not-error-dosomething-else-dosomethingelse, or
// go with if-error-dosomething-return
// also why is console.log(err) being used when below we're using RDB.handle()?
if(!err) {
if (!err) {
callback(userIds.length);
} else {
console.log(err);
@ -560,7 +577,7 @@ var utils = require('./../public/src/utils.js'),
User.getDataForUsers = function(uids, callback) {
var returnData = [];
if(!uids || !Array.isArray(uids) || uids.length === 0) {
if (!uids || !Array.isArray(uids) || uids.length === 0) {
callback(returnData);
return;
}
@ -584,8 +601,8 @@ var utils = require('./../public/src/utils.js'),
topics.getTopicField(tid, 'slug', function(err, slug) {
var message = '<strong>' + username + '</strong> made a new post';
notifications.create(message, 5, nconf.get('relative_path') + '/topic/' + slug + '#' + pid, 'topic:'+ tid, function(nid) {
notifications.push(nid, followers);
notifications.create(message, 5, nconf.get('relative_path') + '/topic/' + slug + '#' + pid, 'topic:' + tid, function(nid) {
notifications.push(nid, followers);
});
});
});
@ -594,7 +611,7 @@ var utils = require('./../public/src/utils.js'),
User.isFollowing = function(uid, theirid, callback) {
RDB.sismember('following:' + uid, theirid, function(err, data) {
if(!err) {
if (!err) {
callback(data === 1);
} else {
console.log(err);
@ -604,7 +621,7 @@ var utils = require('./../public/src/utils.js'),
User.exists = function(userslug, callback) {
User.get_uid_by_userslug(userslug, function(err, exists) {
callback(!!exists);
callback( !! exists);
});
};
@ -612,7 +629,9 @@ var utils = require('./../public/src/utils.js'),
RDB.get('usercount', function(err, count) {
RDB.handle(err);
socket.emit('user.count', { count: count ? count : 0 });
socket.emit('user.count', {
count: count ? count : 0
});
});
};
@ -621,8 +640,11 @@ var utils = require('./../public/src/utils.js'),
RDB.handle(err);
User.getUserFields(uid, ['username', 'userslug'], function(err, userData) {
if(!err && userData)
socket.emit('user.latest', {userslug: userData.userslug, username: userData.username});
if (!err && userData)
socket.emit('user.latest', {
userslug: userData.userslug,
username: userData.username
});
});
});
}
@ -725,7 +747,7 @@ var utils = require('./../public/src/utils.js'),
RDB.handle(err);
}
var expiry = 60*60*24*14, // Login valid for two weeks
var expiry = 60 * 60 * 24 * 14, // Login valid for two weeks
sess_key = 'sess:' + sessionID + ':uid',
uid_key = 'uid:' + uid + ':session';
@ -739,14 +761,14 @@ var utils = require('./../public/src/utils.js'),
User.isModerator = function(uid, cid, callback) {
RDB.sismember('cid:' + cid + ':moderators', uid, function(err, exists) {
RDB.handle(err);
callback(!!exists);
callback( !! exists);
});
}
User.isAdministrator = function(uid, callback) {
Groups.getGidFromName('Administrators', function(err, gid) {
Groups.isMember(uid, gid, function(err, isAdmin) {
callback(!!isAdmin);
callback( !! isAdmin);
});
});
}
@ -769,9 +791,11 @@ var utils = require('./../public/src/utils.js'),
RDB.handle(err);
}
if (expiry >= +Date.now()/1000|0) {
if (expiry >= +Date.now() / 1000 | 0) {
if (!callback) {
socket.emit('user:reset.valid', { valid: true });
socket.emit('user:reset.valid', {
valid: true
});
} else {
callback(true);
}
@ -780,7 +804,9 @@ var utils = require('./../public/src/utils.js'),
RDB.del('reset:' + code + ':uid');
RDB.del('reset:' + code + ':expiry');
if (!callback) {
socket.emit('user:reset.valid', { valid: false });
socket.emit('user:reset.valid', {
valid: false
});
} else {
callback(false);
}
@ -788,7 +814,9 @@ var utils = require('./../public/src/utils.js'),
});
} else {
if (!callback) {
socket.emit('user:reset.valid', { valid: false });
socket.emit('user:reset.valid', {
valid: false
});
} else {
callback(false);
}
@ -801,23 +829,25 @@ var utils = require('./../public/src/utils.js'),
// Generate a new reset code
var reset_code = utils.generateUUID();
RDB.set('reset:' + reset_code + ':uid', uid);
RDB.set('reset:' + reset_code + ':expiry', (60*60)+new Date()/1000|0); // Active for one hour
RDB.set('reset:' + reset_code + ':expiry', (60 * 60) + new Date() / 1000 | 0); // Active for one hour
var reset_link = nconf.get('url') + 'reset/' + reset_code,
reset_email = global.templates['emails/reset'].parse({'RESET_LINK': reset_link}),
reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({ 'RESET_LINK': reset_link });
reset_email = global.templates['emails/reset'].parse({
'RESET_LINK': reset_link
}),
reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({
'RESET_LINK': reset_link
});
var message = emailjs.message.create({
text: reset_email_plaintext,
from: meta.config.mailer?meta.config.mailer.from:'localhost@example.org',
from: meta.config.mailer ? meta.config.mailer.from : 'localhost@example.org',
to: email,
subject: 'Password Reset Requested',
attachment: [
{
data: reset_email,
alternative: true
}
]
attachment: [{
data: reset_email,
alternative: true
}]
});
emailjsServer.send(message, function(err, success) {
@ -860,7 +890,9 @@ var utils = require('./../public/src/utils.js'),
RDB.del('reset:' + code + ':uid');
RDB.del('reset:' + code + ':expiry');
socket.emit('user:reset.commit', { status: 'ok' });
socket.emit('user:reset.commit', {
status: 'ok'
});
});
}
});
@ -870,9 +902,11 @@ var utils = require('./../public/src/utils.js'),
User.email = {
exists: function(socket, email, callback) {
User.get_uid_by_email(email, function(exists) {
exists = !!exists;
exists = !! exists;
if (typeof callback !== 'function') {
socket.emit('user.email.exists', { exists: exists });
socket.emit('user.email.exists', {
exists: exists
});
} else {
callback(exists);
}
@ -887,9 +921,13 @@ var utils = require('./../public/src/utils.js'),
if (email !== null) {
RDB.set('email:' + email + ':confirm', true);
RDB.del('confirm:' + code + ':email');
callback({ status: 'ok' });
callback({
status: 'ok'
});
} else {
callback({ status: 'not_ok' });
callback({
status: 'not_ok'
});
}
});
}
@ -897,7 +935,7 @@ var utils = require('./../public/src/utils.js'),
User.notifications = {
get: function(uid, callback) {
var maxNotifs = 15;
var maxNotifs = 15;
async.parallel({
unread: function(next) {
@ -946,7 +984,7 @@ var utils = require('./../public/src/utils.js'),
}
}, function(err, notifications) {
// While maintaining score sorting, sort by time
var readCount = notifications.read.length,
var readCount = notifications.read.length,
unreadCount = notifications.unread.length;
notifications.read.sort(function(a, b) {
@ -985,4 +1023,4 @@ var utils = require('./../public/src/utils.js'),
});
}
}
}(exports));
}(exports));

@ -31,12 +31,19 @@ var express = require('express'),
* accepts: metaTags
*/
app.build_header = function(options, callback) {
var defaultMetaTags = [
{ name: 'viewport', content: 'width=device-width, initial-scale=1.0' },
{ name: 'content-type', content: 'text/html; charset=UTF-8' },
{ name: 'apple-mobile-web-app-capable', content: 'yes' },
{ property: 'og:site_name', content: meta.config.title || 'NodeBB' },
],
var defaultMetaTags = [{
name: 'viewport',
content: 'width=device-width, initial-scale=1.0'
}, {
name: 'content-type',
content: 'text/html; charset=UTF-8'
}, {
name: 'apple-mobile-web-app-capable',
content: 'yes'
}, {
property: 'og:site_name',
content: meta.config.title || 'NodeBB'
}, ],
metaString = utils.buildMetaTags(defaultMetaTags.concat(options.metaTags || [])),
templateValues = {
cssSrc: meta.config['theme:src'] || nconf.get('relative_path') + '/vendor/bootstrap/css/bootstrap.min.css',
@ -58,21 +65,24 @@ var express = require('express'),
// Middlewares
app.use(express.favicon(path.join(__dirname, '../', 'public', 'favicon.ico')));
app.use(require('less-middleware')({ src: path.join(__dirname, '../', 'public'), prefix:nconf.get('relative_path') }));
app.use(require('less-middleware')({
src: path.join(__dirname, '../', 'public'),
prefix: nconf.get('relative_path')
}));
app.use(nconf.get('relative_path'), express.static(path.join(__dirname, '../', 'public')));
app.use(express.bodyParser()); // Puts POST vars in request.body
app.use(express.bodyParser()); // Puts POST vars in request.body
app.use(express.cookieParser()); // If you want to parse cookies (res.cookies)
app.use(express.cookieParser()); // If you want to parse cookies (res.cookies)
app.use(express.compress());
app.use(express.session({
store: new RedisStore({
client: RDB,
ttl: 60*60*24*30
ttl: 60 * 60 * 24 * 30
}),
secret: nconf.get('secret'),
key: 'express.sid',
cookie: {
maxAge: 60*60*24*30*1000 // 30 days
maxAge: 60 * 60 * 24 * 30 * 1000 // 30 days
}
}));
app.use(express.csrf());
@ -83,7 +93,7 @@ var express = require('express'),
// Static Directories for NodeBB Plugins
app.configure(function() {
var tailMiddlewares = [];
var tailMiddlewares = [];
plugins.ready(function() {
// Remove some middlewares until the router is gone
@ -92,7 +102,7 @@ var express = require('express'),
tailMiddlewares.push(app.stack.pop());
tailMiddlewares.push(app.stack.pop());
tailMiddlewares.push(app.stack.pop());
for(d in plugins.staticDirs) {
for (d in plugins.staticDirs) {
app.use(nconf.get('relative_path') + '/plugins/' + d, express.static(plugins.staticDirs[d]));
}
@ -138,7 +148,9 @@ var express = require('express'),
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
res.send({
error: 'Not found'
});
return;
}
@ -155,7 +167,9 @@ var express = require('express'),
res.status(err.status || 500);
res.json('500', { error: err.message });
res.json('500', {
error: err.message
});
});
@ -177,19 +191,22 @@ var express = require('express'),
(function() {
var routes = ['login', 'register', 'account', 'recent', 'unread', 'popular', 'active', '403', '404'];
for (var i=0, ii=routes.length; i<ii; i++) {
for (var i = 0, ii = routes.length; i < ii; i++) {
(function(route) {
app.get('/' + route, function(req, res) {
if ((route === 'login' || route ==='register') && (req.user && req.user.uid > 0)) {
if ((route === 'login' || route === 'register') && (req.user && req.user.uid > 0)) {
user.getUserField(req.user.uid, 'userslug', function(err, userslug) {
res.redirect('/users/'+userslug);
res.redirect('/users/' + userslug);
});
return;
}
app.build_header({ req: req, res: res }, function(err, header) {
app.build_header({
req: req,
res: res
}, function(err, header) {
res.send(header + app.create_route(route) + templates['footer']);
});
});
@ -204,12 +221,19 @@ var express = require('express'),
app.build_header({
req: req,
res: res,
metaTags: [
{ name: "title", content: meta.config.title || 'NodeBB' },
{ name: "description", content: meta.config.description || '' },
{ property: 'og:title', content: 'Index | ' + (meta.config.title || 'NodeBB') },
{ property: "og:type", content: 'website' }
]
metaTags: [{
name: "title",
content: meta.config.title || 'NodeBB'
}, {
name: "description",
content: meta.config.description || ''
}, {
property: 'og:title',
content: 'Index | ' + (meta.config.title || 'NodeBB')
}, {
property: "og:type",
content: 'website'
}]
}, next);
},
"categories": function(next) {
@ -233,9 +257,9 @@ var express = require('express'),
if (tid.match(/^\d+\.rss$/)) {
tid = tid.slice(0, -4);
var rssPath = path.join(__dirname, '../', 'feeds/topics', tid + '.rss'),
var rssPath = path.join(__dirname, '../', 'feeds/topics', tid + '.rss'),
loadFeed = function() {
fs.readFile(rssPath, function (err, data) {
fs.readFile(rssPath, function(err, data) {
if (err) res.type('text').send(404, "Unable to locate an rss feed at this location.");
else res.type('xml').set('Content-Length', data.length).send(data);
});
@ -255,8 +279,8 @@ var express = require('express'),
async.waterfall([
function(next) {
topics.getTopicWithPosts(tid, ((req.user) ? req.user.uid : 0), 0, -1, function(err, topicData) {
if(topicData) {
if(topicData.deleted === '1' && topicData.expose_tools === 0)
if (topicData) {
if (topicData.deleted === '1' && topicData.expose_tools === 0)
return next(new Error('Topic deleted'), null);
}
@ -267,7 +291,7 @@ var express = require('express'),
var lastMod = 0,
timestamp;
for(var x=0,numPosts=topicData.posts.length;x<numPosts;x++) {
for (var x = 0, numPosts = topicData.posts.length; x < numPosts; x++) {
timestamp = parseInt(topicData.posts[x].timestamp, 10);
if (timestamp > lastMod) lastMod = timestamp;
}
@ -275,16 +299,31 @@ var express = require('express'),
app.build_header({
req: req,
res: res,
metaTags: [
{ name: "title", content: topicData.topic_name },
{ property: 'og:title', content: topicData.topic_name + ' | ' + (meta.config.title || 'NodeBB') },
{ property: "og:type", content: 'article' },
{ property: "og:url", content: nconf.get('url') + 'topic/' + topicData.slug },
{ property: 'og:image', content: topicData.main_posts[0].picture },
{ property: "article:published_time", content: new Date(parseInt(topicData.main_posts[0].timestamp, 10)).toISOString() },
{ property: 'article:modified_time', content: new Date(lastMod).toISOString() },
{ property: 'article:section', content: topicData.category_name }
]
metaTags: [{
name: "title",
content: topicData.topic_name
}, {
property: 'og:title',
content: topicData.topic_name + ' | ' + (meta.config.title || 'NodeBB')
}, {
property: "og:type",
content: 'article'
}, {
property: "og:url",
content: nconf.get('url') + 'topic/' + topicData.slug
}, {
property: 'og:image',
content: topicData.main_posts[0].picture
}, {
property: "article:published_time",
content: new Date(parseInt(topicData.main_posts[0].timestamp, 10)).toISOString()
}, {
property: 'article:modified_time',
content: new Date(lastMod).toISOString()
}, {
property: 'article:section',
content: topicData.category_name
}]
}, function(err, header) {
next(err, {
header: header,
@ -310,9 +349,9 @@ var express = require('express'),
if (cid.match(/^\d+\.rss$/)) {
cid = cid.slice(0, -4);
var rssPath = path.join(__dirname, '../', 'feeds/categories', cid + '.rss'),
var rssPath = path.join(__dirname, '../', 'feeds/categories', cid + '.rss'),
loadFeed = function() {
fs.readFile(rssPath, function (err, data) {
fs.readFile(rssPath, function(err, data) {
if (err) res.type('text').send(404, "Unable to locate an rss feed at this location.");
else res.type('xml').set('Content-Length', data.length).send(data);
});
@ -333,8 +372,8 @@ var express = require('express'),
function(next) {
categories.getCategoryById(cid, 0, function(err, categoryData) {
if(categoryData) {
if(categoryData.disabled === '1')
if (categoryData) {
if (categoryData.disabled === '1')
return next(new Error('Category disabled'), null);
}
next(err, categoryData);
@ -344,11 +383,16 @@ var express = require('express'),
app.build_header({
req: req,
res: res,
metaTags: [
{ name: 'title', content: categoryData.category_name },
{ name: 'description', content: categoryData.category_description },
{ property: "og:type", content: 'website' }
]
metaTags: [{
name: 'title',
content: categoryData.category_name
}, {
name: 'description',
content: categoryData.category_description
}, {
property: "og:type",
content: 'website'
}]
}, function(err, header) {
next(err, {
header: header,
@ -357,7 +401,7 @@ var express = require('express'),
});
}
], function(err, data) {
if(err) return res.redirect('404');
if (err) return res.redirect('404');
var category_url = cid + (req.params.slug ? '/' + req.params.slug : '');
res.send(
@ -370,13 +414,16 @@ var express = require('express'),
});
app.get('/confirm/:code', function(req, res) {
app.build_header({ req: req, res: res }, function(err, header) {
app.build_header({
req: req,
res: res
}, function(err, header) {
res.send(header + '<script>templates.ready(function(){ajaxify.go("confirm/' + req.params.code + '");});</script>' + templates['footer']);
});
});
app.get('/sitemap.xml', function(req, res) {
var sitemap = require('./sitemap.js');
var sitemap = require('./sitemap.js');
sitemap.render(function(xml) {
res.type('xml').set('Content-Length', xml.length).send(xml);
@ -385,15 +432,15 @@ var express = require('express'),
app.get('/robots.txt', function(req, res) {
res.set('Content-Type', 'text/plain');
res.send( "User-agent: *\n" +
"Disallow: \n" +
"Disallow: /admin/\n" +
"Sitemap: " + nconf.get('url') + "sitemap.xml");
res.send("User-agent: *\n" +
"Disallow: \n" +
"Disallow: /admin/\n" +
"Sitemap: " + nconf.get('url') + "sitemap.xml");
});
app.get('/cid/:cid', function(req, res) {
categories.getCategoryData(req.params.cid, function(err, data) {
if(data)
if (data)
res.send(data);
else
res.send(404, "Category doesn't exist!");
@ -401,8 +448,8 @@ var express = require('express'),
});
app.get('/tid/:tid', function(req, res) {
topics.getTopicData(req.params.tid, function(data){
if(data)
topics.getTopicData(req.params.tid, function(data) {
if (data)
res.send(data);
else
res.send(404, "Topic doesn't exist!");
@ -410,8 +457,8 @@ var express = require('express'),
});
app.get('/pid/:pid', function(req, res) {
posts.getPostData(req.params.pid, function(data){
if(data)
posts.getPostData(req.params.pid, function(data) {
if (data)
res.send(data);
else
res.send(404, "Post doesn't exist!");
@ -421,7 +468,10 @@ var express = require('express'),
app.get('/outgoing', function(req, res) {
if (!req.query.url) return res.redirect('/404');
app.build_header({ req: req, res: res }, function(err, header) {
app.build_header({
req: req,
res: res
}, function(err, header) {
res.send(
header +
'\n\t<script>templates.ready(function(){ajaxify.go("outgoing?url=' + encodeURIComponent(req.query.url) + '", null, null, true);});</script>' +
@ -431,25 +481,31 @@ var express = require('express'),
});
app.get('/search', function(req, res) {
app.build_header({ req: req, res: res }, function(err, header) {
app.build_header({
req: req,
res: res
}, function(err, header) {
res.send(header + app.create_route("search", null, "search") + templates['footer']);
});
});
app.get('/search/:term', function(req, res) {
app.build_header({ req: req, res: res }, function(err, header) {
res.send(header + app.create_route("search/"+req.params.term, null, "search") + templates['footer']);
app.build_header({
req: req,
res: res
}, function(err, header) {
res.send(header + app.create_route("search/" + req.params.term, null, "search") + templates['footer']);
});
});
app.get('/reindex', function(req, res) {
topics.reIndexAll(function(err) {
if(err) {
if (err) {
return res.json(err);
}
user.reIndexAll(function(err) {
if(err) {
if (err) {
return res.json(err);
} else {
res.send('Topics and users reindexed');
@ -462,4 +518,4 @@ var express = require('express'),
}(WebServer));
server.listen(nconf.get('PORT') || nconf.get('port'));
global.server = server;
global.server = server;

@ -1,8 +1,7 @@
var SocketIO = require('socket.io').listen(global.server, {
log: false,
transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket']
}),
log: false,
transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket']
}),
cookie = require('cookie'),
express = require('express'),
user = require('./user.js'),
@ -22,7 +21,7 @@ var SocketIO = require('socket.io').listen(global.server, {
RDB = require('./redis'),
RedisStore = new RedisStoreLib({
client: RDB,
ttl: 60*60*24*14
ttl: 60 * 60 * 24 * 14
}),
socketCookieParser = express.cookieParser(nconf.get('secret')),
admin = {
@ -40,7 +39,7 @@ var SocketIO = require('socket.io').listen(global.server, {
global.io = io;
io.sockets.on('connection', function(socket) {
var hs = socket.handshake,
var hs = socket.handshake,
sessionID, uid;
// Validate the session, if present
@ -53,12 +52,16 @@ var SocketIO = require('socket.io').listen(global.server, {
userSockets[uid] = userSockets[uid] || [];
userSockets[uid].push(socket);
if(uid) {
if (uid) {
socket.join('uid_' + uid);
io.sockets.in('global').emit('api:user.isOnline', isUserOnline(uid));
io.sockets. in ('global').emit('api:user.isOnline', isUserOnline(uid));
user.getUserField(uid, 'username', function(err, username) {
socket.emit('event:connect', {status: 1, username:username, uid:uid});
socket.emit('event:connect', {
status: 1,
username: username,
uid: uid
});
});
}
});
@ -69,25 +72,25 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('disconnect', function() {
var index = userSockets[uid].indexOf(socket);
if(index !== -1) {
if (index !== -1) {
userSockets[uid].splice(index, 1);
}
if(userSockets[uid].length === 0) {
if (userSockets[uid].length === 0) {
delete users[sessionID];
delete userSockets[uid];
if(uid) {
io.sockets.in('global').emit('api:user.isOnline', isUserOnline(uid));
if (uid) {
io.sockets. in ('global').emit('api:user.isOnline', isUserOnline(uid));
}
}
emitOnlineUserCount();
for(var roomName in rooms) {
for (var roomName in rooms) {
socket.leave(roomName);
if(rooms[roomName][socket.id]) {
if (rooms[roomName][socket.id]) {
delete rooms[roomName][socket.id];
}
@ -103,8 +106,8 @@ var SocketIO = require('socket.io').listen(global.server, {
function getUidsInRoom(room) {
var uids = [];
for(var socketId in room) {
if(uids.indexOf(room[socketId]) === -1)
for (var socketId in room) {
if (uids.indexOf(room[socketId]) === -1)
uids.push(room[socketId]);
}
return uids;
@ -114,10 +117,10 @@ var SocketIO = require('socket.io').listen(global.server, {
var clients = io.sockets.clients(roomName);
var anonCount = 0;
for(var i=0; i<clients.length; ++i) {
for (var i = 0; i < clients.length; ++i) {
var hs = clients[i].handshake;
if(hs && !users[sessionID]) {
if (hs && !users[sessionID]) {
++anonCount;
}
}
@ -131,24 +134,24 @@ var SocketIO = require('socket.io').listen(global.server, {
function userList(users, anonymousCount, userCount) {
var usernames = [];
for (var i = 0, ii=users.length; i<ii; ++i) {
usernames[i] = '<strong>' + '<a href="/users/'+users[i].userslug+'">' + users[i].username + '</a></strong>';
for (var i = 0, ii = users.length; i < ii; ++i) {
usernames[i] = '<strong>' + '<a href="/users/' + users[i].userslug + '">' + users[i].username + '</a></strong>';
}
var joiner = anonymousCount + userCount == 1 ? 'is' : 'are',
userList = anonymousCount > 0 ? usernames.concat(util.format('%d guest%s', anonymousCount, anonymousCount > 1 ? 's' : '')) : usernames,
lastUser = userList.length > 1 ? ' and ' + userList.pop() : '';
userList = anonymousCount > 0 ? usernames.concat(util.format('%d guest%s', anonymousCount, anonymousCount > 1 ? 's' : '')) : usernames,
lastUser = userList.length > 1 ? ' and ' + userList.pop() : '';
return util.format('%s%s %s browsing this thread', userList.join(', '), lastUser, joiner);
}
if (uids.length === 0) {
io.sockets.in(roomName).emit('api:get_users_in_room', userList([], anonymousCount, 0));
io.sockets. in (roomName).emit('api:get_users_in_room', userList([], anonymousCount, 0));
} else {
user.getMultipleUserFields(uids, ['username', 'userslug'], function(err, users) {
if(!err)
io.sockets.in(roomName).emit('api:get_users_in_room', userList(users, anonymousCount, users.length));
if (!err)
io.sockets. in (roomName).emit('api:get_users_in_room', userList(users, anonymousCount, users.length));
});
}
}
@ -171,42 +174,45 @@ var SocketIO = require('socket.io').listen(global.server, {
}
}
if(data.leave)
if (data.leave)
updateRoomBrowsingText(data.leave);
updateRoomBrowsingText(data.enter);
if (data.enter != 'admin')
io.sockets.in('admin').emit('api:get_all_rooms', io.sockets.manager.rooms);
io.sockets. in ('admin').emit('api:get_all_rooms', io.sockets.manager.rooms);
});
// BEGIN: API calls (todo: organize)
socket.on('api:updateHeader', function(data) {
if(uid) {
if (uid) {
user.getUserFields(uid, data.fields, function(err, fields) {
if(!err && fields) {
if (!err && fields) {
fields.uid = uid;
socket.emit('api:updateHeader', fields);
}
});
}
else {
} else {
socket.emit('api:updateHeader', {
uid:0,
uid: 0,
username: "Anonymous User",
email: '',
picture: require('gravatar').url('', {s:'24'}, https=nconf.get('https'))
picture: require('gravatar').url('', {
s: '24'
}, https = nconf.get('https'))
});
}
});
socket.on('user.exists', function(data) {
if(data.username) {
user.exists(utils.slugify(data.username), function(exists){
socket.emit('user.exists', {exists: exists});
if (data.username) {
user.exists(utils.slugify(data.username), function(exists) {
socket.emit('user.exists', {
exists: exists
});
});
}
});
@ -246,9 +252,9 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('api:user.get_online_users', function(data) {
var returnData = [];
for(var i=0; i<data.length; ++i) {
for (var i = 0; i < data.length; ++i) {
var uid = data[i];
if(isUserOnline(uid))
if (isUserOnline(uid))
returnData.push(uid);
else
returnData.push(0);
@ -257,7 +263,10 @@ var SocketIO = require('socket.io').listen(global.server, {
});
socket.on('api:user.isOnline', function(uid, callback) {
callback({online:isUserOnline(uid), timestamp:Date.now()});
callback({
online: isUserOnline(uid),
timestamp: Date.now()
});
});
socket.on('api:user.changePassword', function(data, callback) {
@ -274,7 +283,7 @@ var SocketIO = require('socket.io').listen(global.server, {
function updateHeader() {
user.getUserFields(uid, ['picture'], function(err, fields) {
if(!err && fields) {
if (!err && fields) {
fields.uid = uid;
socket.emit('api:updateHeader', fields);
callback(true);
@ -284,12 +293,12 @@ var SocketIO = require('socket.io').listen(global.server, {
});
}
if(type === 'gravatar') {
if (type === 'gravatar') {
user.getUserField(uid, 'gravatarpicture', function(err, gravatar) {
user.setUserField(uid, 'picture', gravatar);
updateHeader();
});
} else if(type === 'uploaded') {
} else if (type === 'uploaded') {
user.getUserField(uid, 'uploadedpicture', function(err, uploadedpicture) {
user.setUserField(uid, 'picture', uploadedpicture);
updateHeader();
@ -300,21 +309,21 @@ var SocketIO = require('socket.io').listen(global.server, {
});
socket.on('api:user.follow', function(data, callback) {
if(uid) {
if (uid) {
user.follow(uid, data.uid, callback);
}
});
socket.on('api:user.unfollow', function(data, callback) {
if(uid) {
if (uid) {
user.unfollow(uid, data.uid, callback);
}
});
socket.on('api:user.saveSettings', function(data, callback) {
if(uid) {
if (uid) {
user.setUserFields(uid, {
showemail:data.showemail
showemail: data.showemail
});
callback(true);
}
@ -323,8 +332,8 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('api:topics.post', function(data) {
topics.post(uid, data.title, data.content, data.category_id, data.images, function(err, result) {
if(err) {
if(err.message === 'not-logged-in') {
if (err) {
if (err.message === 'not-logged-in') {
socket.emit('event:alert', {
title: 'Thank you for posting',
message: 'Since you are unregistered, your post is awaiting approval. Click here to register now.',
@ -334,9 +343,9 @@ var SocketIO = require('socket.io').listen(global.server, {
ajaxify.go('register');
}
});
} else if(err.message === 'title-too-short') {
} else if (err.message === 'title-too-short') {
topics.emitTitleTooShortAlert(socket);
} else if(err.message === 'content-too-short') {
} else if (err.message === 'content-too-short') {
posts.emitContentTooShortAlert(socket);
} else if (err.message === 'too-many-posts') {
posts.emitTooManyPostsAlert(socket);
@ -344,7 +353,7 @@ var SocketIO = require('socket.io').listen(global.server, {
return;
}
if(result) {
if (result) {
posts.getTopicPostStats(socket);
socket.emit('event:alert', {
@ -360,7 +369,7 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('api:topics.markAllRead', function(data, callback) {
topics.markAllRead(uid, function(err, success) {
if(!err && success) {
if (!err && success) {
callback(true);
} else {
callback(false);
@ -369,7 +378,7 @@ var SocketIO = require('socket.io').listen(global.server, {
});
socket.on('api:posts.reply', function(data) {
if(uid < 1) {
if (uid < 1) {
socket.emit('event:alert', {
title: 'Reply Unsuccessful',
message: 'You don&apos;t seem to be logged in, so you cannot reply.',
@ -380,12 +389,12 @@ var SocketIO = require('socket.io').listen(global.server, {
}
posts.reply(data.topic_id, uid, data.content, data.images, function(err, result) {
if(err) {
if(err.message === 'content-too-short') {
if (err) {
if (err.message === 'content-too-short') {
posts.emitContentTooShortAlert(socket);
} else if(err.message === 'too-many-posts') {
} else if (err.message === 'too-many-posts') {
posts.emitTooManyPostsAlert(socket);
} else if(err.message === 'reply-error') {
} else if (err.message === 'reply-error') {
socket.emit('event:alert', {
title: 'Reply Unsuccessful',
message: 'Your reply could not be posted at this time. Please try again later.',
@ -396,7 +405,7 @@ var SocketIO = require('socket.io').listen(global.server, {
return;
}
if(result) {
if (result) {
posts.getTopicPostStats(socket);
@ -415,7 +424,7 @@ var SocketIO = require('socket.io').listen(global.server, {
function emitOnlineUserCount() {
var anon = userSockets[0] ? userSockets[0].length : 0;
var registered = Object.keys(userSockets).length;
if(anon)
if (anon)
registered = registered - 1;
var returnObj = {
@ -479,12 +488,14 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('api:posts.getRawPost', function(data) {
posts.getPostField(data.pid, 'content', function(raw) {
socket.emit('api:posts.getRawPost', { post: raw });
socket.emit('api:posts.getRawPost', {
post: raw
});
});
});
socket.on('api:posts.edit', function(data) {
if(!data.title || data.title.length < topics.minimumTitleLength) {
if (!data.title || data.title.length < topics.minimumTitleLength) {
topics.emitTitleTooShortAlert(socket);
return;
} else if (!data.content || data.content.length < require('../public/config.json').minimumPostLength) {
@ -527,7 +538,7 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('getChatMessages', function(data, callback) {
var touid = data.touid;
require('./messaging').getMessages(uid, touid, function(err, messages) {
if(err)
if (err)
return callback(null);
callback(messages);
@ -537,7 +548,7 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('sendChatMessage', function(data) {
var touid = data.touid;
if(touid === uid || uid === 0) {
if (touid === uid || uid === 0) {
return;
}
@ -547,8 +558,8 @@ var SocketIO = require('socket.io').listen(global.server, {
var finalMessage = username + ' : ' + msg,
notifText = 'New message from <strong>' + username + '</strong>';
if(!isUserOnline(touid)) {
notifications.create(notifText, 5, 'javascript:app.openChat(&apos;'+username+'&apos;, '+uid+');', 'notification_' + uid + '_' + touid, function(nid) {
if (!isUserOnline(touid)) {
notifications.create(notifText, 5, 'javascript:app.openChat(&apos;' + username + '&apos;, ' + uid + ');', 'notification_' + uid + '_' + touid, function(nid) {
notifications.push(nid, [touid], function(success) {
});
@ -558,20 +569,30 @@ var SocketIO = require('socket.io').listen(global.server, {
require('./messaging').addMessage(uid, touid, msg, function(err, message) {
var numSockets = 0;
if(userSockets[touid]) {
if (userSockets[touid]) {
numSockets = userSockets[touid].length;
for(var x=0; x<numSockets; ++x) {
userSockets[touid][x].emit('chatMessage', {fromuid:uid, username:username, message: finalMessage, timestamp: Date.now()});
for (var x = 0; x < numSockets; ++x) {
userSockets[touid][x].emit('chatMessage', {
fromuid: uid,
username: username,
message: finalMessage,
timestamp: Date.now()
});
}
}
if(userSockets[uid]) {
if (userSockets[uid]) {
numSockets = userSockets[uid].length;
for(var x=0; x<numSockets; ++x) {
userSockets[uid][x].emit('chatMessage', {fromuid:touid, username:username, message:'You : ' + msg, timestamp: Date.now()});
for (var x = 0; x < numSockets; ++x) {
userSockets[uid][x].emit('chatMessage', {
fromuid: touid,
username: username,
message: 'You : ' + msg,
timestamp: Date.now()
});
}
}
});
@ -586,7 +607,9 @@ var SocketIO = require('socket.io').listen(global.server, {
socket.on('api:config.set', function(data) {
meta.configs.set(data.key, data.value, function(err) {
if (!err) socket.emit('api:config.set', { status: 'ok' });
if (!err) socket.emit('api:config.set', {
status: 'ok'
});
});
});
@ -609,7 +632,7 @@ var SocketIO = require('socket.io').listen(global.server, {
});
} else if (parseInt(data.cid) > 0) {
user.getUserFields(uid, ['username', 'picture'], function(err, userData) {
if(!err && userData) {
if (!err && userData) {
socket.emit('api:composer.push', {
tid: 0,
cid: data.cid,
@ -626,7 +649,7 @@ var SocketIO = require('socket.io').listen(global.server, {
posts.getPostFields(data.pid, ['content', 'uploadedImages'], function(raw) {
try {
raw.uploadedImages = JSON.parse(raw.uploadedImages);
} catch(e) {
} catch (e) {
winston.err(e);
raw.uploadedImages = [];
}
@ -696,7 +719,9 @@ var SocketIO = require('socket.io').listen(global.server, {
end = start + 9;
topics.getTopicPosts(data.tid, start, end, uid, function(posts) {
callback({posts:posts});
callback({
posts: posts
});
});
});
@ -705,7 +730,9 @@ var SocketIO = require('socket.io').listen(global.server, {
end = start + 9;
categories.getCategoryTopics(data.cid, start, end, uid, function(topics) {
callback({topics:topics});
callback({
topics: topics
});
});
});
@ -732,10 +759,12 @@ var SocketIO = require('socket.io').listen(global.server, {
end = start + 19;
user.getUsers(data.set, start, end, function(err, data) {
if(err) {
if (err) {
winston.err(err);
} else {
callback({users:data});
callback({
users: data
});
}
});
});
@ -757,37 +786,37 @@ var SocketIO = require('socket.io').listen(global.server, {
});
socket.on('api:admin.user.makeAdmin', function(theirid) {
if(uid && uid > 0) {
if (uid && uid > 0) {
admin.user.makeAdmin(uid, theirid, socket);
}
});
socket.on('api:admin.user.removeAdmin', function(theirid) {
if(uid && uid > 0) {
if (uid && uid > 0) {
admin.user.removeAdmin(uid, theirid, socket);
}
});
socket.on('api:admin.user.deleteUser', function(theirid) {
if(uid && uid > 0) {
if (uid && uid > 0) {
admin.user.deleteUser(uid, theirid, socket);
}
});
socket.on('api:admin.user.banUser', function(theirid) {
if(uid && uid > 0) {
if (uid && uid > 0) {
admin.user.banUser(uid, theirid, socket);
}
});
socket.on('api:admin.user.unbanUser', function(theirid) {
if(uid && uid > 0) {
if (uid && uid > 0) {
admin.user.unbanUser(uid, theirid, socket);
}
});
socket.on('api:admin.user.search', function(username, callback) {
if(uid && uid > 0) {
if (uid && uid > 0) {
user.search(username, function(data) {
if (!callback) socket.emit('api:admin.user.search', data);
else callback(null, data);
@ -855,4 +884,4 @@ var SocketIO = require('socket.io').listen(global.server, {
});
});
}(SocketIO));
}(SocketIO));
Loading…
Cancel
Save