How to use rid method in wpt

Best JavaScript code snippet using wpt

TransportSession.js.uncompressed.js

Source:TransportSession.js.uncompressed.js Github

copy

Full Screen

1// wrapped by build app2define("dojox/xmpp/TransportSession", ["dijit","dojo","dojox","dojo/require!dojox/xmpp/bosh,dojox/xmpp/util,dojox/data/dom"], function(dijit,dojo,dojox){3dojo.provide("dojox.xmpp.TransportSession");4dojo.require("dojox.xmpp.bosh");5dojo.require("dojox.xmpp.util");6dojo.require("dojox.data.dom");7dojox.xmpp.TransportSession = function(props) {8 // we have to set this here because "this" doesn't work9 // in the dojo.extend call.10 this.sendTimeout = (this.wait+20)*1000;11 //mixin any options that we want to provide to this service12 if (props && dojo.isObject(props)) {13 dojo.mixin(this, props);14 if(this.useScriptSrcTransport){15 this.transportIframes = [];16 }17 }18 19};20dojo.extend(dojox.xmpp.TransportSession, {21 /* options/defaults */22 rid: 0,23 hold: 1,24 polling:1000,25 secure: false,26 wait: 60,27 lang: 'en',28 submitContentType: 'text/xml; charset=utf=8',29 serviceUrl: '/httpbind',30 defaultResource: "dojoIm",31 domain: 'imserver.com',32 sendTimeout: 0, //(this.wait+20)*100033 34 useScriptSrcTransport:false,35 36 37 keepAliveTimer:null,38 //status39 state: "NotReady",40 transmitState: "Idle",41 protocolPacketQueue: [],42 outboundQueue: [],43 outboundRequests: {},44 inboundQueue: [],45 deferredRequests: {},46 matchTypeIdAttribute: {},47 open: function() {48 this.status = "notReady";49 this.rid = Math.round(Math.random() * 1000000000);50 this.protocolPacketQueue = [];51 this.outboundQueue = [];52 this.outboundRequests = {};53 this.inboundQueue = [];54 this.deferredRequests = {};55 this.matchTypeIdAttribute = {};56 57 58 this.keepAliveTimer = setTimeout(dojo.hitch(this, "_keepAlive"), 10000);59 60 if(this.useScriptSrcTransport){61 dojox.xmpp.bosh.initialize({62 iframes: this.hold+1,63 load: dojo.hitch(this, function(){64 this._sendLogin();65 })66 });67 } else {68 this._sendLogin();69 }70 },71 72 _sendLogin: function() {73 var rid = this.rid++;74 var req = {75 content: this.submitContentType,76 hold: this.hold,77 rid: rid,78 to: this.domain,79 secure: this.secure,80 wait: this.wait,81 "xml:lang": this.lang,82 "xmpp:version": "1.0",83 xmlns: dojox.xmpp.xmpp.BODY_NS,84 "xmlns:xmpp": "urn:xmpp:xbosh"85 };86 var msg = dojox.xmpp.util.createElement("body", req, true);87 this.addToOutboundQueue(msg, rid);88 },89 _sendRestart: function(){90 var rid = this.rid++;91 var req = {92 rid: rid,93 sid: this.sid,94 to: this.domain,95 "xmpp:restart": "true",96 "xml:lang": this.lang,97 xmlns: dojox.xmpp.xmpp.BODY_NS,98 "xmlns:xmpp": "urn:xmpp:xbosh"99 };100 var msg = dojox.xmpp.util.createElement("body", req, true);101 this.addToOutboundQueue(msg, rid);102 },103 104 processScriptSrc: function(msg, rid) {105 //console.log("processScriptSrc::", rid, msg);106 // var msgDom = dojox.xml.DomParser.parse(msg);107 var msgDom = dojox.xml.parser.parse(msg, "text/xml");108 //console.log("parsed mgs", msgDom);109 //console.log("Queue", this.outboundQueue);110 if(msgDom) {111 this.processDocument(msgDom, rid);112 } else {113 //console.log("Recived bad document from server",msg);114 }115 },116 117 _keepAlive: function(){118 if (this.state=="wait" || this.isTerminated()) {119 return;120 }121 this._dispatchPacket();122 this.keepAliveTimer = setTimeout(dojo.hitch(this, "_keepAlive"), 10000);123 },124 125 126 close: function(protocolMsg){127 128 var rid = this.rid++;129 var req = {130 131 sid: this.sid,132 rid: rid,133 type: "terminate"134 };135 var envelope = null;136 if (protocolMsg) {137 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));138 envelope.append(protocolMsg);139 envelope.append("</body>");140 } else {141 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));142 }143 // this.sendXml(envelope,rid);144 this.addToOutboundQueue(envelope.toString(), rid);145 this.state=="Terminate";146 },147 dispatchPacket: function(msg, protocolMatchType, matchId, matchProperty){148 // summary:149 // Main Packet dispatcher, most calls should be made with this other150 // than a few setup calls which use add items to the queue directly151 // protocolMatchType, matchId, and matchProperty are optional params152 // that allow a deferred to be tied to a protocol response instad of the whole153 // rid154 155 // //console.log("In dispatchPacket ", msg, protocolMatchType, matchId, matchProperty);156 if (msg){157 this.protocolPacketQueue.push(msg);158 }159 160 var def = new dojo.Deferred();161 //def.rid = req.rid;162 if (protocolMatchType && matchId){163 def.protocolMatchType = protocolMatchType;164 def.matchId = matchId;165 def.matchProperty = matchProperty || "id";166 if(def.matchProperty != "id") {167 this.matchTypeIdAttribute[protocolMatchType] = def.matchProperty;168 }169 }170 this.deferredRequests[def.protocolMatchType + "-" +def.matchId]=def;171 if(!this.dispatchTimer) {172 this.dispatchTimer = setTimeout(dojo.hitch(this, "_dispatchPacket"), 600);173 }174 return def;175 },176 177 _dispatchPacket: function(){178 179 clearTimeout(this.dispatchTimer);180 delete this.dispatchTimer;181 182 if (!this.sid){183 console.debug("TransportSession::dispatchPacket() No SID, packet dropped.")184 return;185 }186 if (!this.authId){187 //FIXME according to original nodes, this should wait a little while and try188 // again up to three times to see if we get this data.189 console.debug("TransportSession::dispatchPacket() No authId, packet dropped [FIXME]")190 return;191 }192 193 //if there is a pending request with the server, don't poll194 if (this.transmitState != "error" && (this.protocolPacketQueue.length == 0) && (this.outboundQueue.length > 0)) {195 return;196 }197 if (this.state=="wait" || this.isTerminated()) {198 return;199 }200 var req = {201 sid: this.sid,202 xmlns: dojox.xmpp.xmpp.BODY_NS203 }204 var envelope205 if (this.protocolPacketQueue.length > 0){206 req.rid= this.rid++;207 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));208 envelope.append(this.processProtocolPacketQueue());209 envelope.append("</body>");210 delete this.lastPollTime;211 } else {212 //console.log("Nothing to send, I'm just polling.");213 if(this.lastPollTime) {214 var now = new Date().getTime();215 if(now - this.lastPollTime < this.polling) {216 //console.log("Waiting to poll ", this.polling - (now - this.lastPollTime)+10);217 this.dispatchTimer = setTimeout(dojo.hitch(this, "_dispatchPacket"), this.polling - (now - this.lastPollTime)+10);218 return;219 }220 221 }222 req.rid= this.rid++;223 this.lastPollTime = new Date().getTime();224 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, true));225 }226 227 this.addToOutboundQueue(envelope.toString(),req.rid);228 },229 redispatchPacket: function(rid){230 var env = this.outboundRequests[rid];231 this.sendXml(env, rid);232 },233 addToOutboundQueue: function(msg, rid){234 this.outboundQueue.push({msg: msg,rid: rid});235 this.outboundRequests[rid]=msg;236 this.sendXml(msg, rid);237 },238 removeFromOutboundQueue: function(rid){239 for(var i=0; i<this.outboundQueue.length;i++){240 if (rid == this.outboundQueue[i]["rid"]){241 this.outboundQueue.splice(i, 1);242 break;243 }244 }245 delete this.outboundRequests[rid];246 },247 processProtocolPacketQueue: function(){248 var packets = new dojox.string.Builder();249 for(var i=0; i<this.protocolPacketQueue.length;i++){250 packets.append(this.protocolPacketQueue[i]);251 }252 this.protocolPacketQueue=[];253 return packets.toString();254 },255 sendXml: function(message, rid){256 if(this.isTerminated()) {257 return false;258 }259 //console.log("TransportSession::sendXml()"+ new Date().getTime() + " RID: ", rid, " MSG: ", message);260 this.transmitState = "transmitting";261 var def = null;262 if(this.useScriptSrcTransport) {263 //console.log("using script src to transmit");264 def = dojox.xmpp.bosh.get({265 rid: rid,266 url: this.serviceUrl+'?'+encodeURIComponent(message),267 error: dojo.hitch(this, function(res, io){268 this.setState("Terminate", "error");269 return false;270 }),271 timeout: this.sendTimeout272 });273 } else {274 def = dojo.rawXhrPost({275 contentType: "text/xml",276 url: this.serviceUrl,277 postData: message,278 handleAs: "xml",279 error: dojo.hitch(this, function(res, io) {280 ////console.log("foo", res, io.xhr.responseXML, io.xhr.status);281 return this.processError(io.xhr.responseXML, io.xhr.status , rid);282 }),283 timeout: this.sendTimeout284 });285 }286 //process the result document287 def.addCallback(this, function(res){288 return this.processDocument(res, rid);289 });290 return def;291 },292 processDocument: function(doc, rid){293 if(this.isTerminated() || !doc.firstChild) {294 return false;295 }296 //console.log("TransportSession:processDocument() ", doc, rid);297 this.transmitState = "idle";298 var body = doc.firstChild;299 if (body.nodeName != 'body'){300 //console.log("TransportSession::processDocument() firstChild is not <body> element ", doc, " RID: ", rid);301 }302 if (this.outboundQueue.length<1){return false;}303 var expectedId = this.outboundQueue[0]["rid"];304 //console.log("expectedId", expectedId);305 if (rid==expectedId){306 this.removeFromOutboundQueue(rid);307 this.processResponse(body, rid);308 this.processInboundQueue();309 }else{310 //console.log("TransportSession::processDocument() rid: ", rid, " expected: ", expectedId);311 var gap = rid-expectedId;312 313 if (gap < this.hold + 2){314 this.addToInboundQueue(doc,rid);315 }else{316 //console.log("TransportSession::processDocument() RID is outside of the expected response window");317 }318 }319 return doc;320 },321 processInboundQueue: function(){322 while (this.inboundQueue.length > 0) {323 var item = this.inboundQueue.shift();324 this.processDocument(item["doc"], item["rid"]);325 }326 },327 addToInboundQueue: function(doc,rid){328 for (var i=0; i<this.inboundQueue.length;i++){329 if (rid < this.inboundQueue[i]["rid"]){continue;}330 this.inboundQueue.splice(i,0,{doc: doc, rid: rid});331 }332 },333 processResponse: function(body,rid){334 ////console.log("TransportSession:processResponse() ", body, " RID: ", rid);335 if (body.getAttribute("type")=='terminate'){336 var reasonNode = body.firstChild.firstChild;337 var errorMessage = "";338 if(reasonNode.nodeName == "conflict") {339 errorMessage = "conflict"340 }341 this.setState("Terminate", errorMessage);342 343 return;344 }345 if ((this.state != 'Ready')&&(this.state != 'Terminate')) {346 var sid=body.getAttribute("sid");347 if (sid){348 this.sid=sid;349 } else {350 throw new Error("No sid returned during xmpp session startup");351 }352 this.authId = body.getAttribute("authid");353 if (this.authId == "") {354 if (this.authRetries-- < 1) {355 console.error("Unable to obtain Authorization ID");356 this.terminateSession();357 }358 }359 this.wait= body.getAttribute("wait");360 if( body.getAttribute("polling")){361 this.polling= parseInt(body.getAttribute("polling"))*1000;362 }363 364 //console.log("Polling value ", this.polling);365 this.inactivity = body.getAttribute("inactivity");366 this.setState("Ready");367 }368 dojo.forEach(body.childNodes, function(node){369 this.processProtocolResponse(node, rid);370 }, this);371 //need to make sure, since if you use sendXml directly instead of using372 //dispatch packets, there wont' be a call back function here373 //normally the deferred will get fired by a child message at the protocol level374 //but if it hasn't fired by now, go ahead and fire it with the full body375 /*if (this.deferredRequests[rid] && this.deferredRequests[rid].fired==-1){376 this.deferredRequests[rid].callback(body);377 }*/378 //delete from the list of outstanding requests379 //delete this.deferredRequests[rid];380 if (this.transmitState == "idle"){381 this.dispatchPacket();382 }383 },384 processProtocolResponse: function(msg, rid){385 // summary:386 // process the individual protocol messages and if there387 // is a matching set of protocolMatchType, matchId, and matchPropery388 // fire off the deferred389 this.onProcessProtocolResponse(msg);390 var key = msg.nodeName + "-" +msg.getAttribute("id");391 var def = this.deferredRequests[key];392 if (def){393 def.callback(msg);394 delete this.deferredRequests[key];395 }396 },397 setState: function(state, message){398 if (this.state != state) {399 if (this["on"+state]){400 this["on"+state](state, this.state, message);401 }402 this.state=state;403 }404 },405 406 isTerminated: function() {407 408 return this.state=="Terminate";409 },410 processError: function(err, httpStatusCode,rid){411 //console.log("Processing server error ", err, httpStatusCode,rid);412 if(this.isTerminated()) {413 return false;414 }415 416 417 if(httpStatusCode != 200) {418 if(httpStatusCode >= 400 && httpStatusCode < 500){419 /* Any status code between 400 and 500 should terminate420 * the connection */421 this.setState("Terminate", errorMessage);422 return false;423 }else{424 this.removeFromOutboundQueue(rid);425 setTimeout(dojo.hitch(this, function(){ this.dispatchPacket(); }), 200);426 return true;427 }428 return false;429 }430 431 if (err && err.dojoType && err.dojoType=="timeout"){432 //console.log("Wait timeout");433 }434 435 this.removeFromOutboundQueue(rid);436 //FIXME conditional processing if request will be needed based on type of error.437 if(err && err.firstChild) {438 //console.log("Error ", err.firstChild.getAttribute("type") + " status code " + httpStatusCode);439 440 if (err.firstChild.getAttribute("type")=='terminate'){441 var reasonNode = err.firstChild.firstChild;442 var errorMessage = "";443 if(reasonNode && reasonNode.nodeName == "conflict") {444 errorMessage = "conflict"445 }446 this.setState("Terminate", errorMessage);447 return false;448 }449 }450 this.transmitState = "error";451 setTimeout(dojo.hitch(this, function(){ this.dispatchPacket(); }), 200);452 //console.log("Error: ", arguments);453 return true;454 },455 //events456 onTerminate: function(newState, oldState, message){ },457 onProcessProtocolResponse: function(msg){},458 onReady: function(newState, oldState){}459});...

