76 lines
2.3 KiB
TypeScript
Executable File
76 lines
2.3 KiB
TypeScript
Executable File
// external imports
|
|
import * as WebSocket from 'ws';
|
|
import * as jwt from 'jsonwebtoken';
|
|
import * as url from 'url';
|
|
|
|
// internal imports
|
|
const app = require('./config/app');
|
|
const logger = require('./logger');
|
|
|
|
import ClientManager from './clientManager';
|
|
import ChannelManager from './channelManager';
|
|
import PublicClient from './clients/types/publicClient';
|
|
import PrivateClient from './clients/types/privateClient';
|
|
import CustomClient from './clients/types/customClient';
|
|
|
|
const wss = new WebSocket.Server({ maxPayload: 250000, port: app.port });
|
|
const clientManager = new ClientManager();
|
|
const channelManager = new ChannelManager();
|
|
|
|
function connectionManager() {
|
|
wss.on('connection', (ws: WebSocket, request: any, args: string) => {
|
|
const result = JSON.parse(validateJWT(request));
|
|
|
|
if (result.error) {
|
|
ws.send(`Unable to validate JWT, please try again or contact support...`);
|
|
ws.close();
|
|
} else {
|
|
const data = result.data;
|
|
let client: PublicClient|PrivateClient|CustomClient|null;
|
|
logger.accessLog.info(`Client Connected: ${data.user_id}`);
|
|
|
|
if (!channelManager.channelExists(data.channel)) channelManager.createChannel(data);
|
|
|
|
if (clientManager.clientExists(data.user_id)) {
|
|
client = clientManager.getClient(data.user_id);
|
|
|
|
if (client != null) {
|
|
client.replaceWebSocket(ws);
|
|
}
|
|
} else {
|
|
client = clientManager.addClient(data, channelManager, ws);
|
|
}
|
|
|
|
if (client != null) channelManager.addClientToChannel(client, data.channel);
|
|
|
|
logger.accessLog.info(`Purging empty channels...`);
|
|
channelManager.purgeEmptyChannels();
|
|
|
|
ws.send(`Hi there, welcome to braid, Measures Web Socket server. Connecting all our services!\nYou are currently in channel: ${data.channel}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
function validateJWT(request: any) {
|
|
try {
|
|
const query = url.parse(request.url, true).query;
|
|
const token = query.token || (app.environment === 'development' ? app.devToken : '');
|
|
return JSON.stringify(jwt.verify(token, app.secret, app.signOptions));
|
|
} catch (e) {
|
|
console.log(e);
|
|
return JSON.stringify({error: e});
|
|
}
|
|
}
|
|
|
|
function startServer() {
|
|
connectionManager();
|
|
}
|
|
|
|
startServer();
|
|
|
|
module.exports = {
|
|
clientManager,
|
|
channelManager,
|
|
connectionManager
|
|
};
|