sync/src/io/backend/frontendmanager.js

70 lines
2.6 KiB
JavaScript
Raw Normal View History

2016-01-01 18:26:43 -08:00
import logger from 'cytube-common/lib/logger';
2015-12-26 15:07:03 -08:00
import ioServer from '../ioserver';
import ProxiedSocket from './proxiedsocket';
2015-12-24 16:24:07 -08:00
export default class FrontendManager {
2015-12-26 15:07:03 -08:00
constructor(socketEmitter) {
this.socketEmitter = socketEmitter;
2015-12-24 16:24:07 -08:00
this.frontendConnections = {};
2015-12-26 15:07:03 -08:00
this.frontendProxiedSockets = {};
2015-12-24 16:24:07 -08:00
}
onConnection(socket) {
if (this.frontendConnections.hasOwnProperty(socket.endpoint)) {
2015-12-24 16:24:07 -08:00
// TODO: do some validation, maybe check if the socket is still connected?
throw new Error();
}
this.frontendConnections[socket.endpoint] = socket;
2016-01-01 18:25:12 -08:00
socket.on('close', this.onFrontendDisconnect.bind(this, socket));
2015-12-28 23:52:39 -08:00
socket.on('SocketConnectEvent', this.onSocketConnect.bind(this, socket));
socket.on('SocketFrameEvent', this.onSocketFrame.bind(this, socket));
2015-12-24 16:24:07 -08:00
}
2016-01-01 18:25:12 -08:00
onFrontendDisconnect(socket) {
const endpoint = socket.endpoint;
if (this.frontendConnections.hasOwnProperty(endpoint)) {
if (this.frontendProxiedSockets.hasOwnProperty(endpoint)) {
logger.warn(`Frontend ${endpoint} disconnected`);
this.frontendProxiedSockets[endpoint].forEach(proxySocket => {
proxySocket.onProxiedEventReceived('disconnect');
});
delete this.frontendProxiedSockets[endpoint];
}
delete this.frontendConnections[endpoint];
}
}
2015-12-30 21:57:46 -08:00
onSocketConnect(frontendConnection, socketID, socketIP, socketUser) {
const mapKey = frontendConnection.endpoint;
2015-12-26 15:07:03 -08:00
const proxiedSocket = new ProxiedSocket(
2015-12-28 23:52:39 -08:00
socketID,
socketIP,
2015-12-30 21:57:46 -08:00
socketUser,
2015-12-26 15:07:03 -08:00
this.socketEmitter,
frontendConnection);
if (!this.frontendProxiedSockets.hasOwnProperty(mapKey)) {
this.frontendProxiedSockets[mapKey] = {};
2015-12-28 23:52:39 -08:00
} else if (this.frontendProxiedSockets[mapKey].hasOwnProperty(socketID)) {
2015-12-26 15:07:03 -08:00
// TODO: Handle this gracefully
throw new Error();
}
2015-12-28 23:52:39 -08:00
this.frontendProxiedSockets[mapKey][socketID] = proxiedSocket;
2015-12-26 15:07:03 -08:00
ioServer.handleConnection(proxiedSocket);
}
2015-12-28 23:52:39 -08:00
onSocketFrame(frontendConnection, socketID, event, args) {
const mapKey = frontendConnection.endpoint;
2015-12-26 15:07:03 -08:00
const socketMap = this.frontendProxiedSockets[mapKey];
2015-12-28 23:52:39 -08:00
if (!socketMap || !socketMap.hasOwnProperty(socketID)) {
2015-12-26 15:07:03 -08:00
// TODO
throw new Error();
}
2015-12-28 23:52:39 -08:00
const socket = socketMap[socketID];
socket.onProxiedEventReceived.apply(socket, [event].concat(args));
2015-12-24 16:24:07 -08:00
}
}