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
2015-08-18 09:56:35 +00:00
* users:authorize - Sign on with arbitary user ID (to be enabled for admin only)
2015-07-29 10:46:30 +00:00
* users:refresh - Request new user list
*
*/
var userCache = {};
2015-07-22 23:30:14 +00:00
var User = require("./user");
var winston = require("winston");
2015-08-18 09:56:35 +00:00
var mongoose = require("mongoose");
var Session = mongoose.model("Session");
2015-07-22 23:30:14 +00:00
var enslClient = require("../ensl/client")();
2015-07-29 13:50:39 +00:00
var _ = require("lodash");
2015-08-18 09:56:35 +00:00
module.exports = namespace => {
var refreshUsers = socket => {
2015-07-27 11:55:36 +00:00
var receivers = (socket !== undefined) ? [socket] : namespace.sockets;
var newCache = {};
2015-08-18 09:56:35 +00:00
namespace.sockets.forEach(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-08-18 09:56:35 +00:00
receivers.forEach(socket => {
2015-07-27 11:55:36 +00:00
socket.emit('users:update', {
count: users.length,
users: users,
currentUser: socket._user
});
});
};
2015-08-18 09:56:35 +00:00
namespace.on('connection', socket => {
refreshUsers();
2015-07-27 11:55:36 +00:00
socket.on('users:refresh', refreshUsers.bind(null, socket));
2015-08-18 09:56:35 +00:00
socket.on('users:online', () => {
2015-07-29 10:46:30 +00:00
socket._user.online = true;
});
2015-08-18 09:56:35 +00:00
socket.on('users:away', () => {
2015-07-29 10:46:30 +00:00
socket._user.online = false;
});
2015-08-18 09:56:35 +00:00
socket.on("users:authorize", data => {
if (!socket._user.admin) return;
var id = parseInt(data.id, 10);
if (isNaN(id)) return;
enslClient.getUserById({
id: id
2015-08-18 09:56:35 +00:00
}, (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();
});
});
2015-08-18 09:56:35 +00:00
socket.on('disconnect', socket => { refreshUsers(); });
});
};