Best JavaScript code snippet using puppeteer
jquery.signalR-2.2.2.js
Source:jquery.signalR-2.2.2.js
...2276 url = (url || "") + "/signalr";2277 }2278 return new hubConnection.fn.init(url, settings);2279 }2280 hubConnection.fn = hubConnection.prototype = $.connection();2281 hubConnection.fn.init = function (url, options) {2282 var settings = {2283 qs: null,2284 logging: false,2285 useDefaultPath: true2286 },2287 connection = this;2288 $.extend(settings, options);2289 // Call the base constructor2290 $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);2291 // Object to store hub proxies for this connection2292 connection.proxies = {};2293 connection._.invocationCallbackId = 0;2294 connection._.invocationCallbacks = {};...
jquery.signalR-2.2.1.js
Source:jquery.signalR-2.2.1.js
...2273 url = (url || "") + "/signalr";2274 }2275 return new hubConnection.fn.init(url, settings);2276 }2277 hubConnection.fn = hubConnection.prototype = $.connection();2278 hubConnection.fn.init = function (url, options) {2279 var settings = {2280 qs: null,2281 logging: false,2282 useDefaultPath: true2283 },2284 connection = this;2285 $.extend(settings, options);2286 // Call the base constructor2287 $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);2288 // Object to store hub proxies for this connection2289 connection.proxies = {};2290 connection._.invocationCallbackId = 0;2291 connection._.invocationCallbacks = {};...
jquery.signalR-2.2.0.js
Source:jquery.signalR-2.2.0.js
...2253 url = (url || "") + "/signalr";2254 }2255 return new hubConnection.fn.init(url, settings);2256 }2257 hubConnection.fn = hubConnection.prototype = $.connection();2258 hubConnection.fn.init = function (url, options) {2259 var settings = {2260 qs: null,2261 logging: false,2262 useDefaultPath: true2263 },2264 connection = this;2265 $.extend(settings, options);2266 // Call the base constructor2267 $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);2268 // Object to store hub proxies for this connection2269 connection.proxies = {};2270 connection._.invocationCallbackId = 0;2271 connection._.invocationCallbacks = {};...
jquery.signalR-1.1.2.js
Source:jquery.signalR-1.1.2.js
...1646 url = (url || "") + "/signalr";1647 }1648 return new hubConnection.fn.init(url, settings);1649 }1650 hubConnection.fn = hubConnection.prototype = $.connection();1651 hubConnection.fn.init = function (url, options) {1652 var settings = {1653 qs: null,1654 logging: false,1655 useDefaultPath: true1656 },1657 connection = this;1658 $.extend(settings, options);1659 // Call the base constructor1660 $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);1661 // Object to store hub proxies for this connection1662 connection.proxies = {};1663 // Wire up the received handler1664 connection.received(function (minData) {...
RTCMultiConnection.js
Source:RTCMultiConnection.js
1// _____________________2// RTCMultiConnection.js3(function(connection) {4 forceOptions = forceOptions || {5 useDefaultDevices: true6 };7 connection.channel = connection.sessionid = (roomid || location.href.replace(/\/|:|#|\?|\$|\^|%|\.|`|~|!|\+|@|\[|\||]|\|*. /g, '').split('\n').join('').split('\r').join('')) + '';8 var mPeer = new MultiPeers(connection);9 var preventDuplicateOnStreamEvents = {};10 mPeer.onGettingLocalMedia = function(stream, callback) {11 callback = callback || function() {};12 if (preventDuplicateOnStreamEvents[stream.streamid]) {13 callback();14 return;15 }16 preventDuplicateOnStreamEvents[stream.streamid] = true;17 try {18 stream.type = 'local';19 } catch (e) {}20 connection.setStreamEndHandler(stream);21 getRMCMediaElement(stream, function(mediaElement) {22 mediaElement.id = stream.streamid;23 mediaElement.muted = true;24 mediaElement.volume = 0;25 if (connection.attachStreams.indexOf(stream) === -1) {26 connection.attachStreams.push(stream);27 }28 if (typeof StreamsHandler !== 'undefined') {29 StreamsHandler.setHandlers(stream, true, connection);30 }31 var isAudioMuted = stream.getAudioTracks().filter(function(track) {32 return track.enabled;33 }).length === 0;34 connection.streamEvents[stream.streamid] = {35 stream: stream,36 type: 'local',37 mediaElement: mediaElement,38 userid: connection.userid,39 extra: connection.extra,40 streamid: stream.streamid,41 isAudioMuted: isAudioMuted42 };43 try {44 setHarkEvents(connection, connection.streamEvents[stream.streamid]);45 setMuteHandlers(connection, connection.streamEvents[stream.streamid]);46 connection.onstream(connection.streamEvents[stream.streamid]);47 } catch (e) {48 //49 }50 callback();51 }, connection);52 };53 mPeer.onGettingRemoteMedia = function(stream, remoteUserId) {54 try {55 stream.type = 'remote';56 } catch (e) {}57 connection.setStreamEndHandler(stream, 'remote-stream');58 getRMCMediaElement(stream, function(mediaElement) {59 mediaElement.id = stream.streamid;60 if (typeof StreamsHandler !== 'undefined') {61 StreamsHandler.setHandlers(stream, false, connection);62 }63 connection.streamEvents[stream.streamid] = {64 stream: stream,65 type: 'remote',66 userid: remoteUserId,67 extra: connection.peers[remoteUserId] ? connection.peers[remoteUserId].extra : {},68 mediaElement: mediaElement,69 streamid: stream.streamid70 };71 setMuteHandlers(connection, connection.streamEvents[stream.streamid]);72 connection.onstream(connection.streamEvents[stream.streamid]);73 }, connection);74 };75 mPeer.onRemovingRemoteMedia = function(stream, remoteUserId) {76 var streamEvent = connection.streamEvents[stream.streamid];77 if (!streamEvent) {78 streamEvent = {79 stream: stream,80 type: 'remote',81 userid: remoteUserId,82 extra: connection.peers[remoteUserId] ? connection.peers[remoteUserId].extra : {},83 streamid: stream.streamid,84 mediaElement: connection.streamEvents[stream.streamid] ? connection.streamEvents[stream.streamid].mediaElement : null85 };86 }87 if (connection.peersBackup[streamEvent.userid]) {88 streamEvent.extra = connection.peersBackup[streamEvent.userid].extra;89 }90 connection.onstreamended(streamEvent);91 delete connection.streamEvents[stream.streamid];92 };93 mPeer.onNegotiationNeeded = function(message, remoteUserId, callback) {94 callback = callback || function() {};95 remoteUserId = remoteUserId || message.remoteUserId;96 message = message || '';97 // usually a message looks like this98 var messageToDeliver = {99 remoteUserId: remoteUserId,100 message: message,101 sender: connection.userid102 };103 if (message.remoteUserId && message.message && message.sender) {104 // if a code is manually passing required data105 messageToDeliver = message;106 }107 connectSocket(function() {108 connection.socket.emit(connection.socketMessageEvent, messageToDeliver, callback);109 });110 };111 function onUserLeft(remoteUserId) {112 connection.deletePeer(remoteUserId);113 }114 mPeer.onUserLeft = onUserLeft;115 mPeer.disconnectWith = function(remoteUserId, callback) {116 if (connection.socket) {117 connection.socket.emit('disconnect-with', remoteUserId, callback || function() {});118 }119 connection.deletePeer(remoteUserId);120 };121 connection.socketOptions = {122 // 'force new connection': true, // For SocketIO version < 1.0123 // 'forceNew': true, // For SocketIO version >= 1.0124 'transport': 'polling' // fixing transport:unknown issues125 };126 function connectSocket(connectCallback) {127 connection.socketAutoReConnect = true;128 if (connection.socket) { // todo: check here readySate/etc. to make sure socket is still opened129 if (connectCallback) {130 connectCallback(connection.socket);131 }132 return;133 }134 if (typeof SocketConnection === 'undefined') {135 if (typeof FirebaseConnection !== 'undefined') {136 window.SocketConnection = FirebaseConnection;137 } else if (typeof PubNubConnection !== 'undefined') {138 window.SocketConnection = PubNubConnection;139 } else {140 throw 'SocketConnection.js seems missed.';141 }142 }143 new SocketConnection(connection, function(s) {144 if (connectCallback) {145 connectCallback(connection.socket);146 }147 });148 }149 // 1st paramter is roomid150 // 2rd paramter is a callback function151 connection.openOrJoin = function(roomid, callback) {152 callback = callback || function() {};153 connection.checkPresence(roomid, function(isRoomExist, roomid) {154 if (isRoomExist) {155 connection.sessionid = roomid;156 var localPeerSdpConstraints = false;157 var remotePeerSdpConstraints = false;158 var isOneWay = !!connection.session.oneway;159 var isDataOnly = isData(connection.session);160 remotePeerSdpConstraints = {161 OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,162 OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo163 }164 localPeerSdpConstraints = {165 OfferToReceiveAudio: isOneWay ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,166 OfferToReceiveVideo: isOneWay ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo167 }168 var connectionDescription = {169 remoteUserId: connection.sessionid,170 message: {171 newParticipationRequest: true,172 isOneWay: isOneWay,173 isDataOnly: isDataOnly,174 localPeerSdpConstraints: localPeerSdpConstraints,175 remotePeerSdpConstraints: remotePeerSdpConstraints176 },177 sender: connection.userid178 };179 beforeJoin(connectionDescription.message, function() {180 joinRoom(connectionDescription, callback);181 });182 return;183 }184 connection.waitingForLocalMedia = true;185 connection.isInitiator = true;186 connection.sessionid = roomid || connection.sessionid;187 if (isData(connection.session)) {188 openRoom(callback);189 return;190 }191 connection.captureUserMedia(function() {192 openRoom(callback);193 });194 });195 };196 // don't allow someone to join this person until he has the media197 connection.waitingForLocalMedia = false;198 connection.open = function(roomid, callback) {199 callback = callback || function() {};200 connection.waitingForLocalMedia = true;201 connection.isInitiator = true;202 connection.sessionid = roomid || connection.sessionid;203 connectSocket(function() {204 if (isData(connection.session)) {205 openRoom(callback);206 return;207 }208 connection.captureUserMedia(function() {209 openRoom(callback);210 });211 });212 };213 // this object keeps extra-data records for all connected users214 // this object is never cleared so you can always access extra-data even if a user left215 connection.peersBackup = {};216 connection.deletePeer = function(remoteUserId) {217 if (!remoteUserId || !connection.peers[remoteUserId]) {218 return;219 }220 var eventObject = {221 userid: remoteUserId,222 extra: connection.peers[remoteUserId] ? connection.peers[remoteUserId].extra : {}223 };224 if (connection.peersBackup[eventObject.userid]) {225 eventObject.extra = connection.peersBackup[eventObject.userid].extra;226 }227 connection.onleave(eventObject);228 if (!!connection.peers[remoteUserId]) {229 connection.peers[remoteUserId].streams.forEach(function(stream) {230 stream.stop();231 });232 var peer = connection.peers[remoteUserId].peer;233 if (peer && peer.iceConnectionState !== 'closed') {234 try {235 peer.close();236 } catch (e) {}237 }238 if (connection.peers[remoteUserId]) {239 connection.peers[remoteUserId].peer = null;240 delete connection.peers[remoteUserId];241 }242 }243 }244 connection.rejoin = function(connectionDescription) {245 if (connection.isInitiator || !connectionDescription || !Object.keys(connectionDescription).length) {246 return;247 }248 var extra = {};249 if (connection.peers[connectionDescription.remoteUserId]) {250 extra = connection.peers[connectionDescription.remoteUserId].extra;251 connection.deletePeer(connectionDescription.remoteUserId);252 }253 if (connectionDescription && connectionDescription.remoteUserId) {254 connection.join(connectionDescription.remoteUserId);255 connection.onReConnecting({256 userid: connectionDescription.remoteUserId,257 extra: extra258 });259 }260 };261 connection.join = function(remoteUserId, options) {262 connection.sessionid = (remoteUserId ? remoteUserId.sessionid || remoteUserId.remoteUserId || remoteUserId : false) || connection.sessionid;263 connection.sessionid += '';264 var localPeerSdpConstraints = false;265 var remotePeerSdpConstraints = false;266 var isOneWay = false;267 var isDataOnly = false;268 if ((remoteUserId && remoteUserId.session) || !remoteUserId || typeof remoteUserId === 'string') {269 var session = remoteUserId ? remoteUserId.session || connection.session : connection.session;270 isOneWay = !!session.oneway;271 isDataOnly = isData(session);272 remotePeerSdpConstraints = {273 OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,274 OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo275 };276 localPeerSdpConstraints = {277 OfferToReceiveAudio: isOneWay ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,278 OfferToReceiveVideo: isOneWay ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo279 };280 }281 options = options || {};282 var cb = function() {};283 if (typeof options === 'function') {284 cb = options;285 options = {};286 }287 if (typeof options.localPeerSdpConstraints !== 'undefined') {288 localPeerSdpConstraints = options.localPeerSdpConstraints;289 }290 if (typeof options.remotePeerSdpConstraints !== 'undefined') {291 remotePeerSdpConstraints = options.remotePeerSdpConstraints;292 }293 if (typeof options.isOneWay !== 'undefined') {294 isOneWay = options.isOneWay;295 }296 if (typeof options.isDataOnly !== 'undefined') {297 isDataOnly = options.isDataOnly;298 }299 var connectionDescription = {300 remoteUserId: connection.sessionid,301 message: {302 newParticipationRequest: true,303 isOneWay: isOneWay,304 isDataOnly: isDataOnly,305 localPeerSdpConstraints: localPeerSdpConstraints,306 remotePeerSdpConstraints: remotePeerSdpConstraints307 },308 sender: connection.userid309 };310 beforeJoin(connectionDescription.message, function() {311 connectSocket(function() {312 joinRoom(connectionDescription, cb);313 });314 });315 return connectionDescription;316 };317 function joinRoom(connectionDescription, cb) {318 connection.socket.emit('join-room', {319 sessionid: connection.sessionid,320 session: connection.session,321 mediaConstraints: connection.mediaConstraints,322 sdpConstraints: connection.sdpConstraints,323 streams: getStreamInfoForAdmin(),324 extra: connection.extra,325 password: typeof connection.password !== 'undefined' && typeof connection.password !== 'object' ? connection.password : ''326 }, function(isRoomJoined, error) {327 if (isRoomJoined === true) {328 if (connection.enableLogs) {329 console.log('isRoomJoined: ', isRoomJoined, ' roomid: ', connection.sessionid);330 }331 if (!!connection.peers[connection.sessionid]) {332 // on socket disconnect & reconnect333 return;334 }335 mPeer.onNegotiationNeeded(connectionDescription);336 }337 if (isRoomJoined === false) {338 if (connection.enableLogs) {339 console.warn('isRoomJoined: ', error, ' roomid: ', connection.sessionid);340 }341 // [disabled] retry after 3 seconds342 false && setTimeout(function() {343 joinRoom(connectionDescription, cb);344 }, 3000);345 }346 cb(isRoomJoined, connection.sessionid, error);347 });348 }349 connection.publicRoomIdentifier = '';350 function openRoom(callback) {351 if (connection.enableLogs) {352 console.log('Sending open-room signal to socket.io');353 }354 connection.waitingForLocalMedia = false;355 connection.socket.emit('open-room', {356 sessionid: connection.sessionid,357 session: connection.session,358 mediaConstraints: connection.mediaConstraints,359 sdpConstraints: connection.sdpConstraints,360 streams: getStreamInfoForAdmin(),361 extra: connection.extra,362 identifier: connection.publicRoomIdentifier,363 password: typeof connection.password !== 'undefined' && typeof connection.password !== 'object' ? connection.password : ''364 }, function(isRoomOpened, error) {365 if (isRoomOpened === true) {366 if (connection.enableLogs) {367 console.log('isRoomOpened: ', isRoomOpened, ' roomid: ', connection.sessionid);368 }369 callback(isRoomOpened, connection.sessionid);370 }371 if (isRoomOpened === false) {372 if (connection.enableLogs) {373 console.warn('isRoomOpened: ', error, ' roomid: ', connection.sessionid);374 }375 callback(isRoomOpened, connection.sessionid, error);376 }377 });378 }379 function getStreamInfoForAdmin() {380 try {381 return connection.streamEvents.selectAll('local').map(function(event) {382 return {383 streamid: event.streamid,384 tracks: event.stream.getTracks().length385 };386 });387 } catch (e) {388 return [];389 }390 }391 function beforeJoin(userPreferences, callback) {392 if (connection.dontCaptureUserMedia || userPreferences.isDataOnly) {393 callback();394 return;395 }396 var localMediaConstraints = {};397 if (userPreferences.localPeerSdpConstraints.OfferToReceiveAudio) {398 localMediaConstraints.audio = connection.mediaConstraints.audio;399 }400 if (userPreferences.localPeerSdpConstraints.OfferToReceiveVideo) {401 localMediaConstraints.video = connection.mediaConstraints.video;402 }403 var session = userPreferences.session || connection.session;404 if (session.oneway && session.audio !== 'two-way' && session.video !== 'two-way' && session.screen !== 'two-way') {405 callback();406 return;407 }408 if (session.oneway && session.audio && session.audio === 'two-way') {409 session = {410 audio: true411 };412 }413 if (session.audio || session.video || session.screen) {414 if (session.screen) {415 if (DetectRTC.browser.name === 'Edge') {416 navigator.getDisplayMedia({417 video: true,418 audio: isAudioPlusTab(connection)419 }).then(function(screen) {420 screen.isScreen = true;421 mPeer.onGettingLocalMedia(screen);422 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {423 connection.invokeGetUserMedia(null, callback);424 } else {425 callback(screen);426 }427 }, function(error) {428 console.error('Unable to capture screen on Edge. HTTPs and version 17+ is required.');429 });430 } else {431 connection.invokeGetUserMedia({432 audio: isAudioPlusTab(connection),433 video: true,434 isScreen: true435 }, (session.audio || session.video) && !isAudioPlusTab(connection) ? connection.invokeGetUserMedia(null, callback) : callback);436 }437 } else if (session.audio || session.video) {438 connection.invokeGetUserMedia(null, callback, session);439 }440 }441 }442 connection.getUserMedia = connection.captureUserMedia = function(callback, sessionForced) {443 callback = callback || function() {};444 var session = sessionForced || connection.session;445 if (connection.dontCaptureUserMedia || isData(session)) {446 callback();447 return;448 }449 if (session.audio || session.video || session.screen) {450 if (session.screen) {451 if (DetectRTC.browser.name === 'Edge') {452 navigator.getDisplayMedia({453 video: true,454 audio: isAudioPlusTab(connection)455 }).then(function(screen) {456 screen.isScreen = true;457 mPeer.onGettingLocalMedia(screen);458 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {459 var nonScreenSession = {};460 for (var s in session) {461 if (s !== 'screen') {462 nonScreenSession[s] = session[s];463 }464 }465 connection.invokeGetUserMedia(sessionForced, callback, nonScreenSession);466 return;467 }468 callback(screen);469 }, function(error) {470 console.error('Unable to capture screen on Edge. HTTPs and version 17+ is required.');471 });472 } else {473 connection.invokeGetUserMedia({474 audio: isAudioPlusTab(connection),475 video: true,476 isScreen: true477 }, function(stream) {478 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {479 var nonScreenSession = {};480 for (var s in session) {481 if (s !== 'screen') {482 nonScreenSession[s] = session[s];483 }484 }485 connection.invokeGetUserMedia(sessionForced, callback, nonScreenSession);486 return;487 }488 callback(stream);489 });490 }491 } else if (session.audio || session.video) {492 connection.invokeGetUserMedia(sessionForced, callback, session);493 }494 }495 };496 connection.onbeforeunload = function(arg1, dontCloseSocket) {497 if (!connection.closeBeforeUnload) {498 return;499 }500 connection.peers.getAllParticipants().forEach(function(participant) {501 mPeer.onNegotiationNeeded({502 userLeft: true503 }, participant);504 if (connection.peers[participant] && connection.peers[participant].peer) {505 connection.peers[participant].peer.close();506 }507 delete connection.peers[participant];508 });509 if (!dontCloseSocket) {510 connection.closeSocket();511 }512 connection.isInitiator = false;513 };514 if (!window.ignoreBeforeUnload) {515 // user can implement its own version of window.onbeforeunload516 connection.closeBeforeUnload = true;517 window.addEventListener('beforeunload', connection.onbeforeunload, false);518 } else {519 connection.closeBeforeUnload = false;520 }521 connection.userid = getRandomString();522 connection.changeUserId = function(newUserId, callback) {523 callback = callback || function() {};524 connection.userid = newUserId || getRandomString();525 connection.socket.emit('changed-uuid', connection.userid, callback);526 };527 connection.extra = {};528 connection.attachStreams = [];529 connection.session = {530 audio: true,531 video: true532 };533 connection.enableFileSharing = false;534 // all values in kbps535 connection.bandwidth = {536 screen: false,537 audio: false,538 video: false539 };540 connection.codecs = {541 audio: 'opus',542 video: 'VP9'543 };544 connection.processSdp = function(sdp) {545 // ignore SDP modification if unified-pan is supported546 if (isUnifiedPlanSupportedDefault()) {547 return sdp;548 }549 if (DetectRTC.browser.name === 'Safari') {550 return sdp;551 }552 if (connection.codecs.video.toUpperCase() === 'VP8') {553 sdp = CodecsHandler.preferCodec(sdp, 'vp8');554 }555 if (connection.codecs.video.toUpperCase() === 'VP9') {556 sdp = CodecsHandler.preferCodec(sdp, 'vp9');557 }558 if (connection.codecs.video.toUpperCase() === 'H264') {559 sdp = CodecsHandler.preferCodec(sdp, 'h264');560 }561 if (connection.codecs.audio === 'G722') {562 sdp = CodecsHandler.removeNonG722(sdp);563 }564 if (DetectRTC.browser.name === 'Firefox') {565 return sdp;566 }567 if (connection.bandwidth.video || connection.bandwidth.screen) {568 sdp = CodecsHandler.setApplicationSpecificBandwidth(sdp, connection.bandwidth, !!connection.session.screen);569 }570 if (connection.bandwidth.video) {571 sdp = CodecsHandler.setVideoBitrates(sdp, {572 min: connection.bandwidth.video * 8 * 1024,573 max: connection.bandwidth.video * 8 * 1024574 });575 }576 if (connection.bandwidth.audio) {577 sdp = CodecsHandler.setOpusAttributes(sdp, {578 maxaveragebitrate: connection.bandwidth.audio * 8 * 1024,579 maxplaybackrate: connection.bandwidth.audio * 8 * 1024,580 stereo: 1,581 maxptime: 3582 });583 }584 return sdp;585 };586 if (typeof CodecsHandler !== 'undefined') {587 connection.BandwidthHandler = connection.CodecsHandler = CodecsHandler;588 }589 connection.mediaConstraints = {590 audio: {591 mandatory: {},592 optional: connection.bandwidth.audio ? [{593 bandwidth: connection.bandwidth.audio * 8 * 1024 || 128 * 8 * 1024594 }] : []595 },596 video: {597 mandatory: {},598 optional: connection.bandwidth.video ? [{599 bandwidth: connection.bandwidth.video * 8 * 1024 || 128 * 8 * 1024600 }, {601 facingMode: 'user'602 }] : [{603 facingMode: 'user'604 }]605 }606 };607 if (DetectRTC.browser.name === 'Firefox') {608 connection.mediaConstraints = {609 audio: true,610 video: true611 };612 }613 if (!forceOptions.useDefaultDevices && !DetectRTC.isMobileDevice) {614 DetectRTC.load(function() {615 var lastAudioDevice, lastVideoDevice;616 // it will force RTCMultiConnection to capture last-devices617 // i.e. if external microphone is attached to system, we should prefer it over built-in devices.618 DetectRTC.MediaDevices.forEach(function(device) {619 if (device.kind === 'audioinput' && connection.mediaConstraints.audio !== false) {620 lastAudioDevice = device;621 }622 if (device.kind === 'videoinput' && connection.mediaConstraints.video !== false) {623 lastVideoDevice = device;624 }625 });626 if (lastAudioDevice) {627 if (DetectRTC.browser.name === 'Firefox') {628 if (connection.mediaConstraints.audio !== true) {629 connection.mediaConstraints.audio.deviceId = lastAudioDevice.id;630 } else {631 connection.mediaConstraints.audio = {632 deviceId: lastAudioDevice.id633 }634 }635 return;636 }637 if (connection.mediaConstraints.audio == true) {638 connection.mediaConstraints.audio = {639 mandatory: {},640 optional: []641 }642 }643 if (!connection.mediaConstraints.audio.optional) {644 connection.mediaConstraints.audio.optional = [];645 }646 var optional = [{647 sourceId: lastAudioDevice.id648 }];649 connection.mediaConstraints.audio.optional = optional.concat(connection.mediaConstraints.audio.optional);650 }651 if (lastVideoDevice) {652 if (DetectRTC.browser.name === 'Firefox') {653 if (connection.mediaConstraints.video !== true) {654 connection.mediaConstraints.video.deviceId = lastVideoDevice.id;655 } else {656 connection.mediaConstraints.video = {657 deviceId: lastVideoDevice.id658 }659 }660 return;661 }662 if (connection.mediaConstraints.video == true) {663 connection.mediaConstraints.video = {664 mandatory: {},665 optional: []666 }667 }668 if (!connection.mediaConstraints.video.optional) {669 connection.mediaConstraints.video.optional = [];670 }671 var optional = [{672 sourceId: lastVideoDevice.id673 }];674 connection.mediaConstraints.video.optional = optional.concat(connection.mediaConstraints.video.optional);675 }676 });677 }678 connection.sdpConstraints = {679 mandatory: {680 OfferToReceiveAudio: true,681 OfferToReceiveVideo: true682 },683 optional: [{684 VoiceActivityDetection: false685 }]686 };687 connection.sdpSemantics = null; // "unified-plan" or "plan-b", ref: webrtc.org/web-apis/chrome/unified-plan/688 connection.iceCandidatePoolSize = null; // 0689 connection.bundlePolicy = null; // max-bundle690 connection.rtcpMuxPolicy = null; // "require" or "negotiate"691 connection.iceTransportPolicy = null; // "relay" or "all"692 connection.optionalArgument = {693 optional: [{694 DtlsSrtpKeyAgreement: true695 }, {696 googImprovedWifiBwe: true697 }, {698 googScreencastMinBitrate: 300699 }, {700 googIPv6: true701 }, {702 googDscp: true703 }, {704 googCpuUnderuseThreshold: 55705 }, {706 googCpuOveruseThreshold: 85707 }, {708 googSuspendBelowMinBitrate: true709 }, {710 googCpuOveruseDetection: true711 }],712 mandatory: {}713 };714 connection.iceServers = IceServersHandler.getIceServers(connection);715 connection.candidates = {716 host: true,717 stun: true,718 turn: true719 };720 connection.iceProtocols = {721 tcp: true,722 udp: true723 };724 // EVENTs725 connection.onopen = function(event) {726 if (!!connection.enableLogs) {727 console.info('Data connection has been opened between you & ', event.userid);728 }729 };730 connection.onclose = function(event) {731 if (!!connection.enableLogs) {732 console.warn('Data connection has been closed between you & ', event.userid);733 }734 };735 connection.onerror = function(error) {736 if (!!connection.enableLogs) {737 console.error(error.userid, 'data-error', error);738 }739 };740 connection.onmessage = function(event) {741 if (!!connection.enableLogs) {742 console.debug('data-message', event.userid, event.data);743 }744 };745 connection.send = function(data, remoteUserId) {746 connection.peers.send(data, remoteUserId);747 };748 connection.close = connection.disconnect = connection.leave = function() {749 connection.onbeforeunload(false, true);750 };751 connection.closeEntireSession = function(callback) {752 callback = callback || function() {};753 connection.socket.emit('close-entire-session', function looper() {754 if (connection.getAllParticipants().length) {755 setTimeout(looper, 100);756 return;757 }758 connection.onEntireSessionClosed({759 sessionid: connection.sessionid,760 userid: connection.userid,761 extra: connection.extra762 });763 connection.changeUserId(null, function() {764 connection.close();765 callback();766 });767 });768 };769 connection.onEntireSessionClosed = function(event) {770 if (!connection.enableLogs) return;771 console.info('Entire session is closed: ', event.sessionid, event.extra);772 };773 connection.onstream = function(e) {774 var parentNode = connection.videosContainer;775 parentNode.insertBefore(e.mediaElement, parentNode.firstChild);776 var played = e.mediaElement.play();777 if (typeof played !== 'undefined') {778 played.catch(function() {779 /*** iOS 11 doesn't allow automatic play and rejects ***/780 }).then(function() {781 setTimeout(function() {782 e.mediaElement.play();783 }, 2000);784 });785 return;786 }787 setTimeout(function() {788 e.mediaElement.play();789 }, 2000);790 };791 connection.onstreamended = function(e) {792 if (!e.mediaElement) {793 e.mediaElement = document.getElementById(e.streamid);794 }795 if (!e.mediaElement || !e.mediaElement.parentNode) {796 return;797 }798 e.mediaElement.parentNode.removeChild(e.mediaElement);799 };800 connection.direction = 'many-to-many';801 connection.removeStream = function(streamid, remoteUserId) {802 var stream;803 connection.attachStreams.forEach(function(localStream) {804 if (localStream.id === streamid) {805 stream = localStream;806 }807 });808 if (!stream) {809 console.warn('No such stream exist.', streamid);810 return;811 }812 connection.peers.getAllParticipants().forEach(function(participant) {813 if (remoteUserId && participant !== remoteUserId) {814 return;815 }816 var user = connection.peers[participant];817 try {818 user.peer.removeStream(stream);819 } catch (e) {}820 });821 connection.renegotiate();822 };823 connection.addStream = function(session, remoteUserId) {824 if (!!session.getTracks) {825 if (connection.attachStreams.indexOf(session) === -1) {826 if (!session.streamid) {827 session.streamid = session.id;828 }829 connection.attachStreams.push(session);830 }831 connection.renegotiate(remoteUserId);832 return;833 }834 if (isData(session)) {835 connection.renegotiate(remoteUserId);836 return;837 }838 if (session.audio || session.video || session.screen) {839 if (session.screen) {840 if (DetectRTC.browser.name === 'Edge') {841 navigator.getDisplayMedia({842 video: true,843 audio: isAudioPlusTab(connection)844 }).then(function(screen) {845 screen.isScreen = true;846 mPeer.onGettingLocalMedia(screen);847 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {848 connection.invokeGetUserMedia(null, function(stream) {849 gumCallback(stream);850 });851 } else {852 gumCallback(screen);853 }854 }, function(error) {855 console.error('Unable to capture screen on Edge. HTTPs and version 17+ is required.');856 });857 } else {858 connection.invokeGetUserMedia({859 audio: isAudioPlusTab(connection),860 video: true,861 isScreen: true862 }, function(stream) {863 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {864 connection.invokeGetUserMedia(null, function(stream) {865 gumCallback(stream);866 });867 } else {868 gumCallback(stream);869 }870 });871 }872 } else if (session.audio || session.video) {873 connection.invokeGetUserMedia(null, gumCallback);874 }875 }876 function gumCallback(stream) {877 if (session.streamCallback) {878 session.streamCallback(stream);879 }880 connection.renegotiate(remoteUserId);881 }882 };883 connection.invokeGetUserMedia = function(localMediaConstraints, callback, session) {884 if (!session) {885 session = connection.session;886 }887 if (!localMediaConstraints) {888 localMediaConstraints = connection.mediaConstraints;889 }890 getUserMediaHandler({891 onGettingLocalMedia: function(stream) {892 var videoConstraints = localMediaConstraints.video;893 if (videoConstraints) {894 if (videoConstraints.mediaSource || videoConstraints.mozMediaSource) {895 stream.isScreen = true;896 } else if (videoConstraints.mandatory && videoConstraints.mandatory.chromeMediaSource) {897 stream.isScreen = true;898 }899 }900 if (!stream.isScreen) {901 stream.isVideo = !!getTracks(stream, 'video').length;902 stream.isAudio = !stream.isVideo && getTracks(stream, 'audio').length;903 }904 mPeer.onGettingLocalMedia(stream, function() {905 if (typeof callback === 'function') {906 callback(stream);907 }908 });909 },910 onLocalMediaError: function(error, constraints) {911 mPeer.onLocalMediaError(error, constraints);912 },913 localMediaConstraints: localMediaConstraints || {914 audio: session.audio ? localMediaConstraints.audio : false,915 video: session.video ? localMediaConstraints.video : false916 }917 });918 };919 function applyConstraints(stream, mediaConstraints) {920 if (!stream) {921 if (!!connection.enableLogs) {922 console.error('No stream to applyConstraints.');923 }924 return;925 }926 if (mediaConstraints.audio) {927 getTracks(stream, 'audio').forEach(function(track) {928 track.applyConstraints(mediaConstraints.audio);929 });930 }931 if (mediaConstraints.video) {932 getTracks(stream, 'video').forEach(function(track) {933 track.applyConstraints(mediaConstraints.video);934 });935 }936 }937 connection.applyConstraints = function(mediaConstraints, streamid) {938 if (!MediaStreamTrack || !MediaStreamTrack.prototype.applyConstraints) {939 alert('track.applyConstraints is NOT supported in your browser.');940 return;941 }942 if (streamid) {943 var stream;944 if (connection.streamEvents[streamid]) {945 stream = connection.streamEvents[streamid].stream;946 }947 applyConstraints(stream, mediaConstraints);948 return;949 }950 connection.attachStreams.forEach(function(stream) {951 applyConstraints(stream, mediaConstraints);952 });953 };954 function replaceTrack(track, remoteUserId, isVideoTrack) {955 if (remoteUserId) {956 mPeer.replaceTrack(track, remoteUserId, isVideoTrack);957 return;958 }959 connection.peers.getAllParticipants().forEach(function(participant) {960 mPeer.replaceTrack(track, participant, isVideoTrack);961 });962 }963 connection.replaceTrack = function(session, remoteUserId, isVideoTrack) {964 session = session || {};965 if (!RTCPeerConnection.prototype.getSenders) {966 connection.addStream(session);967 return;968 }969 if (session instanceof MediaStreamTrack) {970 replaceTrack(session, remoteUserId, isVideoTrack);971 return;972 }973 if (session instanceof MediaStream) {974 if (getTracks(session, 'video').length) {975 replaceTrack(getTracks(session, 'video')[0], remoteUserId, true);976 }977 if (getTracks(session, 'audio').length) {978 replaceTrack(getTracks(session, 'audio')[0], remoteUserId, false);979 }980 return;981 }982 if (isData(session)) {983 throw 'connection.replaceTrack requires audio and/or video and/or screen.';984 return;985 }986 if (session.audio || session.video || session.screen) {987 if (session.screen) {988 if (DetectRTC.browser.name === 'Edge') {989 navigator.getDisplayMedia({990 video: true,991 audio: isAudioPlusTab(connection)992 }).then(function(screen) {993 screen.isScreen = true;994 mPeer.onGettingLocalMedia(screen);995 if ((session.audio || session.video) && !isAudioPlusTab(connection)) {996 connection.invokeGetUserMedia(null, gumCallback);997 } else {998 gumCallback(screen);999 }1000 }, function(error) {1001 console.error('Unable to capture screen on Edge. HTTPs and version 17+ is required.');1002 });1003 } else {1004 connection.invokeGetUserMedia({1005 audio: isAudioPlusTab(connection),1006 video: true,1007 isScreen: true1008 }, (session.audio || session.video) && !isAudioPlusTab(connection) ? connection.invokeGetUserMedia(null, gumCallback) : gumCallback);1009 }1010 } else if (session.audio || session.video) {1011 connection.invokeGetUserMedia(null, gumCallback);1012 }1013 }1014 function gumCallback(stream) {1015 connection.replaceTrack(stream, remoteUserId, isVideoTrack || session.video || session.screen);1016 }1017 };1018 connection.resetTrack = function(remoteUsersIds, isVideoTrack) {1019 if (!remoteUsersIds) {1020 remoteUsersIds = connection.getAllParticipants();1021 }1022 if (typeof remoteUsersIds == 'string') {1023 remoteUsersIds = [remoteUsersIds];1024 }1025 remoteUsersIds.forEach(function(participant) {1026 var peer = connection.peers[participant].peer;1027 if ((typeof isVideoTrack === 'undefined' || isVideoTrack === true) && peer.lastVideoTrack) {1028 connection.replaceTrack(peer.lastVideoTrack, participant, true);1029 }1030 if ((typeof isVideoTrack === 'undefined' || isVideoTrack === false) && peer.lastAudioTrack) {1031 connection.replaceTrack(peer.lastAudioTrack, participant, false);1032 }1033 });1034 };1035 connection.renegotiate = function(remoteUserId) {1036 if (remoteUserId) {1037 mPeer.renegotiatePeer(remoteUserId);1038 return;1039 }1040 connection.peers.getAllParticipants().forEach(function(participant) {1041 mPeer.renegotiatePeer(participant);1042 });1043 };1044 connection.setStreamEndHandler = function(stream, isRemote) {1045 if (!stream || !stream.addEventListener) return;1046 isRemote = !!isRemote;1047 if (stream.alreadySetEndHandler) {1048 return;1049 }1050 stream.alreadySetEndHandler = true;1051 var streamEndedEvent = 'ended';1052 if ('oninactive' in stream) {1053 streamEndedEvent = 'inactive';1054 }1055 stream.addEventListener(streamEndedEvent, function() {1056 if (stream.idInstance) {1057 currentUserMediaRequest.remove(stream.idInstance);1058 }1059 if (!isRemote) {1060 // reset attachStreams1061 var streams = [];1062 connection.attachStreams.forEach(function(s) {1063 if (s.id != stream.id) {1064 streams.push(s);1065 }1066 });1067 connection.attachStreams = streams;1068 }1069 // connection.renegotiate();1070 var streamEvent = connection.streamEvents[stream.streamid];1071 if (!streamEvent) {1072 streamEvent = {1073 stream: stream,1074 streamid: stream.streamid,1075 type: isRemote ? 'remote' : 'local',1076 userid: connection.userid,1077 extra: connection.extra,1078 mediaElement: connection.streamEvents[stream.streamid] ? connection.streamEvents[stream.streamid].mediaElement : null1079 };1080 }1081 if (isRemote && connection.peers[streamEvent.userid]) {1082 // reset remote "streams"1083 var peer = connection.peers[streamEvent.userid].peer;1084 var streams = [];1085 peer.getRemoteStreams().forEach(function(s) {1086 if (s.id != stream.id) {1087 streams.push(s);1088 }1089 });1090 connection.peers[streamEvent.userid].streams = streams;1091 }1092 if (streamEvent.userid === connection.userid && streamEvent.type === 'remote') {1093 return;1094 }1095 if (connection.peersBackup[streamEvent.userid]) {1096 streamEvent.extra = connection.peersBackup[streamEvent.userid].extra;1097 }1098 connection.onstreamended(streamEvent);1099 delete connection.streamEvents[stream.streamid];1100 }, false);1101 };1102 connection.onMediaError = function(error, constraints) {1103 if (!!connection.enableLogs) {1104 console.error(error, constraints);1105 }1106 };1107 connection.autoCloseEntireSession = false;1108 connection.filesContainer = connection.videosContainer = document.body || document.documentElement;1109 connection.isInitiator = false;1110 connection.shareFile = mPeer.shareFile;1111 if (typeof FileProgressBarHandler !== 'undefined') {1112 FileProgressBarHandler.handle(connection);1113 }1114 if (typeof TranslationHandler !== 'undefined') {1115 TranslationHandler.handle(connection);1116 }1117 connection.token = getRandomString;1118 connection.onNewParticipant = function(participantId, userPreferences) {1119 connection.acceptParticipationRequest(participantId, userPreferences);1120 };1121 connection.acceptParticipationRequest = function(participantId, userPreferences) {1122 if (userPreferences.successCallback) {1123 userPreferences.successCallback();1124 delete userPreferences.successCallback;1125 }1126 mPeer.createNewPeer(participantId, userPreferences);1127 };1128 if (typeof StreamsHandler !== 'undefined') {1129 connection.StreamsHandler = StreamsHandler;1130 }1131 connection.onleave = function(userid) {};1132 connection.invokeSelectFileDialog = function(callback) {1133 var selector = new FileSelector();1134 selector.accept = '*.*';1135 selector.selectSingleFile(callback);1136 };1137 connection.onmute = function(e) {1138 if (!e || !e.mediaElement) {1139 return;1140 }1141 if (e.muteType === 'both' || e.muteType === 'video') {1142 e.mediaElement.src = null;1143 var paused = e.mediaElement.pause();1144 if (typeof paused !== 'undefined') {1145 paused.then(function() {1146 e.mediaElement.poster = e.snapshot || 'https://cdn.webrtc-experiment.com/images/muted.png';1147 });1148 } else {1149 e.mediaElement.poster = e.snapshot || 'https://cdn.webrtc-experiment.com/images/muted.png';1150 }1151 } else if (e.muteType === 'audio') {1152 e.mediaElement.muted = true;1153 }1154 };1155 connection.onunmute = function(e) {1156 if (!e || !e.mediaElement || !e.stream) {1157 return;1158 }1159 if (e.unmuteType === 'both' || e.unmuteType === 'video') {1160 e.mediaElement.poster = null;1161 e.mediaElement.srcObject = e.stream;1162 e.mediaElement.play();1163 } else if (e.unmuteType === 'audio') {1164 e.mediaElement.muted = false;1165 }1166 };1167 connection.onExtraDataUpdated = function(event) {1168 event.status = 'online';1169 connection.onUserStatusChanged(event, true);1170 };1171 connection.getAllParticipants = function(sender) {1172 return connection.peers.getAllParticipants(sender);1173 };1174 if (typeof StreamsHandler !== 'undefined') {1175 StreamsHandler.onSyncNeeded = function(streamid, action, type) {1176 connection.peers.getAllParticipants().forEach(function(participant) {1177 mPeer.onNegotiationNeeded({1178 streamid: streamid,1179 action: action,1180 streamSyncNeeded: true,1181 type: type || 'both'1182 }, participant);1183 });1184 };1185 }1186 connection.connectSocket = function(callback) {1187 connectSocket(callback);1188 };1189 connection.closeSocket = function() {1190 try {1191 io.sockets = {};1192 } catch (e) {};1193 if (!connection.socket) return;1194 if (typeof connection.socket.disconnect === 'function') {1195 connection.socket.disconnect();1196 }1197 if (typeof connection.socket.resetProps === 'function') {1198 connection.socket.resetProps();1199 }1200 connection.socket = null;1201 };1202 connection.getSocket = function(callback) {1203 if (!callback && connection.enableLogs) {1204 console.warn('getSocket.callback paramter is required.');1205 }1206 callback = callback || function() {};1207 if (!connection.socket) {1208 connectSocket(function() {1209 callback(connection.socket);1210 });1211 } else {1212 callback(connection.socket);1213 }1214 return connection.socket; // callback is preferred over return-statement1215 };1216 connection.getRemoteStreams = mPeer.getRemoteStreams;1217 var skipStreams = ['selectFirst', 'selectAll', 'forEach'];1218 connection.streamEvents = {1219 selectFirst: function(options) {1220 return connection.streamEvents.selectAll(options)[0];1221 },1222 selectAll: function(options) {1223 if (!options) {1224 // default will always be all streams1225 options = {1226 local: true,1227 remote: true,1228 isScreen: true,1229 isAudio: true,1230 isVideo: true1231 };1232 }1233 if (options == 'local') {1234 options = {1235 local: true1236 };1237 }1238 if (options == 'remote') {1239 options = {1240 remote: true1241 };1242 }1243 if (options == 'screen') {1244 options = {1245 isScreen: true1246 };1247 }1248 if (options == 'audio') {1249 options = {1250 isAudio: true1251 };1252 }1253 if (options == 'video') {1254 options = {1255 isVideo: true1256 };1257 }1258 var streams = [];1259 Object.keys(connection.streamEvents).forEach(function(key) {1260 var event = connection.streamEvents[key];1261 if (skipStreams.indexOf(key) !== -1) return;1262 var ignore = true;1263 if (options.local && event.type === 'local') {1264 ignore = false;1265 }1266 if (options.remote && event.type === 'remote') {1267 ignore = false;1268 }1269 if (options.isScreen && event.stream.isScreen) {1270 ignore = false;1271 }1272 if (options.isVideo && event.stream.isVideo) {1273 ignore = false;1274 }1275 if (options.isAudio && event.stream.isAudio) {1276 ignore = false;1277 }1278 if (options.userid && event.userid === options.userid) {1279 ignore = false;1280 }1281 if (ignore === false) {1282 streams.push(event);1283 }1284 });1285 return streams;1286 }1287 };1288 connection.socketURL = '@@socketURL'; // generated via config.json1289 connection.socketMessageEvent = '@@socketMessageEvent'; // generated via config.json1290 connection.socketCustomEvent = '@@socketCustomEvent'; // generated via config.json1291 connection.DetectRTC = DetectRTC;1292 connection.setCustomSocketEvent = function(customEvent) {1293 if (customEvent) {1294 connection.socketCustomEvent = customEvent;1295 }1296 if (!connection.socket) {1297 return;1298 }1299 connection.socket.emit('set-custom-socket-event-listener', connection.socketCustomEvent);1300 };1301 connection.getNumberOfBroadcastViewers = function(broadcastId, callback) {1302 if (!connection.socket || !broadcastId || !callback) return;1303 connection.socket.emit('get-number-of-users-in-specific-broadcast', broadcastId, callback);1304 };1305 connection.onNumberOfBroadcastViewersUpdated = function(event) {1306 if (!connection.enableLogs || !connection.isInitiator) return;1307 console.info('Number of broadcast (', event.broadcastId, ') viewers', event.numberOfBroadcastViewers);1308 };1309 connection.onUserStatusChanged = function(event, dontWriteLogs) {1310 if (!!connection.enableLogs && !dontWriteLogs) {1311 console.info(event.userid, event.status);1312 }1313 };1314 connection.getUserMediaHandler = getUserMediaHandler;1315 connection.multiPeersHandler = mPeer;1316 connection.enableLogs = true;1317 connection.setCustomSocketHandler = function(customSocketHandler) {1318 if (typeof SocketConnection !== 'undefined') {1319 SocketConnection = customSocketHandler;1320 }1321 };1322 // default value should be 15k because [old]Firefox's receiving limit is 16k!1323 // however 64k works chrome-to-chrome1324 connection.chunkSize = 40 * 1000;1325 connection.maxParticipantsAllowed = 1000;1326 // eject or leave single user1327 connection.disconnectWith = mPeer.disconnectWith;1328 // check if room exist on server1329 // we will pass roomid to the server and wait for callback (i.e. server's response)1330 connection.checkPresence = function(roomid, callback) {1331 roomid = roomid || connection.sessionid;1332 if (SocketConnection.name === 'SSEConnection') {1333 SSEConnection.checkPresence(roomid, function(isRoomExist, _roomid, extra) {1334 if (!connection.socket) {1335 if (!isRoomExist) {1336 connection.userid = _roomid;1337 }1338 connection.connectSocket(function() {1339 callback(isRoomExist, _roomid, extra);1340 });1341 return;1342 }1343 callback(isRoomExist, _roomid);1344 });1345 return;1346 }1347 if (!connection.socket) {1348 connection.connectSocket(function() {1349 connection.checkPresence(roomid, callback);1350 });1351 return;1352 }1353 connection.socket.emit('check-presence', roomid + '', function(isRoomExist, _roomid, extra) {1354 if (connection.enableLogs) {1355 console.log('checkPresence.isRoomExist: ', isRoomExist, ' roomid: ', _roomid);1356 }1357 callback(isRoomExist, _roomid, extra);1358 });1359 };1360 connection.onReadyForOffer = function(remoteUserId, userPreferences) {1361 connection.multiPeersHandler.createNewPeer(remoteUserId, userPreferences);1362 };1363 connection.setUserPreferences = function(userPreferences) {1364 if (connection.dontAttachStream) {1365 userPreferences.dontAttachLocalStream = true;1366 }1367 if (connection.dontGetRemoteStream) {1368 userPreferences.dontGetRemoteStream = true;1369 }1370 return userPreferences;1371 };1372 connection.updateExtraData = function() {1373 connection.socket.emit('extra-data-updated', connection.extra);1374 };1375 connection.enableScalableBroadcast = false;1376 connection.maxRelayLimitPerUser = 3; // each broadcast should serve only 3 users1377 connection.dontCaptureUserMedia = false;1378 connection.dontAttachStream = false;1379 connection.dontGetRemoteStream = false;1380 connection.onReConnecting = function(event) {1381 if (connection.enableLogs) {1382 console.info('ReConnecting with', event.userid, '...');1383 }1384 };1385 connection.beforeAddingStream = function(stream) {1386 return stream;1387 };1388 connection.beforeRemovingStream = function(stream) {1389 return stream;1390 };1391 if (typeof isChromeExtensionAvailable !== 'undefined') {1392 connection.checkIfChromeExtensionAvailable = isChromeExtensionAvailable;1393 }1394 if (typeof isFirefoxExtensionAvailable !== 'undefined') {1395 connection.checkIfChromeExtensionAvailable = isFirefoxExtensionAvailable;1396 }1397 if (typeof getChromeExtensionStatus !== 'undefined') {1398 connection.getChromeExtensionStatus = getChromeExtensionStatus;1399 }1400 connection.modifyScreenConstraints = function(screen_constraints) {1401 return screen_constraints;1402 };1403 connection.onPeerStateChanged = function(state) {1404 if (connection.enableLogs) {1405 if (state.iceConnectionState.search(/closed|failed/gi) !== -1) {1406 console.error('Peer connection is closed between you & ', state.userid, state.extra, 'state:', state.iceConnectionState);1407 }1408 }1409 };1410 connection.isOnline = true;1411 listenEventHandler('online', function() {1412 connection.isOnline = true;1413 });1414 listenEventHandler('offline', function() {1415 connection.isOnline = false;1416 });1417 connection.isLowBandwidth = false;1418 if (navigator && navigator.connection && navigator.connection.type) {1419 connection.isLowBandwidth = navigator.connection.type.toString().toLowerCase().search(/wifi|cell/g) !== -1;1420 if (connection.isLowBandwidth) {1421 connection.bandwidth = {1422 audio: false,1423 video: false,1424 screen: false1425 };1426 if (connection.mediaConstraints.audio && connection.mediaConstraints.audio.optional && connection.mediaConstraints.audio.optional.length) {1427 var newArray = [];1428 connection.mediaConstraints.audio.optional.forEach(function(opt) {1429 if (typeof opt.bandwidth === 'undefined') {1430 newArray.push(opt);1431 }1432 });1433 connection.mediaConstraints.audio.optional = newArray;1434 }1435 if (connection.mediaConstraints.video && connection.mediaConstraints.video.optional && connection.mediaConstraints.video.optional.length) {1436 var newArray = [];1437 connection.mediaConstraints.video.optional.forEach(function(opt) {1438 if (typeof opt.bandwidth === 'undefined') {1439 newArray.push(opt);1440 }1441 });1442 connection.mediaConstraints.video.optional = newArray;1443 }1444 }1445 }1446 connection.getExtraData = function(remoteUserId, callback) {1447 if (!remoteUserId) throw 'remoteUserId is required.';1448 if (typeof callback === 'function') {1449 connection.socket.emit('get-remote-user-extra-data', remoteUserId, function(extra, remoteUserId, error) {1450 callback(extra, remoteUserId, error);1451 });1452 return;1453 }1454 if (!connection.peers[remoteUserId]) {1455 if (connection.peersBackup[remoteUserId]) {1456 return connection.peersBackup[remoteUserId].extra;1457 }1458 return {};1459 }1460 return connection.peers[remoteUserId].extra;1461 };1462 if (!!forceOptions.autoOpenOrJoin) {1463 connection.openOrJoin(connection.sessionid);1464 }1465 connection.onUserIdAlreadyTaken = function(useridAlreadyTaken, yourNewUserId) {1466 // via #6831467 connection.close();1468 connection.closeSocket();1469 connection.isInitiator = false;1470 connection.userid = connection.token();1471 connection.join(connection.sessionid);1472 if (connection.enableLogs) {1473 console.warn('Userid already taken.', useridAlreadyTaken, 'Your new userid:', connection.userid);1474 }1475 };1476 connection.trickleIce = true;1477 connection.version = '@@version';1478 connection.onSettingLocalDescription = function(event) {1479 if (connection.enableLogs) {1480 console.info('Set local description for remote user', event.userid);1481 }1482 };1483 connection.resetScreen = function() {1484 sourceId = null;1485 if (DetectRTC && DetectRTC.screen) {1486 delete DetectRTC.screen.sourceId;1487 }1488 currentUserMediaRequest = {1489 streams: [],1490 mutex: false,1491 queueRequests: []1492 };1493 };1494 // if disabled, "event.mediaElement" for "onstream" will be NULL1495 connection.autoCreateMediaElement = true;1496 // set password1497 connection.password = null;1498 // set password1499 connection.setPassword = function(password, callback) {1500 callback = callback || function() {};1501 if (connection.socket) {1502 connection.socket.emit('set-password', password, callback);1503 } else {1504 connection.password = password;1505 callback(true, connection.sessionid, null);1506 }1507 };1508 connection.onSocketDisconnect = function(event) {1509 if (connection.enableLogs) {1510 console.warn('socket.io connection is closed');1511 }1512 };1513 connection.onSocketError = function(event) {1514 if (connection.enableLogs) {1515 console.warn('socket.io connection is failed');1516 }1517 };1518 // error messages1519 connection.errors = {1520 ROOM_NOT_AVAILABLE: 'Room not available',1521 INVALID_PASSWORD: 'Invalid password',1522 USERID_NOT_AVAILABLE: 'User ID does not exist',1523 ROOM_PERMISSION_DENIED: 'Room permission denied',1524 ROOM_FULL: 'Room full',1525 DID_NOT_JOIN_ANY_ROOM: 'Did not join any room yet',1526 INVALID_SOCKET: 'Invalid socket',1527 PUBLIC_IDENTIFIER_MISSING: 'publicRoomIdentifier is required',1528 INVALID_ADMIN_CREDENTIAL: 'Invalid username or password attempted'1529 };...
jquery.signalR-0.5.3.js
Source:jquery.signalR-0.5.3.js
...1193 url = "/signalr";1194 }1195 return new hubConnection.fn.init(url);1196 }1197 hubConnection.fn = hubConnection.prototype = $.connection();1198 hubConnection.fn.init = function (url, qs, logging) {1199 var connection = this;1200 // Call the base constructor1201 $.signalR.fn.init.call(connection, url, qs, logging);1202 // Object to store hub proxies for this connection1203 connection.proxies = {};1204 // Wire up the sending handler1205 connection.sending(function () {1206 // Set the connection's data object with all the hub proxies with active subscriptions.1207 // These proxies will receive notifications from the server.1208 var subscribedHubs = [];1209 $.each(this.proxies, function (key) {1210 if (this.subscribed) {1211 subscribedHubs.push({ name: key });...
jquery.signalR-0.5.2.js
Source:jquery.signalR-0.5.2.js
1/*!2* SignalR JavaScript Library v0.5.23* http://signalr.net/4*5* Copyright David Fowler and Damian Edwards 20126* Licensed under the MIT.7* https://github.com/SignalR/SignalR/blob/master/LICENSE.md8*/9/// <reference path="jquery-1.6.2.js" />10(function ($, window) {11 /// <param name="$" type="jQuery" />12 "use strict";13 if (typeof ($) !== "function") {14 // no jQuery!15 throw "SignalR: jQuery not found. Please ensure jQuery is referenced before the SignalR.js file.";16 }17 if (!window.JSON) {18 // no JSON!19 throw "SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.";20 }21 var signalR,22 _connection,23 events = {24 onStart: "onStart",25 onStarting: "onStarting",26 onSending: "onSending",27 onReceived: "onReceived",28 onError: "onError",29 onReconnect: "onReconnect",30 onStateChanged: "onStateChanged",31 onDisconnect: "onDisconnect"32 },33 log = function (msg, logging) {34 if (logging === false) {35 return;36 }37 var m;38 if (typeof (window.console) === "undefined") {39 return;40 }41 m = "[" + new Date().toTimeString() + "] SignalR: " + msg;42 if (window.console.debug) {43 window.console.debug(m);44 } else if (window.console.log) {45 window.console.log(m);46 }47 },48 isCrossDomain = function (url) {49 var link;50 url = $.trim(url);51 if (url.indexOf("http") !== 0) {52 return false;53 }54 // Create an anchor tag.55 link = window.document.createElement("a");56 link.href = url;57 return link.protocol + link.host !== window.location.protocol + window.location.host;58 },59 changeState = function (connection, expectedState, newState) {60 if (expectedState === connection.state) {61 // REVIEW: Should event fire before or after the state change actually occurs?62 $(connection).trigger(events.onStateChanged, [{ oldState: connection.state, newState: newState }]);63 connection.state = newState;64 return true;65 }66 return false;67 },68 isDisconnecting = function (connection) {69 return connection.state === signalR.connectionState.disconnected;70 };71 signalR = function (url, qs, logging) {72 /// <summary>Creates a new SignalR connection for the given url</summary>73 /// <param name="url" type="String">The URL of the long polling endpoint</param>74 /// <param name="qs" type="Object">75 /// [Optional] Custom querystring parameters to add to the connection URL.76 /// If an object, every non-function member will be added to the querystring.77 /// If a string, it's added to the QS as specified.78 /// </param>79 /// <param name="logging" type="Boolean">80 /// [Optional] A flag indicating whether connection logging is enabled to the browser81 /// console/log. Defaults to false.82 /// </param>83 /// <returns type="signalR" />84 return new signalR.fn.init(url, qs, logging);85 };86 signalR.connectionState = {87 connecting: 0,88 connected: 1,89 reconnecting: 2,90 disconnected: 491 };92 signalR.fn = signalR.prototype = {93 init: function (url, qs, logging) {94 this.url = url;95 this.qs = qs;96 if (typeof (logging) === "boolean") {97 this.logging = logging;98 }99 },100 ajaxDataType: "json",101 logging: false,102 state: signalR.connectionState.disconnected,103 reconnectDelay: 2000,104 start: function (options, callback) {105 /// <summary>Starts the connection</summary>106 /// <param name="options" type="Object">Options map</param>107 /// <param name="callback" type="Function">A callback function to execute when the connection has started</param>108 var connection = this,109 config = {110 transport: "auto",111 jsonp: false112 },113 initialize,114 deferred = $.Deferred(),115 parser = window.document.createElement("a");116 if (changeState(connection,117 signalR.connectionState.disconnected,118 signalR.connectionState.connecting) === false) {119 // Already started, just return120 deferred.resolve(connection);121 return deferred.promise();122 }123 if ($.type(options) === "function") {124 // Support calling with single callback parameter125 callback = options;126 } else if ($.type(options) === "object") {127 $.extend(config, options);128 if ($.type(config.callback) === "function") {129 callback = config.callback;130 }131 }132 // Resolve the full url133 parser.href = connection.url;134 if (!parser.protocol || parser.protocol === ":") {135 connection.protocol = window.document.location.protocol;136 connection.host = window.document.location.host;137 connection.baseUrl = connection.protocol + "//" + connection.host;138 }139 else {140 connection.protocol = parser.protocol;141 connection.host = parser.host;142 connection.baseUrl = parser.protocol + "//" + parser.host;143 }144 // Set the websocket protocol145 connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";146 if (isCrossDomain(connection.url)) {147 connection.log("Auto detected cross domain url.");148 if (config.transport === "auto") {149 // If you didn't say you wanted to use jsonp, determine if it's your only choice150 // i.e. if your browser doesn't supports CORS151 if (!config.jsonp) {152 config.jsonp = !$.support.cors;153 if (config.jsonp) {154 connection.log("Using jsonp because this browser doesn't support CORS");155 }156 }157 // If we're using jsonp thn just change to longpolling158 if (config.jsonp === true) {159 config.transport = "longPolling";160 }161 else {162 // Otherwise try webSockets and longPolling since SSE doesn't support CORS163 // TODO: Support XDM with foreverFrame164 config.transport = ["webSockets", "longPolling"];165 }166 }167 }168 connection.ajaxDataType = config.jsonp ? "jsonp" : "json";169 $(connection).bind(events.onStart, function (e, data) {170 if ($.type(callback) === "function") {171 callback.call(connection);172 }173 deferred.resolve(connection);174 });175 initialize = function (transports, index) {176 index = index || 0;177 if (index >= transports.length) {178 if (!connection.transport) {179 // No transport initialized successfully180 deferred.reject("SignalR: No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.");181 }182 return;183 }184 var transportName = transports[index],185 transport = $.type(transportName) === "object" ? transportName : signalR.transports[transportName];186 transport.start(connection, function () { // success187 connection.transport = transport;188 changeState(connection,189 signalR.connectionState.connecting,190 signalR.connectionState.connected);191 $(connection).trigger(events.onStart);192 $(window).unload(function () { // failure193 connection.stop(false /* async */);194 });195 }, function () {196 initialize(transports, index + 1);197 });198 };199 window.setTimeout(function () {200 var url = connection.url + "/negotiate";201 connection.log("Negotiating with '" + url + "'.");202 $.ajax({203 url: url,204 global: false,205 cache: false,206 type: "GET",207 data: {},208 dataType: connection.ajaxDataType,209 error: function (error) {210 $(connection).trigger(events.onError, [error.responseText]);211 deferred.reject("SignalR: Error during negotiation request: " + error.responseText);212 // Stop the connection if negotiate failed213 connection.stop();214 },215 success: function (res) {216 connection.appRelativeUrl = res.Url;217 connection.id = res.ConnectionId;218 connection.webSocketServerUrl = res.WebSocketServerUrl;219 if (!res.ProtocolVersion || res.ProtocolVersion !== "1.0") {220 $(connection).trigger(events.onError, "SignalR: Incompatible protocol version.");221 deferred.reject("SignalR: Incompatible protocol version.");222 return;223 }224 $(connection).trigger(events.onStarting);225 var transports = [],226 supportedTransports = [];227 $.each(signalR.transports, function (key) {228 if (key === "webSockets" && !res.TryWebSockets) {229 // Server said don't even try WebSockets, but keep processing the loop230 return true;231 }232 supportedTransports.push(key);233 });234 if ($.isArray(config.transport)) {235 // ordered list provided236 $.each(config.transport, function () {237 var transport = this;238 if ($.type(transport) === "object" || ($.type(transport) === "string" && $.inArray("" + transport, supportedTransports) >= 0)) {239 transports.push($.type(transport) === "string" ? "" + transport : transport);240 }241 });242 } else if ($.type(config.transport) === "object" ||243 $.inArray(config.transport, supportedTransports) >= 0) {244 // specific transport provided, as object or a named transport, e.g. "longPolling"245 transports.push(config.transport);246 } else { // default "auto"247 transports = supportedTransports;248 }249 initialize(transports);250 }251 });252 }, 0);253 return deferred.promise();254 },255 starting: function (callback) {256 /// <summary>Adds a callback that will be invoked before the connection is started</summary>257 /// <param name="callback" type="Function">A callback function to execute when the connection is starting</param>258 /// <returns type="signalR" />259 var connection = this,260 $connection = $(connection);261 $connection.bind(events.onStarting, function (e, data) {262 callback.call(connection);263 // Unbind immediately, we don't want to call this callback again264 $connection.unbind(events.onStarting);265 });266 return connection;267 },268 send: function (data) {269 /// <summary>Sends data over the connection</summary>270 /// <param name="data" type="String">The data to send over the connection</param>271 /// <returns type="signalR" />272 var connection = this;273 if (connection.state === signalR.connectionState.disconnected) {274 // Connection hasn't been started yet275 throw "SignalR: Connection must be started before data can be sent. Call .start() before .send()";276 }277 if (connection.state === signalR.connectionState.connecting) {278 // Connection hasn't been started yet279 throw "SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.";280 }281 connection.transport.send(connection, data);282 // REVIEW: Should we return deferred here?283 return connection;284 },285 sending: function (callback) {286 /// <summary>Adds a callback that will be invoked before anything is sent over the connection</summary>287 /// <param name="callback" type="Function">A callback function to execute before each time data is sent on the connection</param>288 /// <returns type="signalR" />289 var connection = this;290 $(connection).bind(events.onSending, function (e, data) {291 callback.call(connection);292 });293 return connection;294 },295 received: function (callback) {296 /// <summary>Adds a callback that will be invoked after anything is received over the connection</summary>297 /// <param name="callback" type="Function">A callback function to execute when any data is received on the connection</param>298 /// <returns type="signalR" />299 var connection = this;300 $(connection).bind(events.onReceived, function (e, data) {301 callback.call(connection, data);302 });303 return connection;304 },305 stateChanged: function (callback) {306 /// <summary>Adds a callback that will be invoked when the connection state changes</summary>307 /// <param name="callback" type="Function">A callback function to execute when the connection state changes</param>308 /// <returns type="signalR" />309 var connection = this;310 $(connection).bind(events.onStateChanged, function (e, data) {311 callback.call(connection, data);312 });313 return connection;314 },315 error: function (callback) {316 /// <summary>Adds a callback that will be invoked after an error occurs with the connection</summary>317 /// <param name="callback" type="Function">A callback function to execute when an error occurs on the connection</param>318 /// <returns type="signalR" />319 var connection = this;320 $(connection).bind(events.onError, function (e, data) {321 callback.call(connection, data);322 });323 return connection;324 },325 disconnected: function (callback) {326 /// <summary>Adds a callback that will be invoked when the client disconnects</summary>327 /// <param name="callback" type="Function">A callback function to execute when the connection is broken</param>328 /// <returns type="signalR" />329 var connection = this;330 $(connection).bind(events.onDisconnect, function (e, data) {331 callback.call(connection);332 });333 return connection;334 },335 reconnected: function (callback) {336 /// <summary>Adds a callback that will be invoked when the underlying transport reconnects</summary>337 /// <param name="callback" type="Function">A callback function to execute when the connection is restored</param>338 /// <returns type="signalR" />339 var connection = this;340 $(connection).bind(events.onReconnect, function (e, data) {341 callback.call(connection);342 });343 return connection;344 },345 stop: function (async) {346 /// <summary>Stops listening</summary>347 /// <returns type="signalR" />348 var connection = this;349 if (connection.state === signalR.connectionState.disconnected) {350 return;351 }352 try {353 if (connection.transport) {354 connection.transport.abort(connection, async);355 connection.transport.stop(connection);356 connection.transport = null;357 }358 // Trigger the disconnect event359 $(connection).trigger(events.onDisconnect);360 delete connection.messageId;361 delete connection.groups;362 }363 finally {364 changeState(connection, connection.state, signalR.connectionState.disconnected);365 }366 return connection;367 },368 log: function (msg) {369 log(msg, this.logging);370 }371 };372 signalR.fn.init.prototype = signalR.fn;373 // Transports374 var transportLogic = {375 addQs: function (url, connection) {376 if (!connection.qs) {377 return url;378 }379 if (typeof (connection.qs) === "object") {380 return url + "&" + $.param(connection.qs);381 }382 if (typeof (connection.qs) === "string") {383 return url + "&" + connection.qs;384 }385 return url + "&" + window.escape(connection.qs.toString());386 },387 getUrl: function (connection, transport, reconnecting, appendReconnectUrl) {388 /// <summary>Gets the url for making a GET based connect request</summary>389 var baseUrl = transport === "webSockets" ? "" : connection.baseUrl,390 url = baseUrl + connection.appRelativeUrl,391 qs = "transport=" + transport + "&connectionId=" + window.escape(connection.id);392 if (connection.data) {393 qs += "&connectionData=" + window.escape(connection.data);394 }395 if (!reconnecting) {396 url = url + "/connect";397 } else {398 if (appendReconnectUrl) {399 url = url + "/reconnect";400 }401 if (connection.messageId) {402 qs += "&messageId=" + connection.messageId;403 }404 if (connection.groups) {405 qs += "&groups=" + window.escape(JSON.stringify(connection.groups));406 }407 }408 url += "?" + qs;409 url = this.addQs(url, connection);410 url += "&tid=" + Math.floor(Math.random() * 11);411 return url;412 },413 ajaxSend: function (connection, data) {414 var url = connection.url + "/send" + "?transport=" + connection.transport.name + "&connectionId=" + window.escape(connection.id);415 url = this.addQs(url, connection);416 $.ajax({417 url: url,418 global: false,419 type: "POST",420 dataType: connection.ajaxDataType,421 data: {422 data: data423 },424 success: function (result) {425 if (result) {426 $(connection).trigger(events.onReceived, [result]);427 }428 },429 error: function (errData, textStatus) {430 if (textStatus === "abort" ||431 (textStatus === "parsererror" && connection.ajaxDataType === "jsonp")) {432 // The parsererror happens for sends that don't return any data, and hence433 // don't write the jsonp callback to the response. This is harder to fix on the server434 // so just hack around it on the client for now.435 return;436 }437 $(connection).trigger(events.onError, [errData]);438 }439 });440 },441 ajaxAbort: function (connection, async) {442 if (typeof (connection.transport) === "undefined") {443 return;444 }445 // Async by default unless explicitly overidden446 async = typeof async === "undefined" ? true : async;447 var url = connection.url + "/abort" + "?transport=" + connection.transport.name + "&connectionId=" + window.escape(connection.id);448 url = this.addQs(url, connection);449 $.ajax({450 url: url,451 async: async,452 timeout: 1000,453 global: false,454 type: "POST",455 dataType: connection.ajaxDataType,456 data: {}457 });458 connection.log("Fired ajax abort async = " + async);459 },460 processMessages: function (connection, data) {461 var $connection = $(connection);462 if (!data) {463 return;464 }465 if (data.Disconnect) {466 connection.log("Disconnect command received from server");467 // Disconnected by the server468 connection.stop();469 return;470 }471 if (data.Messages) {472 $.each(data.Messages, function () {473 try {474 $connection.trigger(events.onReceived, [this]);475 }476 catch (e) {477 connection.log("Error raising received " + e);478 $(connection).trigger(events.onError, [e]);479 }480 });481 }482 if (data.MessageId) {483 connection.messageId = data.MessageId;484 }485 if (data.TransportData) {486 connection.groups = data.TransportData.Groups;487 }488 },489 foreverFrame: {490 count: 0,491 connections: {}492 }493 };494 signalR.transports = {495 webSockets: {496 name: "webSockets",497 send: function (connection, data) {498 connection.socket.send(data);499 },500 start: function (connection, onSuccess, onFailed) {501 var url,502 opened = false,503 that = this,504 reconnecting = !onSuccess,505 protocol,506 $connection = $(connection);507 if (window.MozWebSocket) {508 window.WebSocket = window.MozWebSocket;509 }510 if (!window.WebSocket) {511 onFailed();512 return;513 }514 if (!connection.socket) {515 if (connection.webSocketServerUrl) {516 url = connection.webSocketServerUrl;517 }518 else {519 url = connection.wsProtocol + connection.host;520 }521 // Build the url522 $(connection).trigger(events.onSending);523 url += transportLogic.getUrl(connection, this.name, reconnecting);524 connection.log("Connecting to websocket endpoint '" + url + "'");525 connection.socket = new window.WebSocket(url);526 connection.socket.onopen = function () {527 opened = true;528 connection.log("Websocket opened");529 if (onSuccess) {530 onSuccess();531 }532 else {533 if (changeState(connection,534 signalR.connectionState.reconnecting,535 signalR.connectionState.connected) === true) {536 $connection.trigger(events.onReconnect);537 }538 }539 };540 connection.socket.onclose = function (event) {541 if (!opened) {542 if (onFailed) {543 onFailed();544 }545 else if(reconnecting) {546 that.reconnect(connection);547 }548 return;549 }550 else if (typeof event.wasClean !== "undefined" && event.wasClean === false) {551 // Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but552 // I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers.553 $(connection).trigger(events.onError, [event.reason]);554 connection.log("Unclean disconnect from websocket." + event.reason);555 }556 else {557 connection.log("Websocket closed");558 }559 that.reconnect(connection);560 };561 connection.socket.onmessage = function (event) {562 var data = window.JSON.parse(event.data),563 $connection;564 if (data) {565 $connection = $(connection);566 if (data.Messages) {567 transportLogic.processMessages(connection, data);568 } else {569 $connection.trigger(events.onReceived, [data]);570 }571 }572 };573 }574 },575 reconnect: function (connection) {576 this.stop(connection);577 if (connection.state === signalR.connectionState.reconnecting ||578 changeState(connection,579 signalR.connectionState.connected,580 signalR.connectionState.reconnecting) === true) {581 connection.log("Websocket reconnecting");582 this.start(connection);583 }584 },585 stop: function (connection) {586 if (connection.socket !== null) {587 connection.log("Closing the Websocket");588 connection.socket.close();589 connection.socket = null;590 }591 },592 abort: function (connection) {593 }594 },595 serverSentEvents: {596 name: "serverSentEvents",597 timeOut: 3000,598 start: function (connection, onSuccess, onFailed) {599 var that = this,600 opened = false,601 $connection = $(connection),602 reconnecting = !onSuccess,603 url,604 connectTimeOut;605 if (connection.eventSource) {606 connection.log("The connection already has an event source. Stopping it.");607 connection.stop();608 }609 if (!window.EventSource) {610 if (onFailed) {611 connection.log("This browser doesn't support SSE.");612 onFailed();613 }614 return;615 }616 $connection.trigger(events.onSending);617 url = transportLogic.getUrl(connection, this.name, reconnecting);618 try {619 connection.log("Attempting to connect to SSE endpoint '" + url + "'");620 connection.eventSource = new window.EventSource(url);621 }622 catch (e) {623 connection.log("EventSource failed trying to connect with error " + e.Message);624 if (onFailed) {625 // The connection failed, call the failed callback626 onFailed();627 }628 else {629 $connection.trigger(events.onError, [e]);630 if (reconnecting) {631 // If we were reconnecting, rather than doing initial connect, then try reconnect again632 that.reconnect(connection);633 }634 }635 return;636 }637 // After connecting, if after the specified timeout there's no response stop the connection638 // and raise on failed639 connectTimeOut = window.setTimeout(function () {640 if (opened === false) {641 connection.log("EventSource timed out trying to connect");642 connection.log("EventSource readyState: " + connection.eventSource.readyState);643 if (!reconnecting) {644 that.stop(connection);645 }646 if (reconnecting) {647 // If we're reconnecting and the event source is attempting to connect,648 // don't keep retrying. This causes duplicate connections to spawn.649 if (connection.eventSource.readyState !== window.EventSource.CONNECTING &&650 connection.eventSource.readyState !== window.EventSource.OPEN) {651 // If we were reconnecting, rather than doing initial connect, then try reconnect again652 that.reconnect(connection);653 }654 } else if (onFailed) {655 onFailed();656 }657 }658 },659 that.timeOut);660 connection.eventSource.addEventListener("open", function (e) {661 connection.log("EventSource connected");662 if (connectTimeOut) {663 window.clearTimeout(connectTimeOut);664 }665 if (opened === false) {666 opened = true;667 if (onSuccess) {668 onSuccess();669 }670 if (reconnecting) {671 if (changeState(connection,672 signalR.connectionState.reconnecting,673 signalR.connectionState.connected) === true) {674 $connection.trigger(events.onReconnect);675 }676 }677 }678 }, false);679 connection.eventSource.addEventListener("message", function (e) {680 // process messages681 if (e.data === "initialized") {682 return;683 }684 transportLogic.processMessages(connection, window.JSON.parse(e.data));685 }, false);686 connection.eventSource.addEventListener("error", function (e) {687 if (!opened) {688 if (onFailed) {689 onFailed();690 }691 return;692 }693 connection.log("EventSource readyState: " + connection.eventSource.readyState);694 if (e.eventPhase === window.EventSource.CLOSED) {695 // We don't use the EventSource's native reconnect function as it696 // doesn't allow us to change the URL when reconnecting. We need697 // to change the URL to not include the /connect suffix, and pass698 // the last message id we received.699 connection.log("EventSource reconnecting due to the server connection ending");700 that.reconnect(connection);701 } else {702 // connection error703 connection.log("EventSource error");704 $connection.trigger(events.onError);705 }706 }, false);707 },708 reconnect: function (connection) {709 var that = this;710 window.setTimeout(function () {711 that.stop(connection);712 if (connection.state === signalR.connectionState.reconnecting ||713 changeState(connection,714 signalR.connectionState.connected,715 signalR.connectionState.reconnecting) === true) {716 connection.log("EventSource reconnecting");717 that.start(connection);718 }719 }, connection.reconnectDelay);720 },721 send: function (connection, data) {722 transportLogic.ajaxSend(connection, data);723 },724 stop: function (connection) {725 if (connection && connection.eventSource) {726 connection.log("EventSource calling close()");727 connection.eventSource.close();728 connection.eventSource = null;729 delete connection.eventSource;730 }731 },732 abort: function (connection, async) {733 transportLogic.ajaxAbort(connection, async);734 }735 },736 foreverFrame: {737 name: "foreverFrame",738 timeOut: 3000,739 start: function (connection, onSuccess, onFailed) {740 var that = this,741 frameId = (transportLogic.foreverFrame.count += 1),742 url,743 connectTimeOut,744 frame = $("<iframe data-signalr-connection-id='" + connection.id + "' style='position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;'></iframe>");745 if (window.EventSource) {746 // If the browser supports SSE, don't use Forever Frame747 if (onFailed) {748 connection.log("This brower supports SSE, skipping Forever Frame.");749 onFailed();750 }751 return;752 }753 $(connection).trigger(events.onSending);754 // Build the url755 url = transportLogic.getUrl(connection, this.name);756 url += "&frameId=" + frameId;757 frame.prop("src", url);758 transportLogic.foreverFrame.connections[frameId] = connection;759 connection.log("Binding to iframe's readystatechange event.");760 frame.bind("readystatechange", function () {761 if ($.inArray(this.readyState, ["loaded", "complete"]) >= 0) {762 connection.log("Forever frame iframe readyState changed to " + this.readyState + ", reconnecting");763 that.reconnect(connection);764 }765 });766 connection.frame = frame[0];767 connection.frameId = frameId;768 if (onSuccess) {769 connection.onSuccess = onSuccess;770 }771 $("body").append(frame);772 // After connecting, if after the specified timeout there's no response stop the connection773 // and raise on failed774 // REVIEW: Why is connectTimeOut set here and never used again?775 connectTimeOut = window.setTimeout(function () {776 if (connection.onSuccess) {777 connection.log("Failed to connect using forever frame source, it timed out after " + that.timeOut + "ms.");778 that.stop(connection);779 if (onFailed) {780 onFailed();781 }782 }783 }, that.timeOut);784 },785 reconnect: function (connection) {786 var that = this;787 window.setTimeout(function () {788 if (!connection.frame) {789 return;790 }791 if (connection.state === signalR.connectionState.reconnecting ||792 changeState(connection,793 signalR.connectionState.connected,794 signalR.connectionState.reconnecting) === true) {795 var frame = connection.frame,796 src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;797 connection.log("Upating iframe src to '" + src + "'.");798 frame.src = src;799 }800 }, connection.reconnectDelay);801 },802 send: function (connection, data) {803 transportLogic.ajaxSend(connection, data);804 },805 receive: function (connection, data) {806 var cw;807 transportLogic.processMessages(connection, data);808 // Delete the script & div elements809 connection.frameMessageCount = (connection.frameMessageCount || 0) + 1;810 if (connection.frameMessageCount > 50) {811 connection.frameMessageCount = 0;812 cw = connection.frame.contentWindow || connection.frame.contentDocument;813 if (cw && cw.document) {814 $("body", cw.document).empty();815 }816 }817 },818 stop: function (connection) {819 var cw = null;820 if (connection.frame) {821 if (connection.frame.stop) {822 connection.frame.stop();823 } else {824 cw = connection.frame.contentWindow || connection.frame.contentDocument;825 if (cw.document && cw.document.execCommand) {826 cw.document.execCommand("Stop");827 }828 }829 $(connection.frame).remove();830 delete transportLogic.foreverFrame.connections[connection.frameId];831 connection.frame = null;832 connection.frameId = null;833 delete connection.frame;834 delete connection.frameId;835 connection.log("Stopping forever frame");836 }837 },838 abort: function (connection, async) {839 transportLogic.ajaxAbort(connection, async);840 },841 getConnection: function (id) {842 return transportLogic.foreverFrame.connections[id];843 },844 started: function (connection) {845 if (connection.onSuccess) {846 connection.onSuccess();847 connection.onSuccess = null;848 delete connection.onSuccess;849 }850 else {851 if (changeState(connection,852 signalR.connectionState.reconnecting,853 signalR.connectionState.connected) === true) {854 // If there's no onSuccess handler we assume this is a reconnect855 $(connection).trigger(events.onReconnect);856 }857 }858 }859 },860 longPolling: {861 name: "longPolling",862 reconnectDelay: 3000,863 start: function (connection, onSuccess, onFailed) {864 /// <summary>Starts the long polling connection</summary>865 /// <param name="connection" type="signalR">The SignalR connection to start</param>866 var that = this,867 initialConnectFired = false;868 if (connection.pollXhr) {869 connection.log("Polling xhr requests already exists, aborting.");870 connection.stop();871 }872 connection.messageId = null;873 window.setTimeout(function () {874 (function poll(instance, raiseReconnect) {875 $(instance).trigger(events.onSending);876 var messageId = instance.messageId,877 connect = (messageId === null),878 reconnecting = !connect,879 url = transportLogic.getUrl(instance, that.name, reconnecting, raiseReconnect),880 reconnectTimeOut = null,881 reconnectFired = false;882 if (reconnecting === true && raiseReconnect === true) {883 if (connection.state !== signalR.connectionState.reconnecting &&884 changeState(connection,885 signalR.connectionState.connected,886 signalR.connectionState.reconnecting) === false) {887 return;888 }889 }890 connection.log("Attempting to connect to '" + url + "' using longPolling.");891 instance.pollXhr = $.ajax({892 url: url,893 global: false,894 type: "GET",895 dataType: connection.ajaxDataType,896 success: function (data) {897 var delay = 0,898 timedOutReceived = false;899 if (initialConnectFired == false) {900 onSuccess();901 initialConnectFired = true;902 }903 if (raiseReconnect === true) {904 // Fire the reconnect event if it hasn't been fired as yet905 if (reconnectFired === false) {906 connection.log("Raising the reconnect event");907 if (changeState(connection,908 signalR.connectionState.reconnecting,909 signalR.connectionState.connected) === true) {910 $(instance).trigger(events.onReconnect);911 reconnectFired = true;912 }913 }914 }915 transportLogic.processMessages(instance, data);916 if (data &&917 data.TransportData &&918 $.type(data.TransportData.LongPollDelay) === "number") {919 delay = data.TransportData.LongPollDelay;920 }921 if (data && data.TimedOut) {922 timedOutReceived = data.TimedOut;923 }924 if (data && data.Disconnect) {925 return;926 }927 if (isDisconnecting(instance) === true) {928 return;929 }930 if (delay > 0) {931 window.setTimeout(function () {932 poll(instance, timedOutReceived);933 }, delay);934 } else {935 poll(instance, timedOutReceived);936 }937 },938 error: function (data, textStatus) {939 if (textStatus === "abort") {940 connection.log("Aborted xhr requst.");941 return;942 }943 connection.log("An error occurred using longPolling. Status = " + textStatus + ". " + data.responseText);944 if (reconnectTimeOut) {945 // If the request failed then we clear the timeout so that the946 // reconnect event doesn't get fired947 clearTimeout(reconnectTimeOut);948 }949 $(instance).trigger(events.onError, [data.responseText]);950 window.setTimeout(function () {951 if (isDisconnecting(instance) === false) {952 poll(instance, true);953 }954 }, connection.reconnectDelay);955 }956 });957 if (raiseReconnect === true) {958 reconnectTimeOut = window.setTimeout(function () {959 if (reconnectFired === false) {960 if (changeState(connection,961 signalR.connectionState.reconnecting,962 signalR.connectionState.connected) === true) {963 $(instance).trigger(events.onReconnect);964 reconnectFired = true;965 }966 }967 },968 that.reconnectDelay);969 }970 } (connection));971 // Now connected972 // There's no good way know when the long poll has actually started so973 // we assume it only takes around 150ms (max) to start the connection974 window.setTimeout(function () {975 if (initialConnectFired === false) {976 onSuccess();977 initialConnectFired = true;978 }979 }, 150);980 }, 250); // Have to delay initial poll so Chrome doesn't show loader spinner in tab981 },982 send: function (connection, data) {983 transportLogic.ajaxSend(connection, data);984 },985 stop: function (connection) {986 /// <summary>Stops the long polling connection</summary>987 /// <param name="connection" type="signalR">The SignalR connection to stop</param>988 if (connection.pollXhr) {989 connection.pollXhr.abort();990 connection.pollXhr = null;991 delete connection.pollXhr;992 }993 },994 abort: function (connection, async) {995 transportLogic.ajaxAbort(connection, async);996 }997 }998 };999 signalR.noConflict = function () {1000 /// <summary>Reinstates the original value of $.connection and returns the signalR object for manual assignment</summary>1001 /// <returns type="signalR" />1002 if ($.connection === signalR) {1003 $.connection = _connection;1004 }1005 return signalR;1006 };1007 if ($.connection) {1008 _connection = $.connection;1009 }1010 $.connection = $.signalR = signalR;...
voltdb.service.js
Source:voltdb.service.js
12(function (window) {34 var procedures = {};5 var tips = $(".validateTips");6 var server = VoltDBConfig.GetDefaultServerIP();7 var port = "8080";8 var user = "";9 var password = "";10 var admin = true;11 var isHashedPassword = true;12 this.connection = null;13 var iVoltDbService = (function () {14 var _connection = connection;1516 this.TestConnection = function (lServerName, lPort, lUsername, lPassword, lAdmin, onConnectionAdded, isLoginTest) {17 try {18 var serverName = lServerName != null ? lServerName : server;19 var portId = lPort != null ? lPort : port;2021 VoltDBCore.TestConnection(serverName, portId, lAdmin, lUsername, lPassword, isHashedPassword, "DATABASE_LOGIN", function (result, response) {22 onConnectionAdded(result, response);23 }, isLoginTest);2425 } catch (e) {26 console.log(e.message);27 }28 };2930 this.CheckServerConnection = function (checkConnection) {31 try {32 VoltDBCore.CheckServerConnection(server, port, admin, user, password, isHashedPassword, "DATABASE_LOGIN", checkConnection);33 } catch (e) {34 console.log(e.message);35 }36 };3738 this.SetUserCredentials = function (lUsername, lPassword, lAdmin) {39 user = lUsername;40 password = lPassword;41 admin = lAdmin;42 };4344 // build Authorization header based on scheme you could flip to diff header. Server understands both.45 this.BuildAuthorization = function(user, isHashedPassword, password) {46 var authz = null;47 if (user != null && isHashedPassword != null) {48 authz = "Hashed " + user + ":" + isHashedPassword;49 } else if (user != null && password != null) {50 var up = user + ":" + password;51 authz = "Basic " + $().crypt({method: "b64enc", source: up});52 }53 return authz;54 }5556 this.ChangeServerConfiguration = function (serverName, portId, userName, pw, isHashPw, isAdmin) {57 server = serverName != null ? serverName : server;58 port = portId != null ? portId : port;59 user = userName != undefined ? userName : "";60 password = pw != undefined ? pw : "";61 isHashedPassword = isHashPw;62 admin = isAdmin != undefined ? isAdmin : true;6364 };6566 this.GetSystemInformation = function (onConnectionAdded) {67 try {68 var processName = "SYSTEM_INFORMATION";69 var procedureNames = ['@SystemInformation', '@Statistics'];70 var parameters = ["OVERVIEW", "MEMORY"];71 var values = [undefined, '0'];72 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);73 if (_connection == null) {74 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {75 if (result == true) {76 updateTips("Connection successful.");7778 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {79 onConnectionAdded(connection, status);80 });81 } else updateTips("Unable to connect.");8283 });8485 } else {86 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {87 onConnectionAdded(connection, status);8889 });9091 }92 } catch (e) {93 console.log(e.message);94 }9596 function updateTips(t) {97 tips98 .text(t)99 .addClass("ui-state-highlight");100 setTimeout(function () {101 tips.removeClass("ui-state-highlight", 1500);102 }, 500);103 }104105106 };107108 this.GetClusterInformation = function (onConnectionAdded) {109 try {110 var processName = "CLUSTER_INFORMATION";111 var procedureNames = ['@SystemInformation'];112 var parameters = ["OVERVIEW"];113 var values = [undefined];114 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);115 if (_connection == null) {116 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {117 if (result == true) {118 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {119 onConnectionAdded(connection, status);120 });121 } 122 });123124 } else {125 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {126 onConnectionAdded(connection, status);127128 });129130 }131 } catch (e) {132 console.log(e.message);133 }134 };135136 this.GetSystemInformationDeployment = function (onConnectionAdded) {137 try {138 var processName = "SYSTEM_INFORMATION_DEPLOYMENT";139 var procedureNames = ['@SystemInformation'];140 var parameters = ["DEPLOYMENT"];141 var values = [];142 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);143 if (_connection == null) {144 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {145 if (result == true) {146 updateTips("Connection successful.");147148 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {149 onConnectionAdded(connection);150 });151 } else updateTips("Unable to connect.");152153 });154155 } else {156 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {157 onConnectionAdded(connection);158159 });160161 }162 } catch (e) {163 console.log(e.message);164 }165166 function updateTips(t) {167 tips168 .text(t)169 .addClass("ui-state-highlight");170 setTimeout(function () {171 tips.removeClass("ui-state-highlight", 1500);172 }, 500);173 }174175176 };177178 this.GetDataTablesInformation = function (onConnectionAdded) {179 try {180 var processName = "DATABASE_INFORMATION";181 var procedureNames = ['@Statistics', '@SystemCatalog', '@SystemCatalog'];182 var parameters = ["TABLE", "TABLES"];183 var values = ['0', undefined];184 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);185 if (_connection == null) {186 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {187 if (result == true) {188 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {189 onConnectionAdded(connection, status);190 });191 }192193 });194195 } else {196 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {197 onConnectionAdded(connection, status);198199 });200201 }202203 } catch (e) {204 console.log(e.message);205 }206207 };208209 this.GetProceduresInformation = function (onConnectionAdded) {210 try {211 var processName = "DATABASE_INFORMATION";212 var procedureNames = ['@Statistics'];213 var parameters = ["PROCEDUREPROFILE"];214 var values = ['0'];215 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);216 if (_connection == null) {217 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {218 if (result == true) {219 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {220 onConnectionAdded(connection, status);221 });222 }223224 });225226 } else {227 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {228 onConnectionAdded(connection, status);229230 });231232 }233234 } catch (e) {235 console.log(e.message);236 }237238 };239240 this.getProcedureContextForSorting = function () {241 try {242 var processName = "DATABASE_INFORMATION";243 var procedureNames = ['@Statistics'];244 var parameters = ["PROCEDUREPROFILE"];245 var values = ['0'];246 var lconnection = VoltDBCore.HasConnection(server, port, admin, user, processName);247 if (lconnection == null) {248 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {249 if (result == true) {250 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {251 lconnection = connection;252 });253 }254255 });256 }257 return lconnection;258259 } catch (e) {260 console.log(e.message);261 }262 };263264 this.getTablesContextForSorting = function () {265 try {266 var processName = "DATABASE_INFORMATION";267 var procedureNames = ['@Statistics'];268 var parameters = ["TABLE"];269 var values = ['0'];270 var lconnection = VoltDBCore.HasConnection(server, port, admin, user, processName);271 if (lconnection == null) {272 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {273 if (result == true) {274 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {275 lconnection = connection;276 });277 }278279 });280 } //else {281 // VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, lconnection, function (connection, status) {282 // lconnection = connection;283 // });284285 //}286 return lconnection;287288289 } catch (e) {290 console.log(e.message);291 }292 };293294 this.GetMemoryInformation = function (onConnectionAdded) {295 try {296 var processName = "GRAPH_MEMORY";297 var procedureNames = ['@Statistics'];298 var parameters = ["MEMORY"];299 var values = ['0'];300 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);301 if (_connection == null) {302 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {303 if (result == true) {304 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {305 onConnectionAdded(connection, status);306 });307 }308309 });310311 } else {312 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {313 onConnectionAdded(connection, status);314315 });316317 }318319 } catch (e) {320 console.log(e.message);321 }322323 };324325 this.GetGraphLatencyInformation = function (onConnectionAdded) {326 try {327 var processName = "GRAPH_LATENCY";328 var procedureNames = ['@Statistics'];329 var parameters = ["LATENCY_HISTOGRAM"];330 var values = ['0'];331 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);332 if (_connection == null) {333 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {334 if (result == true) {335 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {336 onConnectionAdded(connection, status);337 });338 }339340 });341342 } else {343 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {344 onConnectionAdded(connection, status);345346 });347348 }349350 } catch (e) {351 console.log(e.message);352 }353354 };355356 this.GetCPUInformation = function (onConnectionAdded) {357 try {358 //GRAPH_CPU359 var processName = "GRAPH_CPU";360 var procedureNames = ['@Statistics'];361 var parameters = ["CPU"];362 var values = ['0'];363 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);364 if (_connection == null) {365 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {366 if (result == true) {367 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {368 onConnectionAdded(connection, status);369 });370 }371372 });373374 } else {375 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {376 onConnectionAdded(connection, status);377378 });379380 }381382 } catch (e) {383 console.log(e.message);384 }385386 };387 388 //Render Cluster Transaction Graph389 this.GetTransactionInformation = function (onConnectionAdded) {390 try {391 var processName = "GRAPH_TRANSACTION";392 var procedureNames = ['@Statistics'];393 var parameters = ["PROCEDUREPROFILE"];394 var values = ['0'];395 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);396 if (_connection == null) {397 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {398 if (result == true) {399 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {400 onConnectionAdded(connection, status);401 });402 }403404 });405406 } else {407 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {408 onConnectionAdded(connection, status);409410 });411412 }413414 } catch (e) {415 console.log(e.message);416 }417418 };419420 this.GetTableInformation = function (onConnectionAdded) {421 try {422 var processName = "TABLE_INFORMATION";423 var procedureNames = ['@Statistics', '@Statistics', '@SystemCatalog', '@SystemCatalog', '@SystemCatalog'];424 var parameters = ["TABLE", "INDEX", "COLUMNS", "PROCEDURES", "PROCEDURECOLUMNS"];425 var values = ['0', '0', undefined];426 var isAdmin = false;427 _connection = VoltDBCore.HasConnection(server, port, isAdmin, user, processName);428 if (_connection == null) {429 VoltDBCore.TestConnection(server, port, isAdmin, user, password, isHashedPassword, processName, function (result) {430 if (result == true) {431 VoltDBCore.AddConnection(server, port, isAdmin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {432 onConnectionAdded(connection, status);433 });434 }435436 });437438 } else {439 VoltDBCore.updateConnection(server, port, isAdmin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {440 onConnectionAdded(connection, status);441442 });443444 }445446 } catch (e) {447 console.log(e.message);448 }449450 };451452 this.GetShortApiProfile = function (onConnectionAdded) {453 try {454 var processName = "SHORTAPI_PROFILE";455 var procedureNames = [];456 var parameters = [];457 var values = [];458 var shortApiDetails = {459 isShortApiCall: true,460 apiPath: 'profile'461 };462463 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);464 if (_connection == null) {465 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {466 if (result == true) {467 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {468 onConnectionAdded(connection, status);469 }, shortApiDetails);470 }471 });472473 } else {474 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {475 onConnectionAdded(connection, status);476 }, shortApiDetails);477478 }479480 } catch (e) {481 console.log(e.message);482 }483484 };485486 this.GetShortApiDeployment = function (onConnectionAdded) {487 try {488 var processName = "SHORTAPI_DEPLOYMENT";489 var procedureNames = [];490 var parameters = [];491 var values = [];492 var shortApiDetails = {493 isShortApiCall : true,494 apiPath : 'deployment'495 };496497 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);498 if (_connection == null) {499 var status = "";500 var statusString = "";501 502 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {503 if (result == true) {504 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {505 status = connection.Metadata['@SHORTAPI_DEPLOYMENT_status'];506 statusString = connection.Metadata['@SHORTAPI_DEPLOYMENT_statusString'];507 onConnectionAdded(connection);508 509 }, shortApiDetails);510 }511 });512513 } else {514 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {515 status = connection.Metadata['@SHORTAPI_DEPLOYMENT_status'];516 statusString = connection.Metadata['@SHORTAPI_DEPLOYMENT_statusString'];517 onConnectionAdded(connection);518 519 }, shortApiDetails);520521 }522523 } catch (e) {524 console.log(e.message);525 }526527 };528529 //Update admin configuration530 this.UpdateAdminConfiguration = function (updatedData, onConnectionAdded) {531 try {532 var processName = "SHORTAPI_UPDATEDEPLOYMENT";533 var procedureNames = [];534 var parameters = [];535 var values = [];536 var shortApiDetails = {537 isShortApiCall: true,538 isUpdateConfiguration: true,539 apiPath: 'deployment',540 updatedData: 'deployment=' + JSON.stringify(updatedData)541 };542543 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);544 if (_connection == null) {545 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {546 if (result == true) {547 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {548 onConnectionAdded(connection, status);549 }, shortApiDetails);550 }551 });552553 } else {554 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {555 onConnectionAdded(connection, status);556 }, shortApiDetails);557558 }559560 } catch (e) {561 console.log(e.message);562 }563564 };565566 //admin configuration567 this.editConfigurationItem = function (configGroup, configMember,configValue,onConnectionSucceeded) {568 try {569 var processName = "ADMIN_".concat(configGroup);570 var procedureNames = [];571 var parameters = [];572 var values = [];573 var isAdmin = true;574575 switch (configGroup) {576 case 'OVERVIEW':577 procedureNames = ['@SystemInformation'];578 parameters = [configMember];579 values = [configValue];580 break;581582 case 'PORT':583 procedureNames = ['@SystemInformation'];584 parameters = [configMember];585 values = [configValue];586 break;587588 case 'DIRECTORIES':589 procedureNames = ['@SystemInformation'];590 parameters = [configMember];591 values = [configValue];592 break;593594 }595596 _connection = VoltDBCore.HasConnection(server, port, isAdmin, user, processName);597 if (_connection == null) {598 VoltDBCore.TestConnection(server, port, isAdmin, user, password, isHashedPassword, processName, function (result) {599 if (result == true) {600 VoltDBCore.AddConnection(server, port, isAdmin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {601 onConnectionSucceeded(connection, status);602 });603 }604605 });606607 } else {608 VoltDBCore.updateConnection(server, port, isAdmin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {609 onConnectionSucceeded(connection, status);610611 });612613 }614615 }616 catch (e) {617618 }619 };620621 this.stopServerNode = function(nodeId,onConnectionAdded) {622 try {623 var processName = "SYSTEMINFORMATION_STOPSERVER";624 var procedureNames = ['@StopNode'];625 var parameters = [nodeId.toString()];626 var values = [undefined];627 var statusString = "";628629 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);630 if (_connection == null) {631 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {632 if (result == true) {633 var status = 0;634 635 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function(connection, status) {636 status = connection.Metadata['@StopNode_' + nodeId.toString() + '_status'];637 statusString = connection.Metadata['@StopNode_' + nodeId.toString() + '_statusString'];638 if (!(status == "" || status == undefined)) {639 onConnectionAdded(connection, status, statusString);640 }641642 });643 }644645 });646647 } else {648 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {649 status = connection.Metadata['@StopNode_' + nodeId.toString() + '_status'];650 statusString = connection.Metadata['@StopNode_' + nodeId.toString() + '_statusString'];651652 if (!(status == "" || status == undefined)) {653 onConnectionAdded(connection, status, statusString);654 }655656 });657658 }659660 } catch (e) {661 console.log(e.message);662 }663664 };665 666 this.PauseClusterState = function (onConnectionAdded) {667 try {668 var processName = "SYSTEMINFORMATION_PAUSECLUSTER";669 var procedureNames = ['@Pause'];670 var parameters = [undefined];671 var values = [undefined];672673 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);674 if (_connection == null) {675 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {676 if (result == true) {677 var status = 0;678 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {679 status = connection.Metadata['@Pause_status'];680 if (!(status == "" || status == undefined)) {681 onConnectionAdded(connection, status);682 }683684685 });686 }687688 });689690 } else {691 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {692 status = connection.Metadata['@Pause_status'];693 if (!(status == "" || status == undefined)) {694 onConnectionAdded(connection, status);695 }696697 });698699 }700701 } catch (e) {702 console.log(e.message);703 }704705706 };707 708 this.ResumeClusterState = function (onConnectionAdded) {709 try {710 var processName = "SYSTEMINFORMATION_RESUMECLUSTER";711 var procedureNames = ['@Resume'];712 var parameters = [undefined];713 var values = [undefined];714715 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);716 if (_connection == null) {717 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {718 if (result == true) {719 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {720 status = connection.Metadata['@Resume_status'];721 if (!(status == "" || status == undefined)) {722 onConnectionAdded(connection, status);723 }724 });725 }726727 });728729 } else {730 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {731 status = connection.Metadata['@Resume_status'];732 if (!(status == "" || status == undefined)) {733 onConnectionAdded(connection, status);734 }735736 });737738 }739740 } catch (e) {741 console.log(e.message);742 }743744745 };746 747 this.ShutdownClusterState = function (onConnectionAdded) {748 try {749 var processName = "SYSTEMINFORMATION_SHUTDOWNCLUSTER";750 var procedureNames = ['@Shutdown'];751 var parameters = [undefined];752 var values = [undefined];753754 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);755 if (_connection == null) {756 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {757 if (result == true) {758 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {759 status = connection.Metadata['@Shutdown_status'];760 if (!(status == "" || status == undefined)) {761 onConnectionAdded(connection, status);762 }763 });764 }765766 });767768 } else {769 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {770 status = connection.Metadata['@Shutdown_status'];771 if (!(status == "" || status == undefined)) {772 onConnectionAdded(connection, status);773 }774775 });776777 }778779 } catch (e) {780 console.log(e.message);781 }782783784 };785 786 this.PromoteCluster = function (onConnectionAdded) {787 try {788 var processName = "SYSTEMINFORMATION_PROMOTECLUSTER";789 var procedureNames = ['@Promote'];790 var parameters = [undefined];791 var values = [undefined];792793 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);794 if (_connection == null) {795 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {796 if (result == true) {797 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {798 status = connection.Metadata['@Promote_status'];799 if (!(status == "" || status == undefined)) {800 onConnectionAdded(connection, status, connection.Metadata['@Promote_statusstring']);801 }802 });803 }804805 });806807 } else {808 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {809 status = connection.Metadata['@Promote_status'];810 if (!(status == "" || status == undefined)) {811 onConnectionAdded(connection, status, connection.Metadata['@Promote_statusstring']);812 }813814 });815816 }817818 } catch (e) {819 console.log(e.message);820 }821822823 };824825 this.SaveSnapShot = function(snapshotDir,snapshotFileName, onConnectionAdded) {826 try {827 var processName = "SYSTEMINFORMATION_SAVESNAPSHOT";828 var procedureNames = ['@SnapshotSave'];829 var parameters = ["'" + snapshotDir + "'",snapshotFileName, 0];830 var values = [undefined];831832 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);833 if (_connection == null) {834 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {835 if (result == true) {836 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {837 status = connection.Metadata['@SnapshotSave_status'];838 if (!(status == "" || status == undefined)) {839 onConnectionAdded(connection, status);840 }841 });842 }843844 });845846 } else {847 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {848 status = connection.Metadata['@SnapshotSave_status'];849 if (!(status == "" || status == undefined)) {850 onConnectionAdded(connection, status);851 }852853 });854855 }856857 } catch (e) {858 console.log(e.message);859 }860861 };862863 this.GetSnapshotList = function(snapshotDirectory, onConnectionAdded) {864 try {865 var processName = "SYSTEMINFORMATION_SCANSNAPSHOTS";866 var procedureNames = ['@SnapshotScan'];867 var parameters = [snapshotDirectory];868 var values = [undefined];869 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);870 if (_connection == null) {871 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function(result) {872 if (result == true) {873 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function(connection, status) {874 status = connection.Metadata['@SnapshotScan_status'];875 if (!(status == "" || status == undefined)) {876 onConnectionAdded(connection, status);877 }878 });879 }880881 });882883 } else {884 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function(connection, status) {885 status = connection.Metadata['@SnapshotScan_status'];886 if (!(status == "" || status == undefined)) {887 onConnectionAdded(connection, status);888 }889890 });891892 }893894 } catch(e) {895 console.log(e.message);896 }897898 };899 900 this.RestoreSnapShot = function (snapshotDir, snapshotFileName, onConnectionAdded) {901 try {902 var processName = "SYSTEMINFORMATION_RESTORESNAPSHOT";903 var procedureNames = ['@SnapshotRestore'];904 var parameters = ["'" + snapshotDir + "'", snapshotFileName, 0];905 var values = [undefined];906907 _connection = VoltDBCore.HasConnection(server, port, admin, user, processName);908 if (_connection == null) {909 VoltDBCore.TestConnection(server, port, admin, user, password, isHashedPassword, processName, function (result) {910 if (result == true) {911 VoltDBCore.AddConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, function (connection, status) {912 status = connection.Metadata['@SnapshotRestore_status'];913 if (!(status == "" || status == undefined)) {914 onConnectionAdded(connection, status, connection.Metadata['@SnapshotRestore_statusstring']);915 }916 });917 }918919 });920921 } else {922 VoltDBCore.updateConnection(server, port, admin, user, password, isHashedPassword, procedureNames, parameters, values, processName, _connection, function (connection, status) {923 status = connection.Metadata['@SnapshotRestore_status'];924 if (!(status == "" || status == undefined)) {925 onConnectionAdded(connection, status, connection.Metadata['@SnapshotRestore_statusstring']);926 }927928 });929930 }931932 } catch (e) {933 console.log(e.message);934 }935936 };937 //end admin configuration938939 });940941 window.VoltDBService = VoltDBService = new iVoltDbService();942943})(window);
...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'google.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'google.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.screenshot({path: 'google.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.screenshot({path: 'google.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.screenshot({path: 'google.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.screenshot({path: 'google.png'});41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch();46 const page = await browser.newPage();47 await page.goto('
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.screenshot({path: 'example.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.screenshot({path: 'example.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.screenshot({path: 'example.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.screenshot({path: 'example.png'});41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch();46 const page = await browser.newPage();47 await page.goto('
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.screenshot({path: 'google.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 const page = await browser.newPage();12 await page.screenshot({path: 'google.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 await page.screenshot({path: 'google.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch({headless: false});25 const page = await browser.newPage();26 await page.screenshot({path: 'google.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({headless: false});32 const page = await browser.newPage();33 await page.screenshot({path: 'google.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch({headless: false});39 const page = await browser.newPage();40 await page.screenshot({path: 'google.png'});41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch({headless: false});46 const page = await browser.newPage();47 await page.goto('https
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 await page.screenshot({path: 'example.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch({headless: false});25 const page = await browser.newPage();26 await page.screenshot({path: 'example.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({headless: false});32 const page = await browser.newPage();33 await page.screenshot({path: 'example.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch({headless: false});39 const page = await browser.newPage();40 await page.screenshot({path: 'example.png'});41 await browser.close();42})();43const puppeteer = require('p
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();
Using AI Code Generation
1const puppeteer = require("puppeteer");2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.goto(url);6 await page.screenshot({ path: "google.png" });7 await browser.close();8})();9const puppeteer = require("puppeteer");10(async () => {11 const browserWSEndpoint = await puppeteer.launch().wsEndpoint();12 const browser = await puppeteer.connect({ browserWSEndpoint });13 const page = await browser.newPage();14 await page.goto(url);15 await page.screenshot({ path: "google.png" });16 await browser.close();17})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const { Connection } = require('puppeteer/lib/cjs/puppeteer/common/Connection.js');3const { ConnectionTransport } = require('puppeteer/lib/cjs/puppeteer/common/ConnectionTransport.js');4const transport = new ConnectionTransport();5const connection = new Connection('', transport);6const page = await browser.newPage();7await page.screenshot({path: 'google.png'});8await browser.close();9const puppeteer = require('puppeteer');10const { Connection } = require('puppeteer/lib/cjs/puppeteer/common/Connection.js');11const { ConnectionTransport } = require('puppeteer/lib/cjs/puppeteer/common/ConnectionTransport.js');12const transport = new ConnectionTransport();13const connection = new Connection('', transport);14const page = await browser.newPage();15await page.screenshot({path: 'google.png'});16await browser.close();
Using AI Code Generation
1const puppeteer = require('puppeteer')2const fs = require('fs')3const devices = require('puppeteer/DeviceDescriptors')4;(async () => {5 const browser = await puppeteer.launch({6 })7 const page = await browser.newPage()8 await page.setViewport({ width: 1366, height: 768 })9 await page.goto(url, { waitUntil: 'networkidle0' })10 await page.emulate(iPhone)11 await page.screenshot({ path: 'iphone.png', fullPage: true })12 await page.emulate(iPad)13 await page.screenshot({ path: 'ipad.png', fullPage: true })14 await page.emulate(android)15 await page.screenshot({ path: 'android.png', fullPage: true })16 await browser.close()17})()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!