All files websocket_adaptor.js

71.42% Statements 105/147
57.31% Branches 47/82
80.76% Functions 21/26
71.42% Lines 105/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357    1x                         63x           63x           63x           63x           63x           63x     63x 338x 338x       63x 62x     63x 55x   63x 23x 23x 23x           1x       1x             5x   4x 2x 2x     2x 2x         1x 1x 1x           60x 60x   60x   5x   5x   5x 1x       5x   5x   3x 2x 2x   1x       2x   2x     3x 3x 3x           55x 55x 55x                             57x 57x 57x                   57x 57x 55x 55x     57x 57x                                       57x 2x   2x               2x                 2x             2x             2x   2x   2x   2x   2x   2x   2x     2x   2x 2x       2x   2x   1x                   1x   1x             2x             57x 15x 15x 15x   15x 15x     57x 15x 15x 15x     15x 15x           87x 55x     55x 55x                       1x               8x             7x 7x 2x         5x         5x       1x      
import "./external/loglevel.min.js";
 
const Logger = window.log;
 
export class WebSocketAdaptor {
    /**
     * 
     * @param {object} initialValues 
     */
    constructor(initialValues) {
		
		
		/**
		 * Websocket URL
		 */
		this.websocketURL = null;
		
		/**
		 * HTTP Endpoint URL is the endpoint that returns the websocket URL
 
		 */
		this.httpEndpointUrl = null;
		
		
		/**
		 * HTTP Endpoint URL for access token
		 */
		this.httpEndpointAccessToken = null;
		
		
		/**
		 * WebRTCAdaptor which is responsible for handling WebRTC connections
		 */
		this.webrtcadaptor = null; 
				
		
        /**
         * @type {boolean}
         */
        this.debug = false;
		
		
		/**
		 * Init the connectin when constructor is called
		 */
		this.initConnection = true;
		
		
        for (var key in initialValues) {
            Eif (initialValues.hasOwnProperty(key)) {
                this[key] = initialValues[key];
            }
        }
		
		if (this.websocketURL == null) {
			this.websocketURL = this.websocket_url;
		}
 
		if (this.initConnection == true) {
        	this.checkBackendReady();
		}
		addEventListener("offline", (event) => { 
			this.connected = false;
			this.connecting = false;
			Logger.info("Network status has changed to offline. Resetting flags to reconnect faster");
		});
 
    }
	
	getHttpEndpoint(endpointUrl, options) {
		return fetch(endpointUrl,   options)
	}
	
	tryAgainAfterDelay(callbackConnected) {
		setTimeout(()=> {
			this.checkBackendReady(callbackConnected)
		}, 3000);
	}
	
	async checkBackendInstanceUp(data, callbackConnected) 
	{
		return this.getHttpEndpoint(data.http_url, { method: 'HEAD' })
		  .then(response => {
				if (response.status >= 200 && response.status < 400) {
					this.websocketURL = data.websocket_url;
					this.initWebSocketConnection(callbackConnected);
				}
				else {
					Logger.warn('Backend does not return ok. Retrying in 3 seconds...');
					this.tryAgainAfterDelay(callbackConnected);
				}
			
			})
			.catch((e) => {
				Logger.warn('Backend is not ready yet. Retrying in 3 seconds...');
				Logger.error(e);
				this.tryAgainAfterDelay(callbackConnected);
		    });
	}
	