Full Screen

Full Screen

TransportSession.js

Source:TransportSession.js Github

copy

Full Screen

1dojo.provide("dojox.xmpp.TransportSession");2dojo.require("dojox.xmpp.bosh");3dojo.require("dojox.xmpp.util");4dojo.require("dojox.data.dom");5dojox.xmpp.TransportSession = function(props) {6 // we have to set this here because "this" doesn't work7 // in the dojo.extend call.8 this.sendTimeout = (this.wait+20)*1000;9 //mixin any options that we want to provide to this service10 if (props && dojo.isObject(props)) {11 dojo.mixin(this, props);12 if(this.useScriptSrcTransport){13 this.transportIframes = [];14 }15 }16 17};18dojo.extend(dojox.xmpp.TransportSession, {19 /* options/defaults */20 rid: 0,21 hold: 1,22 polling:1000,23 secure: false,24 wait: 60,25 lang: 'en',26 submitContentType: 'text/xml; charset=utf=8',27 serviceUrl: '/httpbind',28 defaultResource: "dojoIm",29 domain: 'imserver.com',30 sendTimeout: 0, //(this.wait+20)*100031 32 useScriptSrcTransport:false,33 34 35 keepAliveTimer:null,36 //status37 state: "NotReady",38 transmitState: "Idle",39 protocolPacketQueue: [],40 outboundQueue: [],41 outboundRequests: {},42 inboundQueue: [],43 deferredRequests: {},44 matchTypeIdAttribute: {},45 open: function() {46 this.status = "notReady";47 this.rid = Math.round(Math.random() * 1000000000);48 this.protocolPacketQueue = [];49 this.outboundQueue = [];50 this.outboundRequests = {};51 this.inboundQueue = [];52 this.deferredRequests = {};53 this.matchTypeIdAttribute = {};54 55 56 this.keepAliveTimer = setTimeout(dojo.hitch(this, "_keepAlive"), 10000);57 58 if(this.useScriptSrcTransport){59 dojox.xmpp.bosh.initialize({60 iframes: this.hold+1,61 load: dojo.hitch(this, function(){62 this._sendLogin();63 })64 });65 } else {66 this._sendLogin();67 }68 },69 70 _sendLogin: function() {71 var rid = this.rid++;72 var req = {73 content: this.submitContentType,74 hold: this.hold,75 rid: rid,76 to: this.domain,77 secure: this.secure,78 wait: this.wait,79 "xml:lang": this.lang,80 "xmpp:version": "1.0",81 xmlns: dojox.xmpp.xmpp.BODY_NS,82 "xmlns:xmpp": "urn:xmpp:xbosh"83 };84 var msg = dojox.xmpp.util.createElement("body", req, true);85 this.addToOutboundQueue(msg, rid);86 },87 _sendRestart: function(){88 var rid = this.rid++;89 var req = {90 rid: rid,91 sid: this.sid,92 to: this.domain,93 "xmpp:restart": "true",94 "xml:lang": this.lang,95 xmlns: dojox.xmpp.xmpp.BODY_NS,96 "xmlns:xmpp": "urn:xmpp:xbosh"97 };98 var msg = dojox.xmpp.util.createElement("body", req, true);99 this.addToOutboundQueue(msg, rid);100 },101 102 processScriptSrc: function(msg, rid) {103 //console.log("processScriptSrc::", rid, msg);104 // var msgDom = dojox.xml.DomParser.parse(msg);105 var msgDom = dojox.xml.parser.parse(msg, "text/xml");106 //console.log("parsed mgs", msgDom);107 //console.log("Queue", this.outboundQueue);108 if(msgDom) {109 this.processDocument(msgDom, rid);110 } else {111 //console.log("Recived bad document from server",msg);112 }113 },114 115 _keepAlive: function(){116 if (this.state=="wait" || this.isTerminated()) {117 return;118 }119 this._dispatchPacket();120 this.keepAliveTimer = setTimeout(dojo.hitch(this, "_keepAlive"), 10000);121 },122 123 124 close: function(protocolMsg){125 126 var rid = this.rid++;127 var req = {128 129 sid: this.sid,130 rid: rid,131 type: "terminate"132 };133 var envelope = null;134 if (protocolMsg) {135 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));136 envelope.append(protocolMsg);137 envelope.append("</body>");138 } else {139 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));140 }141 // this.sendXml(envelope,rid);142 this.addToOutboundQueue(envelope.toString(), rid);143 this.state=="Terminate";144 },145 dispatchPacket: function(msg, protocolMatchType, matchId, matchProperty){146 // summary:147 // Main Packet dispatcher, most calls should be made with this other148 // than a few setup calls which use add items to the queue directly149 // protocolMatchType, matchId, and matchProperty are optional params150 // that allow a deferred to be tied to a protocol response instad of the whole151 // rid152 153 // //console.log("In dispatchPacket ", msg, protocolMatchType, matchId, matchProperty);154 if (msg){155 this.protocolPacketQueue.push(msg);156 }157 158 var def = new dojo.Deferred();159 //def.rid = req.rid;160 if (protocolMatchType && matchId){161 def.protocolMatchType = protocolMatchType;162 def.matchId = matchId;163 def.matchProperty = matchProperty || "id";164 if(def.matchProperty != "id") {165 this.matchTypeIdAttribute[protocolMatchType] = def.matchProperty;166 }167 }168 this.deferredRequests[def.protocolMatchType + "-" +def.matchId]=def;169 if(!this.dispatchTimer) {170 this.dispatchTimer = setTimeout(dojo.hitch(this, "_dispatchPacket"), 600);171 }172 return def;173 },174 175 _dispatchPacket: function(){176 177 clearTimeout(this.dispatchTimer);178 delete this.dispatchTimer;179 180 if (!this.sid){181 console.debug("TransportSession::dispatchPacket() No SID, packet dropped.")182 return;183 }184 if (!this.authId){185 //FIXME according to original nodes, this should wait a little while and try186 // again up to three times to see if we get this data.187 console.debug("TransportSession::dispatchPacket() No authId, packet dropped [FIXME]")188 return;189 }190 191 //if there is a pending request with the server, don't poll192 if (this.transmitState != "error" && (this.protocolPacketQueue.length == 0) && (this.outboundQueue.length > 0)) {193 return;194 }195 if (this.state=="wait" || this.isTerminated()) {196 return;197 }198 var req = {199 sid: this.sid,200 xmlns: dojox.xmpp.xmpp.BODY_NS201 }202 var envelope203 if (this.protocolPacketQueue.length > 0){204 req.rid= this.rid++;205 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, false));206 envelope.append(this.processProtocolPacketQueue());207 envelope.append("</body>");208 delete this.lastPollTime;209 } else {210 //console.log("Nothing to send, I'm just polling.");211 if(this.lastPollTime) {212 var now = new Date().getTime();213 if(now - this.lastPollTime < this.polling) {214 //console.log("Waiting to poll ", this.polling - (now - this.lastPollTime)+10);215 this.dispatchTimer = setTimeout(dojo.hitch(this, "_dispatchPacket"), this.polling - (now - this.lastPollTime)+10);216 return;217 }218 219 }220 req.rid= this.rid++;221 this.lastPollTime = new Date().getTime();222 envelope = new dojox.string.Builder(dojox.xmpp.util.createElement("body", req, true));223 }224 225 this.addToOutboundQueue(envelope.toString(),req.rid);226 },227 redispatchPacket: function(rid){228 var env = this.outboundRequests[rid];229 this.sendXml(env, rid);230 },231 addToOutboundQueue: function(msg, rid){232 this.outboundQueue.push({msg: msg,rid: rid});233 this.outboundRequests[rid]=msg;234 this.sendXml(msg, rid);235 },236 removeFromOutboundQueue: function(rid){237 for(var i=0; i<this.outboundQueue.length;i++){238 if (rid == this.outboundQueue[i]["rid"]){239 this.outboundQueue.splice(i, 1);240 break;241 }242 }243 delete this.outboundRequests[rid];244 },245 processProtocolPacketQueue: function(){246 var packets = new dojox.string.Builder();247 for(var i=0; i<this.protocolPacketQueue.length;i++){248 packets.append(this.protocolPacketQueue[i]);249 }250 this.protocolPacketQueue=[];251 return packets.toString();252 },253 sendXml: function(message, rid){254 if(this.isTerminated()) {255 return false;256 }257 //console.log("TransportSession::sendXml()"+ new Date().getTime() + " RID: ", rid, " MSG: ", message);258 this.transmitState = "transmitting";259 var def = null;260 if(this.useScriptSrcTransport) {261 //console.log("using script src to transmit");262 def = dojox.xmpp.bosh.get({263 rid: rid,264 url: this.serviceUrl+'?'+encodeURIComponent(message),265 error: dojo.hitch(this, function(res, io){266 this.setState("Terminate", "error");267 return false;268 }),269 timeout: this.sendTimeout270 });271 } else {272 def = dojo.rawXhrPost({273 contentType: "text/xml",274 url: this.serviceUrl,275 postData: message,276 handleAs: "xml",277 error: dojo.hitch(this, function(res, io) {278 ////console.log("foo", res, io.xhr.responseXML, io.xhr.status);279 return this.processError(io.xhr.responseXML, io.xhr.status , rid);280 }),281 timeout: this.sendTimeout282 });283 }284 //process the result document285 def.addCallback(this, function(res){286 return this.processDocument(res, rid);287 });288 return def;289 },290 processDocument: function(doc, rid){291 if(this.isTerminated() || !doc.firstChild) {292 return false;293 }294 //console.log("TransportSession:processDocument() ", doc, rid);295 this.transmitState = "idle";296 var body = doc.firstChild;297 if (body.nodeName != 'body'){298 //console.log("TransportSession::processDocument() firstChild is not <body> element ", doc, " RID: ", rid);299 }300 if (this.outboundQueue.length<1){return false;}301 var expectedId = this.outboundQueue[0]["rid"];302 //console.log("expectedId", expectedId);303 if (rid==expectedId){304 this.removeFromOutboundQueue(rid);305 this.processResponse(body, rid);306 this.processInboundQueue();307 }else{308 //console.log("TransportSession::processDocument() rid: ", rid, " expected: ", expectedId);309 var gap = rid-expectedId;310 311 if (gap < this.hold + 2){312 this.addToInboundQueue(doc,rid);313 }else{314 //console.log("TransportSession::processDocument() RID is outside of the expected response window");315 }316 }317 return doc;318 },319 processInboundQueue: function(){320 while (this.inboundQueue.length > 0) {321 var item = this.inboundQueue.shift();322 this.processDocument(item["doc"], item["rid"]);323 }324 },325 addToInboundQueue: function(doc,rid){326 for (var i=0; i<this.inboundQueue.length;i++){327 if (rid < this.inboundQueue[i]["rid"]){continue;}328 this.inboundQueue.splice(i,0,{doc: doc, rid: rid});329 }330 },331 processResponse: function(body,rid){332 ////console.log("TransportSession:processResponse() ", body, " RID: ", rid);333 if (body.getAttribute("type")=='terminate'){334 var reasonNode = body.firstChild.firstChild;335 var errorMessage = "";336 if(reasonNode.nodeName == "conflict") {337 errorMessage = "conflict"338 }339 this.setState("Terminate", errorMessage);340 341 return;342 }343 if ((this.state != 'Ready')&&(this.state != 'Terminate')) {344 var sid=body.getAttribute("sid");345 if (sid){346 this.sid=sid;347 } else {348 throw new Error("No sid returned during xmpp session startup");349 }350 this.authId = body.getAttribute("authid");351 if (this.authId == "") {352 if (this.authRetries-- < 1) {353 console.error("Unable to obtain Authorization ID");354 this.terminateSession();355 }356 }357 this.wait= body.getAttribute("wait");358 if( body.getAttribute("polling")){359 this.polling= parseInt(body.getAttribute("polling"))*1000;360 }361 362 //console.log("Polling value ", this.polling);363 this.inactivity = body.getAttribute("inactivity");364 this.setState("Ready");365 }366 dojo.forEach(body.childNodes, function(node){367 this.processProtocolResponse(node, rid);368 }, this);369 //need to make sure, since if you use sendXml directly instead of using370 //dispatch packets, there wont' be a call back function here371 //normally the deferred will get fired by a child message at the protocol level372 //but if it hasn't fired by now, go ahead and fire it with the full body373 /*if (this.deferredRequests[rid] && this.deferredRequests[rid].fired==-1){374 this.deferredRequests[rid].callback(body);375 }*/376 //delete from the list of outstanding requests377 //delete this.deferredRequests[rid];378 if (this.transmitState == "idle"){379 this.dispatchPacket();380 }381 },382 processProtocolResponse: function(msg, rid){383 // summary:384 // process the individual protocol messages and if there385 // is a matching set of protocolMatchType, matchId, and matchPropery386 // fire off the deferred387 this.onProcessProtocolResponse(msg);388 var key = msg.nodeName + "-" +msg.getAttribute("id");389 var def = this.deferredRequests[key];390 if (def){391 def.callback(msg);392 delete this.deferredRequests[key];393 }394 },395 setState: function(state, message){396 if (this.state != state) {397 if (this["on"+state]){398 this["on"+state](state, this.state, message);399 }400 this.state=state;401 }402 },403 404 isTerminated: function() {405 406 return this.state=="Terminate";407 },408 processError: function(err, httpStatusCode,rid){409 //console.log("Processing server error ", err, httpStatusCode,rid);410 if(this.isTerminated()) {411 return false;412 }413 414 415 if(httpStatusCode != 200) {416 if(httpStatusCode >= 400 && httpStatusCode < 500){417 /* Any status code between 400 and 500 should terminate418 * the connection */419 this.setState("Terminate", errorMessage);420 return false;421 }else{422 this.removeFromOutboundQueue(rid);423 setTimeout(dojo.hitch(this, function(){ this.dispatchPacket(); }), 200);424 return true;425 }426 return false;427 }428 429 if (err && err.dojoType && err.dojoType=="timeout"){430 //console.log("Wait timeout");431 }432 433 this.removeFromOutboundQueue(rid);434 //FIXME conditional processing if request will be needed based on type of error.435 if(err && err.firstChild) {436 //console.log("Error ", err.firstChild.getAttribute("type") + " status code " + httpStatusCode);437 438 if (err.firstChild.getAttribute("type")=='terminate'){439 var reasonNode = err.firstChild.firstChild;440 var errorMessage = "";441 if(reasonNode && reasonNode.nodeName == "conflict") {442 errorMessage = "conflict"443 }444 this.setState("Terminate", errorMessage);445 return false;446 }447 }448 this.transmitState = "error";449 setTimeout(dojo.hitch(this, function(){ this.dispatchPacket(); }), 200);450 //console.log("Error: ", arguments);451 return true;452 },453 //events454 onTerminate: function(newState, oldState, message){ },455 onProcessProtocolResponse: function(msg){},456 onReady: function(newState, oldState){}...

Full Screen

Full Screen

canOpenRoom.js

Source:canOpenRoom.js Github

copy

Full Screen

1import database from '../database';2import store from '../createStore';3const restTypes = {4 channel: 'channels', direct: 'im', group: 'groups'5};6async function open({ type, rid, name }) {7 try {8 const params = rid ? { roomId: rid } : { roomName: name };9 // if it's a direct link without rid we'll create a new dm10 // if the dm already exists it'll return the existent11 if (type === 'direct' && !rid) {12 const result = await this.createDirectMessage(name);13 if (result.success) {14 const { room } = result;15 room.rid = room._id;16 return room;17 }18 }19 // if it's a group we need to check if you can open20 if (type === 'group') {21 try {22 // RC 0.61.023 await this.sdk.post(`${ restTypes[type] }.open`, params);24 } catch (e) {25 if (!(e.data && /is already open/.test(e.data.error))) {26 return false;27 }28 }29 }30 // if it's a channel or group and the link don't have rid31 // we'll get info from the room32 if ((type === 'channel' || type === 'group') && !rid) {33 // RC 0.72.034 const result = await this.sdk.get(`${ restTypes[type] }.info`, params);35 if (result.success) {36 const room = result[type];37 room.rid = room._id;38 return room;39 }40 }41 // if rid was sent by link42 if (rid) {43 return { rid };44 }45 return false;46 } catch (e) {47 return false;48 }49}50export default async function canOpenRoom({ rid, path, isCall }) {51 try {52 const db = database.active;53 const subsCollection = db.get('subscriptions');54 if (isCall && !rid) {55 // Extract rid from a Jitsi URL56 // Eg.: [Jitsi_URL_Room_Prefix][uniqueID][rid][?jwt]57 const { Jitsi_URL_Room_Prefix, uniqueID } = store.getState().settings;58 rid = path.replace(`${ Jitsi_URL_Room_Prefix }${ uniqueID }`, '').replace(/\?(.*)/g, '');59 }60 if (rid) {61 try {62 const room = await subsCollection.find(rid);63 return {64 rid,65 t: room.t,66 name: room.name,67 fname: room.fname,68 prid: room.prid,69 uids: room.uids,70 usernames: room.usernames71 };72 } catch (e) {73 // Do nothing74 }75 }76 const [type, name] = path.split('/');77 try {78 const result = await open.call(this, { type, rid, name });79 return result;80 } catch (e) {81 return false;82 }83 } catch (e) {84 return false;85 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('webpagetest');2const wptClient = wpt('www.webpagetest.org');3 if (err) return console.error(err);4 console.log(data);5 wptClient.rid(data.data.testId, (err, data) => {6 if (err) return console.error(err);7 console.log(data);8 });9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org');3}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6 test.getTestResults(data.data.testId, function(err, data) {7 if (err) return console.error(err);8 console.log(data);9 });10});11var wpt = require('webpagetest');12var test = wpt('www.webpagetest.org');13}, function(err, data) {14 if (err) return console.error(err);15 console.log(data);16 test.getTestResults(data.data.testId, function(err, data) {17 if (err) return console.error(err);18 console.log(data);19 });20});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var fs = require('fs');3var async = require('async');4var request = require('request');5var util = require('util');6var _ = require('underscore');7var csvWriter = require('csv-write-stream');8var writer = csvWriter({ headers: ["title", "image", "caption", "url"] });9writer.pipe(fs.createWriteStream('output.csv'));

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3var fs = require('fs');4client.runTest(url, {5}, function(err, data) {6 if (err) return console.error(err);7 console.log(data.data.runs[1].firstView);8 fs.writeFile('test.json', JSON.stringify(data.data.runs[1].firstView, null, 4), function(err) {9 console.log('File successfully written! - Check your project directory for the test.json file');10 })11})

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2wptools.page('Barack_Obama').then(page => {3 return page.get();4}).then(page => {5 console.log(page.infobox);6}).catch(err => {7 console.log(err);8});9const wptools = require('wptools');10wptools.page('Barack_Obama').then(page => {11 return page.get();12}).then(page => {13 console.log(page.infobox);14}).catch(err => {15 console.log(err);16});17const wptools = require('wptools');18wptools.page('Barack_Obama').then(page => {19 return page.get();20}).then(page => {21 console.log(page.infobox);22}).catch(err => {23 console.log(err);24});25const wptools = require('wptools');26wptools.page('Barack_Obama').then(page => {27 return page.get();28}).then(page => {29 console.log(page.infobox);30}).catch(err => {31 console.log(err);32});33const wptools = require('wptools');34wptools.page('Barack_Obama').then(page => {35 return page.get();36}).then(page => {37 console.log(page.infobox);38}).catch(err => {39 console.log(err);40});41const wptools = require('wptools');42wptools.page('Barack_Obama').then(page => {43 return page.get();44}).then(page => {45 console.log(page.infobox);46}).catch(err => {47 console.log(err);48});49const wptools = require('wptools');50wptools.page('Barack_Obama').then(page => {51 return page.get();52}).then(page => {53 console.log(page.infobox);54}).catch(err => {55 console.log(err);56});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var url = process.argv[2];4var wptKey = process.argv[3];5var wptLocation = process.argv[4];6var testId = process.argv[5];7var options = {8};9wpt.runTest(url, options, function(err, data) {10 if (err) return console.log(err);11 console.log('Test ID:' + data.data.testId);12 wpt.getTestResults(data.data.testId, function(err, data) {13 if (err) return console.log(err);14 console.log('SpeedIndex:' + data.data.average.firstView.SpeedIndex);15 console.log('VisuallyComplete:' + data.data.average.firstView.VisualComplete);16 console.log('TTFB:' + data.data.average.firstView.TTFB);17 console.log('FullyLoaded:' + data.data.average.firstView.fullyLoaded);18 console.log('LoadTime:' + data.data.average.firstView.loadTime);19 console.log('BytesIn:' + data.data.average.firstView.bytesIn);20 console.log('BytesInDoc:' + data.data.average.firstView.bytesInDoc);21 console.log('BytesOut:' + data.data.average.firstView.bytesOut);22 console.log('BytesOutDoc:' + data.data.average.firstView.bytesOutDoc);23 console.log('RequestsDoc:' + data.data.average.firstView.requestsDoc);24 console.log('RequestsFull:' + data.data.average.firstView.requestsFull);25 console.log('DocTime:' + data.data.average.firstView.docTime);26 console.log('TitleTime:' + data.data.average.firstView.titleTime);27 console.log('Render:' + data.data.average.firstView.render);28 console.log('LastVisualChange:' + data.data.average.firstView.lastVisualChange);29 console.log('ScoreCache:' + data.data.average.firstView.score_cache);30 console.log('ScoreCdn:' + data.data.average.firstView.score_cdn);31 console.log('ScoreGzip:' + data.data.average.firstView.score_gzip);32 console.log('ScoreCookies:' + data.data.average.firstView.score_cookies);

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var fs = require('fs');3var options = {4};5var test = wpt(options);6test.runTest(testURL, {video: 1, videoCapture: 1}, function(err, data) {7 if (err) return console.error(err);8 console.log('Test submitted. Polling for results.');9 test.checkTestStatus(data.data.testId, function(err, data) {10 if (err) return console.error(err);11 console.log('Test complete.');12 var results = JSON.stringify(data.data);13 fs.writeFile('results.json', results, 'utf8', function(err) {14 if (err) return console.error(err);15 console.log('Test results saved to results.json');16 });17 });18});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var WebPageTest = new wpt('www.webpagetest.org', options);5console.log(WebPageTest);6 if (err) return console.error(err);7 console.log('Test submitted. Polling for results...');8 WebPageTest.waitForTestToComplete(data.data.testId, function(err, data) {9 if (err) return console.error(err);10 console.log('Test completed!');11 console.log(data);12 });13});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('webpagetest');2const client = wpt('A.9a9f9d4f4c8a7a4d4f4a4a4a4a4a4a4a4a4a4a4');3const options = {4};5client.runTest(url, options, (err, data) => {6 if (err) return console.error(err);7 console.log(data.data.runs[0].firstView);8 const rid = data.data.testId;9 console.log(rid);10 client.getTestResults(rid, (err, data) => {11 if (err) return console.error(err);12 console.log(data.data.runs[0].firstView);13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var test = new wpt(options);5test.runTest(url, function (err, data) {6 if (err) return console.error(err);7 console.log('Test submitted. Polling for results...');8 test.getTestResults(data.data.testId, function (err, data) {9 if (err) return console.error(err);10 console.log('First View (loadTime): ' + data.data.average.firstView.loadTime);11 console.log('Repeat View (loadTime): ' + data.data.average.repeatView.loadTime);12 });13});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful