Best JavaScript code snippet using playwright-internal
server.js
Source:server.js
1/*2 * (C) Copyright 2014-2015 Kurento (http://kurento.org/)3 *4 * All rights reserved. This program and the accompanying materials5 * are made available under the terms of the GNU Lesser General Public License6 * (LGPL) version 2.1 which accompanies this distribution, and is available at7 * http://www.gnu.org/licenses/lgpl-2.1.html8 *9 * This library is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU12 * Lesser General Public License for more details.13 *14 */15var path = require('path');16var url = require('url');17var cookieParser = require('cookie-parser');18var express = require('express');19var session = require('express-session')20var minimist = require('minimist');21var ws = require('ws');22var kurento = require('kurento-client');23var fs = require('fs');24var https = require('https');25process.env.NODE_TLS_REJECT_UNAUTHORIZED=0;26var argv = minimist(process.argv.slice(2), {27 default: {28 as_uri: 'https://localhost:8443/', // Kurento Application IP29 ws_uri: 'ws://localhost:8888/kurento' // Kurento Server IP30 }31});32var options =33{34 key: fs.readFileSync('keys/server.key'),35 cert: fs.readFileSync('keys/server.crt')36};37var app = express();38/*39 * Management of sessions40 */41app.use(cookieParser());42var sessionHandler = session({43 secret : 'none',44 rolling : true,45 resave : true,46 saveUninitialized : true47});48const kilo = 1024;49const BIT_RATE = 320; //kbps50app.use(sessionHandler);51/*52 * Definition of global variables.53 */54var sessions = {};55var candidatesQueue = {};56var kurentoClient = null;57var compositeHub = null;58var mediaPipeline = null;59/*60 * Server startup61 */62var asUrl = url.parse(argv.as_uri);63var port = asUrl.port;64var server = https.createServer(options, app).listen(port, function() {65 console.log('Kurento Tutorial started');66 console.log('Open ' + url.format(asUrl) + ' with a WebRTC capable browser');67});68var wss = new ws.Server({69 server : server,70 path : '/kurentomcu'71});72/*73 * Management of WebSocket messages74 */75wss.on('connection', function(ws, req) {76 var sessionId = null;77 var websocketId = null; // differ tabs78 var request = req;79 var response = {80 writeHead : {}81 };82 sessionHandler(request, response, function(err) {83 sessionId = request.session.id;84 console.log('Connection received with sessionId ' + sessionId);85 var websocketId = request.headers['sec-websocket-key'];86 });87 ws.on('error', function(error) {88 console.log('Connection ' + sessionId + ' error');89 stop(sessionId, websocketId);90 });91 ws.on('close', function() {92 console.log('Connection ' + sessionId + ' , ' + websocketId + ' closed');93 stop(sessionId, websocketId);94 });95 ws.on('message', function(_message) {96 var message = JSON.parse(_message);97 //console.log('Connection ' + sessionId + ' received message ', message);98 switch (message.id) {99 case 'start':100 sessionId = request.session.id;101 websocketId = request.headers['sec-websocket-key'];102 start(sessionId, websocketId, ws, message.sdpOffer, function(error, sdpAnswer) {103 if (error) {104 return ws.send(JSON.stringify({105 id : 'error',106 message : error107 }));108 }109 ws.send(JSON.stringify({110 id : 'startResponse',111 sdpAnswer : sdpAnswer112 }));113 });114 break;115 case 'stop':116 stop(sessionId, websocketId);117 break;118 case 'onIceCandidate':119 onIceCandidate(sessionId, websocketId, message.candidate);120 break;121 default:122 ws.send(JSON.stringify({123 id : 'error',124 message : 'Invalid message ' + message125 }));126 break;127 }128 });129});130/*131 * Definition of functions132 */133// Recover kurentoClient for the first time.134function getKurentoClient(callback) {135 if (kurentoClient !== null) {136 return callback(null, kurentoClient);137 }138 kurento(argv.ws_uri, function(error, _kurentoClient) {139 if (error) {140 console.log("Could not find media server at address " + argv.ws_uri);141 return callback("Could not find media server at address" + argv.ws_uri142 + ". Exiting with error " + error);143 }144 kurentoClient = _kurentoClient;145 callback(null, kurentoClient);146 });147}148function getMediaPipeline(callback) {149 if (mediaPipeline) {150 return callback(null, mediaPipeline);151 } else {152 kurentoClient.create('MediaPipeline', function(error, pipeline) {153 if (error) {154 return callback(error);155 }156 console.log('Creating MediaPipeline and Composite...');157 pipeline.listeners = 0;158 mediaPipeline = pipeline;159 return callback(null,pipeline);160 });161 }162}163function start(sessionId, websocketId, ws, sdpOffer, callback) {164 if (!sessionId || !websocketId) {165 return callback('Cannot use undefined sessionId/websocketId');166 }167 console.log('Adding user to MCU [ ' + sessionId + ', ' + websocketId + ' ]');168 getKurentoClient(function(error, kurentoClient) {169 if (error) {170 return callback(error);171 }172 getMediaPipeline( function(error, pipeline) {173 if (error) {174 return callback(error);175 }176 pipeline.listeners++;177 createMediaElements(pipeline, ws, function(error, webRtcEndpoint,178 hubPort) {179 if (error) {180 pipeline.release();181 return callback(error);182 }183 if (candidatesQueue[sessionId][websocketId]) {184 while(candidatesQueue[sessionId][websocketId].length) {185 var candidate = candidatesQueue[sessionId][websocketId].shift();186 webRtcEndpoint.addIceCandidate(candidate);187 }188 }189 connectMediaElements(webRtcEndpoint, hubPort,190 function(error) {191 if (error) {192 pipeline.release();193 return callback(error);194 }195 webRtcEndpoint.on('OnIceCandidate', function(event) {196 var candidate = kurento.register.complexTypes.IceCandidate(event.candidate);197 ws.send(JSON.stringify({198 id : 'iceCandidate',199 candidate : candidate200 }));201 ws.send(JSON.stringify({202 id : 'iceCandidate',203 candidate : candidate204 }));205 });206 webRtcEndpoint.processOffer(sdpOffer, function(error, sdpAnswer) {207 if (error) {208 pipeline.release();209 return callback(error);210 }211 if (!sessions[sessionId]) {212 sessions[sessionId] = {};213 }214 sessions[sessionId][websocketId] = {215 'pipeline' : pipeline,216 'webRtcEndpoint' : webRtcEndpoint,217 'hubPort' : hubPort218 }219 return callback(null, sdpAnswer);220 });221 webRtcEndpoint.gatherCandidates(function(error) {222 if (error) {223 return callback(error);224 }225 });226 });227 });228 });229 });230}231function createMediaElements(pipeline, ws, callback) {232 pipeline.create('WebRtcEndpoint', function(error, webRtcEndpoint) {233 if (error) {234 return callback(error);235 }236 var maxbps = Math.floor( BIT_RATE * kilo);237 webRtcEndpoint.setMinOutputBitrate(maxbps, function (error) {238 //console.log('[media] Min Output Bitrate (bps) ' + maxbps);239 if (error) {240 console.log('[media] Error: ' + error);241 }242 webRtcEndpoint.setMaxOutputBitrate(maxbps, function (error) {243 //console.log('[media] Min Output Bitrate (bps) ' + maxbps);244 if (error) {245 console.log('[media] Error: ' + error);246 }247 if (compositeHub) {248 compositeHub.createHubPort(function(error, hubPort){249 if (error){250 return callback(error);251 }252 hubPort.setMinOutputBitrate(maxbps, function (error) {253 hubPort.setMaxOutputBitrate(maxbps, function (error){254 return callback(null, webRtcEndpoint, hubPort);255 });256 });257 });258 }259 else260 {261 pipeline.create('Composite', function (error, composite) {262 if (error) {263 return callback(error);264 }265 compositeHub = composite;266 if (!compositeHub.outputVideoPort) {267 compositeHub.createHubPort(function(error, _outputVideoPort){268 if (error){269 return callback(error);270 }271 compositeHub.outputVideoPort = _outputVideoPort;272 _outputVideoPort.setMinOutputBitrate(maxbps, function (error) {273 _outputVideoPort.setMaxOutputBitrate(maxbps, function (error){274 composite.createHubPort(function(error, hubPort){275 if (error){276 return callback(error);277 }278 hubPort.setMinOutputBitrate(maxbps, function (error) {279 hubPort.setMaxOutputBitrate(maxbps, function (error){280 return callback(null, webRtcEndpoint, hubPort);281 });282 });283 });284 });285 });286 });287 } else {288 composite.createHubPort(function(error, hubPort){289 if (error){290 return callback(error);291 }292 hubPort.setMinOutputBitrate(maxbps, function (error) {293 hubPort.setMaxOutputBitrate(maxbps, function (error){294 return callback(null, webRtcEndpoint, hubPort);295 });296 });297 });298 }299 });300 }301 });302 });303 });304}305function connectMediaElements(webRtcEndpoint, hubPort, callback) {306 webRtcEndpoint.connect(hubPort, function(error) {307 if (error) {308 return callback(error);309 }310 if (compositeHub && compositeHub.outputVideoPort) {311 compositeHub.outputVideoPort.connect(webRtcEndpoint, 'VIDEO', function (error){312 if (error) {313 return callback(error);314 }315 hubPort.connect(webRtcEndpoint, 'AUDIO', function (error){316 if (error) {317 return callback(error);318 }319 return callback(null);320 });321 });322 }323 });324}325function stop(sessionId, websocketId) {326 if (sessions[sessionId] && sessions[sessionId][websocketId]) {327 console.log('Removing user from MCU [ ' + sessionId + ', ' + websocketId + ' ]');328 // var pipeline = sessions[sessionId].pipeline;329 // console.info('Releasing pipeline');330 // pipeline.release();331 var hubPort = sessions[sessionId][websocketId].hubPort;332 var webRtcEndpoint = sessions[sessionId][websocketId].webRtcEndpoint;333 if (hubPort) {334 hubPort.release(function (error) {335 if (webRtcEndpoint) {336 webRtcEndpoint.release();337 }338 delete sessions[sessionId][websocketId];339 delete candidatesQueue[sessionId][websocketId];340 if (mediaPipeline) {341 mediaPipeline.listeners--;342 if (mediaPipeline.listeners < 1) {343 mediaPipeline.release();344 mediaPipeline = null;345 compositeHub = null;346 console.log('Removing MediaPipeline and Composite...');347 }348 }349 });350 }351 }352}353process.on('SIGINT', function (error, signal){354 console.log('Stopping application...');355 if (mediaPipeline) {356 console.log('Removing MediaPipeline and Composite...');357 mediaPipeline.release(function (error) {358 exit();359 });360 } else {361 exit();362 }363});364function exit() {365 console.log('Bye!');366 process.exit();367}368function onIceCandidate(sessionId, websocketId, _candidate) {369 var candidate = kurento.register.complexTypes.IceCandidate(_candidate);370 if (sessions[sessionId] && sessions[sessionId][websocketId]) {371 //console.info('Sending candidate');372 var webRtcEndpoint = sessions[sessionId][websocketId].webRtcEndpoint;373 webRtcEndpoint.addIceCandidate(candidate);374 }375 else {376 //console.info('Queueing candidate');377 if (!candidatesQueue[sessionId]) {378 candidatesQueue[sessionId] = {};379 candidatesQueue[sessionId][websocketId] = [];380 } else {381 if (!candidatesQueue[sessionId][websocketId]) {382 candidatesQueue[sessionId][websocketId] = [];383 }384 }385 candidatesQueue[sessionId][websocketId].push(candidate);386 }387}...
main.js
Source:main.js
1const WebSocket = require('ws');2const md5 = require('md5');3const port = 8000;4const { Expo } = require('expo-server-sdk');5const axios = require('axios');6wss = new WebSocket.Server({port: process.env.PORT || port},7console.log(`Running on port ${port}`));8let CLIENTS = [];9let ROADRUNNERS = [];10let ALLIES = [];11let ADMINS = [];12let PYTHON = [];13let IMAGE = "";14let CLIENTS_LISTENING = [];15let ROADRUNNERS_SPEAKING = [];16getKilometers = (lat1, lon1, lat2, lon2) => {17 rad = (x) => {return x * Math.PI/180;}18 var R = 6378.137; 19 var dLat = rad( lat2 - lat1 );20 var dLong = rad( lon2 - lon1 );21 var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 22 Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * 23 Math.sin(dLong/2) * Math.sin(dLong/2);24 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));25 var d = R * c;26 return d.toFixed(3);27}28SendPushNotificationCustomer = (pushToken, AllieName, Datas, Title, Body) => {29 let expo = new Expo();30 let messages = [];31 if (!Expo.isExpoPushToken(pushToken)) {32 console.error(`Push token ${pushToken} is not a valid Expo push token`);33 return;34 }35 messages.push({36 to: pushToken,37 sound: 'default',38 title: Title,39 body: Body,40 data: Datas41 });42 let chunks = expo.chunkPushNotifications(messages);43 let tickets = [];44 (async () => {45 for (let chunk of chunks) {46 try {47 let ticketChunk = await expo.sendPushNotificationsAsync(chunk);48 console.log(ticketChunk);49 tickets.push(...ticketChunk);50 } catch (error) {51 console.error(error);52 }53 }54 })();55}56SendPushNotificationRoadrunner = (pushToken, Datas) => {57 let expo = new Expo();58 let messages = [];59 if (!Expo.isExpoPushToken(pushToken)) {60 console.error(`Push token ${pushToken} is not a valid Expo push token`);61 return;62 }63 messages.push({64 to: pushToken,65 sound: 'default',66 title: '¡Hay un nuevo pedido cerca de tu ubicación!',67 body: `Para ver la infomación acerca del pedido toca aquà âï¸`,68 data: Datas69 });70 let chunks = expo.chunkPushNotifications(messages);71 let tickets = [];72 (async () => {73 for (let chunk of chunks) {74 try {75 let ticketChunk = await expo.sendPushNotificationsAsync(chunk);76 console.log(ticketChunk);77 tickets.push(...ticketChunk);78 } catch (error) {79 console.error(error);80 }81 }82 })();83}84SendDeliveryRequest = (ws) => {85 if (ws.hasOwnProperty('DataAttached')) {86 if (ws.DataAttached.hasOwnProperty('Delivery_Accepted') && ws.DataAttached.Delivery_Accepted === true) {87 const TokenC = ws.DataAttached.PushToken;88 const AllieName = ws.DataAttached.AllieName;89 console.log("Push delivery accepted sent!!!!!");90 let Title = '¡Tu orden ha sido recibida!';91 let Body = `En estos momentos un correcaminos se dirige a ${AllieName} para gestionar tu pedido... ð¥`;92 SendPushNotificationCustomer(TokenC, AllieName, ws.DataAttached, Title, Body);93 } else if (ws.DataAttached.hasOwnProperty('Delivery_Accepted') && ws.DataAttached.Delivery_Accepted === false) {94 if (ws.DataAttached.hasOwnProperty('CustomerLocation')) {95 if (ROADRUNNERS.length !== 0) {96 let C_lat = ws.DataAttached.CustomerLocation.Latitude;97 let C_lon = ws.DataAttached.CustomerLocation.Longitude;98 ROADRUNNERS.map(R => {99 let R_lat = R.DataAttached.RoadrunnerLocation.Latitude;100 let R_lon = R.DataAttached.RoadrunnerLocation.Longitude;101 let TokenR = R.DataAttached.PushToken;102 let kilometers = parseFloat(getKilometers(C_lat, C_lon, R_lat, R_lon));103 if (kilometers <= 2) {104 ws.DataAttached['RoadrunnerData'] = R.DataAttached;105 SendPushNotificationRoadrunner(TokenR, ws.DataAttached);106 }107 });108 }109 }110 }111 }112}113wss.on("connection", ws => {114 console.log(`There is a new client connected!`);115 ws.onmessage = (e) => {116 let res = JSON.parse(e.data);117 //console.log(res);118 if (res[0].hasOwnProperty('Type')) {119 switch (res[0].Type) {120 case "REQUEST_ORDER_CONFIRMATION":121 ws['WebsocketID'] = res[0].PushToken;122 ws['DataAttached'] = res[0];123 res[0]['OrderID'] = md5(res[0].PushToken);124 ws['Counts'] = 1;125 ws.DataAttached['Delivery_Accepted'] = false;126 ws.DataAttached['Order_Accepted'] = false;127 128 if (CLIENTS.length !== 0) {129 for (let s in CLIENTS) { 130 if (CLIENTS[s].WebsocketID !== res[0].PushToken) {131 CLIENTS.push(ws);132 }133 }134 } else if (CLIENTS.length === 0) { 135 CLIENTS.push(ws);136 }137 ALLIES.map(Allie => { if (Allie.AllieName === res[0].AllieName) { Allie.send(JSON.stringify(res[0])) } });138 break;139 case "REQUEST_ROADRUNNER":140 let Client = {};141 CLIENTS.map(item => {142 if (item.DataAttached.PushToken === res[0].PushToken) {143 Client = item;144 item.send(JSON.stringify([res[0]]));145 }146 });147 let Title = '¡Tu orden ha sido recibida!';148 let Body = `En estos momentos ${Client.DataAttached.AllieName} ha empezado a preparar tu orden, te notificaremos 149 cuando esté lista y un correcaminos vaya a retirarla! ð¥`;150 SendPushNotificationCustomer(Client.DataAttached.PushToken, res[0].AllieTable, res[0], Title, Body);151 setInterval(() => {152 if (ROADRUNNERS.length !== 0) {153 CLIENTS.map(client => {154 if (client.PushToken === res[0].PushToken && 155 client.DataAttached.Delivery_Accepted === false && client.Counts > 1) {156 let C_lat = client.DataAttached.CustomerLocation.Latitude;157 let C_lon = client.DataAttached.CustomerLocation.Longitude;158 if (ROADRUNNERS.length !== 0) {159 ROADRUNNERS.map(R => {160 console.log("Checking Mapping");161 let R_lat = R.DataAttached.RoadrunnerLocation.Latitude;162 let R_lon = R.DataAttached.RoadrunnerLocation.Longitude;163 let kilometers = parseFloat(getKilometers(C_lat, C_lon, R_lat, R_lon));164 if (kilometers <= 2) {165 client.DataAttached['RoadrunnerData'] = R.DataAttached;166 console.log("Checking Kilometers")167 SendPushNotificationRoadrunner(R.DataAttached.PushToken, client.DataAttached);168 console.log(`Kilometros: ${kilometers}Km`);169 }170 });171 } client.Counts += 1;172 } else {173 res['Delivery_Accepted'] = false;174 }175 });176 console.log("Nuevo While");177 }178 }, 180000);179 break;180 181 case "LOOKING_FOR_CLIENTS":182 ws['WebsocketID'] = res[0].PushToken;183 ws['DataAttached'] = res[0];184 if (ROADRUNNERS.length !== 0) {185 for (let s in ROADRUNNERS) { 186 if (ROADRUNNERS[s].WebsocketID !== res[0].PushToken) { 187 ROADRUNNERS.push(ws);188 }189 }190 } else if (ROADRUNNERS.length === 0) { 191 ROADRUNNERS.push(ws);192 }193 break;194 195 case "LOOKING_FOR_ORDERS":196 ws['WebsocketID'] = res[0].Token;197 ws['AllieName'] = res[0].AllieName;198 if (ALLIES.length !== 0) {199 for (let s in ALLIES) { 200 if (ALLIES[s].WebsocketID !== res[0].Token) {201 ALLIES.push(ws);202 }203 }204 } else if (ALLIES.length === 0) { 205 ALLIES.push(ws);206 } 207 break;208 209 case "DELIVERY_ACCEPTED":210 if (res[0].hasOwnProperty('Delivery_Accepted') && res[0].Delivery_Accepted === true) {211 CLIENTS.map(item => {212 if (item.DataAttached.PushToken === res[0].PushToken) {213 item.DataAttached.Delivery_Accepted = true;214 }215 });216 const TokenC = res[0].PushToken;217 const AllieName = res[0].AllieName;218 CLIENTS.map(Client => {219 console.log(Client.DataAttached.CustomerData.CustomerOrderID + "=" + res[0].CustomerData.CustomerOrderID);220 if (Client.DataAttached.CustomerData.CustomerOrderID === res[0].CustomerData.CustomerOrderID) {221 OrderAcc = Client.DataAttached.CustomerData.CustomerOrderID;222 ALLIES.map(allie => {223 if (allie.WebsocketID + "=" + res[0].AllieWebsocketID) {224 allie.send(JSON.stringify(res[0]));225 let Title = '¡Tu orden ha sido recibida!';226 let Body = `En estos momentos un correcaminos se dirige a ${AllieName} para gestionar tu pedido... ð¥`;227 SendPushNotificationCustomer(TokenC, AllieName, res[0], Title, Body);228 }229 });230 }231 });232 }233 break;234 235 case "LISTEN_ORDER_STATUS":236 if (CLIENTS_LISTENING.length !== 0) {237 let Client = CLIENTS_LISTENING.find(element => element.FinalOrder.OrderID !== res[0].OrderID);238 if (Client !== undefined) { 239 CLIENTS_LISTENING.push(ws);240 obj = {Type: 'PREPARING_ORDER', OrderID: res[0].OrderID}241 ws.send(JSON.stringify(obj));242 let NewArr = CLIENTS.filter(client => client.DataAttached.CustomerData.CustomerOrderID === res[0].OrderID);243 }244 } else {245 ws['FinalOrder'] = res[0];246 CLIENTS_LISTENING.push(ws);247 obj = {Type: 'PREPARING_ORDER', OrderID: res[0].OrderID}248 ws.send(JSON.stringify(obj));249 let NewArr = CLIENTS.filter(client => client.DataAttached.CustomerData.CustomerOrderID === res[0].OrderID);250 }251 break;252 253 case "SEND_STATUS_FOR_CLIENT":254 ROADRUNNERS_SPEAKING.push(res[0]);255 break;256 case "LOOK_FOR_EXTERNAL_DELIVERY":257 let order = res[0].order;258 259 break;260 261 default:262 ws.send(JSON.stringify({ Response: "No appropriate 'Case' found" }));263 }264 } else {265 ws.send(JSON.stringify({ Access: false, Reason: "There's no 'Type' Property" }));266 }267 console.log("Clientes:", CLIENTS.length);268 console.log("Correcaminos:", ROADRUNNERS.length);269 console.log("Aliados:", ALLIES.length);270 setTimeout(() => {271 SendDeliveryRequest(ws);272 }, 3000);273 };274 ws.on("close", (code) => {275 console.log("There was a close")276 console.log("There was an Automatic Close:", code)277 ws.send(JSON.stringify({CloseCode: code}));278 CLIENTS.map(item => {279 if (item === ws) { CLIENTS.splice(CLIENTS.indexOf(ws), 1) }280 });281 ALLIES.map(item => {282 if (item === ws) { ALLIES.splice(ALLIES.indexOf(ws), 1) }283 });284 ROADRUNNERS.map(item => {285 if (item === ws) { ROADRUNNERS.splice(ROADRUNNERS.indexOf(ws), 1) }286 });287 console.log("Clientes:", CLIENTS.length);288 console.log("Correcaminos:", ROADRUNNERS.length);289 console.log("Aliados:", ALLIES.length);290 });291 ws.on("error", () => {292 CLIENTS.map(item => {293 if (item === ws) { CLIENTS.splice(CLIENTS.indexOf(ws), 1) }294 });295 ALLIES.map(item => {296 if (item === ws) { ALLIES.splice(ALLIES.indexOf(ws), 1) }297 });298 ROADRUNNERS.map(item => {299 if (item === ws) { ROADRUNNERS.splice(ROADRUNNERS.indexOf(ws), 1) }300 });301 console.log("Clientes:", CLIENTS.length);302 console.log("Correcaminos:", ROADRUNNERS.length);303 console.log("Aliados:", ALLIES.length);304 });...
WebSocketPool.js
Source:WebSocketPool.js
1import { eventChannel, delay } from 'redux-saga';2import uuidv4 from 'uuid/v4';3import { call, fork } from 'redux-saga/effects';4import { has } from '../../utils/utils';5export const SOCKET_CLOSED = 3;6export const SOCKET_CLOSING = 2;7export const SOCKET_OPEN = 1;8const KEEP_ALIVE_TIME_INTERVAL = 29000;9const MAX_NUMBEROF_SOCKETS = 10;10class WebSocketItem {11 constructor(socket, socketChannel, webSocketId, requests) {12 this.socket = socket;13 this.socketChannel = socketChannel;14 this.webSocketId = webSocketId;15 this.requests = requests;16 }17}18class WebSocketQueue {19 constructor() {20 this.items = [];21 }22 /*23 * enqueue function to add element24 * to the queue as per priority25 */26 enqueue = (webSocketItem) => {27 let contain = false;28 /*29 * find index through to add element at the30 * correct location of the Queue31 * so that queue is in ascending sort order32 * of number of requests33 */34 const index = this.items.findIndex(item =>35 item.requests.length > webSocketItem.requests.length);36 if (index > -1) {37 this.items.splice(index, 0, webSocketItem);38 contain = true;39 }40 /*41 * if the element have the highest number of requests42 * it is added at the end of the queue43 */44 if (!contain) {45 this.items.push(webSocketItem);46 }47 }48 // dequeue function49 dequeue = () => {50 /*51 * removing element from the queue52 * returns underflow when called53 * on empty queue54 */55 if (this.isEmpty()) { return 'Underflow'; }56 return this.items.shift();57 }58 // front function59 front = () => {60 /*61 * returns the Front element of62 * the queue without removing it.63 */64 if (this.isEmpty()) { return 'No elements in Queue'; }65 return this.items[0];66 }67 removeItem = (requestId) => {68 let webSocketItem = null;69 const webSocketItemIndex = this.items.findIndex(item => item.requests.includes(requestId));70 if (webSocketItemIndex > -1) {71 webSocketItem = this.items[webSocketItemIndex];72 this.items.splice(webSocketItemIndex, 1);73 }74 return webSocketItem;75 }76 // isEmpty function77 isEmpty = () =>78 // return true if the queue is empty.79 this.items.length === 080 // size function81 size = () =>82 // return the length of items.83 this.items.length84 // rear function85 rear = () => {86 /*87 * returns the lowest priorty88 * element of the queue89 */90 if (this.isEmpty()) { return 'No elements in Queue'; }91 return this.items[this.items.length - 1];92 }93 clear = () => {94 this.items.splice(0, this.items.length);95 }96 // printQueue function97 printQueue = () => {98 let str = '';99 this.items.forEach((item) => { str += `WebSocket: ${item.webSocketId} with requests: ${item.requests}\n`; });100 return str;101 }102 createWebSocketAsPromised = (isBroadCast = false) => {103 if (this.items.length >= MAX_NUMBEROF_SOCKETS) {104 return Promise.reject(new Error('Maximum limit for WebSockets reached.'));105 }106 return new Promise(((resolve, reject) => {107 const clarityURI = `${window.location.host}`;108 const webSocketId = `${uuidv4()}`;109 const socket = new WebSocket(110 `wss://${clarityURI}/ws/clarity?websocketId=${webSocketId}`,111 );112 // First eventChannel param is a subscribe function113 const socketChannel = eventChannel((emitter) => {114 const listener = (event) => {115 if (event.data) {116 emitter(JSON.parse(event.data));117 }118 };119 socket.onmessage = listener;120 socket.onerror = listener;121 const unsubscribe = () => {122 socket.close();123 };124 return unsubscribe;125 });126 const socketObj = new WebSocketItem(socket, socketChannel, webSocketId, []);127 socket.onopen = function () {128 console.log(`Socket for --> pool and socketId --> ${webSocketId}`);129 setInterval(() => {130 if (socket.readyState === SOCKET_OPEN) {131 socket.send('Keep alive');132 }133 }, KEEP_ALIVE_TIME_INTERVAL);134 resolve(socketObj);135 };136 socket.onerror = function (error) {137 console.error('WebSocketPoolError: socket connection error : ', error);138 reject(error);139 };140 }));141 }142}143export class WebSocketPool {144 constructor() {145 this.webSocketQueue = new WebSocketQueue();146 this.broadcastSocket = null;147 }148 // createWebSocket creates and returns the websocket149 createWebSocket = (isBroadCast = false) =>150 this.webSocketQueue.createWebSocketAsPromised(isBroadCast)151 .then(socketObj => socketObj)152 .catch(error => ({ error: `WebSocketPoolError:${error}` }));153 // getWebSocket (requestId) returns the next available websocket154 getWebSocket = (requestId, fName) => {155 try {156 const {157 socket, socketChannel, webSocketId, requests,158 } = this.webSocketQueue.dequeue();159 this.webSocketQueue.enqueue({160 socket, socketChannel, webSocketId, requests: [requestId, ...requests],161 });162 console.log(`WebSocketPool: allocated request: ${requestId} for ${fName} to webSocket = ${webSocketId} at: ${new Date()}`);163 console.log(`WebSocketPool - printqueue \n: ${this.webSocketQueue.printQueue()}`);164 return {165 socket, socketChannel, webSocketId, requests,166 };167 } catch (err) {168 console.log(`WebSocketPoolError:${err}`);169 return { webSocketId: null };170 }171 }172 // removeRequestsFromWebSocket (requestId)173 removeRequestsFromWebSocket = (requestId) => {174 try {175 const webSocketItem = this.webSocketQueue.removeItem(requestId);176 if (webSocketItem != null) {177 const {178 socket, socketChannel, webSocketId, requests,179 } = webSocketItem;180 // remove the request from webSocket requests and enqueue it back in the queue181 const index = requests.indexOf(requestId);182 if (index > -1) {183 requests.splice(index, 1);184 }185 this.webSocketQueue.enqueue({186 socket, socketChannel, webSocketId, requests,187 });188 console.log(`WebSocketPool: removed request: ${requestId} from webSocket = ${webSocketId} at: ${new Date()}`);189 console.log(`WebSocketPool - after removing printqueue\n: ${this.webSocketQueue.printQueue()}`);190 } else {191 console.log(`WebSocketPoolError: The requestId is already deleted from webSocket requests ${requestId}`);192 }193 } catch (err) {194 console.log(`WebSocketPoolError:${err}`);195 }196 }197 // closeWebSocket (webSocket)198 clearWebSocketPool = () => {199 // close each websocket first200 this.webSocketQueue.items.forEach((webSocketItem) => {201 if (webSocketItem.socket.readyState !== SOCKET_CLOSED ||202 webSocketItem.socket.readyState !== SOCKET_CLOSING) {203 console.log(`Closing socket for - ${webSocketItem.webSocketId}`);204 webSocketItem.socket.close();205 }206 });207 // clear the items from queue208 this.webSocketQueue.clear();209 }210}211export const BusinessWebSocketPool = new WebSocketPool();212export function* createWebSocketPool(fnwatchWebSocketPoolMessages) {213 if (BusinessWebSocketPool.webSocketQueue.size() < MAX_NUMBEROF_SOCKETS) {214 for (let i = 0; i < MAX_NUMBEROF_SOCKETS; i += 1) {215 if (i % 3 === 0) {216 /**217 * add delay of 2 seconds after every 3 websockets218 * so other requests pending in the queue219 */220 yield delay(2000);221 }222 const timeStart = new Date();223 const socketItem = yield call(BusinessWebSocketPool.createWebSocket);224 if (has(socketItem, 'WebSocketPoolError') || socketItem === undefined) {225 throw Error(socketItem);226 }227 console.log(socketItem);228 BusinessWebSocketPool.webSocketQueue.enqueue(socketItem);229 const { socketChannel } = socketItem;230 const timeEnd = new Date();231 console.log(`Time taken for socket creation for ${i} - ${timeEnd.getTime() - timeStart.getTime()}ms`);232 yield fork(fnwatchWebSocketPoolMessages, socketChannel);233 }234 }235 console.log(`WebSocketPool - printqueue\n:${BusinessWebSocketPool.webSocketQueue.printQueue()}`);...
userServiceTest.js
Source:userServiceTest.js
1var cache = require.cache;2for (var moduleId in cache) {3 delete cache[moduleId];4}5var chai = require('chai');6var spies = require('chai-spies');7chai.use(spies);8var expect = chai.expect;9var should = chai.should();10var sinon = require("sinon");11var UserCommunicationService = require('./../../services/userCommunicationService.js');12var UserRepository = require('./../../repository/userRepository.js');13var UserService = require('./../../services/userService.js');14var userCommunicationServiceStub;15var userRepositoryStub;16var experienceInformation;17var webSocketId;18var token;19var items;20before(function(done){21 webSocketId = 2;22 token = "TOKEN";23 experienceInformation = {24 experiencePerLevel : [100,200,300],25 upgradePointsPerLevel : [1,2,3],26 maximumLevel : 227 };28 items = "ITEM";29 done();30});31describe("userService", function ()32{33 beforeEach(function(done)34 {35 userCommunicationServiceStub = sinon.createStubInstance(UserCommunicationService);36 userRepositoryStub = sinon.createStubInstance(UserRepository);37 done();38 });39 describe("setExperienceInformation", function()40 {41 it("should setExperienceInformation", function()42 {43 //Arrange44 var nextLevel = 1;45 var userService = new UserService(userRepositoryStub, userCommunicationServiceStub);46 var expectedResult = { nextLevelXp: experienceInformation.experiencePerLevel[nextLevel], pointForNextLevel: experienceInformation.upgradePointsPerLevel[nextLevel] };47 //Act48 userService.setExperienceInformation(experienceInformation.experiencePerLevel, experienceInformation.upgradePointsPerLevel, experienceInformation.maximumLevel);49 var result = userService.getInformationNextLevel(nextLevel);50 //Assert51 expect(JSON.stringify(expectedResult)).to.equal(JSON.stringify(result));52 });53 });54 describe("addUserItems", function()55 {56 it("should call userRepository addUserItems", function()57 {58 //Arrange59 var userService = new UserService(userRepositoryStub, userCommunicationServiceStub);60 var userSpy = chai.spy.on(userRepositoryStub, 'addUserItems');61 userService.addUserWebSocket(webSocketId, token);62 //Act63 userService.addUserItems(webSocketId, items);64 //Assert65 expect(userSpy).to.have.been.called.with(token, items);66 expect(userSpy).to.have.been.called.exactly(1);67 });68 });69 describe("updateUserItems", function()70 {71 it("should call userRepository updateUserItems", function()72 {73 //Arrange74 var userService = new UserService(userRepositoryStub, userCommunicationServiceStub);75 var userSpy = chai.spy.on(userRepositoryStub, 'updateUserItems');76 userService.addUserWebSocket(webSocketId, token);77 //Act78 userService.updateUserItems(webSocketId, items);79 //Assert80 expect(userSpy).to.have.been.called.with(token, items);81 expect(userSpy).to.have.been.called.exactly(1);82 });83 });84 describe("levelUpUser", function()85 {86 it("should call userRepository levelUpUser", function()87 {88 //Arrange89 var parameters = {a:1, b:2};90 var levelUpInformation = {c:4, d:5};91 var userService = new UserService(userRepositoryStub, userCommunicationServiceStub);92 var userSpy = chai.spy.on(userRepositoryStub, 'levelUpUser');93 userService.addUserWebSocket(webSocketId, token);94 //Act95 userService.levelUpUser(webSocketId, parameters, levelUpInformation);96 //Assert97 expect(userSpy).to.have.been.called.with(token, parameters, levelUpInformation);98 expect(userSpy).to.have.been.called.exactly(1);99 });100 });101 describe("updateUserExperience", function()102 {103 it("should call userRepository updateUserExperience", function()104 {105 //Arrange106 var experiencePoint = 100;107 var userService = new UserService(userRepositoryStub, userCommunicationServiceStub);108 var userSpy = chai.spy.on(userRepositoryStub, 'updateUserExperience');109 userService.addUserWebSocket(webSocketId, token);110 //Act111 userService.updateUserExperience(webSocketId, experiencePoint);112 //Assert113 expect(userSpy).to.have.been.called.with(token, experiencePoint);114 expect(userSpy).to.have.been.called.exactly(1);115 });116 });...
CordovaWebsocketPlugin.js
Source:CordovaWebsocketPlugin.js
1const WS_ABNORMAL_CODE = 1006;2const connections = {};3const createId = function() {4 return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);5};6const wsAddListeners = function(webSocketId, success, error) {7 const webSocket = connections[webSocketId];8 webSocket.onmessage = function(event) {9 success({10 webSocketId: webSocketId,11 message: event.data,12 callbackMethod: "onMessage"13 });14 };15 webSocket.onclose = function(event) {16 error({17 webSocketId: webSocketId,18 code: event.code,19 reason: event.reason,20 callbackMethod: "onClose"21 });22 wsRemoveListeners(webSocketId);23 };24};25const wsRemoveListeners = function(webSocketId) {26 const webSocket = connections[webSocketId];27 webSocket.onmessage = undefined;28 webSocket.onclose = undefined29 connections[webSocketId] = undefined;30};31const CordovaWebsocketPlugin = {32 wsConnect: function(wsOptions, listener, success, error) {33 const webSocketId = createId();34 const webSocket = new WebSocket(wsOptions.url);35 let timeoutHandler;36 if (wsOptions.timeout && wsOptions.timeout > 0) {37 timeoutHandler = setTimeout(function() {38 webSocket.close();39 }, wsOptions.timeout);40 }41 webSocket.onopen = function() {42 if (timeoutHandler) {43 clearTimeout(timeoutHandler);44 }45 connections[webSocketId] = webSocket;46 wsAddListeners(webSocketId, listener, listener);47 success({ webSocketId: webSocketId, code: 0 });48 };49 webSocket.onerror = function() {50 error({51 webSocketId: webSocketId,52 code: WS_ABNORMAL_CODE,53 reason: "Error connecting to " + wsOptions.url,54 callbackMethod: "onFail"55 });56 }57 },58 wsSend: function(webSocketId, message) {59 const webSocket = connections[webSocketId];60 if (webSocket) {61 webSocket.send(message);62 }63 },64 wsClose: function(webSocketId, code, reason) {65 const webSocket = connections[webSocketId];66 if (webSocket) {67 webSocket.close(code, reason);68 wsRemoveListeners(webSocketId);69 }70 }71};...
userService.js
Source:userService.js
1//Constructor2function UserService(userRepository, userCommunicationService)3{4 this.userWebSockets = {};5 this.userRepository = userRepository;6 this.userCommunicationService = userCommunicationService;7 this.experiencePerLevel = [];8 this.upgradePointsPerLevel = [];9 this.maximumLevel = 0;10}11//Public method12UserService.prototype.addUserWebSocket = function(webSocketId, token)13{14 this.userWebSockets[webSocketId] = token;15};16UserService.prototype.addUserItems = function(webSocketId, items)17{18 var token = this.userWebSockets[webSocketId];19 this.userRepository.addUserItems(token, items);20};21UserService.prototype.updateUserItems = function(webSocketId, items)22{23 var token = this.userWebSockets[webSocketId];24 this.userRepository.updateUserItems(token, items);25};26UserService.prototype.levelUpUser = function(webSocketId, parameters, levelUpInformation)27{28 var token = this.userWebSockets[webSocketId];29 this.userRepository.levelUpUser(token, parameters, levelUpInformation);30};31UserService.prototype.updateUserExperience = function(webSocketId, experiencePoints)32{33 var token = this.userWebSockets[webSocketId];34 this.userRepository.updateUserExperience(token, experiencePoints);35};36UserService.prototype.getInformationNextLevel = function(nextLevel)37{38 var levelPoint = { nextLevelXp: this.experiencePerLevel[nextLevel], pointForNextLevel: this.upgradePointsPerLevel[nextLevel] };39 return levelPoint;40};41UserService.prototype.setExperienceInformation = function(experiencePerLevel, upgradePointsPerLevel, maximumLevel) {42 this.experiencePerLevel = experiencePerLevel;43 this.upgradePointsPerLevel = upgradePointsPerLevel;44 this.maximumLevel = maximumLevel;45};46//Private method...
client.js
Source:client.js
1import axios from 'axios'2import manageJwtToken from './manageJwtToken';3// Set config defaults when creating the instance4const client = axios.create({5 baseURL: "http://localhost:8080/api/"6 });7 client.interceptors.request.use((config) => {8 config.headers.token = manageJwtToken.getTokenFromLocalStorage()9 // if (store.getters['auth/webSocketId'] !== null) {10 // const webSocketId = store.getters['auth/webSocketId']11 // config.headers.WebSocketId = webSocketId12 // }13 return config14 })15// Add a response interceptor16client.interceptors.response.use(function (response) {17 // Any status code that lie within the range of 2xx cause this function to trigger18 // Do something with response data19 return response;20 }, function (error) {21 // Any status codes that falls outside the range of 2xx cause this function to trigger22 // Do something with response error23 return Promise.reject(error);24 });...
Room.js
Source:Room.js
1const { hydrate } = require('../functions/utils');2class Room {3 constructor(data = {}) {4 /**5 * @type {string}6 */7 this.code = '';8 /**9 * @type {Object<Player>}10 */11 this.players = {};12 /**13 * @type {?Question}14 */15 this.currentQuestion = null;16 /**17 * @type {string}18 */19 this.hostWebsocketIds = [];20 hydrate(this, data);21 }22 /**23 * @param {Player} player24 */25 addPlayer(player) {26 this.players[player.id] = player;27 }28 /**29 * @param {string} websocketId30 *31 * @return {Player|undefined}32 */33 getPlayerByWebsocketId(websocketId) {34 return Object.values(this.players).find((p) => p.websocketId === websocketId);35 }36 /**37 * @param {?Question} question38 */39 setQuestion(question) {40 this.currentQuestion = question;41 }42}...
Using AI Code Generation
1const playwright = require("playwright");2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 console.log(await page.evaluate(() => window.webSocketId));7 await browser.close();8})();9const playwright = require("playwright");10(async () => {11 const browser = await playwright.chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 console.log(await page.evaluate(() => window.webSocketId));15 await browser.close();16})();17const playwright = require("playwright");18(async () => {19 const browser = await playwright.chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 console.log(await page.evaluate(() => window.webSocketId));23 await browser.close();24})();25const playwright = require("playwright");26(async () => {27 const browser = await playwright.chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 console.log(await page.evaluate(() => window.webSocketId));31 await browser.close();32})();33const playwright = require("playwright");34(async () => {35 const browser = await playwright.chromium.launch({ headless: false });36 const context = await browser.newContext();37 const page = await context.newPage();38 console.log(await page.evaluate(() => window.webSocketId));39 await browser.close();40})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const webSocket = await page.webSocketId();7 console.log(webSocket);8 await browser.close();9})();
Using AI Code Generation
1const { webSocketId } = require('playwright/lib/internal/browserContext');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 const wsId = webSocketId(context);8 console.log(wsId);9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();
Using AI Code Generation
1const { webSocketId } = require("playwright/lib/client/webSocketTransport");2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 console.log(webSocketId(page));6 await browser.close();7})();
Using AI Code Generation
1const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;2console.log(webSocketId);3const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;4console.log(webSocketId);5const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;6console.log(webSocketId);7const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;8console.log(webSocketId);9const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;10console.log(webSocketId);11const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;12console.log(webSocketId);13const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;14console.log(webSocketId);15const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;16console.log(webSocketId);17const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;18console.log(webSocketId);19const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;20console.log(webSocketId);21const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;22console.log(webSocketId);23const webSocketId = browserContext._browser._connection._transport._ws._webSocketId;24console.log(webSocketId);
Using AI Code Generation
1const { webSocketId } = require('playwright/internal/transport/webSocketTransport');2module.exports = { webSocketId };3const { webSocketId } = require('./test.js');4const playwright = require('playwright');5(async () => {6 const browser = await playwright.chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const id = webSocketId(page);10 console.log(id);11})();12[Error: Cannot find module 'playwright/internal/transport/webSocketTransport'] {13}14I tried to use browser.wsEndpoint() to get the web socket endpoint. But I’m getting an error
Using AI Code Generation
1const webSocketId = require('playwright/lib/server/webSocketTransport').webSocketId;2console.log(webSocketId);3const webSocketId = require('playwright/lib/server/webSocketTransport').webSocketId;4ws.on('open', function open() {5 ws.send(JSON.stringify({id: 1, method: 'Target.getTargets'}));6});7ws.on('message', function incoming(data) {8 console.log(data);9});10{"id":1,"result":{"targetInfos":[{"targetId":"CD7E8D3E-7F51-4B0D-8E8B-9A5A5B5A5B5B","type":"page","title":"","url":"","attached":true,"browserContextId":"B1B1B1B1-B1B1-B1B1-B1B1-B1B1B1B1B1B1"}]}}11const webSocketDebuggerUrl = browserContext._browser._connection._transport.url();12const ws = new WebSocket(webSocketDebuggerUrl);13ws.on('open', function open() {14 ws.send(JSON.stringify({id: 1, method: 'Target.getTargets'}));15});16ws.on('message', function incoming(data) {17 console.log(data);18});19{"id":1,"result":{"targetInfos":[{"targetId":"CD7E8D3E-7F51-4B0D-8E8B-9A5A5B5A5B5B","type":"page","title":"","url":"","attached":true,"browserContextId":"B1B1B1B1-B1B1-B1B1-B
Using AI Code Generation
1const { webSocketId } = require('playwright');2const wsEndpoint = webSocketId(browser);3const browser = await chromium.connect({ wsEndpoint });4const context = await browser.newContext();5const page = await context.newPage();6browser.close();
Using AI Code Generation
1const webSocketId = await playwright._getBrowserForPage(page).webSocketId();2console.log(webSocketId);3const webSocketId = await playwright._getBrowserForPage(page).webSocketId();4console.log(webSocketId);5const webSocketId = await playwright._getBrowserForPage(page).webSocketId();6console.log(webSocketId);7const webSocketId = await playwright._getBrowserForPage(page).webSocketId();8console.log(webSocketId);9const webSocketId = await playwright._getBrowserForPage(page).webSocketId();10console.log(webSocketId);11const webSocketId = await playwright._getBrowserForPage(page).webSocketId();12console.log(webSocketId);13const webSocketId = await playwright._getBrowserForPage(page).webSocketId();14console.log(webSocketId);15const webSocketId = await playwright._getBrowserForPage(page).webSocketId();16console.log(webSocketId);17const webSocketId = await playwright._getBrowserForPage(page).webSocketId();18console.log(webSocketId);19const webSocketId = await playwright._getBrowserForPage(page).webSocketId();20console.log(webSocketId);21const webSocketId = await playwright._getBrowserForPage(page).webSocketId();22console.log(webSocketId);
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!