"use strict"; var SocketIO = require('socket.io'), socketioWildcard = require('socket.io-wildcard'), util = require('util'), async = require('async'), path = require('path'), fs = require('fs'), nconf = require('nconf'), express = require('express'), socketCookieParser = express.cookieParser(nconf.get('secret')), winston = require('winston'), db = require('../database'), user = require('../user'), socketUser = require('./user'), topics = require('../topics'), logger = require('../logger'), meta = require('../meta'), Sockets = {}, Namespaces = {}; /* === */ var io; Sockets.userSockets = {}; Sockets.init = function(server) { io = socketioWildcard(SocketIO).listen(server, { log: false, transports: ['websocket', 'xhr-polling', 'jsonp-polling', 'flashsocket'], 'browser client minification': true }); Sockets.server = io; fs.readdir(__dirname, function(err, files) { files.splice(files.indexOf('index.js'), 1); async.each(files, function(lib, next) { lib = lib.slice(0, -3); Namespaces[lib] = require('./' + lib); next(); }); }); io.sockets.on('connection', function(socket) { var hs = socket.handshake, sessionID, uid, lastPostTime = 0; // Validate the session, if present socketCookieParser(hs, {}, function(err) { if(err) { winston.error(err.message); } sessionID = socket.handshake.signedCookies["express.sid"]; db.sessionStore.get(sessionID, function(err, sessionData) { if (!err && sessionData && sessionData.passport && sessionData.passport.user) { uid = sessionData.passport.user; } else { uid = 0; } socket.uid = parseInt(uid, 10); Sockets.userSockets[uid] = Sockets.userSockets[uid] || []; Sockets.userSockets[uid].push(socket); /* Need to save some state for the logger & maybe some other modules later on */ socket.state = { user : { uid : uid } }; /* If meta.config.loggerIOStatus > 0, logger.io_one will hook into this socket */ logger.io_one(socket,uid); if (uid) { db.sortedSetAdd('users:online', Date.now(), uid, function(err, data) { socket.join('uid_' + uid); user.getUserField(uid, 'username', function(err, username) { socket.emit('event:connect', { status: 1, username: username, uid: uid }); }); }); } socketUser.isOnline(socket, uid, function(err, data) { socket.broadcast.emit('user.isOnline', err, data); }); }); }); socket.on('disconnect', function() { var index = (Sockets.userSockets[uid] || []).indexOf(socket); if (index !== -1) { Sockets.userSockets[uid].splice(index, 1); } if (Sockets.userSockets[uid] && Sockets.userSockets[uid].length === 0) { delete Sockets.userSockets[uid]; if (uid) { db.sortedSetRemove('users:online', uid, function(err, data) { }); } } socketUser.isOnline(socket, uid, function(err, data) { socket.broadcast.emit('user.isOnline', err, data); }); emitOnlineUserCount(); for(var roomName in io.sockets.manager.roomClients[socket.id]) { updateRoomBrowsingText(roomName.slice(1)); } }); socket.on('*', function(payload, callback) { function callMethod(method) { if(socket.uid) { user.setUserField(socket.uid, 'lastonline', Date.now()); } method.call(null, socket, payload.args.length ? payload.args[0] : null, function(err, result) { if (callback) { callback(err?{message:err.message}:null, result); } }); } if(!payload.name) { return winston.warn('[socket.io] Empty method name'); } var parts = payload.name.toString().split('.'), namespace = parts.slice(0, 1), methodToCall = parts.reduce(function(prev, cur) { if (prev !== null && prev[cur]) { return prev[cur]; } else { return null; } }, Namespaces); if(!methodToCall) { return winston.warn('[socket.io] Unrecognized message: ' + payload.name); } if (Namespaces[namespace].before) { Namespaces[namespace].before(socket, function() { callMethod(methodToCall); }); } else { callMethod(methodToCall); } }); }); }; Sockets.logoutUser = function(uid) { if(Sockets.userSockets[uid] && Sockets.userSockets[uid].length) { for(var i=0; i< Sockets.userSockets[uid].length; ++i) { Sockets.userSockets[uid][i].emit('event:disconnect'); Sockets.userSockets[uid][i].disconnect(); if(!Sockets.userSockets[uid]) { return; } } } }; Sockets.emitUserCount = function() { db.getObjectField('global', 'userCount', function(err, count) { io.sockets.emit('user.count', err?{message:err.message}:null, { count: count }); }); }; Sockets.in = function(room) { return io.sockets.in(room); }; Sockets.getConnectedClients = function() { return Sockets.userSockets; }; Sockets.getOnlineAnonCount = function () { return Sockets.userSockets[0] ? Sockets.userSockets[0].length : 0; }; /* Helpers */ Sockets.isUserOnline = isUserOnline; function isUserOnline(uid) { return !!Sockets.userSockets[uid] && Sockets.userSockets[uid].length > 0; } Sockets.updateRoomBrowsingText = updateRoomBrowsingText; function updateRoomBrowsingText(roomName) { function getUidsInRoom(room) { var uids = []; var clients = io.sockets.clients(roomName); for(var i=0; i