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) {
|
2015-12-27 15:10:43 -08:00
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-27 15:10:43 -08:00
|
|
|
this.frontendConnections[socket.endpoint] = 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
|
|
|
}
|
|
|
|
|
|
2015-12-28 23:52:39 -08:00
|
|
|
onSocketConnect(frontendConnection, socketID, socketIP) {
|
2015-12-27 15:10:43 -08:00
|
|
|
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-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) {
|
2015-12-27 15:10:43 -08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
}
|