ensl_gathers/lib/user/controller.js

87 lines
1.9 KiB
JavaScript
Raw Normal View History

"use strict";
/*
* User Controller
*
* Server API
2015-07-29 10:46:30 +00:00
* users:update - Update list of users
*
* 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
*
*/
var userCache = {};
2015-07-22 23:30:14 +00:00
var User = require("./user");
var winston = require("winston");
var enslClient = require("../ensl/client")();
module.exports = function (namespace) {
var refreshUsers = function (socket) {
2015-07-27 11:55:36 +00:00
var receivers = (socket !== undefined) ? [socket] : namespace.sockets;
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
});
});
};
namespace.on('connection', function (socket) {
refreshUsers();
2015-07-27 11:55:36 +00:00
socket.on('users:refresh', refreshUsers.bind(null, socket));
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();
});
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);
refreshUsers();
});
});
socket.on('disconnect', function (socket) {
refreshUsers();
});
});
};