2015-07-22 16:38:58 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
/*
|
|
|
|
* User Controller
|
|
|
|
*
|
|
|
|
* Server API
|
2015-07-29 10:46:30 +00:00
|
|
|
* users:update - Update list of users
|
2015-07-22 16:38:58 +00:00
|
|
|
*
|
|
|
|
* Client API
|
2015-07-29 10:46:30 +00:00
|
|
|
* users:online - User is on the page
|
|
|
|
* users:away - User is away from page
|
|
|
|
* users:authorize - Authorize user
|
|
|
|
* users:refresh - Request new user list
|
2015-07-22 16:38:58 +00:00
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
|
|
|
var userCache = {};
|
2015-07-22 23:30:14 +00:00
|
|
|
var User = require("./user");
|
|
|
|
var winston = require("winston");
|
|
|
|
var enslClient = require("../ensl/client")();
|
2015-07-22 16:38:58 +00:00
|
|
|
|
|
|
|
module.exports = function (namespace) {
|
|
|
|
var refreshUsers = function (socket) {
|
2015-07-27 11:55:36 +00:00
|
|
|
var receivers = (socket !== undefined) ? [socket] : namespace.sockets;
|
2015-07-22 16:38:58 +00:00
|
|
|
|
|
|
|
var newCache = {};
|
|
|
|
namespace.sockets.forEach(function (socket) {
|
|
|
|
var user = socket._user;
|
|
|
|
newCache[user.id] = user;
|
|
|
|
});
|
|
|
|
userCache = newCache;
|
|
|
|
|
|
|
|
var users = [];
|
|
|
|
|
|
|
|
for (var id in userCache) {
|
|
|
|
if (userCache.hasOwnProperty(id)) {
|
|
|
|
users.push(userCache[id]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-07-27 11:55:36 +00:00
|
|
|
receivers.forEach(function (socket) {
|
|
|
|
socket.emit('users:update', {
|
|
|
|
count: users.length,
|
|
|
|
users: users,
|
|
|
|
currentUser: socket._user
|
|
|
|
});
|
|
|
|
});
|
2015-07-22 16:38:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
namespace.on('connection', function (socket) {
|
|
|
|
refreshUsers();
|
|
|
|
|
2015-07-27 11:55:36 +00:00
|
|
|
socket.on('users:refresh', refreshUsers.bind(null, socket));
|
2015-07-22 16:38:58 +00:00
|
|
|
|
2015-07-29 10:46:30 +00:00
|
|
|
socket.on('users:online', function () {
|
|
|
|
socket._user.online = true;
|
|
|
|
refreshUsers();
|
|
|
|
});
|
|
|
|
|
|
|
|
socket.on('users:away', function () {
|
|
|
|
socket._user.online = false;
|
|
|
|
refreshUsers();
|
|
|
|
});
|
|
|
|
|
2015-07-22 16:38:58 +00:00
|
|
|
socket.on("users:authorize", function (data) {
|
|
|
|
var id = parseInt(data.id, 10);
|
|
|
|
if (isNaN(id)) return;
|
|
|
|
enslClient.getUserById({
|
|
|
|
id: id
|
|
|
|
}, function (error, response, body) {
|
|
|
|
if (error || response.statusCode !== 200) {
|
|
|
|
winston.error("An error occurred in authorising id", id);
|
|
|
|
winston.error(error);
|
|
|
|
winston.error("ENSL API status:", response.statusCode);
|
|
|
|
return;
|
|
|
|
}
|
2015-07-22 23:30:14 +00:00
|
|
|
socket._user = new User(body);
|
2015-07-22 16:38:58 +00:00
|
|
|
refreshUsers();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
socket.on('disconnect', function (socket) {
|
|
|
|
refreshUsers();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|