import Ws from "@adonisjs/websocket-client"; import CallService from './call.service'; import UserChannelService from './user.channel.service'; import { EventEmitter } from 'events'; let singleton: WebSocketService = null; enum EEvents { NEW_CONNECTION, CONNECTION_ONLINE, CONNECTION_OFFLINE, INCOMING_CALL, SIGNALING_EVENTS, CALL_ACTIONS } export default class WebSocketService { static Events = EEvents; private emitter; private callService: CallService; private constructor(private ws, private userChannelService: UserChannelService) { this.emitter = new EventEmitter(); this.callService = new CallService(this.ws); this.userChannelService.on('new:connection', this.onUserNewConnection.bind(this)); this.userChannelService.on('connection:online', this.onUserConnectionOnline.bind(this)); this.userChannelService.on('connection:offline', this.onUserConnectionOffline.bind(this)); } on(event: EEvents, callback: Function) { this.emitter.on(event, callback); } removeListener(event: EEvents, callback) { this.emitter.removeListener(event, callback); } // onPublicChannelMessage(msg) { // this.emitter // } private onUserNewConnection(data) { this.emitter.emit(EEvents.NEW_CONNECTION, data); } private onUserConnectionOnline(data) { this.emitter.emit(EEvents.CONNECTION_ONLINE, data); } private onUserConnectionOffline(data) { this.emitter.emit(EEvents.CONNECTION_OFFLINE, data); } async getLocalMedia(constraints: MediaStreamConstraints = null) { return this.callService.getUserMedia(constraints); } getRemoteStream() { return this.callService.getRemoteStream(); } static getInstance(): Promise { return new Promise((resolve, reject) => { // resolve(); // return; if (singleton) return resolve(singleton); const ws = Ws('', { path: 'connect' }); ws.connect(); ws.on('open', async () => { const userChannelService = await UserChannelService.getInstance(ws); const success = await userChannelService.connect(); console.log('Connected to user socket:', success); singleton = new WebSocketService(ws, userChannelService); resolve(singleton); }); ws.on('error', (error) => { console.log(error) reject(new Error('Failed to connect')); }) ws.on('close', _ => { console.log('Socket Closed'); }); }); } async connectToCall(callId: string) { return this.callService.connectToCall(callId); } async leaveCall() { this.callService.close(); } onSignalingMsg(message) { console.log(message); } }