Skip to content

Node.js based forum software built for the modern web

merge

barisusaklic213f77f9199
diff --cc src/socket.io/index.js
index 83f838d73b,b7e18eb596..9b75711c99
--- a/src/socket.io/index.js
+++ b/src/socket.io/index.js
@@@ -22,62 -22,39 +22,21 @@@ var SocketIO = require('socket.io')
/* === */
-var io;
+var io;
- var onlineUsers = [];
-
- process.on('message', onMessage);
-
- function onMessage(msg) {
- if (typeof msg !== 'object') {
- return;
- }
-
- if (msg.action === 'user:connect') {
- if (msg.uid && onlineUsers.indexOf(msg.uid) === -1) {
- onlineUsers.push(msg.uid);
- }
- } else if(msg.action === 'user:disconnect') {
- if (msg.uid && msg.socketCount <= 1) {
- var index = onlineUsers.indexOf(msg.uid);
- if (index !== -1) {
- onlineUsers.splice(index, 1);
- }
- }
- }
- }
-
- function onUserConnect(uid, socketid) {
- var msg = {action: 'user:connect', uid: uid, socketid: socketid};
- if (process.send) {
- process.send(msg);
- } else {
- onMessage(msg);
- }
- }
-
- function onUserDisconnect(uid, socketid, socketCount) {
- var msg = {action: 'user:disconnect', uid: uid, socketid: socketid, socketCount: socketCount};
- if (process.send) {
- process.send(msg);
- } else {
- onMessage(msg);
- }
- }
-
Sockets.init = function(server) {
- // Default socket.io config
var config = {
- log: true,
- 'log level': process.env.NODE_ENV === 'development' ? 2 : 0,
- transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket'],
- 'browser client minification': true,
- resource: nconf.get('relative_path') + '/socket.io'
- };
-
- // If a redis server is configured, use it as a socket.io store, otherwise, fall back to in-memory store
- if (nconf.get('redis')) {
- var RedisStore = require('socket.io/lib/stores/redis'),
- database = require('../database/redis'),
- pub = database.connect(),
- sub = database.connect(),
- client = database.connect();
-
- // "redis" property needs to be passed in as referenced here: https://github.com/Automattic/socket.io/issues/808
- // Probably fixed in socket.IO 1.0
- config.store = new RedisStore({
- redis: require('redis'),
- redisPub : pub,
- redisSub : sub,
- redisClient : client
- });
- } else if (nconf.get('cluster')) {
- winston.warn('[socket.io] Clustering detected, you are advised to configure Redis as a websocket store.');
- }
+ transports: ['polling', 'websocket'],
+ path: nconf.get('relative_path') + '/socket.io'
+ };
+
+ io = new SocketIO();
- io = socketioWildcard(SocketIO).listen(server, config);
+ addRedisAdapter(io);
+
+ io.use(socketioWildcard);
+
+ io.listen(server, config);
Sockets.server = io;
@@@ -94,105 -71,87 +53,102 @@@
});
});
- io.sockets.on('connection', function(socket) {
- var hs = socket.handshake,
- sessionID, uid;
+ io.use(function(socket, next) {
+ console.log('AUTH');
- if (!hs) {
- return;
+ var handshake = socket.request,
+ sessionID;
+
+ if (!handshake) {
+ return next(new Error('[[error:not-authorized]]'));
}
- // Validate the session, if present
- socketCookieParser(hs, {}, function(err) {
- if(err) {
- return winston.error(err.message);
+ cookieParser(handshake, {}, function(err) {
+ if (err) {
+ return next(err);
}
- sessionID = socket.handshake.signedCookies['express.sid'];
+ var sessionID = handshake.signedCookies['express.sid'];
+
db.sessionStore.get(sessionID, function(err, sessionData) {
- if (!err && sessionData && sessionData.passport && sessionData.passport.user) {
- uid = parseInt(sessionData.passport.user, 10);
+ if (err) {
+ return next(err);
+ }
+ if (sessionData && sessionData.passport && sessionData.passport.user) {
+ socket.uid = parseInt(sessionData.passport.user, 10);
} else {
- uid = 0;
+ socket.uid = 0;
}
+ next();
+ });
+ });
+ });
- socket.uid = parseInt(uid, 10);
-
- /* If meta.config.loggerIOStatus > 0, logger.io_one will hook into this socket */
- logger.io_one(socket, uid);
-
- if (uid) {
- socket.join('uid_' + uid);
- socket.join('online_users');
-
- async.parallel({
- user: function(next) {
- user.getUserFields(uid, ['username', 'userslug', 'picture', 'status'], next);
- },
- isAdmin: function(next) {
- user.isAdministrator(uid, next);
- }
- }, function(err, userData) {
- if (err || !userData.user) {
- return;
- }
- socket.emit('event:connect', {
- status: 1,
- username: userData.user.username,
- userslug: userData.user.userslug,
- picture: userData.user.picture,
- isAdmin: userData.isAdmin,
- uid: uid
- });
-
- socket.broadcast.emit('event:user_status_change', {uid:uid, status: userData.user.status});
- });
+ io.on('connection', function(socket) {
+ console.log('CONNECTED', socket.uid, socket.id);
- } else {
- socket.join('online_guests');
- socket.emit('event:connect', {
- status: 1,
- username: '[[global:guest]]',
- isAdmin: false,
- uid: 0
- });
+ logger.io_one(socket, socket.uid);
+
+ if (socket.uid) {
- onUserConnect(socket.uid, socket.id);
+ socket.join('uid_' + socket.uid);
+ socket.join('online_users');
+
+ async.parallel({
+ user: function(next) {
+ user.getUserFields(socket.uid, ['username', 'userslug', 'picture', 'status'], next);
+ },
+ isAdmin: function(next) {
+ user.isAdministrator(socket.uid, next);
}
+ }, function(err, userData) {
+ if (err || !userData.user) {
+ return;
+ }
+ socket.emit('event:connect', {
+ status: 1,
+ username: userData.user.username,
+ userslug: userData.user.userslug,
+ picture: userData.user.picture,
+ isAdmin: userData.isAdmin,
+ uid: socket.uid
+ });
+
+ socket.broadcast.emit('event:user_status_change', {uid: socket.uid, status: userData.user.status});
});
- });
+ } else {
+ socket.join('online_guests');
+ socket.emit('event:connect', {
+ status: 1,
+ username: '[[global:guest]]',
+ isAdmin: false,
+ uid: 0
+ });
+ }
socket.on('disconnect', function() {
- var socketCount = Sockets.getUserSocketCount(uid);
- if (uid && socketCount <= 1) {
- socket.broadcast.emit('event:user_status_change', {uid: uid, status: 'offline'});
+ var socketCount = Sockets.getUserSocketCount(socket.uid);
+ console.log('DISCONNECT', socket.uid, socket.id);
+ if (socket.uid && socketCount <= 1) {
+ socket.broadcast.emit('event:user_status_change', {uid: socket.uid, status: 'offline'});
}
- onUserDisconnect(socket.uid, socket.id, socketCount);
-
- for(var roomName in io.sockets.manager.roomClients[socket.id]) {
- if (roomName.indexOf('topic') !== -1) {
- io.sockets.in(roomName.slice(1)).emit('event:user_leave', socket.uid);
- }
- }
+ // for(var roomName in io.sockets.manager.roomClients[socket.id]) {
+ // if (roomName.indexOf('topic') !== -1) {
+ // io.sockets.in(roomName.slice(1)).emit('event:user_leave', socket.uid);
+ // }
+ // }
});
- socket.on('*', function(payload, callback) {
- if (!payload.name) {
+ socket.on('*', function(payload) {
+ if (!payload.data.length) {
+ return winston.warn('[socket.io] Empty payload');
+ }
+
+ var eventName = payload.data[0];
+ var params = payload.data[1];
+ var callback = typeof payload.data[payload.data.length - 1] === 'function' ? payload.data[payload.data.length - 1] : function() {};
+
+ if (!eventName) {
return winston.warn('[socket.io] Empty method name');
}
@@@ -291,13 -235,7 +247,9 @@@ Sockets.getSocketCount = function()
return Array.isArray(clients) ? clients.length : 0;
};
- Sockets.getConnectedClients = function() {
- return onlineUsers;
- };
-
Sockets.getUserSocketCount = function(uid) {
+ return 0;
+
var roomClients = io.sockets.manager.rooms['/uid_' + uid];
if(!Array.isArray(roomClients)) {
return 0;
@@@ -305,13 -243,7 +257,9 @@@
return roomClients.length;
};
- Sockets.getOnlineUserCount = function () {
- return onlineUsers.length;
- };
-
Sockets.getOnlineAnonCount = function () {
+ return 0;
+
var guestRoom = io.sockets.manager.rooms['/online_guests'];
if (!Array.isArray(guestRoom)) {
return 0;
diff --cc src/socket.io/meta.js
index e067b03c02,65a4038d2e..d483591f65
--- a/src/socket.io/meta.js
+++ b/src/socket.io/meta.js
@@@ -86,62 -86,67 +86,67 @@@ SocketMeta.rooms.enter = function(socke
};
SocketMeta.rooms.getAll = function(socket, data, callback) {
- var rooms = {}; //websockets.server.sockets.manager.rooms; doesnt work in socket.io 1.x
-
- var socketData = {
- onlineGuestCount: websockets.getOnlineAnonCount(),
- onlineRegisteredCount: websockets.getOnlineUserCount(),
- socketCount: websockets.getSocketCount(),
- users: {
- home: rooms['/home'] ? rooms['/home'].length : 0,
- topics: 0,
- category: 0
- },
- topics: {}
- };
-
- var scores = {},
- topTenTopics = [],
- tid;
-
- for (var room in rooms) {
- if (rooms.hasOwnProperty(room)) {
- if (tid = room.match(/^\/topic_(\d+)/)) {
- var length = rooms[room].length;
- socketData.users.topics += length;
-
- if (scores[length]) {
- scores[length].push(tid[1]);
- } else {
- scores[length] = [tid[1]];
+ db.sortedSetCount('users:online', now - 300000, now, function(err, onlineRegisteredCount) {
+ if (err) {
+ return callback(err);
+ }
+
- var rooms = websockets.server.sockets.manager.rooms,
- socketData = {
++ var rooms = {}; //websockets.server.sockets.manager.rooms; doesnt work in socket.io 1.x
++ var socketData = {
+ onlineGuestCount: websockets.getOnlineAnonCount(),
+ onlineRegisteredCount: onlineRegisteredCount,
+ socketCount: websockets.getSocketCount(),
+ users: {
+ home: rooms['/home'] ? rooms['/home'].length : 0,
+ topics: 0,
+ category: 0
+ },
+ topics: {}
+ };
+
+ var scores = {},
+ topTenTopics = [],
+ tid;
+
+ for (var room in rooms) {
+ if (rooms.hasOwnProperty(room)) {
+ if (tid = room.match(/^\/topic_(\d+)/)) {
+ var length = rooms[room].length;
+ socketData.users.topics += length;
+
+ if (scores[length]) {
+ scores[length].push(tid[1]);
+ } else {
+ scores[length] = [tid[1]];
+ }
+ } else if (room.match(/^\/category/)) {
+ socketData.users.category += rooms[room].length;
}
- } else if (room.match(/^\/category/)) {
- socketData.users.category += rooms[room].length;
}
}
- }
- var scoreKeys = Object.keys(scores),
- mostActive = scoreKeys.sort();
+ var scoreKeys = Object.keys(scores),
+ mostActive = scoreKeys.sort();
- while(topTenTopics.length < 10 && mostActive.length > 0) {
- topTenTopics = topTenTopics.concat(scores[mostActive.pop()]);
- }
+ while(topTenTopics.length < 10 && mostActive.length > 0) {
+ topTenTopics = topTenTopics.concat(scores[mostActive.pop()]);
+ }
- topTenTopics = topTenTopics.slice(0, 10);
+ topTenTopics = topTenTopics.slice(0, 10);
- topics.getTopicsFields(topTenTopics, ['title'], function(err, titles) {
- if (err) {
- return callback(err);
- }
- topTenTopics.forEach(function(tid, id) {
- socketData.topics[tid] = {
- value: rooms['/topic_' + tid].length,
- title: validator.escape(titles[id].title)
- };
+ topics.getTopicsFields(topTenTopics, ['title'], function(err, titles) {
+ if (err) {
+ return callback(err);
+ }
+ topTenTopics.forEach(function(tid, id) {
+ socketData.topics[tid] = {
+ value: rooms['/topic_' + tid].length,
+ title: validator.escape(titles[id].title)
+ };
+ });
+
+ callback(null, socketData);
});
-
- callback(null, socketData);
});
};