const io = require('socket.io-client'); const EventEmitter = require('events'); class GatewayConnection extends EventEmitter { constructor(url) { super(); this.isConnected = false; this.socket = null; this.url = url; } } GatewayConnection.prototype.disconnect = function() { if (this.socket) this.socket.disconnect(); this.socket = null; this.isConnected = false; }; GatewayConnection.prototype.connect = function(token) { console.log('[*] [gateway] [handshake] Trying to connect to gateway'); this.socket = io(`${this.url}/gateway`, { query: { token }, transports: ['websocket'] }); this.socket.on('connect', () => { this.socket.once('hello', (debugInfo) => { console.log('[*] [gateway] [handshake] Got hello from server, sending yoo...', debugInfo); this.socket.emit('yoo'); this.isConnected = true; this.debugInfo = debugInfo; this.emit('connect', { message: 'CONNECT_RECEIVED_HELLO' }); console.log('[*] [gateway] [handshake] Assuming that server received yoo and that connection is completed.'); }); }) this.socket.on('error', (e) => { console.log('[E] [gateway] Gateway error', e); this.isConnected = false; this.socket = null; this.emit('disconnect', { message: 'DISCONNECT_ERR' }); }); this.socket.on('disconnectNotification', (e) => { console.log('[E] [gateway] Received disconnect notfication', e); this.isConnected = false; this.socket = null; this.emit('disconnect', { message: 'DISCONNECT_NOTIF', reason: e }); }); this.socket.on('disconnect', (e) => { console.log('[E] [gateway] Disconnected from gateway: ', e); this.isConnected = false; this.emit('disconnect', { message: 'DISCONNECT', reason: e }); }); this.socket.on('message', (e) => this.emit('message', e)); this.socket.on('refreshClient', (e) => this.emit('refreshClient', e)); this.socket.on('clientListUpdate', (e) => this.emit('clientListUpdate', e)); }; GatewayConnection.prototype.sendMessage = function(categoryId, content, { nickAuthor, destUser }) { if (!this.isConnected) return 1; if (content.length >= 2000) return 1; this.socket.emit('message', { category: { _id: categoryId }, nickAuthor, destUser, content }); }; GatewayConnection.prototype.subscribeToCategoryChat = function(categoryId) { if (!this.isConnected) return; const request = [categoryId]; console.log('[*] [gateway] Subscribing to channel(s)', request); this.socket.emit('subscribe', request); return categoryId; }; module.exports = GatewayConnection;