	async checkBackendReady(callbackConnected) {
		
		this.connecting = true;
		this.connected = false;
		
		if (this.httpEndpointUrl != null) {
					
			const endpointUrl = new URL(this.httpEndpointUrl);
			
			endpointUrl.searchParams.set('source', 'sdk');
			
			if (this.httpEndpointAccessToken != null) {
				endpointUrl.searchParams.set('accessToken', this.httpEndpointAccessToken);
			}
			
			
			this.httpEndpointUrl = endpointUrl.toString();
			//return promise for this case
			return this.getHttpEndpoint(this.httpEndpointUrl,  { method: "GET" })
		      .then(response => {
                  if (response.ok) {
                      Logger.info("http endpoint returns ok")
					  return response.json(); // Parse JSON from body
                  }
				  throw new Error('Network response was not ok');
		                  
              })
			  .then(data => {
			          Logger.info("Response body -> fqdn :" + data.fqdn + "	websocket_url: " + data.websocket_url + " http_url: " + data.http_url); 
					  
					  return this.checkBackendInstanceUp(data, callbackConnected)
			      })
              .catch(e => {
			  	this.tryAgainAfterDelay(callbackConnected);
                Logger.warn('HttpEndpoint is not ready yet', e);
				Logger.error(e);
				  
              });
					  
		}
		else {
			return new Promise((resolve, reject) => {
				this.initWebSocketConnection(callbackConnected);
				resolve();
			});
				
			
		}
		
	}
	
	
    /**
     * Initializes the WebSocket connection.
     * @param {Function} callbackConnected - Optional callback function to be called when the connection is established.
     * @returns {void}
     */
    initWebSocketConnection(callbackConnected) {
        this.connecting = true;
        this.connected = false;
        this.clearPingTimer();
		
		
				
 
        /*
        * It's not mandatory if you don't use the new Load Balancer mechanism
        * It uses one of the nodes on Cluster mode
        * Example parameters: "origin" or "edge"
        */
        const url = new URL(this.websocketURL);
        if (!['origin', 'edge'].includes(url.searchParams.get('target'))) {
            url.searchParams.set('target', this.webrtcadaptor.isPlayMode ? 'edge' : 'origin');
            this.websocketURL = url.toString();
        }
 
        this.wsConn = new WebSocket(this.websocketURL);
        this.wsConn.onopen = () => {
            Logger.debug("websocket connected");
            
 
            this.pingTimerId = setInterval(() => {
                this.sendPing();
            }, 3000);
 
            this.connected = true;
            this.connecting = false;
            this.callback("initialized");
            
            // Request ICE server configuration from server if user hasn't provided any
            this.webrtcadaptor.getIceServerConfiguration();
 
            if (typeof callbackConnected != "undefined") {
                callbackConnected();
            }
        }
 
        this.wsConn.onmessage = (event) => {
            var obj = JSON.parse(event.data);
 
            Iif (obj.command == "start") {
                //this command is received first, when publishing so playmode is false
 
                if (this.debug) {
                    Logger.debug("received start command");
                }
 
                this.webrtcadaptor.startPublishing(obj.streamId);
            } else Iif (obj.command == "takeCandidate") {
 
                if (this.debug) {
                    Logger.debug("received ice candidate for stream id " + obj.streamId);
                    Logger.debug(obj.candidate);
                }
 
                this.webrtcadaptor.takeCandidate(obj.streamId, obj.label, obj.candidate);
 
            } else Iif (obj.command == "takeConfiguration") {
 
                if (this.debug) {
                    Logger.debug("received remote description type for stream id: " + obj.streamId + " type: " + obj.type);
                }
                this.webrtcadaptor.takeConfiguration(obj.streamId, obj.sdp, obj.type, obj.idMapping);
 
            } else Iif (obj.command == "stop") {
                if (this.debug) {
                    Logger.debug("Stop command received");
                }
                //server sends stop command when the peers are connected to each other in peer-to-peer.
                //It is not being sent in publish,play modes
                this.webrtcadaptor.closePeerConnection(obj.streamId);
            } else Iif (obj.command == "error") {
                this.callbackError(obj.definition, obj);
            } else Iif (obj.command == "notification") {
                this.callback(obj.definition, obj);
            } else Iif (obj.command == "streamInformation") {
                this.callback(obj.command, obj);
            } else Iif (obj.command == "roomInformation") {
                this.callback(obj.command, obj);
            } else Iif (obj.command == "pong") {
                this.callback(obj.command);
            } else Iif (obj.command == "trackList") {
                this.callback(obj.command, obj);
            } else Iif (obj.command == "connectWithNewId") {
                this.multiPeerStreamId = obj.streamId;
                this.join(obj.streamId);
            } else Iif (obj.command == "peerMessageCommand") {
                this.callback(obj.command, obj);
            } else Eif (obj.command == "iceServerConfig") {
                Iif (this.debug) {
                    Logger.debug("received ice server config");
                }
 
                Eif (obj.stunServerUri) {
                    // Construct the iceServers configuration based on URI type
                    if (obj.stunServerUri.startsWith("turn:")) {
                        // For TURN server
                        this.webrtcadaptor.peerconnection_config.iceServers = [
                            {
                                'urls': 'stun:stun1.l.google.com:19302'
                            },
                            {
                                'urls': obj.stunServerUri,
                                'username': obj.turnServerUsername || "",
                                'credential': obj.turnServerCredential || ""
                            }
                        ];
                    } else Eif (obj.stunServerUri.startsWith("stun:")) {
                        // For STUN server
                        this.webrtcadaptor.peerconnection_config.iceServers = [
                            {
                                'urls': obj.stunServerUri
                            }
                        ];
                    }
                    
                    Iif (this.debug) {
                        Logger.debug("ice servers updated: " + JSON.stringify(this.webrtcadaptor.peerconnection_config.iceServers));
                    }
                }
            }
        }
 
        this.wsConn.onerror = (error) => {
            this.connecting = false;
            this.connected = false;
            Logger.info(" error occured: " + JSON.stringify(error));
 
            this.clearPingTimer();
            this.callbackError("WebSocketNotConnected", error)
        }
 
        this.wsConn.onclose = (event) => {
            this.connecting = false;
            this.connected = false;
            Iif (this.debug) {
                Logger.debug("connection closed.");
            }
            this.clearPingTimer();
            this.callback("closed", event);
        }
 
    }
 
    clearPingTimer() {
        if (this.pingTimerId != -1) {
            Iif (this.debug) {
                Logger.debug("Clearing ping message timer");
            }
            clearInterval(this.pingTimerId);
            this.pingTimerId = -1;
        }
    }
 
    sendPing() {
        var jsCmd = {
            command: "ping"
        };
        this.wsConn.send(JSON.stringify(jsCmd));
    }
 
    close() {
        this.wsConn.close();
    }
    /**
     * 
     * @param {*} text 
     * @returns 
     */
    send(text) {
        Iif (this.connecting == false && this.connected == false) {
            //try to reconnect
            this.checkBackendReady(() => {
                this.send(text);
            });
            return;
        }
        try {
            this.wsConn.send(text);
            Iif (this.debug) {
                Logger.debug("sent message:" + text);
            }
        }
        catch (error) {
            Logger.warn("Make sure you call methods after you receive initialized callback. Cannot send message:" + text + " Error is " + error);
        }
    }
 
    isConnected() {
        return this.connected;
    }
 
    isConnecting() {
        return this.connecting;
    }
}